Actual source code: plexcreate.c

petsc-master 2020-08-25
Report Typos and Errors
  1: #define PETSCDM_DLL
  2:  #include <petsc/private/dmpleximpl.h>
  3:  #include <petsc/private/hashseti.h>
  4:  #include <petscsf.h>

  6: PetscLogEvent DMPLEX_CreateFromFile, DMPLEX_BuildFromCellList, DMPLEX_BuildCoordinatesFromCellList;

  8: /*@
  9:   DMPlexCreateDoublet - Creates a mesh of two cells of the specified type, optionally with later refinement.

 11:   Collective

 13:   Input Parameters:
 14: + comm - The communicator for the DM object
 15: . dim - The spatial dimension
 16: . simplex - Flag for simplicial cells, otherwise they are tensor product cells
 17: . interpolate - Flag to create intermediate mesh pieces (edges, faces)
 18: . refinementUniform - Flag for uniform parallel refinement
 19: - refinementLimit - A nonzero number indicates the largest admissible volume for a refined cell

 21:   Output Parameter:
 22: . dm - The DM object

 24:   Level: beginner

 26: .seealso: DMSetType(), DMCreate()
 27: @*/
 28: PetscErrorCode DMPlexCreateDoublet(MPI_Comm comm, PetscInt dim, PetscBool simplex, PetscBool interpolate, PetscBool refinementUniform, PetscReal refinementLimit, DM *newdm)
 29: {
 30:   DM             dm;
 31:   PetscInt       p;
 32:   PetscMPIInt    rank;

 36:   DMCreate(comm, &dm);
 37:   DMSetType(dm, DMPLEX);
 38:   DMSetDimension(dm, dim);
 39:   MPI_Comm_rank(comm, &rank);
 40:   switch (dim) {
 41:   case 2:
 42:     if (simplex) {PetscObjectSetName((PetscObject) dm, "triangular");}
 43:     else         {PetscObjectSetName((PetscObject) dm, "quadrilateral");}
 44:     break;
 45:   case 3:
 46:     if (simplex) {PetscObjectSetName((PetscObject) dm, "tetrahedral");}
 47:     else         {PetscObjectSetName((PetscObject) dm, "hexahedral");}
 48:     break;
 49:   default:
 50:     SETERRQ1(comm, PETSC_ERR_ARG_OUTOFRANGE, "Cannot make meshes for dimension %D", dim);
 51:   }
 52:   if (rank) {
 53:     PetscInt numPoints[2] = {0, 0};
 54:     DMPlexCreateFromDAG(dm, 1, numPoints, NULL, NULL, NULL, NULL);
 55:   } else {
 56:     switch (dim) {
 57:     case 2:
 58:       if (simplex) {
 59:         PetscInt    numPoints[2]        = {4, 2};
 60:         PetscInt    coneSize[6]         = {3, 3, 0, 0, 0, 0};
 61:         PetscInt    cones[6]            = {2, 3, 4,  5, 4, 3};
 62:         PetscInt    coneOrientations[6] = {0, 0, 0,  0, 0, 0};
 63:         PetscScalar vertexCoords[8]     = {-0.5, 0.5, 0.0, 0.0, 0.0, 1.0, 0.5, 0.5};
 64:         PetscInt    markerPoints[8]     = {2, 1, 3, 1, 4, 1, 5, 1};

 66:         DMPlexCreateFromDAG(dm, 1, numPoints, coneSize, cones, coneOrientations, vertexCoords);
 67:         for (p = 0; p < 4; ++p) {DMSetLabelValue(dm, "marker", markerPoints[p*2], markerPoints[p*2+1]);}
 68:       } else {
 69:         PetscInt    numPoints[2]        = {6, 2};
 70:         PetscInt    coneSize[8]         = {4, 4, 0, 0, 0, 0, 0, 0};
 71:         PetscInt    cones[8]            = {2, 3, 4, 5,  3, 6, 7, 4};
 72:         PetscInt    coneOrientations[8] = {0, 0, 0, 0,  0, 0, 0, 0};
 73:         PetscScalar vertexCoords[12]    = {-1.0, -0.5,  0.0, -0.5,  0.0, 0.5,  -1.0, 0.5,  1.0, -0.5,  1.0, 0.5};

 75:         DMPlexCreateFromDAG(dm, 1, numPoints, coneSize, cones, coneOrientations, vertexCoords);
 76:       }
 77:       break;
 78:     case 3:
 79:       if (simplex) {
 80:         PetscInt    numPoints[2]        = {5, 2};
 81:         PetscInt    coneSize[7]         = {4, 4, 0, 0, 0, 0, 0};
 82:         PetscInt    cones[8]            = {4, 3, 5, 2,  5, 3, 4, 6};
 83:         PetscInt    coneOrientations[8] = {0, 0, 0, 0,  0, 0, 0, 0};
 84:         PetscScalar vertexCoords[15]    = {-1.0, 0.0, 0.0,  0.0, -1.0, 0.0,  0.0, 0.0, 1.0,  0.0, 1.0, 0.0,  1.0, 0.0, 0.0};
 85:         PetscInt    markerPoints[10]    = {2, 1, 3, 1, 4, 1, 5, 1, 6, 1};

 87:         DMPlexCreateFromDAG(dm, 1, numPoints, coneSize, cones, coneOrientations, vertexCoords);
 88:         for (p = 0; p < 5; ++p) {DMSetLabelValue(dm, "marker", markerPoints[p*2], markerPoints[p*2+1]);}
 89:       } else {
 90:         PetscInt    numPoints[2]         = {12, 2};
 91:         PetscInt    coneSize[14]         = {8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
 92:         PetscInt    cones[16]            = {2, 3, 4, 5, 6, 7, 8, 9,  5, 4, 10, 11, 7, 12, 13, 8};
 93:         PetscInt    coneOrientations[16] = {0, 0, 0, 0, 0, 0, 0, 0,  0, 0,  0,  0, 0,  0,  0, 0};
 94:         PetscScalar vertexCoords[36]     = {-1.0, -0.5, -0.5,  -1.0,  0.5, -0.5,  0.0,  0.5, -0.5,   0.0, -0.5, -0.5,
 95:                                             -1.0, -0.5,  0.5,   0.0, -0.5,  0.5,  0.0,  0.5,  0.5,  -1.0,  0.5,  0.5,
 96:                                              1.0,  0.5, -0.5,   1.0, -0.5, -0.5,  1.0, -0.5,  0.5,   1.0,  0.5,  0.5};

 98:         DMPlexCreateFromDAG(dm, 1, numPoints, coneSize, cones, coneOrientations, vertexCoords);
 99:       }
100:       break;
101:     default:
102:       SETERRQ1(comm, PETSC_ERR_ARG_OUTOFRANGE, "Cannot make meshes for dimension %D", dim);
103:     }
104:   }
105:   *newdm = dm;
106:   if (refinementLimit > 0.0) {
107:     DM rdm;
108:     const char *name;

110:     DMPlexSetRefinementUniform(*newdm, PETSC_FALSE);
111:     DMPlexSetRefinementLimit(*newdm, refinementLimit);
112:     DMRefine(*newdm, comm, &rdm);
113:     PetscObjectGetName((PetscObject) *newdm, &name);
114:     PetscObjectSetName((PetscObject)    rdm,  name);
115:     DMDestroy(newdm);
116:     *newdm = rdm;
117:   }
118:   if (interpolate) {
119:     DM idm;

121:     DMPlexInterpolate(*newdm, &idm);
122:     DMDestroy(newdm);
123:     *newdm = idm;
124:   }
125:   {
126:     DM refinedMesh     = NULL;
127:     DM distributedMesh = NULL;

129:     /* Distribute mesh over processes */
130:     DMPlexDistribute(*newdm, 0, NULL, &distributedMesh);
131:     if (distributedMesh) {
132:       DMDestroy(newdm);
133:       *newdm = distributedMesh;
134:     }
135:     if (refinementUniform) {
136:       DMPlexSetRefinementUniform(*newdm, refinementUniform);
137:       DMRefine(*newdm, comm, &refinedMesh);
138:       if (refinedMesh) {
139:         DMDestroy(newdm);
140:         *newdm = refinedMesh;
141:       }
142:     }
143:   }
144:   return(0);
145: }

147: /*@
148:   DMPlexCreateSquareBoundary - Creates a 1D mesh the is the boundary of a square lattice.

150:   Collective

152:   Input Parameters:
153: + comm  - The communicator for the DM object
154: . lower - The lower left corner coordinates
155: . upper - The upper right corner coordinates
156: - edges - The number of cells in each direction

158:   Output Parameter:
159: . dm  - The DM object

161:   Note: Here is the numbering returned for 2 cells in each direction:
162: $ 18--5-17--4--16
163: $  |     |     |
164: $  6    10     3
165: $  |     |     |
166: $ 19-11-20--9--15
167: $  |     |     |
168: $  7     8     2
169: $  |     |     |
170: $ 12--0-13--1--14

172:   Level: beginner

174: .seealso: DMPlexCreateBoxMesh(), DMPlexCreateCubeBoundary(), DMSetType(), DMCreate()
175: @*/
176: PetscErrorCode DMPlexCreateSquareBoundary(DM dm, const PetscReal lower[], const PetscReal upper[], const PetscInt edges[])
177: {
178:   const PetscInt numVertices    = (edges[0]+1)*(edges[1]+1);
179:   const PetscInt numEdges       = edges[0]*(edges[1]+1) + (edges[0]+1)*edges[1];
180:   PetscInt       markerTop      = 1;
181:   PetscInt       markerBottom   = 1;
182:   PetscInt       markerRight    = 1;
183:   PetscInt       markerLeft     = 1;
184:   PetscBool      markerSeparate = PETSC_FALSE;
185:   Vec            coordinates;
186:   PetscSection   coordSection;
187:   PetscScalar    *coords;
188:   PetscInt       coordSize;
189:   PetscMPIInt    rank;
190:   PetscInt       v, vx, vy;

194:   PetscOptionsGetBool(((PetscObject) dm)->options,((PetscObject) dm)->prefix, "-dm_plex_separate_marker", &markerSeparate, NULL);
195:   if (markerSeparate) {
196:     markerTop    = 3;
197:     markerBottom = 1;
198:     markerRight  = 2;
199:     markerLeft   = 4;
200:   }
201:   MPI_Comm_rank(PetscObjectComm((PetscObject)dm), &rank);
202:   if (!rank) {
203:     PetscInt e, ex, ey;

205:     DMPlexSetChart(dm, 0, numEdges+numVertices);
206:     for (e = 0; e < numEdges; ++e) {
207:       DMPlexSetConeSize(dm, e, 2);
208:     }
209:     DMSetUp(dm); /* Allocate space for cones */
210:     for (vx = 0; vx <= edges[0]; vx++) {
211:       for (ey = 0; ey < edges[1]; ey++) {
212:         PetscInt edge   = vx*edges[1] + ey + edges[0]*(edges[1]+1);
213:         PetscInt vertex = ey*(edges[0]+1) + vx + numEdges;
214:         PetscInt cone[2];

216:         cone[0] = vertex; cone[1] = vertex+edges[0]+1;
217:         DMPlexSetCone(dm, edge, cone);
218:         if (vx == edges[0]) {
219:           DMSetLabelValue(dm, "marker", edge,    markerRight);
220:           DMSetLabelValue(dm, "marker", cone[0], markerRight);
221:           if (ey == edges[1]-1) {
222:             DMSetLabelValue(dm, "marker", cone[1], markerRight);
223:             DMSetLabelValue(dm, "Face Sets", cone[1], markerRight);
224:           }
225:         } else if (vx == 0) {
226:           DMSetLabelValue(dm, "marker", edge,    markerLeft);
227:           DMSetLabelValue(dm, "marker", cone[0], markerLeft);
228:           if (ey == edges[1]-1) {
229:             DMSetLabelValue(dm, "marker", cone[1], markerLeft);
230:             DMSetLabelValue(dm, "Face Sets", cone[1], markerLeft);
231:           }
232:         }
233:       }
234:     }
235:     for (vy = 0; vy <= edges[1]; vy++) {
236:       for (ex = 0; ex < edges[0]; ex++) {
237:         PetscInt edge   = vy*edges[0]     + ex;
238:         PetscInt vertex = vy*(edges[0]+1) + ex + numEdges;
239:         PetscInt cone[2];

241:         cone[0] = vertex; cone[1] = vertex+1;
242:         DMPlexSetCone(dm, edge, cone);
243:         if (vy == edges[1]) {
244:           DMSetLabelValue(dm, "marker", edge,    markerTop);
245:           DMSetLabelValue(dm, "marker", cone[0], markerTop);
246:           if (ex == edges[0]-1) {
247:             DMSetLabelValue(dm, "marker", cone[1], markerTop);
248:             DMSetLabelValue(dm, "Face Sets", cone[1], markerTop);
249:           }
250:         } else if (vy == 0) {
251:           DMSetLabelValue(dm, "marker", edge,    markerBottom);
252:           DMSetLabelValue(dm, "marker", cone[0], markerBottom);
253:           if (ex == edges[0]-1) {
254:             DMSetLabelValue(dm, "marker", cone[1], markerBottom);
255:             DMSetLabelValue(dm, "Face Sets", cone[1], markerBottom);
256:           }
257:         }
258:       }
259:     }
260:   }
261:   DMPlexSymmetrize(dm);
262:   DMPlexStratify(dm);
263:   /* Build coordinates */
264:   DMSetCoordinateDim(dm, 2);
265:   DMGetCoordinateSection(dm, &coordSection);
266:   PetscSectionSetNumFields(coordSection, 1);
267:   PetscSectionSetChart(coordSection, numEdges, numEdges + numVertices);
268:   PetscSectionSetFieldComponents(coordSection, 0, 2);
269:   for (v = numEdges; v < numEdges+numVertices; ++v) {
270:     PetscSectionSetDof(coordSection, v, 2);
271:     PetscSectionSetFieldDof(coordSection, v, 0, 2);
272:   }
273:   PetscSectionSetUp(coordSection);
274:   PetscSectionGetStorageSize(coordSection, &coordSize);
275:   VecCreate(PETSC_COMM_SELF, &coordinates);
276:   PetscObjectSetName((PetscObject) coordinates, "coordinates");
277:   VecSetSizes(coordinates, coordSize, PETSC_DETERMINE);
278:   VecSetBlockSize(coordinates, 2);
279:   VecSetType(coordinates,VECSTANDARD);
280:   VecGetArray(coordinates, &coords);
281:   for (vy = 0; vy <= edges[1]; ++vy) {
282:     for (vx = 0; vx <= edges[0]; ++vx) {
283:       coords[(vy*(edges[0]+1)+vx)*2+0] = lower[0] + ((upper[0] - lower[0])/edges[0])*vx;
284:       coords[(vy*(edges[0]+1)+vx)*2+1] = lower[1] + ((upper[1] - lower[1])/edges[1])*vy;
285:     }
286:   }
287:   VecRestoreArray(coordinates, &coords);
288:   DMSetCoordinatesLocal(dm, coordinates);
289:   VecDestroy(&coordinates);
290:   return(0);
291: }

293: /*@
294:   DMPlexCreateCubeBoundary - Creates a 2D mesh that is the boundary of a cubic lattice.

296:   Collective

298:   Input Parameters:
299: + comm  - The communicator for the DM object
300: . lower - The lower left front corner coordinates
301: . upper - The upper right back corner coordinates
302: - faces - The number of faces in each direction (the same as the number of cells)

304:   Output Parameter:
305: . dm  - The DM object

307:   Level: beginner

309: .seealso: DMPlexCreateBoxMesh(), DMPlexCreateSquareBoundary(), DMSetType(), DMCreate()
310: @*/
311: PetscErrorCode DMPlexCreateCubeBoundary(DM dm, const PetscReal lower[], const PetscReal upper[], const PetscInt faces[])
312: {
313:   PetscInt       vertices[3], numVertices;
314:   PetscInt       numFaces    = 2*faces[0]*faces[1] + 2*faces[1]*faces[2] + 2*faces[0]*faces[2];
315:   Vec            coordinates;
316:   PetscSection   coordSection;
317:   PetscScalar    *coords;
318:   PetscInt       coordSize;
319:   PetscMPIInt    rank;
320:   PetscInt       v, vx, vy, vz;
321:   PetscInt       voffset, iface=0, cone[4];

325:   if ((faces[0] < 1) || (faces[1] < 1) || (faces[2] < 1)) SETERRQ(PetscObjectComm((PetscObject)dm), PETSC_ERR_SUP, "Must have at least 1 face per side");
326:   MPI_Comm_rank(PetscObjectComm((PetscObject)dm), &rank);
327:   vertices[0] = faces[0]+1; vertices[1] = faces[1]+1; vertices[2] = faces[2]+1;
328:   numVertices = vertices[0]*vertices[1]*vertices[2];
329:   if (!rank) {
330:     PetscInt f;

332:     DMPlexSetChart(dm, 0, numFaces+numVertices);
333:     for (f = 0; f < numFaces; ++f) {
334:       DMPlexSetConeSize(dm, f, 4);
335:     }
336:     DMSetUp(dm); /* Allocate space for cones */

338:     /* Side 0 (Top) */
339:     for (vy = 0; vy < faces[1]; vy++) {
340:       for (vx = 0; vx < faces[0]; vx++) {
341:         voffset = numFaces + vertices[0]*vertices[1]*(vertices[2]-1) + vy*vertices[0] + vx;
342:         cone[0] = voffset; cone[1] = voffset+1; cone[2] = voffset+vertices[0]+1; cone[3] = voffset+vertices[0];
343:         DMPlexSetCone(dm, iface, cone);
344:         DMSetLabelValue(dm, "marker", iface, 1);
345:         DMSetLabelValue(dm, "marker", voffset+0, 1);
346:         DMSetLabelValue(dm, "marker", voffset+1, 1);
347:         DMSetLabelValue(dm, "marker", voffset+vertices[0]+0, 1);
348:         DMSetLabelValue(dm, "marker", voffset+vertices[0]+1, 1);
349:         iface++;
350:       }
351:     }

353:     /* Side 1 (Bottom) */
354:     for (vy = 0; vy < faces[1]; vy++) {
355:       for (vx = 0; vx < faces[0]; vx++) {
356:         voffset = numFaces + vy*(faces[0]+1) + vx;
357:         cone[0] = voffset+1; cone[1] = voffset; cone[2] = voffset+vertices[0]; cone[3] = voffset+vertices[0]+1;
358:         DMPlexSetCone(dm, iface, cone);
359:         DMSetLabelValue(dm, "marker", iface, 1);
360:         DMSetLabelValue(dm, "marker", voffset+0, 1);
361:         DMSetLabelValue(dm, "marker", voffset+1, 1);
362:         DMSetLabelValue(dm, "marker", voffset+vertices[0]+0, 1);
363:         DMSetLabelValue(dm, "marker", voffset+vertices[0]+1, 1);
364:         iface++;
365:       }
366:     }

368:     /* Side 2 (Front) */
369:     for (vz = 0; vz < faces[2]; vz++) {
370:       for (vx = 0; vx < faces[0]; vx++) {
371:         voffset = numFaces + vz*vertices[0]*vertices[1] + vx;
372:         cone[0] = voffset; cone[1] = voffset+1; cone[2] = voffset+vertices[0]*vertices[1]+1; cone[3] = voffset+vertices[0]*vertices[1];
373:         DMPlexSetCone(dm, iface, cone);
374:         DMSetLabelValue(dm, "marker", iface, 1);
375:         DMSetLabelValue(dm, "marker", voffset+0, 1);
376:         DMSetLabelValue(dm, "marker", voffset+1, 1);
377:         DMSetLabelValue(dm, "marker", voffset+vertices[0]*vertices[1]+0, 1);
378:         DMSetLabelValue(dm, "marker", voffset+vertices[0]*vertices[1]+1, 1);
379:         iface++;
380:       }
381:     }

383:     /* Side 3 (Back) */
384:     for (vz = 0; vz < faces[2]; vz++) {
385:       for (vx = 0; vx < faces[0]; vx++) {
386:         voffset = numFaces + vz*vertices[0]*vertices[1] + vertices[0]*(vertices[1]-1) + vx;
387:         cone[0] = voffset+vertices[0]*vertices[1]; cone[1] = voffset+vertices[0]*vertices[1]+1;
388:         cone[2] = voffset+1; cone[3] = voffset;
389:         DMPlexSetCone(dm, iface, cone);
390:         DMSetLabelValue(dm, "marker", iface, 1);
391:         DMSetLabelValue(dm, "marker", voffset+0, 1);
392:         DMSetLabelValue(dm, "marker", voffset+1, 1);
393:         DMSetLabelValue(dm, "marker", voffset+vertices[0]*vertices[1]+0, 1);
394:         DMSetLabelValue(dm, "marker", voffset+vertices[0]*vertices[1]+1, 1);
395:         iface++;
396:       }
397:     }

399:     /* Side 4 (Left) */
400:     for (vz = 0; vz < faces[2]; vz++) {
401:       for (vy = 0; vy < faces[1]; vy++) {
402:         voffset = numFaces + vz*vertices[0]*vertices[1] + vy*vertices[0];
403:         cone[0] = voffset; cone[1] = voffset+vertices[0]*vertices[1];
404:         cone[2] = voffset+vertices[0]*vertices[1]+vertices[0]; cone[3] = voffset+vertices[0];
405:         DMPlexSetCone(dm, iface, cone);
406:         DMSetLabelValue(dm, "marker", iface, 1);
407:         DMSetLabelValue(dm, "marker", voffset+0, 1);
408:         DMSetLabelValue(dm, "marker", voffset+vertices[0]+0, 1);
409:         DMSetLabelValue(dm, "marker", voffset+vertices[1]+0, 1);
410:         DMSetLabelValue(dm, "marker", voffset+vertices[0]*vertices[1]+vertices[0], 1);
411:         iface++;
412:       }
413:     }

415:     /* Side 5 (Right) */
416:     for (vz = 0; vz < faces[2]; vz++) {
417:       for (vy = 0; vy < faces[1]; vy++) {
418:         voffset = numFaces + vz*vertices[0]*vertices[1] + vy*vertices[0] + faces[0];
419:         cone[0] = voffset+vertices[0]*vertices[1]; cone[1] = voffset;
420:         cone[2] = voffset+vertices[0]; cone[3] = voffset+vertices[0]*vertices[1]+vertices[0];
421:         DMPlexSetCone(dm, iface, cone);
422:         DMSetLabelValue(dm, "marker", iface, 1);
423:         DMSetLabelValue(dm, "marker", voffset+0, 1);
424:         DMSetLabelValue(dm, "marker", voffset+vertices[0]+0, 1);
425:         DMSetLabelValue(dm, "marker", voffset+vertices[0]*vertices[1]+0, 1);
426:         DMSetLabelValue(dm, "marker", voffset+vertices[0]*vertices[1]+vertices[0], 1);
427:         iface++;
428:       }
429:     }
430:   }
431:   DMPlexSymmetrize(dm);
432:   DMPlexStratify(dm);
433:   /* Build coordinates */
434:   DMSetCoordinateDim(dm, 3);
435:   DMGetCoordinateSection(dm, &coordSection);
436:   PetscSectionSetChart(coordSection, numFaces, numFaces + numVertices);
437:   for (v = numFaces; v < numFaces+numVertices; ++v) {
438:     PetscSectionSetDof(coordSection, v, 3);
439:   }
440:   PetscSectionSetUp(coordSection);
441:   PetscSectionGetStorageSize(coordSection, &coordSize);
442:   VecCreate(PETSC_COMM_SELF, &coordinates);
443:   PetscObjectSetName((PetscObject) coordinates, "coordinates");
444:   VecSetSizes(coordinates, coordSize, PETSC_DETERMINE);
445:   VecSetBlockSize(coordinates, 3);
446:   VecSetType(coordinates,VECSTANDARD);
447:   VecGetArray(coordinates, &coords);
448:   for (vz = 0; vz <= faces[2]; ++vz) {
449:     for (vy = 0; vy <= faces[1]; ++vy) {
450:       for (vx = 0; vx <= faces[0]; ++vx) {
451:         coords[((vz*(faces[1]+1)+vy)*(faces[0]+1)+vx)*3+0] = lower[0] + ((upper[0] - lower[0])/faces[0])*vx;
452:         coords[((vz*(faces[1]+1)+vy)*(faces[0]+1)+vx)*3+1] = lower[1] + ((upper[1] - lower[1])/faces[1])*vy;
453:         coords[((vz*(faces[1]+1)+vy)*(faces[0]+1)+vx)*3+2] = lower[2] + ((upper[2] - lower[2])/faces[2])*vz;
454:       }
455:     }
456:   }
457:   VecRestoreArray(coordinates, &coords);
458:   DMSetCoordinatesLocal(dm, coordinates);
459:   VecDestroy(&coordinates);
460:   return(0);
461: }

463: static PetscErrorCode DMPlexCreateLineMesh_Internal(MPI_Comm comm,PetscInt segments,PetscReal lower,PetscReal upper,DMBoundaryType bd,DM *dm)
464: {
465:   PetscInt       i,fStart,fEnd,numCells = 0,numVerts = 0;
466:   PetscInt       numPoints[2],*coneSize,*cones,*coneOrientations;
467:   PetscScalar    *vertexCoords;
468:   PetscReal      L,maxCell;
469:   PetscBool      markerSeparate = PETSC_FALSE;
470:   PetscInt       markerLeft  = 1, faceMarkerLeft  = 1;
471:   PetscInt       markerRight = 1, faceMarkerRight = 2;
472:   PetscBool      wrap = (bd == DM_BOUNDARY_PERIODIC || bd == DM_BOUNDARY_TWIST) ? PETSC_TRUE : PETSC_FALSE;
473:   PetscMPIInt    rank;


479:   DMCreate(comm,dm);
480:   DMSetType(*dm,DMPLEX);
481:   DMSetDimension(*dm,1);
482:   DMCreateLabel(*dm,"marker");
483:   DMCreateLabel(*dm,"Face Sets");

485:   MPI_Comm_rank(comm,&rank);
486:   if (!rank) numCells = segments;
487:   if (!rank) numVerts = segments + (wrap ? 0 : 1);

489:   numPoints[0] = numVerts ; numPoints[1] = numCells;
490:   PetscMalloc4(numCells+numVerts,&coneSize,numCells*2,&cones,numCells+numVerts,&coneOrientations,numVerts,&vertexCoords);
491:   PetscArrayzero(coneOrientations,numCells+numVerts);
492:   for (i = 0; i < numCells; ++i) { coneSize[i] = 2; }
493:   for (i = 0; i < numVerts; ++i) { coneSize[numCells+i] = 0; }
494:   for (i = 0; i < numCells; ++i) { cones[2*i] = numCells + i%numVerts; cones[2*i+1] = numCells + (i+1)%numVerts; }
495:   for (i = 0; i < numVerts; ++i) { vertexCoords[i] = lower + (upper-lower)*((PetscReal)i/(PetscReal)numCells); }
496:   DMPlexCreateFromDAG(*dm,1,numPoints,coneSize,cones,coneOrientations,vertexCoords);
497:   PetscFree4(coneSize,cones,coneOrientations,vertexCoords);

499:   PetscOptionsGetBool(((PetscObject)*dm)->options,((PetscObject)*dm)->prefix,"-dm_plex_separate_marker",&markerSeparate,NULL);
500:   if (markerSeparate) { markerLeft = faceMarkerLeft; markerRight = faceMarkerRight;}
501:   if (!wrap && !rank) {
502:     DMPlexGetHeightStratum(*dm,1,&fStart,&fEnd);
503:     DMSetLabelValue(*dm,"marker",fStart,markerLeft);
504:     DMSetLabelValue(*dm,"marker",fEnd-1,markerRight);
505:     DMSetLabelValue(*dm,"Face Sets",fStart,faceMarkerLeft);
506:     DMSetLabelValue(*dm,"Face Sets",fEnd-1,faceMarkerRight);
507:   }
508:   if (wrap) {
509:     L       = upper - lower;
510:     maxCell = (PetscReal)1.1*(L/(PetscReal)PetscMax(1,segments));
511:     DMSetPeriodicity(*dm,PETSC_TRUE,&maxCell,&L,&bd);
512:   }
513:   return(0);
514: }

516: static PetscErrorCode DMPlexCreateBoxMesh_Simplex_Internal(MPI_Comm comm, PetscInt dim, const PetscInt faces[], const PetscReal lower[], const PetscReal upper[], const DMBoundaryType periodicity[], PetscBool interpolate, DM *dm)
517: {
518:   DM             boundary;
519:   PetscInt       i;

524:   for (i = 0; i < dim; ++i) if (periodicity[i] != DM_BOUNDARY_NONE) SETERRQ(comm, PETSC_ERR_SUP, "Periodicity is not supported for simplex meshes");
525:   DMCreate(comm, &boundary);
527:   DMSetType(boundary, DMPLEX);
528:   DMSetDimension(boundary, dim-1);
529:   DMSetCoordinateDim(boundary, dim);
530:   switch (dim) {
531:   case 2: DMPlexCreateSquareBoundary(boundary, lower, upper, faces);break;
532:   case 3: DMPlexCreateCubeBoundary(boundary, lower, upper, faces);break;
533:   default: SETERRQ1(comm, PETSC_ERR_SUP, "Dimension not supported: %D", dim);
534:   }
535:   DMPlexGenerate(boundary, NULL, interpolate, dm);
536:   DMDestroy(&boundary);
537:   return(0);
538: }

540: static PetscErrorCode DMPlexCreateCubeMesh_Internal(DM dm, const PetscReal lower[], const PetscReal upper[], const PetscInt edges[], DMBoundaryType bdX, DMBoundaryType bdY, DMBoundaryType bdZ)
541: {
542:   DMLabel        cutLabel = NULL;
543:   PetscInt       markerTop      = 1, faceMarkerTop      = 1;
544:   PetscInt       markerBottom   = 1, faceMarkerBottom   = 1;
545:   PetscInt       markerFront    = 1, faceMarkerFront    = 1;
546:   PetscInt       markerBack     = 1, faceMarkerBack     = 1;
547:   PetscInt       markerRight    = 1, faceMarkerRight    = 1;
548:   PetscInt       markerLeft     = 1, faceMarkerLeft     = 1;
549:   PetscInt       dim;
550:   PetscBool      markerSeparate = PETSC_FALSE, cutMarker = PETSC_FALSE;
551:   PetscMPIInt    rank;

555:   DMGetDimension(dm,&dim);
556:   MPI_Comm_rank(PetscObjectComm((PetscObject)dm), &rank);
557:   DMCreateLabel(dm,"marker");
558:   DMCreateLabel(dm,"Face Sets");
559:   PetscOptionsGetBool(((PetscObject) dm)->options,((PetscObject) dm)->prefix, "-dm_plex_periodic_cut", &cutMarker, NULL);
560:   if (bdX == DM_BOUNDARY_PERIODIC || bdX == DM_BOUNDARY_TWIST ||
561:       bdY == DM_BOUNDARY_PERIODIC || bdY == DM_BOUNDARY_TWIST ||
562:       bdZ == DM_BOUNDARY_PERIODIC || bdZ == DM_BOUNDARY_TWIST) {

564:     if (cutMarker) {DMCreateLabel(dm, "periodic_cut"); DMGetLabel(dm, "periodic_cut", &cutLabel);}
565:   }
566:   switch (dim) {
567:   case 2:
568:     faceMarkerTop    = 3;
569:     faceMarkerBottom = 1;
570:     faceMarkerRight  = 2;
571:     faceMarkerLeft   = 4;
572:     break;
573:   case 3:
574:     faceMarkerBottom = 1;
575:     faceMarkerTop    = 2;
576:     faceMarkerFront  = 3;
577:     faceMarkerBack   = 4;
578:     faceMarkerRight  = 5;
579:     faceMarkerLeft   = 6;
580:     break;
581:   default:
582:     SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Dimension %D not supported",dim);
583:     break;
584:   }
585:   PetscOptionsGetBool(((PetscObject) dm)->options,((PetscObject) dm)->prefix, "-dm_plex_separate_marker", &markerSeparate, NULL);
586:   if (markerSeparate) {
587:     markerBottom = faceMarkerBottom;
588:     markerTop    = faceMarkerTop;
589:     markerFront  = faceMarkerFront;
590:     markerBack   = faceMarkerBack;
591:     markerRight  = faceMarkerRight;
592:     markerLeft   = faceMarkerLeft;
593:   }
594:   {
595:     const PetscInt numXEdges    = !rank ? edges[0] : 0;
596:     const PetscInt numYEdges    = !rank ? edges[1] : 0;
597:     const PetscInt numZEdges    = !rank ? edges[2] : 0;
598:     const PetscInt numXVertices = !rank ? (bdX == DM_BOUNDARY_PERIODIC || bdX == DM_BOUNDARY_TWIST ? edges[0] : edges[0]+1) : 0;
599:     const PetscInt numYVertices = !rank ? (bdY == DM_BOUNDARY_PERIODIC || bdY == DM_BOUNDARY_TWIST ? edges[1] : edges[1]+1) : 0;
600:     const PetscInt numZVertices = !rank ? (bdZ == DM_BOUNDARY_PERIODIC || bdZ == DM_BOUNDARY_TWIST ? edges[2] : edges[2]+1) : 0;
601:     const PetscInt numCells     = numXEdges*numYEdges*numZEdges;
602:     const PetscInt numXFaces    = numYEdges*numZEdges;
603:     const PetscInt numYFaces    = numXEdges*numZEdges;
604:     const PetscInt numZFaces    = numXEdges*numYEdges;
605:     const PetscInt numTotXFaces = numXVertices*numXFaces;
606:     const PetscInt numTotYFaces = numYVertices*numYFaces;
607:     const PetscInt numTotZFaces = numZVertices*numZFaces;
608:     const PetscInt numFaces     = numTotXFaces + numTotYFaces + numTotZFaces;
609:     const PetscInt numTotXEdges = numXEdges*numYVertices*numZVertices;
610:     const PetscInt numTotYEdges = numYEdges*numXVertices*numZVertices;
611:     const PetscInt numTotZEdges = numZEdges*numXVertices*numYVertices;
612:     const PetscInt numVertices  = numXVertices*numYVertices*numZVertices;
613:     const PetscInt numEdges     = numTotXEdges + numTotYEdges + numTotZEdges;
614:     const PetscInt firstVertex  = (dim == 2) ? numFaces : numCells;
615:     const PetscInt firstXFace   = (dim == 2) ? 0 : numCells + numVertices;
616:     const PetscInt firstYFace   = firstXFace + numTotXFaces;
617:     const PetscInt firstZFace   = firstYFace + numTotYFaces;
618:     const PetscInt firstXEdge   = numCells + numFaces + numVertices;
619:     const PetscInt firstYEdge   = firstXEdge + numTotXEdges;
620:     const PetscInt firstZEdge   = firstYEdge + numTotYEdges;
621:     Vec            coordinates;
622:     PetscSection   coordSection;
623:     PetscScalar   *coords;
624:     PetscInt       coordSize;
625:     PetscInt       v, vx, vy, vz;
626:     PetscInt       c, f, fx, fy, fz, e, ex, ey, ez;

628:     DMPlexSetChart(dm, 0, numCells+numFaces+numEdges+numVertices);
629:     for (c = 0; c < numCells; c++) {
630:       DMPlexSetConeSize(dm, c, 6);
631:     }
632:     for (f = firstXFace; f < firstXFace+numFaces; ++f) {
633:       DMPlexSetConeSize(dm, f, 4);
634:     }
635:     for (e = firstXEdge; e < firstXEdge+numEdges; ++e) {
636:       DMPlexSetConeSize(dm, e, 2);
637:     }
638:     DMSetUp(dm); /* Allocate space for cones */
639:     /* Build cells */
640:     for (fz = 0; fz < numZEdges; ++fz) {
641:       for (fy = 0; fy < numYEdges; ++fy) {
642:         for (fx = 0; fx < numXEdges; ++fx) {
643:           PetscInt cell    = (fz*numYEdges + fy)*numXEdges + fx;
644:           PetscInt faceB   = firstZFace + (fy*numXEdges+fx)*numZVertices +   fz;
645:           PetscInt faceT   = firstZFace + (fy*numXEdges+fx)*numZVertices + ((fz+1)%numZVertices);
646:           PetscInt faceF   = firstYFace + (fz*numXEdges+fx)*numYVertices +   fy;
647:           PetscInt faceK   = firstYFace + (fz*numXEdges+fx)*numYVertices + ((fy+1)%numYVertices);
648:           PetscInt faceL   = firstXFace + (fz*numYEdges+fy)*numXVertices +   fx;
649:           PetscInt faceR   = firstXFace + (fz*numYEdges+fy)*numXVertices + ((fx+1)%numXVertices);
650:                             /* B,  T,  F,  K,  R,  L */
651:           PetscInt ornt[6] = {-4,  0,  0, -1,  0, -4}; /* ??? */
652:           PetscInt cone[6];

654:           /* no boundary twisting in 3D */
655:           cone[0] = faceB; cone[1] = faceT; cone[2] = faceF; cone[3] = faceK; cone[4] = faceR; cone[5] = faceL;
656:           DMPlexSetCone(dm, cell, cone);
657:           DMPlexSetConeOrientation(dm, cell, ornt);
658:           if (bdX != DM_BOUNDARY_NONE && fx == numXEdges-1 && cutLabel) {DMLabelSetValue(cutLabel, cell, 2);}
659:           if (bdY != DM_BOUNDARY_NONE && fy == numYEdges-1 && cutLabel) {DMLabelSetValue(cutLabel, cell, 2);}
660:           if (bdZ != DM_BOUNDARY_NONE && fz == numZEdges-1 && cutLabel) {DMLabelSetValue(cutLabel, cell, 2);}
661:         }
662:       }
663:     }
664:     /* Build x faces */
665:     for (fz = 0; fz < numZEdges; ++fz) {
666:       for (fy = 0; fy < numYEdges; ++fy) {
667:         for (fx = 0; fx < numXVertices; ++fx) {
668:           PetscInt face    = firstXFace + (fz*numYEdges+fy)     *numXVertices+fx;
669:           PetscInt edgeL   = firstZEdge + (fy                   *numXVertices+fx)*numZEdges + fz;
670:           PetscInt edgeR   = firstZEdge + (((fy+1)%numYVertices)*numXVertices+fx)*numZEdges + fz;
671:           PetscInt edgeB   = firstYEdge + (fz                   *numXVertices+fx)*numYEdges + fy;
672:           PetscInt edgeT   = firstYEdge + (((fz+1)%numZVertices)*numXVertices+fx)*numYEdges + fy;
673:           PetscInt ornt[4] = {0, 0, -2, -2};
674:           PetscInt cone[4];

676:           if (dim == 3) {
677:             /* markers */
678:             if (bdX != DM_BOUNDARY_PERIODIC) {
679:               if (fx == numXVertices-1) {
680:                 DMSetLabelValue(dm, "Face Sets", face, faceMarkerRight);
681:                 DMSetLabelValue(dm, "marker", face, markerRight);
682:               }
683:               else if (fx == 0) {
684:                 DMSetLabelValue(dm, "Face Sets", face, faceMarkerLeft);
685:                 DMSetLabelValue(dm, "marker", face, markerLeft);
686:               }
687:             }
688:           }
689:           cone[0] = edgeB; cone[1] = edgeR; cone[2] = edgeT; cone[3] = edgeL;
690:           DMPlexSetCone(dm, face, cone);
691:           DMPlexSetConeOrientation(dm, face, ornt);
692:         }
693:       }
694:     }
695:     /* Build y faces */
696:     for (fz = 0; fz < numZEdges; ++fz) {
697:       for (fx = 0; fx < numXEdges; ++fx) {
698:         for (fy = 0; fy < numYVertices; ++fy) {
699:           PetscInt face    = firstYFace + (fz*numXEdges+fx)*numYVertices + fy;
700:           PetscInt edgeL   = firstZEdge + (fy*numXVertices+  fx)*numZEdges + fz;
701:           PetscInt edgeR   = firstZEdge + (fy*numXVertices+((fx+1)%numXVertices))*numZEdges + fz;
702:           PetscInt edgeB   = firstXEdge + (fz                   *numYVertices+fy)*numXEdges + fx;
703:           PetscInt edgeT   = firstXEdge + (((fz+1)%numZVertices)*numYVertices+fy)*numXEdges + fx;
704:           PetscInt ornt[4] = {0, 0, -2, -2};
705:           PetscInt cone[4];

707:           if (dim == 3) {
708:             /* markers */
709:             if (bdY != DM_BOUNDARY_PERIODIC) {
710:               if (fy == numYVertices-1) {
711:                 DMSetLabelValue(dm, "Face Sets", face, faceMarkerBack);
712:                 DMSetLabelValue(dm, "marker", face, markerBack);
713:               }
714:               else if (fy == 0) {
715:                 DMSetLabelValue(dm, "Face Sets", face, faceMarkerFront);
716:                 DMSetLabelValue(dm, "marker", face, markerFront);
717:               }
718:             }
719:           }
720:           cone[0] = edgeB; cone[1] = edgeR; cone[2] = edgeT; cone[3] = edgeL;
721:           DMPlexSetCone(dm, face, cone);
722:           DMPlexSetConeOrientation(dm, face, ornt);
723:         }
724:       }
725:     }
726:     /* Build z faces */
727:     for (fy = 0; fy < numYEdges; ++fy) {
728:       for (fx = 0; fx < numXEdges; ++fx) {
729:         for (fz = 0; fz < numZVertices; fz++) {
730:           PetscInt face    = firstZFace + (fy*numXEdges+fx)*numZVertices + fz;
731:           PetscInt edgeL   = firstYEdge + (fz*numXVertices+  fx)*numYEdges + fy;
732:           PetscInt edgeR   = firstYEdge + (fz*numXVertices+((fx+1)%numXVertices))*numYEdges + fy;
733:           PetscInt edgeB   = firstXEdge + (fz*numYVertices+  fy)*numXEdges + fx;
734:           PetscInt edgeT   = firstXEdge + (fz*numYVertices+((fy+1)%numYVertices))*numXEdges + fx;
735:           PetscInt ornt[4] = {0, 0, -2, -2};
736:           PetscInt cone[4];

738:           if (dim == 2) {
739:             if (bdX == DM_BOUNDARY_TWIST && fx == numXEdges-1) {edgeR += numYEdges-1-2*fy; ornt[1] = -2;}
740:             if (bdY == DM_BOUNDARY_TWIST && fy == numYEdges-1) {edgeT += numXEdges-1-2*fx; ornt[2] =  0;}
741:             if (bdX != DM_BOUNDARY_NONE && fx == numXEdges-1 && cutLabel) {DMLabelSetValue(cutLabel, face, 2);}
742:             if (bdY != DM_BOUNDARY_NONE && fy == numYEdges-1 && cutLabel) {DMLabelSetValue(cutLabel, face, 2);}
743:           } else {
744:             /* markers */
745:             if (bdZ != DM_BOUNDARY_PERIODIC) {
746:               if (fz == numZVertices-1) {
747:                 DMSetLabelValue(dm, "Face Sets", face, faceMarkerTop);
748:                 DMSetLabelValue(dm, "marker", face, markerTop);
749:               }
750:               else if (fz == 0) {
751:                 DMSetLabelValue(dm, "Face Sets", face, faceMarkerBottom);
752:                 DMSetLabelValue(dm, "marker", face, markerBottom);
753:               }
754:             }
755:           }
756:           cone[0] = edgeB; cone[1] = edgeR; cone[2] = edgeT; cone[3] = edgeL;
757:           DMPlexSetCone(dm, face, cone);
758:           DMPlexSetConeOrientation(dm, face, ornt);
759:         }
760:       }
761:     }
762:     /* Build Z edges*/
763:     for (vy = 0; vy < numYVertices; vy++) {
764:       for (vx = 0; vx < numXVertices; vx++) {
765:         for (ez = 0; ez < numZEdges; ez++) {
766:           const PetscInt edge    = firstZEdge  + (vy*numXVertices+vx)*numZEdges + ez;
767:           const PetscInt vertexB = firstVertex + (ez                   *numYVertices+vy)*numXVertices + vx;
768:           const PetscInt vertexT = firstVertex + (((ez+1)%numZVertices)*numYVertices+vy)*numXVertices + vx;
769:           PetscInt       cone[2];

771:           if (dim == 3) {
772:             if (bdX != DM_BOUNDARY_PERIODIC) {
773:               if (vx == numXVertices-1) {
774:                 DMSetLabelValue(dm, "marker", edge, markerRight);
775:               }
776:               else if (vx == 0) {
777:                 DMSetLabelValue(dm, "marker", edge, markerLeft);
778:               }
779:             }
780:             if (bdY != DM_BOUNDARY_PERIODIC) {
781:               if (vy == numYVertices-1) {
782:                 DMSetLabelValue(dm, "marker", edge, markerBack);
783:               }
784:               else if (vy == 0) {
785:                 DMSetLabelValue(dm, "marker", edge, markerFront);
786:               }
787:             }
788:           }
789:           cone[0] = vertexB; cone[1] = vertexT;
790:           DMPlexSetCone(dm, edge, cone);
791:         }
792:       }
793:     }
794:     /* Build Y edges*/
795:     for (vz = 0; vz < numZVertices; vz++) {
796:       for (vx = 0; vx < numXVertices; vx++) {
797:         for (ey = 0; ey < numYEdges; ey++) {
798:           const PetscInt nextv   = (dim == 2 && bdY == DM_BOUNDARY_TWIST && ey == numYEdges-1) ? (numXVertices-vx-1) : (vz*numYVertices+((ey+1)%numYVertices))*numXVertices + vx;
799:           const PetscInt edge    = firstYEdge  + (vz*numXVertices+vx)*numYEdges + ey;
800:           const PetscInt vertexF = firstVertex + (vz*numYVertices+ey)*numXVertices + vx;
801:           const PetscInt vertexK = firstVertex + nextv;
802:           PetscInt       cone[2];

804:           cone[0] = vertexF; cone[1] = vertexK;
805:           DMPlexSetCone(dm, edge, cone);
806:           if (dim == 2) {
807:             if ((bdX != DM_BOUNDARY_PERIODIC) && (bdX != DM_BOUNDARY_TWIST)) {
808:               if (vx == numXVertices-1) {
809:                 DMSetLabelValue(dm, "Face Sets", edge, faceMarkerRight);
810:                 DMSetLabelValue(dm, "marker", edge,    markerRight);
811:                 DMSetLabelValue(dm, "marker", cone[0], markerRight);
812:                 if (ey == numYEdges-1) {
813:                   DMSetLabelValue(dm, "marker", cone[1], markerRight);
814:                 }
815:               } else if (vx == 0) {
816:                 DMSetLabelValue(dm, "Face Sets", edge, faceMarkerLeft);
817:                 DMSetLabelValue(dm, "marker", edge,    markerLeft);
818:                 DMSetLabelValue(dm, "marker", cone[0], markerLeft);
819:                 if (ey == numYEdges-1) {
820:                   DMSetLabelValue(dm, "marker", cone[1], markerLeft);
821:                 }
822:               }
823:             } else {
824:               if (vx == 0 && cutLabel) {
825:                 DMLabelSetValue(cutLabel, edge,    1);
826:                 DMLabelSetValue(cutLabel, cone[0], 1);
827:                 if (ey == numYEdges-1) {
828:                   DMLabelSetValue(cutLabel, cone[1], 1);
829:                 }
830:               }
831:             }
832:           } else {
833:             if (bdX != DM_BOUNDARY_PERIODIC) {
834:               if (vx == numXVertices-1) {
835:                 DMSetLabelValue(dm, "marker", edge, markerRight);
836:               } else if (vx == 0) {
837:                 DMSetLabelValue(dm, "marker", edge, markerLeft);
838:               }
839:             }
840:             if (bdZ != DM_BOUNDARY_PERIODIC) {
841:               if (vz == numZVertices-1) {
842:                 DMSetLabelValue(dm, "marker", edge, markerTop);
843:               } else if (vz == 0) {
844:                 DMSetLabelValue(dm, "marker", edge, markerBottom);
845:               }
846:             }
847:           }
848:         }
849:       }
850:     }
851:     /* Build X edges*/
852:     for (vz = 0; vz < numZVertices; vz++) {
853:       for (vy = 0; vy < numYVertices; vy++) {
854:         for (ex = 0; ex < numXEdges; ex++) {
855:           const PetscInt nextv   = (dim == 2 && bdX == DM_BOUNDARY_TWIST && ex == numXEdges-1) ? (numYVertices-vy-1)*numXVertices : (vz*numYVertices+vy)*numXVertices + (ex+1)%numXVertices;
856:           const PetscInt edge    = firstXEdge  + (vz*numYVertices+vy)*numXEdges + ex;
857:           const PetscInt vertexL = firstVertex + (vz*numYVertices+vy)*numXVertices + ex;
858:           const PetscInt vertexR = firstVertex + nextv;
859:           PetscInt       cone[2];

861:           cone[0] = vertexL; cone[1] = vertexR;
862:           DMPlexSetCone(dm, edge, cone);
863:           if (dim == 2) {
864:             if ((bdY != DM_BOUNDARY_PERIODIC) && (bdY != DM_BOUNDARY_TWIST)) {
865:               if (vy == numYVertices-1) {
866:                 DMSetLabelValue(dm, "Face Sets", edge, faceMarkerTop);
867:                 DMSetLabelValue(dm, "marker", edge,    markerTop);
868:                 DMSetLabelValue(dm, "marker", cone[0], markerTop);
869:                 if (ex == numXEdges-1) {
870:                   DMSetLabelValue(dm, "marker", cone[1], markerTop);
871:                 }
872:               } else if (vy == 0) {
873:                 DMSetLabelValue(dm, "Face Sets", edge, faceMarkerBottom);
874:                 DMSetLabelValue(dm, "marker", edge,    markerBottom);
875:                 DMSetLabelValue(dm, "marker", cone[0], markerBottom);
876:                 if (ex == numXEdges-1) {
877:                   DMSetLabelValue(dm, "marker", cone[1], markerBottom);
878:                 }
879:               }
880:             } else {
881:               if (vy == 0 && cutLabel) {
882:                 DMLabelSetValue(cutLabel, edge,    1);
883:                 DMLabelSetValue(cutLabel, cone[0], 1);
884:                 if (ex == numXEdges-1) {
885:                   DMLabelSetValue(cutLabel, cone[1], 1);
886:                 }
887:               }
888:             }
889:           } else {
890:             if (bdY != DM_BOUNDARY_PERIODIC) {
891:               if (vy == numYVertices-1) {
892:                 DMSetLabelValue(dm, "marker", edge, markerBack);
893:               }
894:               else if (vy == 0) {
895:                 DMSetLabelValue(dm, "marker", edge, markerFront);
896:               }
897:             }
898:             if (bdZ != DM_BOUNDARY_PERIODIC) {
899:               if (vz == numZVertices-1) {
900:                 DMSetLabelValue(dm, "marker", edge, markerTop);
901:               }
902:               else if (vz == 0) {
903:                 DMSetLabelValue(dm, "marker", edge, markerBottom);
904:               }
905:             }
906:           }
907:         }
908:       }
909:     }
910:     DMPlexSymmetrize(dm);
911:     DMPlexStratify(dm);
912:     /* Build coordinates */
913:     DMGetCoordinateSection(dm, &coordSection);
914:     PetscSectionSetNumFields(coordSection, 1);
915:     PetscSectionSetFieldComponents(coordSection, 0, dim);
916:     PetscSectionSetChart(coordSection, firstVertex, firstVertex+numVertices);
917:     for (v = firstVertex; v < firstVertex+numVertices; ++v) {
918:       PetscSectionSetDof(coordSection, v, dim);
919:       PetscSectionSetFieldDof(coordSection, v, 0, dim);
920:     }
921:     PetscSectionSetUp(coordSection);
922:     PetscSectionGetStorageSize(coordSection, &coordSize);
923:     VecCreate(PETSC_COMM_SELF, &coordinates);
924:     PetscObjectSetName((PetscObject) coordinates, "coordinates");
925:     VecSetSizes(coordinates, coordSize, PETSC_DETERMINE);
926:     VecSetBlockSize(coordinates, dim);
927:     VecSetType(coordinates,VECSTANDARD);
928:     VecGetArray(coordinates, &coords);
929:     for (vz = 0; vz < numZVertices; ++vz) {
930:       for (vy = 0; vy < numYVertices; ++vy) {
931:         for (vx = 0; vx < numXVertices; ++vx) {
932:           coords[((vz*numYVertices+vy)*numXVertices+vx)*dim+0] = lower[0] + ((upper[0] - lower[0])/numXEdges)*vx;
933:           coords[((vz*numYVertices+vy)*numXVertices+vx)*dim+1] = lower[1] + ((upper[1] - lower[1])/numYEdges)*vy;
934:           if (dim == 3) {
935:             coords[((vz*numYVertices+vy)*numXVertices+vx)*dim+2] = lower[2] + ((upper[2] - lower[2])/numZEdges)*vz;
936:           }
937:         }
938:       }
939:     }
940:     VecRestoreArray(coordinates, &coords);
941:     DMSetCoordinatesLocal(dm, coordinates);
942:     VecDestroy(&coordinates);
943:   }
944:   return(0);
945: }

947: static PetscErrorCode DMPlexCreateBoxMesh_Tensor_Internal(MPI_Comm comm, PetscInt dim, const PetscInt faces[], const PetscReal lower[], const PetscReal upper[], const DMBoundaryType periodicity[], PetscBool interpolate, DM *dm)
948: {
949:   PetscInt       i;

954:   DMCreate(comm, dm);
956:   DMSetType(*dm, DMPLEX);
957:   DMSetDimension(*dm, dim);
958:   switch (dim) {
959:   case 2: {DMPlexCreateCubeMesh_Internal(*dm, lower, upper, faces, periodicity[0], periodicity[1], DM_BOUNDARY_NONE);break;}
960:   case 3: {DMPlexCreateCubeMesh_Internal(*dm, lower, upper, faces, periodicity[0], periodicity[1], periodicity[2]);break;}
961:   default: SETERRQ1(comm, PETSC_ERR_SUP, "Dimension not supported: %D", dim);
962:   }
963:   if (periodicity[0] == DM_BOUNDARY_PERIODIC || periodicity[0] == DM_BOUNDARY_TWIST ||
964:       periodicity[1] == DM_BOUNDARY_PERIODIC || periodicity[1] == DM_BOUNDARY_TWIST ||
965:       (dim > 2 && (periodicity[2] == DM_BOUNDARY_PERIODIC || periodicity[2] == DM_BOUNDARY_TWIST))) {
966:     PetscReal L[3];
967:     PetscReal maxCell[3];

969:     for (i = 0; i < dim; i++) {
970:       L[i]       = upper[i] - lower[i];
971:       maxCell[i] = 1.1 * (L[i] / PetscMax(1,faces[i]));
972:     }
973:     DMSetPeriodicity(*dm,PETSC_TRUE,maxCell,L,periodicity);
974:   }
975:   if (!interpolate) {
976:     DM udm;

978:     DMPlexUninterpolate(*dm, &udm);
979:     DMPlexCopyCoordinates(*dm, udm);
980:     DMDestroy(dm);
981:     *dm  = udm;
982:   }
983:   return(0);
984: }

986: /*@C
987:   DMPlexCreateBoxMesh - Creates a mesh on the tensor product of unit intervals (box) using simplices or tensor cells (hexahedra).

989:   Collective

991:   Input Parameters:
992: + comm        - The communicator for the DM object
993: . dim         - The spatial dimension
994: . simplex     - PETSC_TRUE for simplices, PETSC_FALSE for tensor cells
995: . faces       - Number of faces per dimension, or NULL for (1,) in 1D and (2, 2) in 2D and (1, 1, 1) in 3D
996: . lower       - The lower left corner, or NULL for (0, 0, 0)
997: . upper       - The upper right corner, or NULL for (1, 1, 1)
998: . periodicity - The boundary type for the X,Y,Z direction, or NULL for DM_BOUNDARY_NONE
999: - interpolate - Flag to create intermediate mesh pieces (edges, faces)

1001:   Output Parameter:
1002: . dm  - The DM object

1004:   Options Database Keys:
1005: + -dm_plex_box_lower <x,y,z> - Specify lower-left-bottom coordinates for the box
1006: . -dm_plex_box_upper <x,y,z> - Specify upper-right-top coordinates for the box
1007: - -dm_plex_box_faces <m,n,p> - Number of faces in each linear direction

1009:   Notes:
1010:   The options database keys above take lists of length d in d dimensions.

1012:   Here is the numbering returned for 2 faces in each direction for tensor cells:
1013: $ 10---17---11---18----12
1014: $  |         |         |
1015: $  |         |         |
1016: $ 20    2   22    3    24
1017: $  |         |         |
1018: $  |         |         |
1019: $  7---15----8---16----9
1020: $  |         |         |
1021: $  |         |         |
1022: $ 19    0   21    1   23
1023: $  |         |         |
1024: $  |         |         |
1025: $  4---13----5---14----6

1027: and for simplicial cells

1029: $ 14----8---15----9----16
1030: $  |\     5  |\      7 |
1031: $  | \       | \       |
1032: $ 13   2    14    3    15
1033: $  | 4   \   | 6   \   |
1034: $  |       \ |       \ |
1035: $ 11----6---12----7----13
1036: $  |\        |\        |
1037: $  | \    1  | \     3 |
1038: $ 10   0    11    1    12
1039: $  | 0   \   | 2   \   |
1040: $  |       \ |       \ |
1041: $  8----4----9----5----10

1043:   Level: beginner

1045: .seealso: DMPlexCreateFromFile(), DMPlexCreateHexCylinderMesh(), DMSetType(), DMCreate()
1046: @*/
1047: PetscErrorCode DMPlexCreateBoxMesh(MPI_Comm comm, PetscInt dim, PetscBool simplex, const PetscInt faces[], const PetscReal lower[], const PetscReal upper[], const DMBoundaryType periodicity[], PetscBool interpolate, DM *dm)
1048: {
1049:   PetscInt       fac[3] = {0, 0, 0};
1050:   PetscReal      low[3] = {0, 0, 0};
1051:   PetscReal      upp[3] = {1, 1, 1};
1052:   DMBoundaryType bdt[3] = {DM_BOUNDARY_NONE, DM_BOUNDARY_NONE, DM_BOUNDARY_NONE};
1053:   PetscInt       i, n;
1054:   PetscBool      flg;

1058:   PetscOptionsGetInt(NULL, NULL, "-dm_plex_box_dim", &dim, &flg);
1059:   if ((dim < 0) || (dim > 3)) SETERRQ1(comm, PETSC_ERR_ARG_OUTOFRANGE, "Dimension %D should be in [1, 3]", dim);
1060:   PetscOptionsGetBool(NULL, NULL, "-dm_plex_box_simplex", &simplex, &flg);
1061:   n    = 3;
1062:   PetscOptionsGetIntArray(NULL, NULL, "-dm_plex_box_faces", fac, &n, &flg);
1063:   for (i = 0; i < dim; ++i) fac[i] = faces ? faces[i] : (flg && i < n ? fac[i] : (dim == 1 ? 1 : 4-dim));
1064:   if (lower) for (i = 0; i < dim; ++i) low[i] = lower[i];
1065:   if (upper) for (i = 0; i < dim; ++i) upp[i] = upper[i];
1066:   if (periodicity) for (i = 0; i < dim; ++i) bdt[i] = periodicity[i];
1067:   /* Allow bounds to be specified from the command line */
1068:   n    = 3;
1069:   PetscOptionsGetRealArray(NULL, NULL, "-dm_plex_box_lower", low, &n, &flg);
1070:   if (flg && (n != dim)) SETERRQ2(comm, PETSC_ERR_ARG_SIZ, "Lower box point had %D values, should have been %D", n, dim);
1071:   n    = 3;
1072:   PetscOptionsGetRealArray(NULL, NULL, "-dm_plex_box_upper", upp, &n, &flg);
1073:   if (flg && (n != dim)) SETERRQ2(comm, PETSC_ERR_ARG_SIZ, "Upper box point had %D values, should have been %D", n, dim);

1075:   if (dim == 1)      {DMPlexCreateLineMesh_Internal(comm, fac[0], low[0], upp[0], bdt[0], dm);}
1076:   else if (simplex)  {DMPlexCreateBoxMesh_Simplex_Internal(comm, dim, fac, low, upp, bdt, interpolate, dm);}
1077:   else               {DMPlexCreateBoxMesh_Tensor_Internal(comm, dim, fac, low, upp, bdt, interpolate, dm);}
1078:   return(0);
1079: }

1081: /*@
1082:   DMPlexCreateWedgeBoxMesh - Creates a 3-D mesh tesselating the (x,y) plane and extruding in the third direction using wedge cells.

1084:   Collective

1086:   Input Parameters:
1087: + comm        - The communicator for the DM object
1088: . faces       - Number of faces per dimension, or NULL for (1, 1, 1)
1089: . lower       - The lower left corner, or NULL for (0, 0, 0)
1090: . upper       - The upper right corner, or NULL for (1, 1, 1)
1091: . periodicity - The boundary type for the X,Y,Z direction, or NULL for DM_BOUNDARY_NONE
1092: . orderHeight - If PETSC_TRUE, orders the extruded cells in the height first. Otherwise, orders the cell on the layers first
1093: - interpolate - Flag to create intermediate mesh pieces (edges, faces)

1095:   Output Parameter:
1096: . dm  - The DM object

1098:   Level: beginner

1100: .seealso: DMPlexCreateHexCylinderMesh(), DMPlexCreateWedgeCylinderMesh(), DMPlexExtrude(), DMPlexCreateBoxMesh(), DMSetType(), DMCreate()
1101: @*/
1102: PetscErrorCode DMPlexCreateWedgeBoxMesh(MPI_Comm comm, const PetscInt faces[], const PetscReal lower[], const PetscReal upper[], const DMBoundaryType periodicity[], PetscBool orderHeight, PetscBool interpolate, DM *dm)
1103: {
1104:   DM             bdm, botdm;
1105:   PetscInt       i;
1106:   PetscInt       fac[3] = {0, 0, 0};
1107:   PetscReal      low[3] = {0, 0, 0};
1108:   PetscReal      upp[3] = {1, 1, 1};
1109:   DMBoundaryType bdt[3] = {DM_BOUNDARY_NONE, DM_BOUNDARY_NONE, DM_BOUNDARY_NONE};

1113:   for (i = 0; i < 3; ++i) fac[i] = faces ? (faces[i] > 0 ? faces[i] : 1) : 1;
1114:   if (lower) for (i = 0; i < 3; ++i) low[i] = lower[i];
1115:   if (upper) for (i = 0; i < 3; ++i) upp[i] = upper[i];
1116:   if (periodicity) for (i = 0; i < 3; ++i) bdt[i] = periodicity[i];
1117:   for (i = 0; i < 3; ++i) if (bdt[i] != DM_BOUNDARY_NONE) SETERRQ(comm, PETSC_ERR_SUP, "Periodicity not yet supported");

1119:   DMCreate(comm, &bdm);
1120:   DMSetType(bdm, DMPLEX);
1121:   DMSetDimension(bdm, 1);
1122:   DMSetCoordinateDim(bdm, 2);
1123:   DMPlexCreateSquareBoundary(bdm, low, upp, fac);
1124:   DMPlexGenerate(bdm, NULL, PETSC_FALSE, &botdm);
1125:   DMDestroy(&bdm);
1126:   DMPlexExtrude(botdm, fac[2], upp[2] - low[2], orderHeight, NULL, interpolate, dm);
1127:   if (low[2] != 0.0) {
1128:     Vec         v;
1129:     PetscScalar *x;
1130:     PetscInt    cDim, n;

1132:     DMGetCoordinatesLocal(*dm, &v);
1133:     VecGetBlockSize(v, &cDim);
1134:     VecGetLocalSize(v, &n);
1135:     VecGetArray(v, &x);
1136:     x   += cDim;
1137:     for (i=0; i<n; i+=cDim) x[i] += low[2];
1138:     VecRestoreArray(v,&x);
1139:     DMSetCoordinatesLocal(*dm, v);
1140:   }
1141:   DMDestroy(&botdm);
1142:   return(0);
1143: }

1145: /*@C
1146:   DMPlexExtrude - Creates a (d+1)-D mesh by extruding a d-D mesh in the normal direction using prismatic cells.

1148:   Collective on idm

1150:   Input Parameters:
1151: + idm         - The mesh to be extruded
1152: . layers      - The number of layers, or PETSC_DETERMINE to use the default
1153: . height      - The height of the extruded layer, or PETSC_DETERMINE to use the default
1154: . orderHeight - If PETSC_TRUE, orders the extruded cells in the height first. Otherwise, orders the cell on the layers first
1155: . extNormal   - The normal direction in which the mesh should be extruded, or NULL to extrude using the surface normal
1156: - interpolate - Flag to create intermediate mesh pieces (edges, faces)

1158:   Output Parameter:
1159: . dm  - The DM object

1161:   Notes:
1162:   The mesh created has prismatic cells, and the vertex ordering in the cone of the cell is that of the tensor prismatic cells. Not currently supported in Fortran.

1164:   Options Database Keys:
1165: +   -dm_plex_extrude_layers <k> - Sets the nubmer of layers k
1166: .   -dm_plex_extrude_height <h> - Sets the height h of each layer
1167: .   -dm_plex_extrude_order_height - If true, order cells by height first
1168: -   -dm_plex_extrude_normal <n0,...,nd> - Sets the normal vector along which to extrude

1170:   Level: advanced

1172: .seealso: DMPlexCreateWedgeCylinderMesh(), DMPlexCreateWedgeBoxMesh(), DMSetType(), DMCreate()
1173: @*/
1174: PetscErrorCode DMPlexExtrude(DM idm, PetscInt layers, PetscReal height, PetscBool orderHeight, const PetscReal extNormal[], PetscBool interpolate, DM* dm)
1175: {
1176:   PetscScalar       *coordsB;
1177:   const PetscScalar *coordsA;
1178:   PetscReal         *normals = NULL;
1179:   PetscReal         clNormal[3];
1180:   Vec               coordinatesA, coordinatesB;
1181:   PetscSection      coordSectionA, coordSectionB;
1182:   PetscInt          dim, cDim, cDimB, c, l, v, coordSize, *newCone;
1183:   PetscInt          cStart, cEnd, vStart, vEnd, cellV, numCells, numVertices;
1184:   const char       *prefix;
1185:   PetscBool         haveCLNormal;
1186:   PetscErrorCode    ierr;

1193:   DMGetDimension(idm, &dim);
1194:   DMGetCoordinateDim(idm, &cDim);
1195:   cDimB = cDim == dim ? cDim+1 : cDim;
1196:   if (dim < 1 || dim > 3) SETERRQ1(PetscObjectComm((PetscObject)idm), PETSC_ERR_SUP, "Support for dimension %D not coded", dim);

1198:   PetscObjectGetOptionsPrefix((PetscObject) idm, &prefix);
1199:   if (layers < 0) layers = 1;
1200:   PetscOptionsGetInt(NULL, prefix, "-dm_plex_extrude_layers", &layers, NULL);
1201:   if (layers <= 0) SETERRQ1(PetscObjectComm((PetscObject) idm), PETSC_ERR_ARG_OUTOFRANGE, "Number of layers %D must be positive", layers);
1202:   if (height < 0.) height = 1.;
1203:   PetscOptionsGetReal(NULL, prefix, "-dm_plex_extrude_height", &height, NULL);
1204:   if (height <= 0.) SETERRQ1(PetscObjectComm((PetscObject) idm), PETSC_ERR_ARG_OUTOFRANGE, "Height of layers %g must be positive", (double) height);
1205:   PetscOptionsGetBool(NULL, prefix, "-dm_plex_extrude_order_height", &orderHeight, NULL);
1206:   c = 3;
1207:   PetscOptionsGetRealArray(NULL, prefix, "-dm_plex_extrude_normal", clNormal, &c, &haveCLNormal);
1208:   if (haveCLNormal && c != cDimB) SETERRQ2(PetscObjectComm((PetscObject)idm), PETSC_ERR_ARG_SIZ, "Input normal has size %D != %D extruded coordinate dimension", c, cDimB);

1210:   DMPlexGetHeightStratum(idm, 0, &cStart, &cEnd);
1211:   DMPlexGetDepthStratum(idm, 0, &vStart, &vEnd);
1212:   numCells = (cEnd - cStart)*layers;
1213:   numVertices = (vEnd - vStart)*(layers+1);
1214:   DMCreate(PetscObjectComm((PetscObject)idm), dm);
1215:   DMSetType(*dm, DMPLEX);
1216:   DMSetDimension(*dm, dim+1);
1217:   DMPlexSetChart(*dm, 0, numCells+numVertices);
1218:   /* Must create the celltype label here so that we do not automatically try to compute the types */
1219:   DMCreateLabel(*dm, "celltype");
1220:   for (c = cStart, cellV = 0; c < cEnd; ++c) {
1221:     DMPolytopeType ct, nct;
1222:     PetscInt      *closure = NULL;
1223:     PetscInt       closureSize, numCorners = 0;

1225:     DMPlexGetCellType(idm, c, &ct);
1226:     switch (ct) {
1227:       case DM_POLYTOPE_SEGMENT:       nct = DM_POLYTOPE_SEG_PRISM_TENSOR;break;
1228:       case DM_POLYTOPE_TRIANGLE:      nct = DM_POLYTOPE_TRI_PRISM_TENSOR;break;
1229:       case DM_POLYTOPE_QUADRILATERAL: nct = DM_POLYTOPE_QUAD_PRISM_TENSOR;break;
1230:       default: nct = DM_POLYTOPE_UNKNOWN;
1231:     }
1232:     DMPlexGetTransitiveClosure(idm, c, PETSC_TRUE, &closureSize, &closure);
1233:     for (v = 0; v < closureSize*2; v += 2) if ((closure[v] >= vStart) && (closure[v] < vEnd)) numCorners++;
1234:     DMPlexRestoreTransitiveClosure(idm, c, PETSC_TRUE, &closureSize, &closure);
1235:     for (l = 0; l < layers; ++l) {
1236:       const PetscInt cell = orderHeight ? layers*(c - cStart) + l : l*(cEnd - cStart) + c - cStart;

1238:       DMPlexSetConeSize(*dm, cell, 2*numCorners);
1239:       DMPlexSetCellType(*dm, cell, nct);
1240:     }
1241:     cellV = PetscMax(numCorners,cellV);
1242:   }
1243:   DMSetUp(*dm);

1245:   if (dim != cDim && !(extNormal || haveCLNormal)) {PetscCalloc1(cDim*(vEnd - vStart), &normals);}
1246:   PetscMalloc1(3*cellV,&newCone);
1247:   for (c = cStart; c < cEnd; ++c) {
1248:     PetscInt *closure = NULL;
1249:     PetscInt closureSize, numCorners = 0, l;
1250:     PetscReal normal[3] = {0, 0, 0};

1252:     if (normals) {DMPlexComputeCellGeometryFVM(idm, c, NULL, NULL, normal);}
1253:     DMPlexGetTransitiveClosure(idm, c, PETSC_TRUE, &closureSize, &closure);
1254:     for (v = 0; v < closureSize*2; v += 2) {
1255:       if ((closure[v] >= vStart) && (closure[v] < vEnd)) {
1256:         PetscInt d;

1258:         newCone[numCorners++] = closure[v] - vStart;
1259:         if (normals) {for (d = 0; d < cDim; ++d) normals[cDim*(closure[v]-vStart)+d] += normal[d];}
1260:       }
1261:     }
1262:     DMPlexRestoreTransitiveClosure(idm, c, PETSC_TRUE, &closureSize, &closure);
1263:     for (l = 0; l < layers; ++l) {
1264:       PetscInt i;

1266:       for (i = 0; i < numCorners; ++i) {
1267:         newCone[  numCorners + i] = orderHeight ? (layers+1)*newCone[i] + l     + numCells :     l*(vEnd - vStart) + newCone[i] + numCells;
1268:         newCone[2*numCorners + i] = orderHeight ? (layers+1)*newCone[i] + l + 1 + numCells : (l+1)*(vEnd - vStart) + newCone[i] + numCells;
1269:       }
1270:       DMPlexSetCone(*dm, orderHeight ? layers*(c - cStart) + l : l*(cEnd - cStart) + c - cStart, newCone + numCorners);
1271:     }
1272:   }
1273:   DMPlexSymmetrize(*dm);
1274:   DMPlexStratify(*dm);
1275:   PetscFree(newCone);

1277:   DMGetCoordinateSection(*dm, &coordSectionB);
1278:   PetscSectionSetNumFields(coordSectionB, 1);
1279:   PetscSectionSetFieldComponents(coordSectionB, 0, cDimB);
1280:   PetscSectionSetChart(coordSectionB, numCells, numCells+numVertices);
1281:   for (v = numCells; v < numCells+numVertices; ++v) {
1282:     PetscSectionSetDof(coordSectionB, v, cDimB);
1283:     PetscSectionSetFieldDof(coordSectionB, v, 0, cDimB);
1284:     DMPlexSetCellType(*dm, v, DM_POLYTOPE_POINT);
1285:   }
1286:   PetscSectionSetUp(coordSectionB);
1287:   PetscSectionGetStorageSize(coordSectionB, &coordSize);
1288:   VecCreate(PETSC_COMM_SELF, &coordinatesB);
1289:   PetscObjectSetName((PetscObject) coordinatesB, "coordinates");
1290:   VecSetSizes(coordinatesB, coordSize, PETSC_DETERMINE);
1291:   VecSetBlockSize(coordinatesB, cDimB);
1292:   VecSetType(coordinatesB,VECSTANDARD);

1294:   DMGetCoordinateSection(idm, &coordSectionA);
1295:   DMGetCoordinatesLocal(idm, &coordinatesA);
1296:   VecGetArray(coordinatesB, &coordsB);
1297:   VecGetArrayRead(coordinatesA, &coordsA);
1298:   for (v = vStart; v < vEnd; ++v) {
1299:     const PetscScalar *cptr;
1300:     PetscReal         ones2[2] = { 0., 1.}, ones3[3] = { 0., 0., 1.};
1301:     PetscReal         normal[3];
1302:     PetscReal         norm, h = height/layers;
1303:     PetscInt          offA, d, cDimA = cDim;

1305:     if (normals)           {for (d = 0; d < cDimB; ++d) normal[d] = normals[cDimB*(v - vStart)+d];}
1306:     else if (haveCLNormal) {for (d = 0; d < cDimB; ++d) normal[d] = clNormal[d];}
1307:     else if (extNormal)    {for (d = 0; d < cDimB; ++d) normal[d] = extNormal[d];}
1308:     else if (cDimB == 2)   {for (d = 0; d < cDimB; ++d) normal[d] = ones2[d];}
1309:     else if (cDimB == 3)   {for (d = 0; d < cDimB; ++d) normal[d] = ones3[d];}
1310:     else SETERRQ(PETSC_COMM_SELF, PETSC_ERR_PLIB, "Unable to determine normal for extrusion");
1311:     for (d = 0, norm = 0.0; d < cDimB; ++d) norm += normal[d]*normal[d];
1312:     for (d = 0; d < cDimB; ++d) normal[d] *= 1./PetscSqrtReal(norm);

1314:     PetscSectionGetOffset(coordSectionA, v, &offA);
1315:     cptr = coordsA + offA;
1316:     for (l = 0; l < layers+1; ++l) {
1317:       PetscInt offB, d, newV;

1319:       newV = orderHeight ? (layers+1)*(v -vStart) + l + numCells : (vEnd -vStart)*l + (v -vStart) + numCells;
1320:       PetscSectionGetOffset(coordSectionB, newV, &offB);
1321:       for (d = 0; d < cDimA; ++d) { coordsB[offB+d]  = cptr[d]; }
1322:       for (d = 0; d < cDimB; ++d) { coordsB[offB+d] += l ? normal[d]*h : 0.0; }
1323:       cptr    = coordsB + offB;
1324:       cDimA   = cDimB;
1325:     }
1326:   }
1327:   VecRestoreArrayRead(coordinatesA, &coordsA);
1328:   VecRestoreArray(coordinatesB, &coordsB);
1329:   DMSetCoordinatesLocal(*dm, coordinatesB);
1330:   VecDestroy(&coordinatesB);
1331:   PetscFree(normals);
1332:   if (interpolate) {
1333:     DM idm;

1335:     DMPlexInterpolate(*dm, &idm);
1336:     DMPlexCopyCoordinates(*dm, idm);
1337:     DMDestroy(dm);
1338:     *dm  = idm;
1339:   }
1340:   return(0);
1341: }

1343: /*@C
1344:   DMPlexSetOptionsPrefix - Sets the prefix used for searching for all DM options in the database.

1346:   Logically Collective on dm

1348:   Input Parameters:
1349: + dm - the DM context
1350: - prefix - the prefix to prepend to all option names

1352:   Notes:
1353:   A hyphen (-) must NOT be given at the beginning of the prefix name.
1354:   The first character of all runtime options is AUTOMATICALLY the hyphen.

1356:   Level: advanced

1358: .seealso: SNESSetFromOptions()
1359: @*/
1360: PetscErrorCode DMPlexSetOptionsPrefix(DM dm, const char prefix[])
1361: {
1362:   DM_Plex       *mesh = (DM_Plex *) dm->data;

1367:   PetscObjectSetOptionsPrefix((PetscObject) dm, prefix);
1368:   PetscObjectSetOptionsPrefix((PetscObject) mesh->partitioner, prefix);
1369:   return(0);
1370: }

1372: /*@
1373:   DMPlexCreateHexCylinderMesh - Creates a mesh on the tensor product of the unit interval with the circle (cylinder) using hexahedra.

1375:   Collective

1377:   Input Parameters:
1378: + comm      - The communicator for the DM object
1379: . numRefine - The number of regular refinements to the basic 5 cell structure
1380: - periodicZ - The boundary type for the Z direction

1382:   Output Parameter:
1383: . dm  - The DM object

1385:   Note: Here is the output numbering looking from the bottom of the cylinder:
1386: $       17-----14
1387: $        |     |
1388: $        |  2  |
1389: $        |     |
1390: $ 17-----8-----7-----14
1391: $  |     |     |     |
1392: $  |  3  |  0  |  1  |
1393: $  |     |     |     |
1394: $ 19-----5-----6-----13
1395: $        |     |
1396: $        |  4  |
1397: $        |     |
1398: $       19-----13
1399: $
1400: $ and up through the top
1401: $
1402: $       18-----16
1403: $        |     |
1404: $        |  2  |
1405: $        |     |
1406: $ 18----10----11-----16
1407: $  |     |     |     |
1408: $  |  3  |  0  |  1  |
1409: $  |     |     |     |
1410: $ 20-----9----12-----15
1411: $        |     |
1412: $        |  4  |
1413: $        |     |
1414: $       20-----15

1416:   Level: beginner

1418: .seealso: DMPlexCreateBoxMesh(), DMSetType(), DMCreate()
1419: @*/
1420: PetscErrorCode DMPlexCreateHexCylinderMesh(MPI_Comm comm, PetscInt numRefine, DMBoundaryType periodicZ, DM *dm)
1421: {
1422:   const PetscInt dim = 3;
1423:   PetscInt       numCells, numVertices, r;
1424:   PetscMPIInt    rank;

1429:   MPI_Comm_rank(comm, &rank);
1430:   if (numRefine < 0) SETERRQ1(comm, PETSC_ERR_ARG_OUTOFRANGE, "Number of refinements %D cannot be negative", numRefine);
1431:   DMCreate(comm, dm);
1432:   DMSetType(*dm, DMPLEX);
1433:   DMSetDimension(*dm, dim);
1434:   /* Create topology */
1435:   {
1436:     PetscInt cone[8], c;

1438:     numCells    = !rank ?  5 : 0;
1439:     numVertices = !rank ? 16 : 0;
1440:     if (periodicZ == DM_BOUNDARY_PERIODIC) {
1441:       numCells   *= 3;
1442:       numVertices = !rank ? 24 : 0;
1443:     }
1444:     DMPlexSetChart(*dm, 0, numCells+numVertices);
1445:     for (c = 0; c < numCells; c++) {DMPlexSetConeSize(*dm, c, 8);}
1446:     DMSetUp(*dm);
1447:     if (!rank) {
1448:       if (periodicZ == DM_BOUNDARY_PERIODIC) {
1449:         cone[0] = 15; cone[1] = 18; cone[2] = 17; cone[3] = 16;
1450:         cone[4] = 31; cone[5] = 32; cone[6] = 33; cone[7] = 34;
1451:         DMPlexSetCone(*dm, 0, cone);
1452:         cone[0] = 16; cone[1] = 17; cone[2] = 24; cone[3] = 23;
1453:         cone[4] = 32; cone[5] = 36; cone[6] = 37; cone[7] = 33; /* 22 25 26 21 */
1454:         DMPlexSetCone(*dm, 1, cone);
1455:         cone[0] = 18; cone[1] = 27; cone[2] = 24; cone[3] = 17;
1456:         cone[4] = 34; cone[5] = 33; cone[6] = 37; cone[7] = 38;
1457:         DMPlexSetCone(*dm, 2, cone);
1458:         cone[0] = 29; cone[1] = 27; cone[2] = 18; cone[3] = 15;
1459:         cone[4] = 35; cone[5] = 31; cone[6] = 34; cone[7] = 38;
1460:         DMPlexSetCone(*dm, 3, cone);
1461:         cone[0] = 29; cone[1] = 15; cone[2] = 16; cone[3] = 23;
1462:         cone[4] = 35; cone[5] = 36; cone[6] = 32; cone[7] = 31;
1463:         DMPlexSetCone(*dm, 4, cone);

1465:         cone[0] = 31; cone[1] = 34; cone[2] = 33; cone[3] = 32;
1466:         cone[4] = 19; cone[5] = 22; cone[6] = 21; cone[7] = 20;
1467:         DMPlexSetCone(*dm, 5, cone);
1468:         cone[0] = 32; cone[1] = 33; cone[2] = 37; cone[3] = 36;
1469:         cone[4] = 22; cone[5] = 25; cone[6] = 26; cone[7] = 21;
1470:         DMPlexSetCone(*dm, 6, cone);
1471:         cone[0] = 34; cone[1] = 38; cone[2] = 37; cone[3] = 33;
1472:         cone[4] = 20; cone[5] = 21; cone[6] = 26; cone[7] = 28;
1473:         DMPlexSetCone(*dm, 7, cone);
1474:         cone[0] = 35; cone[1] = 38; cone[2] = 34; cone[3] = 31;
1475:         cone[4] = 30; cone[5] = 19; cone[6] = 20; cone[7] = 28;
1476:         DMPlexSetCone(*dm, 8, cone);
1477:         cone[0] = 35; cone[1] = 31; cone[2] = 32; cone[3] = 36;
1478:         cone[4] = 30; cone[5] = 25; cone[6] = 22; cone[7] = 19;
1479:         DMPlexSetCone(*dm, 9, cone);

1481:         cone[0] = 19; cone[1] = 20; cone[2] = 21; cone[3] = 22;
1482:         cone[4] = 15; cone[5] = 16; cone[6] = 17; cone[7] = 18;
1483:         DMPlexSetCone(*dm, 10, cone);
1484:         cone[0] = 22; cone[1] = 21; cone[2] = 26; cone[3] = 25;
1485:         cone[4] = 16; cone[5] = 23; cone[6] = 24; cone[7] = 17;
1486:         DMPlexSetCone(*dm, 11, cone);
1487:         cone[0] = 20; cone[1] = 28; cone[2] = 26; cone[3] = 21;
1488:         cone[4] = 18; cone[5] = 17; cone[6] = 24; cone[7] = 27;
1489:         DMPlexSetCone(*dm, 12, cone);
1490:         cone[0] = 30; cone[1] = 28; cone[2] = 20; cone[3] = 19;
1491:         cone[4] = 29; cone[5] = 15; cone[6] = 18; cone[7] = 27;
1492:         DMPlexSetCone(*dm, 13, cone);
1493:         cone[0] = 30; cone[1] = 19; cone[2] = 22; cone[3] = 25;
1494:         cone[4] = 29; cone[5] = 23; cone[6] = 16; cone[7] = 15;
1495:         DMPlexSetCone(*dm, 14, cone);
1496:       } else {
1497:         cone[0] =  5; cone[1] =  8; cone[2] =  7; cone[3] =  6;
1498:         cone[4] =  9; cone[5] = 12; cone[6] = 11; cone[7] = 10;
1499:         DMPlexSetCone(*dm, 0, cone);
1500:         cone[0] =  6; cone[1] =  7; cone[2] = 14; cone[3] = 13;
1501:         cone[4] = 12; cone[5] = 15; cone[6] = 16; cone[7] = 11;
1502:         DMPlexSetCone(*dm, 1, cone);
1503:         cone[0] =  8; cone[1] = 17; cone[2] = 14; cone[3] =  7;
1504:         cone[4] = 10; cone[5] = 11; cone[6] = 16; cone[7] = 18;
1505:         DMPlexSetCone(*dm, 2, cone);
1506:         cone[0] = 19; cone[1] = 17; cone[2] =  8; cone[3] =  5;
1507:         cone[4] = 20; cone[5] =  9; cone[6] = 10; cone[7] = 18;
1508:         DMPlexSetCone(*dm, 3, cone);
1509:         cone[0] = 19; cone[1] =  5; cone[2] =  6; cone[3] = 13;
1510:         cone[4] = 20; cone[5] = 15; cone[6] = 12; cone[7] =  9;
1511:         DMPlexSetCone(*dm, 4, cone);
1512:       }
1513:     }
1514:     DMPlexSymmetrize(*dm);
1515:     DMPlexStratify(*dm);
1516:   }
1517:   /* Interpolate */
1518:   {
1519:     DM idm;

1521:     DMPlexInterpolate(*dm, &idm);
1522:     DMDestroy(dm);
1523:     *dm  = idm;
1524:   }
1525:   /* Create cube geometry */
1526:   {
1527:     Vec             coordinates;
1528:     PetscSection    coordSection;
1529:     PetscScalar    *coords;
1530:     PetscInt        coordSize, v;
1531:     const PetscReal dis = 1.0/PetscSqrtReal(2.0);
1532:     const PetscReal ds2 = dis/2.0;

1534:     /* Build coordinates */
1535:     DMGetCoordinateSection(*dm, &coordSection);
1536:     PetscSectionSetNumFields(coordSection, 1);
1537:     PetscSectionSetFieldComponents(coordSection, 0, dim);
1538:     PetscSectionSetChart(coordSection, numCells, numCells+numVertices);
1539:     for (v = numCells; v < numCells+numVertices; ++v) {
1540:       PetscSectionSetDof(coordSection, v, dim);
1541:       PetscSectionSetFieldDof(coordSection, v, 0, dim);
1542:     }
1543:     PetscSectionSetUp(coordSection);
1544:     PetscSectionGetStorageSize(coordSection, &coordSize);
1545:     VecCreate(PETSC_COMM_SELF, &coordinates);
1546:     PetscObjectSetName((PetscObject) coordinates, "coordinates");
1547:     VecSetSizes(coordinates, coordSize, PETSC_DETERMINE);
1548:     VecSetBlockSize(coordinates, dim);
1549:     VecSetType(coordinates,VECSTANDARD);
1550:     VecGetArray(coordinates, &coords);
1551:     if (!rank) {
1552:       coords[0*dim+0] = -ds2; coords[0*dim+1] = -ds2; coords[0*dim+2] = 0.0;
1553:       coords[1*dim+0] =  ds2; coords[1*dim+1] = -ds2; coords[1*dim+2] = 0.0;
1554:       coords[2*dim+0] =  ds2; coords[2*dim+1] =  ds2; coords[2*dim+2] = 0.0;
1555:       coords[3*dim+0] = -ds2; coords[3*dim+1] =  ds2; coords[3*dim+2] = 0.0;
1556:       coords[4*dim+0] = -ds2; coords[4*dim+1] = -ds2; coords[4*dim+2] = 1.0;
1557:       coords[5*dim+0] = -ds2; coords[5*dim+1] =  ds2; coords[5*dim+2] = 1.0;
1558:       coords[6*dim+0] =  ds2; coords[6*dim+1] =  ds2; coords[6*dim+2] = 1.0;
1559:       coords[7*dim+0] =  ds2; coords[7*dim+1] = -ds2; coords[7*dim+2] = 1.0;
1560:       coords[ 8*dim+0] =  dis; coords[ 8*dim+1] = -dis; coords[ 8*dim+2] = 0.0;
1561:       coords[ 9*dim+0] =  dis; coords[ 9*dim+1] =  dis; coords[ 9*dim+2] = 0.0;
1562:       coords[10*dim+0] =  dis; coords[10*dim+1] = -dis; coords[10*dim+2] = 1.0;
1563:       coords[11*dim+0] =  dis; coords[11*dim+1] =  dis; coords[11*dim+2] = 1.0;
1564:       coords[12*dim+0] = -dis; coords[12*dim+1] =  dis; coords[12*dim+2] = 0.0;
1565:       coords[13*dim+0] = -dis; coords[13*dim+1] =  dis; coords[13*dim+2] = 1.0;
1566:       coords[14*dim+0] = -dis; coords[14*dim+1] = -dis; coords[14*dim+2] = 0.0;
1567:       coords[15*dim+0] = -dis; coords[15*dim+1] = -dis; coords[15*dim+2] = 1.0;
1568:       if (periodicZ == DM_BOUNDARY_PERIODIC) {
1569:         /* 15 31 19 */ coords[16*dim+0] = -ds2; coords[16*dim+1] = -ds2; coords[16*dim+2] = 0.5;
1570:         /* 16 32 22 */ coords[17*dim+0] =  ds2; coords[17*dim+1] = -ds2; coords[17*dim+2] = 0.5;
1571:         /* 17 33 21 */ coords[18*dim+0] =  ds2; coords[18*dim+1] =  ds2; coords[18*dim+2] = 0.5;
1572:         /* 18 34 20 */ coords[19*dim+0] = -ds2; coords[19*dim+1] =  ds2; coords[19*dim+2] = 0.5;
1573:         /* 29 35 30 */ coords[20*dim+0] = -dis; coords[20*dim+1] = -dis; coords[20*dim+2] = 0.5;
1574:         /* 23 36 25 */ coords[21*dim+0] =  dis; coords[21*dim+1] = -dis; coords[21*dim+2] = 0.5;
1575:         /* 24 37 26 */ coords[22*dim+0] =  dis; coords[22*dim+1] =  dis; coords[22*dim+2] = 0.5;
1576:         /* 27 38 28 */ coords[23*dim+0] = -dis; coords[23*dim+1] =  dis; coords[23*dim+2] = 0.5;
1577:       }
1578:     }
1579:     VecRestoreArray(coordinates, &coords);
1580:     DMSetCoordinatesLocal(*dm, coordinates);
1581:     VecDestroy(&coordinates);
1582:   }
1583:   /* Create periodicity */
1584:   if (periodicZ == DM_BOUNDARY_PERIODIC || periodicZ == DM_BOUNDARY_TWIST) {
1585:     PetscReal      L[3];
1586:     PetscReal      maxCell[3];
1587:     DMBoundaryType bdType[3];
1588:     PetscReal      lower[3] = {0.0, 0.0, 0.0};
1589:     PetscReal      upper[3] = {1.0, 1.0, 1.5};
1590:     PetscInt       i, numZCells = 3;

1592:     bdType[0] = DM_BOUNDARY_NONE;
1593:     bdType[1] = DM_BOUNDARY_NONE;
1594:     bdType[2] = periodicZ;
1595:     for (i = 0; i < dim; i++) {
1596:       L[i]       = upper[i] - lower[i];
1597:       maxCell[i] = 1.1 * (L[i] / numZCells);
1598:     }
1599:     DMSetPeriodicity(*dm, PETSC_TRUE, maxCell, L, bdType);
1600:   }
1601:   /* Refine topology */
1602:   for (r = 0; r < numRefine; ++r) {
1603:     DM rdm = NULL;

1605:     DMRefine(*dm, comm, &rdm);
1606:     DMDestroy(dm);
1607:     *dm  = rdm;
1608:   }
1609:   /* Remap geometry to cylinder
1610:        Interior square: Linear interpolation is correct
1611:        The other cells all have vertices on rays from the origin. We want to uniformly expand the spacing
1612:        such that the last vertex is on the unit circle. So the closest and farthest vertices are at distance

1614:          phi     = arctan(y/x)
1615:          d_close = sqrt(1/8 + 1/4 sin^2(phi))
1616:          d_far   = sqrt(1/2 + sin^2(phi))

1618:        so we remap them using

1620:          x_new = x_close + (x - x_close) (1 - d_close) / (d_far - d_close)
1621:          y_new = y_close + (y - y_close) (1 - d_close) / (d_far - d_close)

1623:        If pi/4 < phi < 3pi/4 or -3pi/4 < phi < -pi/4, then we switch x and y.
1624:   */
1625:   {
1626:     Vec           coordinates;
1627:     PetscSection  coordSection;
1628:     PetscScalar  *coords;
1629:     PetscInt      vStart, vEnd, v;
1630:     const PetscReal dis = 1.0/PetscSqrtReal(2.0);
1631:     const PetscReal ds2 = 0.5*dis;

1633:     DMPlexGetDepthStratum(*dm, 0, &vStart, &vEnd);
1634:     DMGetCoordinateSection(*dm, &coordSection);
1635:     DMGetCoordinatesLocal(*dm, &coordinates);
1636:     VecGetArray(coordinates, &coords);
1637:     for (v = vStart; v < vEnd; ++v) {
1638:       PetscReal phi, sinp, cosp, dc, df, x, y, xc, yc;
1639:       PetscInt  off;

1641:       PetscSectionGetOffset(coordSection, v, &off);
1642:       if ((PetscAbsScalar(coords[off+0]) <= ds2) && (PetscAbsScalar(coords[off+1]) <= ds2)) continue;
1643:       x    = PetscRealPart(coords[off]);
1644:       y    = PetscRealPart(coords[off+1]);
1645:       phi  = PetscAtan2Real(y, x);
1646:       sinp = PetscSinReal(phi);
1647:       cosp = PetscCosReal(phi);
1648:       if ((PetscAbsReal(phi) > PETSC_PI/4.0) && (PetscAbsReal(phi) < 3.0*PETSC_PI/4.0)) {
1649:         dc = PetscAbsReal(ds2/sinp);
1650:         df = PetscAbsReal(dis/sinp);
1651:         xc = ds2*x/PetscAbsReal(y);
1652:         yc = ds2*PetscSignReal(y);
1653:       } else {
1654:         dc = PetscAbsReal(ds2/cosp);
1655:         df = PetscAbsReal(dis/cosp);
1656:         xc = ds2*PetscSignReal(x);
1657:         yc = ds2*y/PetscAbsReal(x);
1658:       }
1659:       coords[off+0] = xc + (coords[off+0] - xc)*(1.0 - dc)/(df - dc);
1660:       coords[off+1] = yc + (coords[off+1] - yc)*(1.0 - dc)/(df - dc);
1661:     }
1662:     VecRestoreArray(coordinates, &coords);
1663:     if (periodicZ == DM_BOUNDARY_PERIODIC || periodicZ == DM_BOUNDARY_TWIST) {
1664:       DMLocalizeCoordinates(*dm);
1665:     }
1666:   }
1667:   return(0);
1668: }

1670: /*@
1671:   DMPlexCreateWedgeCylinderMesh - Creates a mesh on the tensor product of the unit interval with the circle (cylinder) using wedges.

1673:   Collective

1675:   Input Parameters:
1676: + comm - The communicator for the DM object
1677: . n    - The number of wedges around the origin
1678: - interpolate - Create edges and faces

1680:   Output Parameter:
1681: . dm  - The DM object

1683:   Level: beginner

1685: .seealso: DMPlexCreateHexCylinderMesh(), DMPlexCreateBoxMesh(), DMSetType(), DMCreate()
1686: @*/
1687: PetscErrorCode DMPlexCreateWedgeCylinderMesh(MPI_Comm comm, PetscInt n, PetscBool interpolate, DM *dm)
1688: {
1689:   const PetscInt dim = 3;
1690:   PetscInt       numCells, numVertices, v;
1691:   PetscMPIInt    rank;

1696:   MPI_Comm_rank(comm, &rank);
1697:   if (n < 0) SETERRQ1(comm, PETSC_ERR_ARG_OUTOFRANGE, "Number of wedges %D cannot be negative", n);
1698:   DMCreate(comm, dm);
1699:   DMSetType(*dm, DMPLEX);
1700:   DMSetDimension(*dm, dim);
1701:   /* Must create the celltype label here so that we do not automatically try to compute the types */
1702:   DMCreateLabel(*dm, "celltype");
1703:   /* Create topology */
1704:   {
1705:     PetscInt cone[6], c;

1707:     numCells    = !rank ?        n : 0;
1708:     numVertices = !rank ?  2*(n+1) : 0;
1709:     DMPlexSetChart(*dm, 0, numCells+numVertices);
1710:     for (c = 0; c < numCells; c++) {DMPlexSetConeSize(*dm, c, 6);}
1711:     DMSetUp(*dm);
1712:     for (c = 0; c < numCells; c++) {
1713:       cone[0] =  c+n*1; cone[1] = (c+1)%n+n*1; cone[2] = 0+3*n;
1714:       cone[3] =  c+n*2; cone[4] = (c+1)%n+n*2; cone[5] = 1+3*n;
1715:       DMPlexSetCone(*dm, c, cone);
1716:       DMPlexSetCellType(*dm, c, DM_POLYTOPE_TRI_PRISM_TENSOR);
1717:     }
1718:     DMPlexSymmetrize(*dm);
1719:     DMPlexStratify(*dm);
1720:   }
1721:   for (v = numCells; v < numCells+numVertices; ++v) {
1722:     DMPlexSetCellType(*dm, v, DM_POLYTOPE_POINT);
1723:   }
1724:   /* Interpolate */
1725:   if (interpolate) {
1726:     DM idm;

1728:     DMPlexInterpolate(*dm, &idm);
1729:     DMDestroy(dm);
1730:     *dm  = idm;
1731:   }
1732:   /* Create cylinder geometry */
1733:   {
1734:     Vec          coordinates;
1735:     PetscSection coordSection;
1736:     PetscScalar *coords;
1737:     PetscInt     coordSize, c;

1739:     /* Build coordinates */
1740:     DMGetCoordinateSection(*dm, &coordSection);
1741:     PetscSectionSetNumFields(coordSection, 1);
1742:     PetscSectionSetFieldComponents(coordSection, 0, dim);
1743:     PetscSectionSetChart(coordSection, numCells, numCells+numVertices);
1744:     for (v = numCells; v < numCells+numVertices; ++v) {
1745:       PetscSectionSetDof(coordSection, v, dim);
1746:       PetscSectionSetFieldDof(coordSection, v, 0, dim);
1747:     }
1748:     PetscSectionSetUp(coordSection);
1749:     PetscSectionGetStorageSize(coordSection, &coordSize);
1750:     VecCreate(PETSC_COMM_SELF, &coordinates);
1751:     PetscObjectSetName((PetscObject) coordinates, "coordinates");
1752:     VecSetSizes(coordinates, coordSize, PETSC_DETERMINE);
1753:     VecSetBlockSize(coordinates, dim);
1754:     VecSetType(coordinates,VECSTANDARD);
1755:     VecGetArray(coordinates, &coords);
1756:     for (c = 0; c < numCells; c++) {
1757:       coords[(c+0*n)*dim+0] = PetscCosReal(2.0*c*PETSC_PI/n); coords[(c+0*n)*dim+1] = PetscSinReal(2.0*c*PETSC_PI/n); coords[(c+0*n)*dim+2] = 1.0;
1758:       coords[(c+1*n)*dim+0] = PetscCosReal(2.0*c*PETSC_PI/n); coords[(c+1*n)*dim+1] = PetscSinReal(2.0*c*PETSC_PI/n); coords[(c+1*n)*dim+2] = 0.0;
1759:     }
1760:     if (!rank) {
1761:       coords[(2*n+0)*dim+0] = 0.0; coords[(2*n+0)*dim+1] = 0.0; coords[(2*n+0)*dim+2] = 1.0;
1762:       coords[(2*n+1)*dim+0] = 0.0; coords[(2*n+1)*dim+1] = 0.0; coords[(2*n+1)*dim+2] = 0.0;
1763:     }
1764:     VecRestoreArray(coordinates, &coords);
1765:     DMSetCoordinatesLocal(*dm, coordinates);
1766:     VecDestroy(&coordinates);
1767:   }
1768:   return(0);
1769: }

1771: PETSC_STATIC_INLINE PetscReal DiffNormReal(PetscInt dim, const PetscReal x[], const PetscReal y[])
1772: {
1773:   PetscReal prod = 0.0;
1774:   PetscInt  i;
1775:   for (i = 0; i < dim; ++i) prod += PetscSqr(x[i] - y[i]);
1776:   return PetscSqrtReal(prod);
1777: }
1778: PETSC_STATIC_INLINE PetscReal DotReal(PetscInt dim, const PetscReal x[], const PetscReal y[])
1779: {
1780:   PetscReal prod = 0.0;
1781:   PetscInt  i;
1782:   for (i = 0; i < dim; ++i) prod += x[i]*y[i];
1783:   return prod;
1784: }

1786: /* The first constant is the sphere radius */
1787: static void snapToSphere(PetscInt dim, PetscInt Nf, PetscInt NfAux,
1788:                          const PetscInt uOff[], const PetscInt uOff_x[], const PetscScalar u[], const PetscScalar u_t[], const PetscScalar u_x[],
1789:                          const PetscInt aOff[], const PetscInt aOff_x[], const PetscScalar a[], const PetscScalar a_t[], const PetscScalar a_x[],
1790:                          PetscReal t, const PetscReal x[], PetscInt numConstants, const PetscScalar constants[], PetscScalar f0[])
1791: {
1792:   PetscReal r = PetscRealPart(constants[0]);
1793:   PetscReal norm2 = 0.0, fac;
1794:   PetscInt  n = uOff[1] - uOff[0], d;

1796:   for (d = 0; d < n; ++d) norm2 += PetscSqr(PetscRealPart(u[d]));
1797:   fac = r/PetscSqrtReal(norm2);
1798:   for (d = 0; d < n; ++d) f0[d] = u[d]*fac;
1799: }

1801: /*@
1802:   DMPlexCreateSphereMesh - Creates a mesh on the d-dimensional sphere, S^d.

1804:   Collective

1806:   Input Parameters:
1807: + comm    - The communicator for the DM object
1808: . dim     - The dimension
1809: . simplex - Use simplices, or tensor product cells
1810: - R       - The radius

1812:   Output Parameter:
1813: . dm  - The DM object

1815:   Level: beginner

1817: .seealso: DMPlexCreateBallMesh(), DMPlexCreateBoxMesh(), DMSetType(), DMCreate()
1818: @*/
1819: PetscErrorCode DMPlexCreateSphereMesh(MPI_Comm comm, PetscInt dim, PetscBool simplex, PetscReal R, DM *dm)
1820: {
1821:   const PetscInt  embedDim = dim+1;
1822:   PetscSection    coordSection;
1823:   Vec             coordinates;
1824:   PetscScalar    *coords;
1825:   PetscReal      *coordsIn;
1826:   PetscInt        numCells, numEdges, numVerts, firstVertex, v, firstEdge, coordSize, d, c, e;
1827:   PetscMPIInt     rank;
1828:   PetscErrorCode  ierr;

1832:   DMCreate(comm, dm);
1833:   DMSetType(*dm, DMPLEX);
1834:   DMSetDimension(*dm, dim);
1835:   DMSetCoordinateDim(*dm, dim+1);
1836:   MPI_Comm_rank(PetscObjectComm((PetscObject) *dm), &rank);
1837:   switch (dim) {
1838:   case 2:
1839:     if (simplex) {
1840:       DM              idm;
1841:       const PetscReal radius    = PetscSqrtReal(1 + PETSC_PHI*PETSC_PHI)/(1.0 + PETSC_PHI);
1842:       const PetscReal edgeLen   = 2.0/(1.0 + PETSC_PHI) * (R/radius);
1843:       const PetscInt  degree    = 5;
1844:       PetscReal       vertex[3] = {0.0, 1.0/(1.0 + PETSC_PHI), PETSC_PHI/(1.0 + PETSC_PHI)};
1845:       PetscInt        s[3]      = {1, 1, 1};
1846:       PetscInt        cone[3];
1847:       PetscInt       *graph, p, i, j, k;

1849:       vertex[0] *= R/radius; vertex[1] *= R/radius; vertex[2] *= R/radius;
1850:       numCells    = !rank ? 20 : 0;
1851:       numVerts    = !rank ? 12 : 0;
1852:       firstVertex = numCells;
1853:       /* Use icosahedron, which for a R-sphere has coordinates which are all cyclic permutations of

1855:            (0, \pm 1/\phi+1, \pm \phi/\phi+1)

1857:          where \phi^2 - \phi - 1 = 0, meaning \phi is the golden ratio \frac{1 + \sqrt{5}}{2}. The edge
1858:          length is then given by 2/(1+\phi) = 2 * 0.38197 = 0.76393.
1859:       */
1860:       /* Construct vertices */
1861:       PetscCalloc1(numVerts * embedDim, &coordsIn);
1862:       if (!rank) {
1863:         for (p = 0, i = 0; p < embedDim; ++p) {
1864:           for (s[1] = -1; s[1] < 2; s[1] += 2) {
1865:             for (s[2] = -1; s[2] < 2; s[2] += 2) {
1866:               for (d = 0; d < embedDim; ++d) coordsIn[i*embedDim+d] = s[(d+p)%embedDim]*vertex[(d+p)%embedDim];
1867:               ++i;
1868:             }
1869:           }
1870:         }
1871:       }
1872:       /* Construct graph */
1873:       PetscCalloc1(numVerts * numVerts, &graph);
1874:       for (i = 0; i < numVerts; ++i) {
1875:         for (j = 0, k = 0; j < numVerts; ++j) {
1876:           if (PetscAbsReal(DiffNormReal(embedDim, &coordsIn[i*embedDim], &coordsIn[j*embedDim]) - edgeLen) < PETSC_SMALL) {graph[i*numVerts+j] = 1; ++k;}
1877:         }
1878:         if (k != degree) SETERRQ3(comm, PETSC_ERR_PLIB, "Invalid icosahedron, vertex %D degree %D != %D", i, k, degree);
1879:       }
1880:       /* Build Topology */
1881:       DMPlexSetChart(*dm, 0, numCells+numVerts);
1882:       for (c = 0; c < numCells; c++) {
1883:         DMPlexSetConeSize(*dm, c, embedDim);
1884:       }
1885:       DMSetUp(*dm); /* Allocate space for cones */
1886:       /* Cells */
1887:       for (i = 0, c = 0; i < numVerts; ++i) {
1888:         for (j = 0; j < i; ++j) {
1889:           for (k = 0; k < j; ++k) {
1890:             if (graph[i*numVerts+j] && graph[j*numVerts+k] && graph[k*numVerts+i]) {
1891:               cone[0] = firstVertex+i; cone[1] = firstVertex+j; cone[2] = firstVertex+k;
1892:               /* Check orientation */
1893:               {
1894:                 const PetscInt epsilon[3][3][3] = {{{0, 0, 0}, {0, 0, 1}, {0, -1, 0}}, {{0, 0, -1}, {0, 0, 0}, {1, 0, 0}}, {{0, 1, 0}, {-1, 0, 0}, {0, 0, 0}}};
1895:                 PetscReal normal[3];
1896:                 PetscInt  e, f;

1898:                 for (d = 0; d < embedDim; ++d) {
1899:                   normal[d] = 0.0;
1900:                   for (e = 0; e < embedDim; ++e) {
1901:                     for (f = 0; f < embedDim; ++f) {
1902:                       normal[d] += epsilon[d][e][f]*(coordsIn[j*embedDim+e] - coordsIn[i*embedDim+e])*(coordsIn[k*embedDim+f] - coordsIn[i*embedDim+f]);
1903:                     }
1904:                   }
1905:                 }
1906:                 if (DotReal(embedDim, normal, &coordsIn[i*embedDim]) < 0) {PetscInt tmp = cone[1]; cone[1] = cone[2]; cone[2] = tmp;}
1907:               }
1908:               DMPlexSetCone(*dm, c++, cone);
1909:             }
1910:           }
1911:         }
1912:       }
1913:       DMPlexSymmetrize(*dm);
1914:       DMPlexStratify(*dm);
1915:       PetscFree(graph);
1916:       /* Interpolate mesh */
1917:       DMPlexInterpolate(*dm, &idm);
1918:       DMDestroy(dm);
1919:       *dm  = idm;
1920:     } else {
1921:       /*
1922:         12-21--13
1923:          |     |
1924:         25  4  24
1925:          |     |
1926:   12-25--9-16--8-24--13
1927:    |     |     |     |
1928:   23  5 17  0 15  3  22
1929:    |     |     |     |
1930:   10-20--6-14--7-19--11
1931:          |     |
1932:         20  1  19
1933:          |     |
1934:         10-18--11
1935:          |     |
1936:         23  2  22
1937:          |     |
1938:         12-21--13
1939:        */
1940:       PetscInt cone[4], ornt[4];

1942:       numCells    = !rank ?  6 : 0;
1943:       numEdges    = !rank ? 12 : 0;
1944:       numVerts    = !rank ?  8 : 0;
1945:       firstVertex = numCells;
1946:       firstEdge   = numCells + numVerts;
1947:       /* Build Topology */
1948:       DMPlexSetChart(*dm, 0, numCells+numEdges+numVerts);
1949:       for (c = 0; c < numCells; c++) {
1950:         DMPlexSetConeSize(*dm, c, 4);
1951:       }
1952:       for (e = firstEdge; e < firstEdge+numEdges; ++e) {
1953:         DMPlexSetConeSize(*dm, e, 2);
1954:       }
1955:       DMSetUp(*dm); /* Allocate space for cones */
1956:       if (!rank) {
1957:         /* Cell 0 */
1958:         cone[0] = 14; cone[1] = 15; cone[2] = 16; cone[3] = 17;
1959:         DMPlexSetCone(*dm, 0, cone);
1960:         ornt[0] = 0; ornt[1] = 0; ornt[2] = 0; ornt[3] = 0;
1961:         DMPlexSetConeOrientation(*dm, 0, ornt);
1962:         /* Cell 1 */
1963:         cone[0] = 18; cone[1] = 19; cone[2] = 14; cone[3] = 20;
1964:         DMPlexSetCone(*dm, 1, cone);
1965:         ornt[0] = 0; ornt[1] = 0; ornt[2] = -2; ornt[3] = 0;
1966:         DMPlexSetConeOrientation(*dm, 1, ornt);
1967:         /* Cell 2 */
1968:         cone[0] = 21; cone[1] = 22; cone[2] = 18; cone[3] = 23;
1969:         DMPlexSetCone(*dm, 2, cone);
1970:         ornt[0] = 0; ornt[1] = 0; ornt[2] = -2; ornt[3] = 0;
1971:         DMPlexSetConeOrientation(*dm, 2, ornt);
1972:         /* Cell 3 */
1973:         cone[0] = 19; cone[1] = 22; cone[2] = 24; cone[3] = 15;
1974:         DMPlexSetCone(*dm, 3, cone);
1975:         ornt[0] = -2; ornt[1] = -2; ornt[2] = 0; ornt[3] = -2;
1976:         DMPlexSetConeOrientation(*dm, 3, ornt);
1977:         /* Cell 4 */
1978:         cone[0] = 16; cone[1] = 24; cone[2] = 21; cone[3] = 25;
1979:         DMPlexSetCone(*dm, 4, cone);
1980:         ornt[0] = -2; ornt[1] = -2; ornt[2] = -2; ornt[3] = 0;
1981:         DMPlexSetConeOrientation(*dm, 4, ornt);
1982:         /* Cell 5 */
1983:         cone[0] = 20; cone[1] = 17; cone[2] = 25; cone[3] = 23;
1984:         DMPlexSetCone(*dm, 5, cone);
1985:         ornt[0] = -2; ornt[1] = -2; ornt[2] = -2; ornt[3] = -2;
1986:         DMPlexSetConeOrientation(*dm, 5, ornt);
1987:         /* Edges */
1988:         cone[0] =  6; cone[1] =  7;
1989:         DMPlexSetCone(*dm, 14, cone);
1990:         cone[0] =  7; cone[1] =  8;
1991:         DMPlexSetCone(*dm, 15, cone);
1992:         cone[0] =  8; cone[1] =  9;
1993:         DMPlexSetCone(*dm, 16, cone);
1994:         cone[0] =  9; cone[1] =  6;
1995:         DMPlexSetCone(*dm, 17, cone);
1996:         cone[0] = 10; cone[1] = 11;
1997:         DMPlexSetCone(*dm, 18, cone);
1998:         cone[0] = 11; cone[1] =  7;
1999:         DMPlexSetCone(*dm, 19, cone);
2000:         cone[0] =  6; cone[1] = 10;
2001:         DMPlexSetCone(*dm, 20, cone);
2002:         cone[0] = 12; cone[1] = 13;
2003:         DMPlexSetCone(*dm, 21, cone);
2004:         cone[0] = 13; cone[1] = 11;
2005:         DMPlexSetCone(*dm, 22, cone);
2006:         cone[0] = 10; cone[1] = 12;
2007:         DMPlexSetCone(*dm, 23, cone);
2008:         cone[0] = 13; cone[1] =  8;
2009:         DMPlexSetCone(*dm, 24, cone);
2010:         cone[0] = 12; cone[1] =  9;
2011:         DMPlexSetCone(*dm, 25, cone);
2012:       }
2013:       DMPlexSymmetrize(*dm);
2014:       DMPlexStratify(*dm);
2015:       /* Build coordinates */
2016:       PetscCalloc1(numVerts * embedDim, &coordsIn);
2017:       if (!rank) {
2018:         coordsIn[0*embedDim+0] = -R; coordsIn[0*embedDim+1] =  R; coordsIn[0*embedDim+2] = -R;
2019:         coordsIn[1*embedDim+0] =  R; coordsIn[1*embedDim+1] =  R; coordsIn[1*embedDim+2] = -R;
2020:         coordsIn[2*embedDim+0] =  R; coordsIn[2*embedDim+1] = -R; coordsIn[2*embedDim+2] = -R;
2021:         coordsIn[3*embedDim+0] = -R; coordsIn[3*embedDim+1] = -R; coordsIn[3*embedDim+2] = -R;
2022:         coordsIn[4*embedDim+0] = -R; coordsIn[4*embedDim+1] =  R; coordsIn[4*embedDim+2] =  R;
2023:         coordsIn[5*embedDim+0] =  R; coordsIn[5*embedDim+1] =  R; coordsIn[5*embedDim+2] =  R;
2024:         coordsIn[6*embedDim+0] = -R; coordsIn[6*embedDim+1] = -R; coordsIn[6*embedDim+2] =  R;
2025:         coordsIn[7*embedDim+0] =  R; coordsIn[7*embedDim+1] = -R; coordsIn[7*embedDim+2] =  R;
2026:       }
2027:     }
2028:     break;
2029:   case 3:
2030:     if (simplex) {
2031:       DM              idm;
2032:       const PetscReal edgeLen         = 1.0/PETSC_PHI;
2033:       PetscReal       vertexA[4]      = {0.5, 0.5, 0.5, 0.5};
2034:       PetscReal       vertexB[4]      = {1.0, 0.0, 0.0, 0.0};
2035:       PetscReal       vertexC[4]      = {0.5, 0.5*PETSC_PHI, 0.5/PETSC_PHI, 0.0};
2036:       const PetscInt  degree          = 12;
2037:       PetscInt        s[4]            = {1, 1, 1};
2038:       PetscInt        evenPerm[12][4] = {{0, 1, 2, 3}, {0, 2, 3, 1}, {0, 3, 1, 2}, {1, 0, 3, 2}, {1, 2, 0, 3}, {1, 3, 2, 0},
2039:                                          {2, 0, 1, 3}, {2, 1, 3, 0}, {2, 3, 0, 1}, {3, 0, 2, 1}, {3, 1, 0, 2}, {3, 2, 1, 0}};
2040:       PetscInt        cone[4];
2041:       PetscInt       *graph, p, i, j, k, l;

2043:       vertexA[0] *= R; vertexA[1] *= R; vertexA[2] *= R; vertexA[3] *= R;
2044:       vertexB[0] *= R; vertexB[1] *= R; vertexB[2] *= R; vertexB[3] *= R;
2045:       vertexC[0] *= R; vertexC[1] *= R; vertexC[2] *= R; vertexC[3] *= R;
2046:       numCells    = !rank ? 600 : 0;
2047:       numVerts    = !rank ? 120 : 0;
2048:       firstVertex = numCells;
2049:       /* Use the 600-cell, which for a unit sphere has coordinates which are

2051:            1/2 (\pm 1, \pm 1,    \pm 1, \pm 1)                          16
2052:                (\pm 1,    0,       0,      0)  all cyclic permutations   8
2053:            1/2 (\pm 1, \pm phi, \pm 1/phi, 0)  all even permutations    96

2055:          where \phi^2 - \phi - 1 = 0, meaning \phi is the golden ratio \frac{1 + \sqrt{5}}{2}. The edge
2056:          length is then given by 1/\phi = 0.61803.

2058:          http://buzzard.pugetsound.edu/sage-practice/ch03s03.html
2059:          http://mathworld.wolfram.com/600-Cell.html
2060:       */
2061:       /* Construct vertices */
2062:       PetscCalloc1(numVerts * embedDim, &coordsIn);
2063:       i    = 0;
2064:       if (!rank) {
2065:         for (s[0] = -1; s[0] < 2; s[0] += 2) {
2066:           for (s[1] = -1; s[1] < 2; s[1] += 2) {
2067:             for (s[2] = -1; s[2] < 2; s[2] += 2) {
2068:               for (s[3] = -1; s[3] < 2; s[3] += 2) {
2069:                 for (d = 0; d < embedDim; ++d) coordsIn[i*embedDim+d] = s[d]*vertexA[d];
2070:                 ++i;
2071:               }
2072:             }
2073:           }
2074:         }
2075:         for (p = 0; p < embedDim; ++p) {
2076:           s[1] = s[2] = s[3] = 1;
2077:           for (s[0] = -1; s[0] < 2; s[0] += 2) {
2078:             for (d = 0; d < embedDim; ++d) coordsIn[i*embedDim+d] = s[(d+p)%embedDim]*vertexB[(d+p)%embedDim];
2079:             ++i;
2080:           }
2081:         }
2082:         for (p = 0; p < 12; ++p) {
2083:           s[3] = 1;
2084:           for (s[0] = -1; s[0] < 2; s[0] += 2) {
2085:             for (s[1] = -1; s[1] < 2; s[1] += 2) {
2086:               for (s[2] = -1; s[2] < 2; s[2] += 2) {
2087:                 for (d = 0; d < embedDim; ++d) coordsIn[i*embedDim+d] = s[evenPerm[p][d]]*vertexC[evenPerm[p][d]];
2088:                 ++i;
2089:               }
2090:             }
2091:           }
2092:         }
2093:       }
2094:       if (i != numVerts) SETERRQ2(comm, PETSC_ERR_PLIB, "Invalid 600-cell, vertices %D != %D", i, numVerts);
2095:       /* Construct graph */
2096:       PetscCalloc1(numVerts * numVerts, &graph);
2097:       for (i = 0; i < numVerts; ++i) {
2098:         for (j = 0, k = 0; j < numVerts; ++j) {
2099:           if (PetscAbsReal(DiffNormReal(embedDim, &coordsIn[i*embedDim], &coordsIn[j*embedDim]) - edgeLen) < PETSC_SMALL) {graph[i*numVerts+j] = 1; ++k;}
2100:         }
2101:         if (k != degree) SETERRQ3(comm, PETSC_ERR_PLIB, "Invalid 600-cell, vertex %D degree %D != %D", i, k, degree);
2102:       }
2103:       /* Build Topology */
2104:       DMPlexSetChart(*dm, 0, numCells+numVerts);
2105:       for (c = 0; c < numCells; c++) {
2106:         DMPlexSetConeSize(*dm, c, embedDim);
2107:       }
2108:       DMSetUp(*dm); /* Allocate space for cones */
2109:       /* Cells */
2110:       if (!rank) {
2111:         for (i = 0, c = 0; i < numVerts; ++i) {
2112:           for (j = 0; j < i; ++j) {
2113:             for (k = 0; k < j; ++k) {
2114:               for (l = 0; l < k; ++l) {
2115:                 if (graph[i*numVerts+j] && graph[j*numVerts+k] && graph[k*numVerts+i] &&
2116:                     graph[l*numVerts+i] && graph[l*numVerts+j] && graph[l*numVerts+k]) {
2117:                   cone[0] = firstVertex+i; cone[1] = firstVertex+j; cone[2] = firstVertex+k; cone[3] = firstVertex+l;
2118:                   /* Check orientation: https://ef.gy/linear-algebra:normal-vectors-in-higher-dimensional-spaces */
2119:                   {
2120:                     const PetscInt epsilon[4][4][4][4] = {{{{0,  0,  0,  0}, { 0, 0,  0,  0}, { 0,  0, 0,  0}, { 0,  0,  0, 0}},
2121:                                                            {{0,  0,  0,  0}, { 0, 0,  0,  0}, { 0,  0, 0,  1}, { 0,  0, -1, 0}},
2122:                                                            {{0,  0,  0,  0}, { 0, 0,  0, -1}, { 0,  0, 0,  0}, { 0,  1,  0, 0}},
2123:                                                            {{0,  0,  0,  0}, { 0, 0,  1,  0}, { 0, -1, 0,  0}, { 0,  0,  0, 0}}},

2125:                                                           {{{0,  0,  0,  0}, { 0, 0,  0,  0}, { 0,  0, 0, -1}, { 0,  0,  1, 0}},
2126:                                                            {{0,  0,  0,  0}, { 0, 0,  0,  0}, { 0,  0, 0,  0}, { 0,  0,  0, 0}},
2127:                                                            {{0,  0,  0,  1}, { 0, 0,  0,  0}, { 0,  0, 0,  0}, {-1,  0,  0, 0}},
2128:                                                            {{0,  0, -1,  0}, { 0, 0,  0,  0}, { 1,  0, 0,  0}, { 0,  0,  0, 0}}},

2130:                                                           {{{0,  0,  0,  0}, { 0, 0,  0,  1}, { 0,  0, 0,  0}, { 0, -1,  0, 0}},
2131:                                                            {{0,  0,  0, -1}, { 0, 0,  0,  0}, { 0,  0, 0,  0}, { 1,  0,  0, 0}},
2132:                                                            {{0,  0,  0,  0}, { 0, 0,  0,  0}, { 0,  0, 0,  0}, { 0,  0,  0, 0}},
2133:                                                            {{0,  1,  0,  0}, {-1, 0,  0,  0}, { 0,  0, 0,  0}, { 0,  0,  0, 0}}},

2135:                                                           {{{0,  0,  0,  0}, { 0, 0, -1,  0}, { 0,  1, 0,  0}, { 0,  0,  0, 0}},
2136:                                                            {{0,  0,  1,  0}, { 0, 0,  0,  0}, {-1,  0, 0,  0}, { 0,  0,  0, 0}},
2137:                                                            {{0, -1,  0,  0}, { 1, 0,  0,  0}, { 0,  0, 0,  0}, { 0,  0,  0, 0}},
2138:                                                            {{0,  0,  0,  0}, { 0, 0,  0,  0}, { 0,  0, 0,  0}, { 0,  0,  0, 0}}}};
2139:                     PetscReal normal[4];
2140:                     PetscInt  e, f, g;

2142:                     for (d = 0; d < embedDim; ++d) {
2143:                       normal[d] = 0.0;
2144:                       for (e = 0; e < embedDim; ++e) {
2145:                         for (f = 0; f < embedDim; ++f) {
2146:                           for (g = 0; g < embedDim; ++g) {
2147:                             normal[d] += epsilon[d][e][f][g]*(coordsIn[j*embedDim+e] - coordsIn[i*embedDim+e])*(coordsIn[k*embedDim+f] - coordsIn[i*embedDim+f])*(coordsIn[l*embedDim+f] - coordsIn[i*embedDim+f]);
2148:                           }
2149:                         }
2150:                       }
2151:                     }
2152:                     if (DotReal(embedDim, normal, &coordsIn[i*embedDim]) < 0) {PetscInt tmp = cone[1]; cone[1] = cone[2]; cone[2] = tmp;}
2153:                   }
2154:                   DMPlexSetCone(*dm, c++, cone);
2155:                 }
2156:               }
2157:             }
2158:           }
2159:         }
2160:       }
2161:       DMPlexSymmetrize(*dm);
2162:       DMPlexStratify(*dm);
2163:       PetscFree(graph);
2164:       /* Interpolate mesh */
2165:       DMPlexInterpolate(*dm, &idm);
2166:       DMDestroy(dm);
2167:       *dm  = idm;
2168:       break;
2169:     }
2170:   default: SETERRQ1(comm, PETSC_ERR_SUP, "Unsupported dimension for sphere: %D", dim);
2171:   }
2172:   /* Create coordinates */
2173:   DMGetCoordinateSection(*dm, &coordSection);
2174:   PetscSectionSetNumFields(coordSection, 1);
2175:   PetscSectionSetFieldComponents(coordSection, 0, embedDim);
2176:   PetscSectionSetChart(coordSection, firstVertex, firstVertex+numVerts);
2177:   for (v = firstVertex; v < firstVertex+numVerts; ++v) {
2178:     PetscSectionSetDof(coordSection, v, embedDim);
2179:     PetscSectionSetFieldDof(coordSection, v, 0, embedDim);
2180:   }
2181:   PetscSectionSetUp(coordSection);
2182:   PetscSectionGetStorageSize(coordSection, &coordSize);
2183:   VecCreate(PETSC_COMM_SELF, &coordinates);
2184:   VecSetBlockSize(coordinates, embedDim);
2185:   PetscObjectSetName((PetscObject) coordinates, "coordinates");
2186:   VecSetSizes(coordinates, coordSize, PETSC_DETERMINE);
2187:   VecSetType(coordinates,VECSTANDARD);
2188:   VecGetArray(coordinates, &coords);
2189:   for (v = 0; v < numVerts; ++v) for (d = 0; d < embedDim; ++d) {coords[v*embedDim+d] = coordsIn[v*embedDim+d];}
2190:   VecRestoreArray(coordinates, &coords);
2191:   DMSetCoordinatesLocal(*dm, coordinates);
2192:   VecDestroy(&coordinates);
2193:   PetscFree(coordsIn);
2194:   /* Create coordinate function space */
2195:   {
2196:     DM          cdm;
2197:     PetscDS     cds;
2198:     PetscFE     fe;
2199:     PetscScalar radius = R;
2200:     PetscInt    dT, dE;

2202:     DMGetCoordinateDM(*dm, &cdm);
2203:     DMGetDimension(*dm, &dT);
2204:     DMGetCoordinateDim(*dm, &dE);
2205:     PetscFECreateLagrange(PETSC_COMM_SELF, dT, dE, simplex, 1, -1, &fe);
2206:     DMSetField(cdm, 0, NULL, (PetscObject) fe);
2207:     PetscFEDestroy(&fe);
2208:     DMCreateDS(cdm);

2210:     DMGetDS(cdm, &cds);
2211:     PetscDSSetConstants(cds, 1, &radius);
2212:   }
2213:   ((DM_Plex *) (*dm)->data)->coordFunc = snapToSphere;
2214:   return(0);
2215: }

2217: /*@
2218:   DMPlexCreateBallMesh - Creates a simplex mesh on the d-dimensional ball, B^d.

2220:   Collective

2222:   Input Parameters:
2223: + comm  - The communicator for the DM object
2224: . dim   - The dimension
2225: - R     - The radius

2227:   Output Parameter:
2228: . dm  - The DM object

2230:   Options Database Keys:
2231: - bd_dm_refine - This will refine the surface mesh preserving the sphere geometry

2233:   Level: beginner

2235: .seealso: DMPlexCreateSphereMesh(), DMPlexCreateBoxMesh(), DMSetType(), DMCreate()
2236: @*/
2237: PetscErrorCode DMPlexCreateBallMesh(MPI_Comm comm, PetscInt dim, PetscReal R, DM *dm)
2238: {
2239:   DM             sdm;
2240:   DMLabel        bdlabel;

2244:   DMPlexCreateSphereMesh(comm, dim-1, PETSC_TRUE, R, &sdm);
2245:   PetscObjectSetOptionsPrefix((PetscObject) sdm, "bd_");
2246:   DMSetFromOptions(sdm);
2247:   DMPlexGenerate(sdm, NULL, PETSC_TRUE, dm);
2248:   DMDestroy(&sdm);
2249:   DMCreateLabel(*dm, "marker");
2250:   DMGetLabel(*dm, "marker", &bdlabel);
2251:   DMPlexMarkBoundaryFaces(*dm, PETSC_DETERMINE, bdlabel);
2252:   DMPlexLabelComplete(*dm, bdlabel);
2253:   return(0);
2254: }

2256: /* External function declarations here */
2257: extern PetscErrorCode DMCreateInterpolation_Plex(DM dmCoarse, DM dmFine, Mat *interpolation, Vec *scaling);
2258: extern PetscErrorCode DMCreateInjection_Plex(DM dmCoarse, DM dmFine, Mat *mat);
2259: extern PetscErrorCode DMCreateMassMatrix_Plex(DM dmCoarse, DM dmFine, Mat *mat);
2260: extern PetscErrorCode DMCreateLocalSection_Plex(DM dm);
2261: extern PetscErrorCode DMCreateDefaultConstraints_Plex(DM dm);
2262: extern PetscErrorCode DMCreateMatrix_Plex(DM dm,  Mat *J);
2263: extern PetscErrorCode DMCreateCoordinateDM_Plex(DM dm, DM *cdm);
2264: extern PetscErrorCode DMCreateCoordinateField_Plex(DM dm, DMField *field);
2265: PETSC_INTERN PetscErrorCode DMClone_Plex(DM dm, DM *newdm);
2266: extern PetscErrorCode DMSetUp_Plex(DM dm);
2267: extern PetscErrorCode DMDestroy_Plex(DM dm);
2268: extern PetscErrorCode DMView_Plex(DM dm, PetscViewer viewer);
2269: extern PetscErrorCode DMLoad_Plex(DM dm, PetscViewer viewer);
2270: extern PetscErrorCode DMCreateSubDM_Plex(DM dm, PetscInt numFields, const PetscInt fields[], IS *is, DM *subdm);
2271: extern PetscErrorCode DMCreateSuperDM_Plex(DM dms[], PetscInt len, IS **is, DM *superdm);
2272: static PetscErrorCode DMInitialize_Plex(DM dm);

2274: /* Replace dm with the contents of dmNew
2275:    - Share the DM_Plex structure
2276:    - Share the coordinates
2277:    - Share the SF
2278: */
2279: static PetscErrorCode DMPlexReplace_Static(DM dm, DM dmNew)
2280: {
2281:   PetscSF               sf;
2282:   DM                    coordDM, coarseDM;
2283:   DMField               coordField;
2284:   Vec                   coords;
2285:   PetscBool             isper;
2286:   const PetscReal      *maxCell, *L;
2287:   const DMBoundaryType *bd;
2288:   PetscErrorCode        ierr;

2291:   DMGetPointSF(dmNew, &sf);
2292:   DMSetPointSF(dm, sf);
2293:   DMGetCoordinateDM(dmNew, &coordDM);
2294:   DMGetCoordinatesLocal(dmNew, &coords);
2295:   DMGetCoordinateField(dmNew, &coordField);
2296:   DMSetCoordinateDM(dm, coordDM);
2297:   DMSetCoordinatesLocal(dm, coords);
2298:   DMSetCoordinateField(dm, coordField);
2299:   DMGetPeriodicity(dm, &isper, &maxCell, &L, &bd);
2300:   DMSetPeriodicity(dmNew, isper, maxCell, L, bd);
2301:   DMDestroy_Plex(dm);
2302:   DMInitialize_Plex(dm);
2303:   dm->data = dmNew->data;
2304:   ((DM_Plex *) dmNew->data)->refct++;
2305:   DMDestroyLabelLinkList_Internal(dm);
2306:   DMCopyLabels(dmNew, dm, PETSC_OWN_POINTER, PETSC_TRUE);
2307:   DMGetCoarseDM(dmNew,&coarseDM);
2308:   DMSetCoarseDM(dm,coarseDM);
2309:   return(0);
2310: }

2312: /* Swap dm with the contents of dmNew
2313:    - Swap the DM_Plex structure
2314:    - Swap the coordinates
2315:    - Swap the point PetscSF
2316: */
2317: static PetscErrorCode DMPlexSwap_Static(DM dmA, DM dmB)
2318: {
2319:   DM              coordDMA, coordDMB;
2320:   Vec             coordsA,  coordsB;
2321:   PetscSF         sfA,      sfB;
2322:   void            *tmp;
2323:   DMLabelLink     listTmp;
2324:   DMLabel         depthTmp;
2325:   PetscInt        tmpI;
2326:   PetscErrorCode  ierr;

2329:   DMGetPointSF(dmA, &sfA);
2330:   DMGetPointSF(dmB, &sfB);
2331:   PetscObjectReference((PetscObject) sfA);
2332:   DMSetPointSF(dmA, sfB);
2333:   DMSetPointSF(dmB, sfA);
2334:   PetscObjectDereference((PetscObject) sfA);

2336:   DMGetCoordinateDM(dmA, &coordDMA);
2337:   DMGetCoordinateDM(dmB, &coordDMB);
2338:   PetscObjectReference((PetscObject) coordDMA);
2339:   DMSetCoordinateDM(dmA, coordDMB);
2340:   DMSetCoordinateDM(dmB, coordDMA);
2341:   PetscObjectDereference((PetscObject) coordDMA);

2343:   DMGetCoordinatesLocal(dmA, &coordsA);
2344:   DMGetCoordinatesLocal(dmB, &coordsB);
2345:   PetscObjectReference((PetscObject) coordsA);
2346:   DMSetCoordinatesLocal(dmA, coordsB);
2347:   DMSetCoordinatesLocal(dmB, coordsA);
2348:   PetscObjectDereference((PetscObject) coordsA);

2350:   tmp       = dmA->data;
2351:   dmA->data = dmB->data;
2352:   dmB->data = tmp;
2353:   listTmp   = dmA->labels;
2354:   dmA->labels = dmB->labels;
2355:   dmB->labels = listTmp;
2356:   depthTmp  = dmA->depthLabel;
2357:   dmA->depthLabel = dmB->depthLabel;
2358:   dmB->depthLabel = depthTmp;
2359:   depthTmp  = dmA->celltypeLabel;
2360:   dmA->celltypeLabel = dmB->celltypeLabel;
2361:   dmB->celltypeLabel = depthTmp;
2362:   tmpI         = dmA->levelup;
2363:   dmA->levelup = dmB->levelup;
2364:   dmB->levelup = tmpI;
2365:   return(0);
2366: }

2368: PetscErrorCode DMSetFromOptions_NonRefinement_Plex(PetscOptionItems *PetscOptionsObject,DM dm)
2369: {
2370:   DM_Plex       *mesh = (DM_Plex*) dm->data;
2371:   PetscBool      flg;

2375:   /* Handle viewing */
2376:   PetscOptionsBool("-dm_plex_print_set_values", "Output all set values info", "DMPlexMatSetClosure", PETSC_FALSE, &mesh->printSetValues, NULL);
2377:   PetscOptionsBoundedInt("-dm_plex_print_fem", "Debug output level all fem computations", "DMPlexSNESComputeResidualFEM", 0, &mesh->printFEM, NULL,0);
2378:   PetscOptionsReal("-dm_plex_print_tol", "Tolerance for FEM output", "DMPlexSNESComputeResidualFEM", mesh->printTol, &mesh->printTol, NULL);
2379:   PetscOptionsBoundedInt("-dm_plex_print_l2", "Debug output level all L2 diff computations", "DMComputeL2Diff", 0, &mesh->printL2, NULL,0);
2380:   DMMonitorSetFromOptions(dm, "-dm_plex_monitor_throughput", "Monitor the simulation throughput", "DMPlexMonitorThroughput", DMPlexMonitorThroughput, NULL, &flg);
2381:   if (flg) {PetscLogDefaultBegin();}
2382:   /* Point Location */
2383:   PetscOptionsBool("-dm_plex_hash_location", "Use grid hashing for point location", "DMInterpolate", PETSC_FALSE, &mesh->useHashLocation, NULL);
2384:   /* Partitioning and distribution */
2385:   PetscOptionsBool("-dm_plex_partition_balance", "Attempt to evenly divide points on partition boundary between processes", "DMPlexSetPartitionBalance", PETSC_FALSE, &mesh->partitionBalance, NULL);
2386:   /* Generation and remeshing */
2387:   PetscOptionsBool("-dm_plex_remesh_bd", "Allow changes to the boundary on remeshing", "DMAdapt", PETSC_FALSE, &mesh->remeshBd, NULL);
2388:   /* Projection behavior */
2389:   PetscOptionsBoundedInt("-dm_plex_max_projection_height", "Maxmimum mesh point height used to project locally", "DMPlexSetMaxProjectionHeight", 0, &mesh->maxProjectionHeight, NULL,0);
2390:   PetscOptionsBool("-dm_plex_regular_refinement", "Use special nested projection algorithm for regular refinement", "DMPlexSetRegularRefinement", mesh->regularRefinement, &mesh->regularRefinement, NULL);
2391:   PetscOptionsEnum("-dm_plex_cell_refiner", "Strategy for cell refinment", "ex40.c", DMPlexCellRefinerTypes, (PetscEnum) mesh->cellRefiner, (PetscEnum *) &mesh->cellRefiner, NULL);
2392:   /* Checking structure */
2393:   {
2394:     PetscBool   flg = PETSC_FALSE, flg2 = PETSC_FALSE, all = PETSC_FALSE;

2396:     PetscOptionsBool("-dm_plex_check_all", "Perform all checks", NULL, PETSC_FALSE, &all, &flg2);
2397:     PetscOptionsBool("-dm_plex_check_symmetry", "Check that the adjacency information in the mesh is symmetric", "DMPlexCheckSymmetry", PETSC_FALSE, &flg, &flg2);
2398:     if (all || (flg && flg2)) {DMPlexCheckSymmetry(dm);}
2399:     PetscOptionsBool("-dm_plex_check_skeleton", "Check that each cell has the correct number of vertices (only for homogeneous simplex or tensor meshes)", "DMPlexCheckSkeleton", PETSC_FALSE, &flg, &flg2);
2400:     if (all || (flg && flg2)) {DMPlexCheckSkeleton(dm, 0);}
2401:     PetscOptionsBool("-dm_plex_check_faces", "Check that the faces of each cell give a vertex order this is consistent with what we expect from the cell type", "DMPlexCheckFaces", PETSC_FALSE, &flg, &flg2);
2402:     if (all || (flg && flg2)) {DMPlexCheckFaces(dm, 0);}
2403:     PetscOptionsBool("-dm_plex_check_geometry", "Check that cells have positive volume", "DMPlexCheckGeometry", PETSC_FALSE, &flg, &flg2);
2404:     if (all || (flg && flg2)) {DMPlexCheckGeometry(dm);}
2405:     PetscOptionsBool("-dm_plex_check_pointsf", "Check some necessary conditions for PointSF", "DMPlexCheckPointSF", PETSC_FALSE, &flg, &flg2);
2406:     if (all || (flg && flg2)) {DMPlexCheckPointSF(dm);}
2407:     PetscOptionsBool("-dm_plex_check_interface_cones", "Check points on inter-partition interfaces have conforming order of cone points", "DMPlexCheckInterfaceCones", PETSC_FALSE, &flg, &flg2);
2408:     if (all || (flg && flg2)) {DMPlexCheckInterfaceCones(dm);}
2409:     PetscOptionsBool("-dm_plex_check_cell_shape", "Check cell shape", "DMPlexCheckCellShape", PETSC_FALSE, &flg, &flg2);
2410:     if (flg && flg2) {DMPlexCheckCellShape(dm, PETSC_TRUE, PETSC_DETERMINE);}
2411:   }

2413:   PetscPartitionerSetFromOptions(mesh->partitioner);
2414:   return(0);
2415: }

2417: static PetscErrorCode DMSetFromOptions_Plex(PetscOptionItems *PetscOptionsObject,DM dm)
2418: {
2419:   PetscInt       prerefine = 0, refine = 0, r, coarsen = 0, overlap = 0;
2420:   PetscBool      distribute = PETSC_FALSE, isHierarchy;

2425:   PetscOptionsHead(PetscOptionsObject,"DMPlex Options");
2426:   /* Handle DMPlex refinement before distribution */
2427:   PetscOptionsBoundedInt("-dm_refine_pre", "The number of uniform refinements before distribution", "DMCreate", prerefine, &prerefine, NULL,0);
2428:   if (prerefine) {DMPlexSetRefinementUniform(dm, PETSC_TRUE);}
2429:   for (r = 0; r < prerefine; ++r) {
2430:     DM             rdm;
2431:     PetscPointFunc coordFunc = ((DM_Plex*) dm->data)->coordFunc;

2433:     DMSetFromOptions_NonRefinement_Plex(PetscOptionsObject, dm);
2434:     DMRefine(dm, PetscObjectComm((PetscObject) dm), &rdm);
2435:     /* Total hack since we do not pass in a pointer */
2436:     DMPlexReplace_Static(dm, rdm);
2437:     DMSetFromOptions_NonRefinement_Plex(PetscOptionsObject, dm);
2438:     if (coordFunc) {
2439:       DMPlexRemapGeometry(dm, 0.0, coordFunc);
2440:       ((DM_Plex*) dm->data)->coordFunc = coordFunc;
2441:     }
2442:     DMDestroy(&rdm);
2443:   }
2444:   /* Handle DMPlex distribution */
2445:   PetscOptionsBool("-dm_distribute", "Flag to redistribute a mesh among processes", "DMCreate", distribute, &distribute, NULL);
2446:   PetscOptionsBoundedInt("-dm_distribute_overlap", "The size of the overlap halo", "DMCreate", overlap, &overlap, NULL, 0);
2447:   if (distribute) {
2448:     DM               pdm = NULL;
2449:     PetscPartitioner part;

2451:     DMPlexGetPartitioner(dm, &part);
2452:     PetscPartitionerSetFromOptions(part);
2453:     DMPlexDistribute(dm, overlap, NULL, &pdm);
2454:     if (pdm) {
2455:       DMPlexReplace_Static(dm, pdm);
2456:       DMDestroy(&pdm);
2457:     }
2458:   }
2459:   /* Handle DMPlex refinement */
2460:   PetscOptionsBoundedInt("-dm_refine", "The number of uniform refinements", "DMCreate", refine, &refine, NULL,0);
2461:   PetscOptionsBoundedInt("-dm_refine_hierarchy", "The number of uniform refinements", "DMCreate", refine, &refine, &isHierarchy,0);
2462:   if (refine) {DMPlexSetRefinementUniform(dm, PETSC_TRUE);}
2463:   if (refine && isHierarchy) {
2464:     DM *dms, coarseDM;

2466:     DMGetCoarseDM(dm, &coarseDM);
2467:     PetscObjectReference((PetscObject)coarseDM);
2468:     PetscMalloc1(refine,&dms);
2469:     DMRefineHierarchy(dm, refine, dms);
2470:     /* Total hack since we do not pass in a pointer */
2471:     DMPlexSwap_Static(dm, dms[refine-1]);
2472:     if (refine == 1) {
2473:       DMSetCoarseDM(dm, dms[0]);
2474:       DMPlexSetRegularRefinement(dm, PETSC_TRUE);
2475:     } else {
2476:       DMSetCoarseDM(dm, dms[refine-2]);
2477:       DMPlexSetRegularRefinement(dm, PETSC_TRUE);
2478:       DMSetCoarseDM(dms[0], dms[refine-1]);
2479:       DMPlexSetRegularRefinement(dms[0], PETSC_TRUE);
2480:     }
2481:     DMSetCoarseDM(dms[refine-1], coarseDM);
2482:     PetscObjectDereference((PetscObject)coarseDM);
2483:     /* Free DMs */
2484:     for (r = 0; r < refine; ++r) {
2485:       DMSetFromOptions_NonRefinement_Plex(PetscOptionsObject, dms[r]);
2486:       DMDestroy(&dms[r]);
2487:     }
2488:     PetscFree(dms);
2489:   } else {
2490:     for (r = 0; r < refine; ++r) {
2491:       DM refinedMesh;
2492:       PetscPointFunc coordFunc = ((DM_Plex*) dm->data)->coordFunc;

2494:       DMSetFromOptions_NonRefinement_Plex(PetscOptionsObject, dm);
2495:       DMRefine(dm, PetscObjectComm((PetscObject) dm), &refinedMesh);
2496:       /* Total hack since we do not pass in a pointer */
2497:       DMPlexReplace_Static(dm, refinedMesh);
2498:       DMSetFromOptions_NonRefinement_Plex(PetscOptionsObject, dm);
2499:       if (coordFunc) {
2500:         DMPlexRemapGeometry(dm, 0.0, coordFunc);
2501:         ((DM_Plex*) dm->data)->coordFunc = coordFunc;
2502:       }
2503:       DMDestroy(&refinedMesh);
2504:     }
2505:   }
2506:   /* Handle DMPlex coarsening */
2507:   PetscOptionsBoundedInt("-dm_coarsen", "Coarsen the mesh", "DMCreate", coarsen, &coarsen, NULL,0);
2508:   PetscOptionsBoundedInt("-dm_coarsen_hierarchy", "The number of coarsenings", "DMCreate", coarsen, &coarsen, &isHierarchy,0);
2509:   if (coarsen && isHierarchy) {
2510:     DM *dms;

2512:     PetscMalloc1(coarsen, &dms);
2513:     DMCoarsenHierarchy(dm, coarsen, dms);
2514:     /* Free DMs */
2515:     for (r = 0; r < coarsen; ++r) {
2516:       DMSetFromOptions_NonRefinement_Plex(PetscOptionsObject, dms[r]);
2517:       DMDestroy(&dms[r]);
2518:     }
2519:     PetscFree(dms);
2520:   } else {
2521:     for (r = 0; r < coarsen; ++r) {
2522:       DM coarseMesh;

2524:       DMSetFromOptions_NonRefinement_Plex(PetscOptionsObject, dm);
2525:       DMCoarsen(dm, PetscObjectComm((PetscObject) dm), &coarseMesh);
2526:       /* Total hack since we do not pass in a pointer */
2527:       DMPlexReplace_Static(dm, coarseMesh);
2528:       DMSetFromOptions_NonRefinement_Plex(PetscOptionsObject, dm);
2529:       DMDestroy(&coarseMesh);
2530:     }
2531:   }
2532:   /* Handle */
2533:   DMSetFromOptions_NonRefinement_Plex(PetscOptionsObject, dm);
2534:   PetscOptionsTail();
2535:   return(0);
2536: }

2538: static PetscErrorCode DMCreateGlobalVector_Plex(DM dm,Vec *vec)
2539: {

2543:   DMCreateGlobalVector_Section_Private(dm,vec);
2544:   /* VecSetOperation(*vec, VECOP_DUPLICATE, (void(*)(void)) VecDuplicate_MPI_DM); */
2545:   VecSetOperation(*vec, VECOP_VIEW, (void (*)(void)) VecView_Plex);
2546:   VecSetOperation(*vec, VECOP_VIEWNATIVE, (void (*)(void)) VecView_Plex_Native);
2547:   VecSetOperation(*vec, VECOP_LOAD, (void (*)(void)) VecLoad_Plex);
2548:   VecSetOperation(*vec, VECOP_LOADNATIVE, (void (*)(void)) VecLoad_Plex_Native);
2549:   return(0);
2550: }

2552: static PetscErrorCode DMCreateLocalVector_Plex(DM dm,Vec *vec)
2553: {

2557:   DMCreateLocalVector_Section_Private(dm,vec);
2558:   VecSetOperation(*vec, VECOP_VIEW, (void (*)(void)) VecView_Plex_Local);
2559:   VecSetOperation(*vec, VECOP_LOAD, (void (*)(void)) VecLoad_Plex_Local);
2560:   return(0);
2561: }

2563: static PetscErrorCode DMGetDimPoints_Plex(DM dm, PetscInt dim, PetscInt *pStart, PetscInt *pEnd)
2564: {
2565:   PetscInt       depth, d;

2569:   DMPlexGetDepth(dm, &depth);
2570:   if (depth == 1) {
2571:     DMGetDimension(dm, &d);
2572:     if (dim == 0)      {DMPlexGetDepthStratum(dm, dim, pStart, pEnd);}
2573:     else if (dim == d) {DMPlexGetDepthStratum(dm, 1, pStart, pEnd);}
2574:     else               {*pStart = 0; *pEnd = 0;}
2575:   } else {
2576:     DMPlexGetDepthStratum(dm, dim, pStart, pEnd);
2577:   }
2578:   return(0);
2579: }

2581: static PetscErrorCode DMGetNeighbors_Plex(DM dm, PetscInt *nranks, const PetscMPIInt *ranks[])
2582: {
2583:   PetscSF           sf;
2584:   PetscInt          niranks, njranks, n;
2585:   const PetscMPIInt *iranks, *jranks;
2586:   DM_Plex           *data = (DM_Plex*) dm->data;
2587:   PetscErrorCode    ierr;

2590:   DMGetPointSF(dm, &sf);
2591:   if (!data->neighbors) {
2592:     PetscSFGetRootRanks(sf, &njranks, &jranks, NULL, NULL, NULL);
2593:     PetscSFGetLeafRanks(sf, &niranks, &iranks, NULL, NULL);
2594:     PetscMalloc1(njranks + niranks + 1, &data->neighbors);
2595:     PetscArraycpy(data->neighbors + 1, jranks, njranks);
2596:     PetscArraycpy(data->neighbors + njranks + 1, iranks, niranks);
2597:     n = njranks + niranks;
2598:     PetscSortRemoveDupsMPIInt(&n, data->neighbors + 1);
2599:     /* The following cast should never fail: can't have more neighbors than PETSC_MPI_INT_MAX */
2600:     PetscMPIIntCast(n, data->neighbors);
2601:   }
2602:   if (nranks) *nranks = data->neighbors[0];
2603:   if (ranks) {
2604:     if (data->neighbors[0]) *ranks = data->neighbors + 1;
2605:     else                    *ranks = NULL;
2606:   }
2607:   return(0);
2608: }

2610: static PetscErrorCode DMInitialize_Plex(DM dm)
2611: {

2615:   dm->ops->view                            = DMView_Plex;
2616:   dm->ops->load                            = DMLoad_Plex;
2617:   dm->ops->setfromoptions                  = DMSetFromOptions_Plex;
2618:   dm->ops->clone                           = DMClone_Plex;
2619:   dm->ops->setup                           = DMSetUp_Plex;
2620:   dm->ops->createlocalsection              = DMCreateLocalSection_Plex;
2621:   dm->ops->createdefaultconstraints        = DMCreateDefaultConstraints_Plex;
2622:   dm->ops->createglobalvector              = DMCreateGlobalVector_Plex;
2623:   dm->ops->createlocalvector               = DMCreateLocalVector_Plex;
2624:   dm->ops->getlocaltoglobalmapping         = NULL;
2625:   dm->ops->createfieldis                   = NULL;
2626:   dm->ops->createcoordinatedm              = DMCreateCoordinateDM_Plex;
2627:   dm->ops->createcoordinatefield           = DMCreateCoordinateField_Plex;
2628:   dm->ops->getcoloring                     = NULL;
2629:   dm->ops->creatematrix                    = DMCreateMatrix_Plex;
2630:   dm->ops->createinterpolation             = DMCreateInterpolation_Plex;
2631:   dm->ops->createmassmatrix                = DMCreateMassMatrix_Plex;
2632:   dm->ops->createinjection                 = DMCreateInjection_Plex;
2633:   dm->ops->refine                          = DMRefine_Plex;
2634:   dm->ops->coarsen                         = DMCoarsen_Plex;
2635:   dm->ops->refinehierarchy                 = DMRefineHierarchy_Plex;
2636:   dm->ops->coarsenhierarchy                = DMCoarsenHierarchy_Plex;
2637:   dm->ops->adaptlabel                      = DMAdaptLabel_Plex;
2638:   dm->ops->adaptmetric                     = DMAdaptMetric_Plex;
2639:   dm->ops->globaltolocalbegin              = NULL;
2640:   dm->ops->globaltolocalend                = NULL;
2641:   dm->ops->localtoglobalbegin              = NULL;
2642:   dm->ops->localtoglobalend                = NULL;
2643:   dm->ops->destroy                         = DMDestroy_Plex;
2644:   dm->ops->createsubdm                     = DMCreateSubDM_Plex;
2645:   dm->ops->createsuperdm                   = DMCreateSuperDM_Plex;
2646:   dm->ops->getdimpoints                    = DMGetDimPoints_Plex;
2647:   dm->ops->locatepoints                    = DMLocatePoints_Plex;
2648:   dm->ops->projectfunctionlocal            = DMProjectFunctionLocal_Plex;
2649:   dm->ops->projectfunctionlabellocal       = DMProjectFunctionLabelLocal_Plex;
2650:   dm->ops->projectfieldlocal               = DMProjectFieldLocal_Plex;
2651:   dm->ops->projectfieldlabellocal          = DMProjectFieldLabelLocal_Plex;
2652:   dm->ops->projectbdfieldlabellocal        = DMProjectBdFieldLabelLocal_Plex;
2653:   dm->ops->computel2diff                   = DMComputeL2Diff_Plex;
2654:   dm->ops->computel2gradientdiff           = DMComputeL2GradientDiff_Plex;
2655:   dm->ops->computel2fielddiff              = DMComputeL2FieldDiff_Plex;
2656:   dm->ops->getneighbors                    = DMGetNeighbors_Plex;
2657:   PetscObjectComposeFunction((PetscObject)dm,"DMPlexInsertBoundaryValues_C",DMPlexInsertBoundaryValues_Plex);
2658:   PetscObjectComposeFunction((PetscObject)dm,"DMPlexInsertTimeDerviativeBoundaryValues_C",DMPlexInsertTimeDerivativeBoundaryValues_Plex);
2659:   PetscObjectComposeFunction((PetscObject)dm,"DMSetUpGLVisViewer_C",DMSetUpGLVisViewer_Plex);
2660:   PetscObjectComposeFunction((PetscObject)dm,"DMCreateNeumannOverlap_C",DMCreateNeumannOverlap_Plex);
2661:   PetscObjectComposeFunction((PetscObject)dm,"DMPlexGetOverlap_C",DMPlexGetOverlap_Plex);
2662:   return(0);
2663: }

2665: PETSC_INTERN PetscErrorCode DMClone_Plex(DM dm, DM *newdm)
2666: {
2667:   DM_Plex        *mesh = (DM_Plex *) dm->data;

2671:   mesh->refct++;
2672:   (*newdm)->data = mesh;
2673:   PetscObjectChangeTypeName((PetscObject) *newdm, DMPLEX);
2674:   DMInitialize_Plex(*newdm);
2675:   return(0);
2676: }

2678: /*MC
2679:   DMPLEX = "plex" - A DM object that encapsulates an unstructured mesh, or CW Complex, which can be expressed using a Hasse Diagram.
2680:                     In the local representation, Vecs contain all unknowns in the interior and shared boundary. This is
2681:                     specified by a PetscSection object. Ownership in the global representation is determined by
2682:                     ownership of the underlying DMPlex points. This is specified by another PetscSection object.

2684:   Options Database Keys:
2685: + -dm_plex_hash_location             - Use grid hashing for point location
2686: . -dm_plex_partition_balance         - Attempt to evenly divide points on partition boundary between processes
2687: . -dm_plex_remesh_bd                 - Allow changes to the boundary on remeshing
2688: . -dm_plex_max_projection_height     - Maxmimum mesh point height used to project locally
2689: . -dm_plex_regular_refinement        - Use special nested projection algorithm for regular refinement
2690: . -dm_plex_check_symmetry            - Check that the adjacency information in the mesh is symmetric
2691: . -dm_plex_check_skeleton <celltype> - Check that each cell has the correct number of vertices
2692: . -dm_plex_check_faces <celltype>    - Check that the faces of each cell give a vertex order this is consistent with what we expect from the cell type
2693: . -dm_plex_check_geometry            - Check that cells have positive volume
2694: . -dm_view :mesh.tex:ascii_latex     - View the mesh in LaTeX/TikZ
2695: . -dm_plex_view_scale <num>          - Scale the TikZ
2696: - -dm_plex_print_fem <num>           - View FEM assembly information, such as element vectors and matrices


2699:   Level: intermediate

2701: .seealso: DMType, DMPlexCreate(), DMCreate(), DMSetType()
2702: M*/

2704: PETSC_EXTERN PetscErrorCode DMCreate_Plex(DM dm)
2705: {
2706:   DM_Plex       *mesh;
2707:   PetscInt       unit;

2712:   PetscNewLog(dm,&mesh);
2713:   dm->dim  = 0;
2714:   dm->data = mesh;

2716:   mesh->refct             = 1;
2717:   PetscSectionCreate(PetscObjectComm((PetscObject)dm), &mesh->coneSection);
2718:   mesh->maxConeSize       = 0;
2719:   mesh->cones             = NULL;
2720:   mesh->coneOrientations  = NULL;
2721:   PetscSectionCreate(PetscObjectComm((PetscObject)dm), &mesh->supportSection);
2722:   mesh->maxSupportSize    = 0;
2723:   mesh->supports          = NULL;
2724:   mesh->refinementUniform = PETSC_TRUE;
2725:   mesh->refinementLimit   = -1.0;
2726:   mesh->interpolated      = DMPLEX_INTERPOLATED_INVALID;
2727:   mesh->interpolatedCollective = DMPLEX_INTERPOLATED_INVALID;

2729:   mesh->facesTmp = NULL;

2731:   mesh->tetgenOpts   = NULL;
2732:   mesh->triangleOpts = NULL;
2733:   PetscPartitionerCreate(PetscObjectComm((PetscObject)dm), &mesh->partitioner);
2734:   mesh->remeshBd     = PETSC_FALSE;

2736:   mesh->subpointMap = NULL;

2738:   for (unit = 0; unit < NUM_PETSC_UNITS; ++unit) mesh->scale[unit] = 1.0;

2740:   mesh->regularRefinement   = PETSC_FALSE;
2741:   mesh->depthState          = -1;
2742:   mesh->celltypeState       = -1;
2743:   mesh->globalVertexNumbers = NULL;
2744:   mesh->globalCellNumbers   = NULL;
2745:   mesh->anchorSection       = NULL;
2746:   mesh->anchorIS            = NULL;
2747:   mesh->createanchors       = NULL;
2748:   mesh->computeanchormatrix = NULL;
2749:   mesh->parentSection       = NULL;
2750:   mesh->parents             = NULL;
2751:   mesh->childIDs            = NULL;
2752:   mesh->childSection        = NULL;
2753:   mesh->children            = NULL;
2754:   mesh->referenceTree       = NULL;
2755:   mesh->getchildsymmetry    = NULL;
2756:   mesh->vtkCellHeight       = 0;
2757:   mesh->useAnchors          = PETSC_FALSE;

2759:   mesh->maxProjectionHeight = 0;

2761:   mesh->neighbors           = NULL;

2763:   mesh->printSetValues = PETSC_FALSE;
2764:   mesh->printFEM       = 0;
2765:   mesh->printTol       = 1.0e-10;

2767:   DMInitialize_Plex(dm);
2768:   return(0);
2769: }

2771: /*@
2772:   DMPlexCreate - Creates a DMPlex object, which encapsulates an unstructured mesh, or CW complex, which can be expressed using a Hasse Diagram.

2774:   Collective

2776:   Input Parameter:
2777: . comm - The communicator for the DMPlex object

2779:   Output Parameter:
2780: . mesh  - The DMPlex object

2782:   Level: beginner

2784: @*/
2785: PetscErrorCode DMPlexCreate(MPI_Comm comm, DM *mesh)
2786: {

2791:   DMCreate(comm, mesh);
2792:   DMSetType(*mesh, DMPLEX);
2793:   return(0);
2794: }

2796: /*@C
2797:   DMPlexBuildFromCellListParallel - Build distributed DMPLEX topology from a list of vertices for each cell (common mesh generator output)

2799:   Input Parameters:
2800: + dm - The DM
2801: . numCells - The number of cells owned by this process
2802: . numVertices - The number of vertices owned by this process, or PETSC_DECIDE
2803: . NVertices - The global number of vertices, or PETSC_DECIDE
2804: . numCorners - The number of vertices for each cell
2805: - cells - An array of numCells*numCorners numbers, the global vertex numbers for each cell

2807:   Output Parameter:
2808: . vertexSF - (Optional) SF describing complete vertex ownership

2810:   Notes:
2811:   Two triangles sharing a face
2812: $
2813: $        2
2814: $      / | \
2815: $     /  |  \
2816: $    /   |   \
2817: $   0  0 | 1  3
2818: $    \   |   /
2819: $     \  |  /
2820: $      \ | /
2821: $        1
2822: would have input
2823: $  numCells = 2, numVertices = 4
2824: $  cells = [0 1 2  1 3 2]
2825: $
2826: which would result in the DMPlex
2827: $
2828: $        4
2829: $      / | \
2830: $     /  |  \
2831: $    /   |   \
2832: $   2  0 | 1  5
2833: $    \   |   /
2834: $     \  |  /
2835: $      \ | /
2836: $        3

2838:   Vertices are implicitly numbered consecutively 0,...,NVertices.
2839:   Each rank owns a chunk of numVertices consecutive vertices.
2840:   If numVertices is PETSC_DECIDE, PETSc will distribute them as evenly as possible using PetscLayout.
2841:   If both NVertices and numVertices are PETSC_DECIDE, NVertices is computed by PETSc as the maximum vertex index in cells + 1.
2842:   If only NVertices is PETSC_DECIDE, it is computed as the sum of numVertices over all ranks.

2844:   The cell distribution is arbitrary non-overlapping, independent of the vertex distribution.

2846:   Not currently supported in Fortran.

2848:   Level: advanced

2850: .seealso: DMPlexBuildFromCellList(), DMPlexCreateFromCellListParallelPetsc(), DMPlexBuildCoordinatesFromCellListParallel()
2851: @*/
2852: PetscErrorCode DMPlexBuildFromCellListParallel(DM dm, PetscInt numCells, PetscInt numVertices, PetscInt NVertices, PetscInt numCorners, const PetscInt cells[], PetscSF *vertexSF)
2853: {
2854:   PetscSF         sfPoint, sfVert;
2855:   PetscLayout     vLayout;
2856:   PetscHSetI      vhash;
2857:   PetscSFNode    *remoteVerticesAdj, *vertexLocal, *vertexOwner, *remoteVertex;
2858:   const PetscInt *vrange;
2859:   PetscInt        numVerticesAdj, off = 0, *verticesAdj, numVerticesGhost = 0, *localVertex, *cones, c, p, v, g, dim;
2860:   PetscMPIInt     rank, size;
2861:   PetscErrorCode  ierr;

2865:   PetscLogEventBegin(DMPLEX_BuildFromCellList,dm,0,0,0);
2866:   MPI_Comm_rank(PetscObjectComm((PetscObject) dm), &rank);
2867:   MPI_Comm_size(PetscObjectComm((PetscObject) dm), &size);
2868:   DMGetDimension(dm, &dim);
2869:   /* Get/check global number of vertices */
2870:   {
2871:     PetscInt NVerticesInCells, i;
2872:     const PetscInt len = numCells * numCorners;

2874:     /* NVerticesInCells = max(cells) + 1 */
2875:     NVerticesInCells = PETSC_MIN_INT;
2876:     for (i=0; i<len; i++) if (cells[i] > NVerticesInCells) NVerticesInCells = cells[i];
2877:     ++NVerticesInCells;
2878:     MPI_Allreduce(MPI_IN_PLACE, &NVerticesInCells, 1, MPIU_INT, MPI_MAX, PetscObjectComm((PetscObject) dm));

2880:     if (numVertices == PETSC_DECIDE && NVertices == PETSC_DECIDE) NVertices = NVerticesInCells;
2881:     else if (NVertices != PETSC_DECIDE && NVertices < NVerticesInCells) SETERRQ2(PetscObjectComm((PetscObject) dm), PETSC_ERR_ARG_WRONG, "Specified global number of vertices %D must be greater than or equal to the number of vertices in cells %D",NVertices,NVerticesInCells);
2882:   }
2883:   /* Partition vertices */
2884:   PetscLayoutCreate(PetscObjectComm((PetscObject) dm), &vLayout);
2885:   PetscLayoutSetLocalSize(vLayout, numVertices);
2886:   PetscLayoutSetSize(vLayout, NVertices);
2887:   PetscLayoutSetBlockSize(vLayout, 1);
2888:   PetscLayoutSetUp(vLayout);
2889:   PetscLayoutGetRanges(vLayout, &vrange);
2890:   /* Count vertices and map them to procs */
2891:   PetscHSetICreate(&vhash);
2892:   for (c = 0; c < numCells; ++c) {
2893:     for (p = 0; p < numCorners; ++p) {
2894:       PetscHSetIAdd(vhash, cells[c*numCorners+p]);
2895:     }
2896:   }
2897:   PetscHSetIGetSize(vhash, &numVerticesAdj);
2898:   PetscMalloc1(numVerticesAdj, &verticesAdj);
2899:   PetscHSetIGetElems(vhash, &off, verticesAdj);
2900:   PetscHSetIDestroy(&vhash);
2901:   if (off != numVerticesAdj) SETERRQ2(PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Invalid number of local vertices %D should be %D", off, numVerticesAdj);
2902:   PetscSortInt(numVerticesAdj, verticesAdj);
2903:   PetscMalloc1(numVerticesAdj, &remoteVerticesAdj);
2904:   for (v = 0; v < numVerticesAdj; ++v) {
2905:     const PetscInt gv = verticesAdj[v];
2906:     PetscInt       vrank;

2908:     PetscFindInt(gv, size+1, vrange, &vrank);
2909:     vrank = vrank < 0 ? -(vrank+2) : vrank;
2910:     remoteVerticesAdj[v].index = gv - vrange[vrank];
2911:     remoteVerticesAdj[v].rank  = vrank;
2912:   }
2913:   /* Create cones */
2914:   DMPlexSetChart(dm, 0, numCells+numVerticesAdj);
2915:   for (c = 0; c < numCells; ++c) {DMPlexSetConeSize(dm, c, numCorners);}
2916:   DMSetUp(dm);
2917:   DMPlexGetCones(dm,&cones);
2918:   for (c = 0; c < numCells; ++c) {
2919:     for (p = 0; p < numCorners; ++p) {
2920:       const PetscInt gv = cells[c*numCorners+p];
2921:       PetscInt       lv;

2923:       PetscFindInt(gv, numVerticesAdj, verticesAdj, &lv);
2924:       if (lv < 0) SETERRQ1(PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Could not find global vertex %D in local connectivity", gv);
2925:       cones[c*numCorners+p] = lv+numCells;
2926:     }
2927:   }
2928:   /* Create SF for vertices */
2929:   PetscSFCreate(PetscObjectComm((PetscObject)dm), &sfVert);
2930:   PetscObjectSetName((PetscObject) sfVert, "Vertex Ownership SF");
2931:   PetscSFSetFromOptions(sfVert);
2932:   PetscSFSetGraph(sfVert, numVertices, numVerticesAdj, NULL, PETSC_OWN_POINTER, remoteVerticesAdj, PETSC_OWN_POINTER);
2933:   PetscFree(verticesAdj);
2934:   /* Build pointSF */
2935:   PetscMalloc2(numVerticesAdj, &vertexLocal, numVertices, &vertexOwner);
2936:   for (v = 0; v < numVerticesAdj; ++v) {vertexLocal[v].index = v+numCells; vertexLocal[v].rank = rank;}
2937:   for (v = 0; v < numVertices;    ++v) {vertexOwner[v].index = -1;         vertexOwner[v].rank = -1;}
2938:   PetscSFReduceBegin(sfVert, MPIU_2INT, vertexLocal, vertexOwner, MPI_MAXLOC);
2939:   PetscSFReduceEnd(sfVert, MPIU_2INT, vertexLocal, vertexOwner, MPI_MAXLOC);
2940:   for (v = 0; v < numVertices;    ++v) if (vertexOwner[v].rank < 0) SETERRQ2(PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Global vertex %D on rank %d was unclaimed", v + vrange[rank], rank);
2941:   PetscSFBcastBegin(sfVert, MPIU_2INT, vertexOwner, vertexLocal);
2942:   PetscSFBcastEnd(sfVert, MPIU_2INT, vertexOwner, vertexLocal);
2943:   for (v = 0; v < numVerticesAdj; ++v) if (vertexLocal[v].rank != rank) ++numVerticesGhost;
2944:   PetscMalloc1(numVerticesGhost, &localVertex);
2945:   PetscMalloc1(numVerticesGhost, &remoteVertex);
2946:   for (v = 0, g = 0; v < numVerticesAdj; ++v) {
2947:     if (vertexLocal[v].rank != rank) {
2948:       localVertex[g]        = v+numCells;
2949:       remoteVertex[g].index = vertexLocal[v].index;
2950:       remoteVertex[g].rank  = vertexLocal[v].rank;
2951:       ++g;
2952:     }
2953:   }
2954:   PetscFree2(vertexLocal, vertexOwner);
2955:   if (g != numVerticesGhost) SETERRQ2(PETSC_COMM_SELF, PETSC_ERR_PLIB, "Invalid number of vertex ghosts %D should be %D", g, numVerticesGhost);
2956:   DMGetPointSF(dm, &sfPoint);
2957:   PetscObjectSetName((PetscObject) sfPoint, "point SF");
2958:   PetscSFSetGraph(sfPoint, numCells+numVerticesAdj, numVerticesGhost, localVertex, PETSC_OWN_POINTER, remoteVertex, PETSC_OWN_POINTER);
2959:   PetscLayoutDestroy(&vLayout);
2960:   /* Fill in the rest of the topology structure */
2961:   DMPlexSymmetrize(dm);
2962:   DMPlexStratify(dm);
2963:   PetscLogEventEnd(DMPLEX_BuildFromCellList,dm,0,0,0);
2964:   if (vertexSF) *vertexSF = sfVert;
2965:   else {PetscSFDestroy(&sfVert);}
2966:   return(0);
2967: }

2969: /*@C
2970:   DMPlexBuildCoordinatesFromCellListParallel - Build DM coordinates from a list of coordinates for each owned vertex (common mesh generator output)

2972:   Input Parameters:
2973: + dm - The DM
2974: . spaceDim - The spatial dimension used for coordinates
2975: . sfVert - SF describing complete vertex ownership
2976: - vertexCoords - An array of numVertices*spaceDim numbers, the coordinates of each vertex

2978:   Level: advanced

2980:   Notes:
2981:   Not currently supported in Fortran.

2983: .seealso: DMPlexBuildCoordinatesFromCellList(), DMPlexCreateFromCellListParallelPetsc(), DMPlexBuildFromCellListParallel()
2984: @*/
2985: PetscErrorCode DMPlexBuildCoordinatesFromCellListParallel(DM dm, PetscInt spaceDim, PetscSF sfVert, const PetscReal vertexCoords[])
2986: {
2987:   PetscSection   coordSection;
2988:   Vec            coordinates;
2989:   PetscScalar   *coords;
2990:   PetscInt       numVertices, numVerticesAdj, coordSize, v, vStart, vEnd;

2994:   PetscLogEventBegin(DMPLEX_BuildCoordinatesFromCellList,dm,0,0,0);
2995:   DMPlexGetDepthStratum(dm, 0, &vStart, &vEnd);
2996:   if (vStart < 0 || vEnd < 0) SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "DM is not set up properly. DMPlexBuildFromCellList() should be called first.");
2997:   DMSetCoordinateDim(dm, spaceDim);
2998:   PetscSFGetGraph(sfVert, &numVertices, &numVerticesAdj, NULL, NULL);
2999:   if (vEnd - vStart != numVerticesAdj) SETERRQ2(PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Supplied sfVert has wrong number of leaves = %D != %D = vEnd - vStart",numVerticesAdj,vEnd - vStart);
3000:   DMGetCoordinateSection(dm, &coordSection);
3001:   PetscSectionSetNumFields(coordSection, 1);
3002:   PetscSectionSetFieldComponents(coordSection, 0, spaceDim);
3003:   PetscSectionSetChart(coordSection, vStart, vEnd);
3004:   for (v = vStart; v < vEnd; ++v) {
3005:     PetscSectionSetDof(coordSection, v, spaceDim);
3006:     PetscSectionSetFieldDof(coordSection, v, 0, spaceDim);
3007:   }
3008:   PetscSectionSetUp(coordSection);
3009:   PetscSectionGetStorageSize(coordSection, &coordSize);
3010:   VecCreate(PetscObjectComm((PetscObject)dm), &coordinates);
3011:   VecSetBlockSize(coordinates, spaceDim);
3012:   PetscObjectSetName((PetscObject) coordinates, "coordinates");
3013:   VecSetSizes(coordinates, coordSize, PETSC_DETERMINE);
3014:   VecSetType(coordinates,VECSTANDARD);
3015:   VecGetArray(coordinates, &coords);
3016:   {
3017:     MPI_Datatype coordtype;

3019:     /* Need a temp buffer for coords if we have complex/single */
3020:     MPI_Type_contiguous(spaceDim, MPIU_SCALAR, &coordtype);
3021:     MPI_Type_commit(&coordtype);
3022: #if defined(PETSC_USE_COMPLEX)
3023:     {
3024:     PetscScalar *svertexCoords;
3025:     PetscInt    i;
3026:     PetscMalloc1(numVertices*spaceDim,&svertexCoords);
3027:     for (i=0; i<numVertices*spaceDim; i++) svertexCoords[i] = vertexCoords[i];
3028:     PetscSFBcastBegin(sfVert, coordtype, svertexCoords, coords);
3029:     PetscSFBcastEnd(sfVert, coordtype, svertexCoords, coords);
3030:     PetscFree(svertexCoords);
3031:     }
3032: #else
3033:     PetscSFBcastBegin(sfVert, coordtype, vertexCoords, coords);
3034:     PetscSFBcastEnd(sfVert, coordtype, vertexCoords, coords);
3035: #endif
3036:     MPI_Type_free(&coordtype);
3037:   }
3038:   VecRestoreArray(coordinates, &coords);
3039:   DMSetCoordinatesLocal(dm, coordinates);
3040:   VecDestroy(&coordinates);
3041:   PetscLogEventEnd(DMPLEX_BuildCoordinatesFromCellList,dm,0,0,0);
3042:   return(0);
3043: }

3045: /*@
3046:   DMPlexCreateFromCellListParallelPetsc - Create distributed DMPLEX from a list of vertices for each cell (common mesh generator output)

3048:   Input Parameters:
3049: + comm - The communicator
3050: . dim - The topological dimension of the mesh
3051: . numCells - The number of cells owned by this process
3052: . numVertices - The number of vertices owned by this process, or PETSC_DECIDE
3053: . NVertices - The global number of vertices, or PETSC_DECIDE
3054: . numCorners - The number of vertices for each cell
3055: . interpolate - Flag indicating that intermediate mesh entities (faces, edges) should be created automatically
3056: . cells - An array of numCells*numCorners numbers, the global vertex numbers for each cell
3057: . spaceDim - The spatial dimension used for coordinates
3058: - vertexCoords - An array of numVertices*spaceDim numbers, the coordinates of each vertex

3060:   Output Parameter:
3061: + dm - The DM
3062: - vertexSF - (Optional) SF describing complete vertex ownership

3064:   Notes:
3065:   This function is just a convenient sequence of DMCreate(), DMSetType(), DMSetDimension(),
3066:   DMPlexBuildFromCellListParallel(), DMPlexInterpolate(), DMPlexBuildCoordinatesFromCellListParallel()

3068:   See DMPlexBuildFromCellListParallel() for an example and details about the topology-related parameters.
3069:   See DMPlexBuildCoordinatesFromCellListParallel() for details about the geometry-related parameters.

3071:   Level: intermediate

3073: .seealso: DMPlexCreateFromCellListPetsc(), DMPlexBuildFromCellListParallel(), DMPlexBuildCoordinatesFromCellListParallel(), DMPlexCreateFromDAG(), DMPlexCreate()
3074: @*/
3075: PetscErrorCode DMPlexCreateFromCellListParallelPetsc(MPI_Comm comm, PetscInt dim, PetscInt numCells, PetscInt numVertices, PetscInt NVertices, PetscInt numCorners, PetscBool interpolate, const PetscInt cells[], PetscInt spaceDim, const PetscReal vertexCoords[], PetscSF *vertexSF, DM *dm)
3076: {
3077:   PetscSF        sfVert;

3081:   DMCreate(comm, dm);
3082:   DMSetType(*dm, DMPLEX);
3085:   DMSetDimension(*dm, dim);
3086:   DMPlexBuildFromCellListParallel(*dm, numCells, numVertices, NVertices, numCorners, cells, &sfVert);
3087:   if (interpolate) {
3088:     DM idm;

3090:     DMPlexInterpolate(*dm, &idm);
3091:     DMDestroy(dm);
3092:     *dm  = idm;
3093:   }
3094:   DMPlexBuildCoordinatesFromCellListParallel(*dm, spaceDim, sfVert, vertexCoords);
3095:   if (vertexSF) *vertexSF = sfVert;
3096:   else {PetscSFDestroy(&sfVert);}
3097:   return(0);
3098: }


3101: /*@
3102:   DMPlexCreateFromCellListParallel - Deprecated, use DMPlexCreateFromCellListParallelPetsc()

3104:   Level: deprecated

3106: .seealso: DMPlexCreateFromCellListParallelPetsc()
3107: @*/
3108: PetscErrorCode DMPlexCreateFromCellListParallel(MPI_Comm comm, PetscInt dim, PetscInt numCells, PetscInt numVertices, PetscInt numCorners, PetscBool interpolate, const int cells[], PetscInt spaceDim, const PetscReal vertexCoords[], PetscSF *vertexSF, DM *dm)
3109: {
3111:   PetscInt       i;
3112:   PetscInt       *pintCells;

3115:   if (sizeof(int) > sizeof(PetscInt)) SETERRQ2(comm, PETSC_ERR_ARG_SIZ, "Size of int %zd greater than size of PetscInt %zd. Reconfigure PETSc --with-64-bit-indices=1", sizeof(int), sizeof(PetscInt));
3116:   if (sizeof(int) == sizeof(PetscInt)) {
3117:     pintCells = (PetscInt *) cells;
3118:   } else {
3119:     PetscMalloc1(numCells*numCorners, &pintCells);
3120:     for (i = 0; i < numCells*numCorners; i++) {
3121:       pintCells[i] = (PetscInt) cells[i];
3122:     }
3123:   }
3124:   DMPlexCreateFromCellListParallelPetsc(comm, dim, numCells, numVertices, PETSC_DECIDE, numCorners, interpolate, pintCells, spaceDim, vertexCoords, vertexSF, dm);
3125:   if (sizeof(int) != sizeof(PetscInt)) {
3126:     PetscFree(pintCells);
3127:   }
3128:   return(0);
3129: }

3131: /*@C
3132:   DMPlexBuildFromCellList - Build DMPLEX topology from a list of vertices for each cell (common mesh generator output)

3134:   Input Parameters:
3135: + dm - The DM
3136: . numCells - The number of cells owned by this process
3137: . numVertices - The number of vertices owned by this process, or PETSC_DECIDE
3138: . numCorners - The number of vertices for each cell
3139: - cells - An array of numCells*numCorners numbers, the global vertex numbers for each cell

3141:   Level: advanced

3143:   Notes:
3144:   Two triangles sharing a face
3145: $
3146: $        2
3147: $      / | \
3148: $     /  |  \
3149: $    /   |   \
3150: $   0  0 | 1  3
3151: $    \   |   /
3152: $     \  |  /
3153: $      \ | /
3154: $        1
3155: would have input
3156: $  numCells = 2, numVertices = 4
3157: $  cells = [0 1 2  1 3 2]
3158: $
3159: which would result in the DMPlex
3160: $
3161: $        4
3162: $      / | \
3163: $     /  |  \
3164: $    /   |   \
3165: $   2  0 | 1  5
3166: $    \   |   /
3167: $     \  |  /
3168: $      \ | /
3169: $        3

3171:   If numVertices is PETSC_DECIDE, it is computed by PETSc as the maximum vertex index in cells + 1.

3173:   Not currently supported in Fortran.

3175: .seealso: DMPlexBuildFromCellListParallel(), DMPlexBuildCoordinatesFromCellList(), DMPlexCreateFromCellListPetsc()
3176: @*/
3177: PetscErrorCode DMPlexBuildFromCellList(DM dm, PetscInt numCells, PetscInt numVertices, PetscInt numCorners, const PetscInt cells[])
3178: {
3179:   PetscInt      *cones, c, p, dim;

3183:   PetscLogEventBegin(DMPLEX_BuildFromCellList,dm,0,0,0);
3184:   DMGetDimension(dm, &dim);
3185:   /* Get/check global number of vertices */
3186:   {
3187:     PetscInt NVerticesInCells, i;
3188:     const PetscInt len = numCells * numCorners;

3190:     /* NVerticesInCells = max(cells) + 1 */
3191:     NVerticesInCells = PETSC_MIN_INT;
3192:     for (i=0; i<len; i++) if (cells[i] > NVerticesInCells) NVerticesInCells = cells[i];
3193:     ++NVerticesInCells;

3195:     if (numVertices == PETSC_DECIDE) numVertices = NVerticesInCells;
3196:     else if (numVertices < NVerticesInCells) SETERRQ2(PetscObjectComm((PetscObject) dm), PETSC_ERR_ARG_WRONG, "Specified number of vertices %D must be greater than or equal to the number of vertices in cells %D",numVertices,NVerticesInCells);
3197:   }
3198:   DMPlexSetChart(dm, 0, numCells+numVertices);
3199:   for (c = 0; c < numCells; ++c) {
3200:     DMPlexSetConeSize(dm, c, numCorners);
3201:   }
3202:   DMSetUp(dm);
3203:   DMPlexGetCones(dm,&cones);
3204:   for (c = 0; c < numCells; ++c) {
3205:     for (p = 0; p < numCorners; ++p) {
3206:       cones[c*numCorners+p] = cells[c*numCorners+p]+numCells;
3207:     }
3208:   }
3209:   DMPlexSymmetrize(dm);
3210:   DMPlexStratify(dm);
3211:   PetscLogEventEnd(DMPLEX_BuildFromCellList,dm,0,0,0);
3212:   return(0);
3213: }

3215: /*@C
3216:   DMPlexBuildCoordinatesFromCellList - Build DM coordinates from a list of coordinates for each owned vertex (common mesh generator output)

3218:   Input Parameters:
3219: + dm - The DM
3220: . spaceDim - The spatial dimension used for coordinates
3221: - vertexCoords - An array of numVertices*spaceDim numbers, the coordinates of each vertex

3223:   Level: advanced

3225:   Notes:
3226:   Not currently supported in Fortran.

3228: .seealso: DMPlexBuildCoordinatesFromCellListParallel(), DMPlexCreateFromCellListPetsc(), DMPlexBuildFromCellList()
3229: @*/
3230: PetscErrorCode DMPlexBuildCoordinatesFromCellList(DM dm, PetscInt spaceDim, const PetscReal vertexCoords[])
3231: {
3232:   PetscSection   coordSection;
3233:   Vec            coordinates;
3234:   DM             cdm;
3235:   PetscScalar   *coords;
3236:   PetscInt       v, vStart, vEnd, d;

3240:   PetscLogEventBegin(DMPLEX_BuildCoordinatesFromCellList,dm,0,0,0);
3241:   DMPlexGetDepthStratum(dm, 0, &vStart, &vEnd);
3242:   if (vStart < 0 || vEnd < 0) SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "DM is not set up properly. DMPlexBuildFromCellList() should be called first.");
3243:   DMSetCoordinateDim(dm, spaceDim);
3244:   DMGetCoordinateSection(dm, &coordSection);
3245:   PetscSectionSetNumFields(coordSection, 1);
3246:   PetscSectionSetFieldComponents(coordSection, 0, spaceDim);
3247:   PetscSectionSetChart(coordSection, vStart, vEnd);
3248:   for (v = vStart; v < vEnd; ++v) {
3249:     PetscSectionSetDof(coordSection, v, spaceDim);
3250:     PetscSectionSetFieldDof(coordSection, v, 0, spaceDim);
3251:   }
3252:   PetscSectionSetUp(coordSection);

3254:   DMGetCoordinateDM(dm, &cdm);
3255:   DMCreateLocalVector(cdm, &coordinates);
3256:   VecSetBlockSize(coordinates, spaceDim);
3257:   PetscObjectSetName((PetscObject) coordinates, "coordinates");
3258:   VecGetArrayWrite(coordinates, &coords);
3259:   for (v = 0; v < vEnd-vStart; ++v) {
3260:     for (d = 0; d < spaceDim; ++d) {
3261:       coords[v*spaceDim+d] = vertexCoords[v*spaceDim+d];
3262:     }
3263:   }
3264:   VecRestoreArrayWrite(coordinates, &coords);
3265:   DMSetCoordinatesLocal(dm, coordinates);
3266:   VecDestroy(&coordinates);
3267:   PetscLogEventEnd(DMPLEX_BuildCoordinatesFromCellList,dm,0,0,0);
3268:   return(0);
3269: }

3271: /*@
3272:   DMPlexCreateFromCellListPetsc - Create DMPLEX from a list of vertices for each cell (common mesh generator output)

3274:   Input Parameters:
3275: + comm - The communicator
3276: . dim - The topological dimension of the mesh
3277: . numCells - The number of cells
3278: . numVertices - The number of vertices owned by this process, or PETSC_DECIDE
3279: . numCorners - The number of vertices for each cell
3280: . interpolate - Flag indicating that intermediate mesh entities (faces, edges) should be created automatically
3281: . cells - An array of numCells*numCorners numbers, the vertices for each cell
3282: . spaceDim - The spatial dimension used for coordinates
3283: - vertexCoords - An array of numVertices*spaceDim numbers, the coordinates of each vertex

3285:   Output Parameter:
3286: . dm - The DM

3288:   Notes:
3289:   This function is just a convenient sequence of DMCreate(), DMSetType(), DMSetDimension(), DMPlexBuildFromCellList(),
3290:   DMPlexInterpolate(), DMPlexBuildCoordinatesFromCellList()

3292:   See DMPlexBuildFromCellList() for an example and details about the topology-related parameters.
3293:   See DMPlexBuildCoordinatesFromCellList() for details about the geometry-related parameters.

3295:   Level: intermediate

3297: .seealso: DMPlexCreateFromCellListParallelPetsc(), DMPlexBuildFromCellList(), DMPlexBuildCoordinatesFromCellList(), DMPlexCreateFromDAG(), DMPlexCreate()
3298: @*/
3299: PetscErrorCode DMPlexCreateFromCellListPetsc(MPI_Comm comm, PetscInt dim, PetscInt numCells, PetscInt numVertices, PetscInt numCorners, PetscBool interpolate, const PetscInt cells[], PetscInt spaceDim, const PetscReal vertexCoords[], DM *dm)
3300: {

3304:   if (!dim) SETERRQ(comm, PETSC_ERR_ARG_OUTOFRANGE, "This is not appropriate for 0-dimensional meshes. Consider either creating the DM using DMPlexCreateFromDAG(), by hand, or using DMSwarm.");
3305:   DMCreate(comm, dm);
3306:   DMSetType(*dm, DMPLEX);
3307:   DMSetDimension(*dm, dim);
3308:   DMPlexBuildFromCellList(*dm, numCells, numVertices, numCorners, cells);
3309:   if (interpolate) {
3310:     DM idm;

3312:     DMPlexInterpolate(*dm, &idm);
3313:     DMDestroy(dm);
3314:     *dm  = idm;
3315:   }
3316:   DMPlexBuildCoordinatesFromCellList(*dm, spaceDim, vertexCoords);
3317:   return(0);
3318: }

3320: /*@
3321:   DMPlexCreateFromCellList - Deprecated, use DMPlexCreateFromCellListPetsc()

3323:   Level: deprecated

3325: .seealso: DMPlexCreateFromCellListPetsc()
3326: @*/
3327: PetscErrorCode DMPlexCreateFromCellList(MPI_Comm comm, PetscInt dim, PetscInt numCells, PetscInt numVertices, PetscInt numCorners, PetscBool interpolate, const int cells[], PetscInt spaceDim, const double vertexCoords[], DM *dm)
3328: {
3330:   PetscInt       i;
3331:   PetscInt       *pintCells;
3332:   PetscReal      *prealVC;

3335:   if (sizeof(int) > sizeof(PetscInt)) SETERRQ2(comm, PETSC_ERR_ARG_SIZ, "Size of int %zd greater than size of PetscInt %zd. Reconfigure PETSc --with-64-bit-indices=1", sizeof(int), sizeof(PetscInt));
3336:   if (sizeof(int) == sizeof(PetscInt)) {
3337:     pintCells = (PetscInt *) cells;
3338:   } else {
3339:     PetscMalloc1(numCells*numCorners, &pintCells);
3340:     for (i = 0; i < numCells*numCorners; i++) {
3341:       pintCells[i] = (PetscInt) cells[i];
3342:     }
3343:   }
3344:   if (sizeof(double) > sizeof(PetscReal)) SETERRQ2(comm, PETSC_ERR_ARG_SIZ, "Size of double %zd greater than size of PetscReal %zd. Reconfigure PETSc --with-precision=<higher precision>.", sizeof(double), sizeof(PetscReal));
3345:   if (sizeof(double) == sizeof(PetscReal)) {
3346:     prealVC = (PetscReal *) vertexCoords;
3347:   } else {
3348:     PetscMalloc1(numVertices*spaceDim, &prealVC);
3349:     for (i = 0; i < numVertices*spaceDim; i++) {
3350:       prealVC[i] = (PetscReal) vertexCoords[i];
3351:     }
3352:   }
3353:   DMPlexCreateFromCellListPetsc(comm, dim, numCells, numVertices, numCorners, interpolate, pintCells, spaceDim, prealVC, dm);
3354:   if (sizeof(int) != sizeof(PetscInt)) {
3355:     PetscFree(pintCells);
3356:   }
3357:   if (sizeof(double) != sizeof(PetscReal)) {
3358:     PetscFree(prealVC);
3359:   }
3360:   return(0);
3361: }

3363: /*@
3364:   DMPlexCreateFromDAG - This takes as input the adjacency-list representation of the Directed Acyclic Graph (Hasse Diagram) encoding a mesh, and produces a DM

3366:   Input Parameters:
3367: + dm - The empty DM object, usually from DMCreate() and DMSetDimension()
3368: . depth - The depth of the DAG
3369: . numPoints - Array of size depth + 1 containing the number of points at each depth
3370: . coneSize - The cone size of each point
3371: . cones - The concatenation of the cone points for each point, the cone list must be oriented correctly for each point
3372: . coneOrientations - The orientation of each cone point
3373: - vertexCoords - An array of numPoints[0]*spacedim numbers representing the coordinates of each vertex, with spacedim the value set via DMSetCoordinateDim()

3375:   Output Parameter:
3376: . dm - The DM

3378:   Note: Two triangles sharing a face would have input
3379: $  depth = 1, numPoints = [4 2], coneSize = [3 3 0 0 0 0]
3380: $  cones = [2 3 4  3 5 4], coneOrientations = [0 0 0  0 0 0]
3381: $ vertexCoords = [-1.0 0.0  0.0 -1.0  0.0 1.0  1.0 0.0]
3382: $
3383: which would result in the DMPlex
3384: $
3385: $        4
3386: $      / | \
3387: $     /  |  \
3388: $    /   |   \
3389: $   2  0 | 1  5
3390: $    \   |   /
3391: $     \  |  /
3392: $      \ | /
3393: $        3
3394: $
3395: $ Notice that all points are numbered consecutively, unlike DMPlexCreateFromCellListPetsc()

3397:   Level: advanced

3399: .seealso: DMPlexCreateFromCellListPetsc(), DMPlexCreate()
3400: @*/
3401: PetscErrorCode DMPlexCreateFromDAG(DM dm, PetscInt depth, const PetscInt numPoints[], const PetscInt coneSize[], const PetscInt cones[], const PetscInt coneOrientations[], const PetscScalar vertexCoords[])
3402: {
3403:   Vec            coordinates;
3404:   PetscSection   coordSection;
3405:   PetscScalar    *coords;
3406:   PetscInt       coordSize, firstVertex = -1, pStart = 0, pEnd = 0, p, v, dim, dimEmbed, d, off;

3410:   DMGetDimension(dm, &dim);
3411:   DMGetCoordinateDim(dm, &dimEmbed);
3412:   if (dimEmbed < dim) SETERRQ2(PETSC_COMM_SELF,PETSC_ERR_PLIB,"Embedding dimension %D cannot be less than intrinsic dimension %d",dimEmbed,dim);
3413:   for (d = 0; d <= depth; ++d) pEnd += numPoints[d];
3414:   DMPlexSetChart(dm, pStart, pEnd);
3415:   for (p = pStart; p < pEnd; ++p) {
3416:     DMPlexSetConeSize(dm, p, coneSize[p-pStart]);
3417:     if (firstVertex < 0 && !coneSize[p - pStart]) {
3418:       firstVertex = p - pStart;
3419:     }
3420:   }
3421:   if (firstVertex < 0 && numPoints[0]) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONG,"Expected %D vertices but could not find any", numPoints[0]);
3422:   DMSetUp(dm); /* Allocate space for cones */
3423:   for (p = pStart, off = 0; p < pEnd; off += coneSize[p-pStart], ++p) {
3424:     DMPlexSetCone(dm, p, &cones[off]);
3425:     DMPlexSetConeOrientation(dm, p, &coneOrientations[off]);
3426:   }
3427:   DMPlexSymmetrize(dm);
3428:   DMPlexStratify(dm);
3429:   /* Build coordinates */
3430:   DMGetCoordinateSection(dm, &coordSection);
3431:   PetscSectionSetNumFields(coordSection, 1);
3432:   PetscSectionSetFieldComponents(coordSection, 0, dimEmbed);
3433:   PetscSectionSetChart(coordSection, firstVertex, firstVertex+numPoints[0]);
3434:   for (v = firstVertex; v < firstVertex+numPoints[0]; ++v) {
3435:     PetscSectionSetDof(coordSection, v, dimEmbed);
3436:     PetscSectionSetFieldDof(coordSection, v, 0, dimEmbed);
3437:   }
3438:   PetscSectionSetUp(coordSection);
3439:   PetscSectionGetStorageSize(coordSection, &coordSize);
3440:   VecCreate(PETSC_COMM_SELF, &coordinates);
3441:   PetscObjectSetName((PetscObject) coordinates, "coordinates");
3442:   VecSetSizes(coordinates, coordSize, PETSC_DETERMINE);
3443:   VecSetBlockSize(coordinates, dimEmbed);
3444:   VecSetType(coordinates,VECSTANDARD);
3445:   VecGetArray(coordinates, &coords);
3446:   for (v = 0; v < numPoints[0]; ++v) {
3447:     PetscInt off;

3449:     PetscSectionGetOffset(coordSection, v+firstVertex, &off);
3450:     for (d = 0; d < dimEmbed; ++d) {
3451:       coords[off+d] = vertexCoords[v*dimEmbed+d];
3452:     }
3453:   }
3454:   VecRestoreArray(coordinates, &coords);
3455:   DMSetCoordinatesLocal(dm, coordinates);
3456:   VecDestroy(&coordinates);
3457:   return(0);
3458: }

3460: /*@C
3461:   DMPlexCreateCellVertexFromFile - Create a DMPlex mesh from a simple cell-vertex file.

3463: + comm        - The MPI communicator
3464: . filename    - Name of the .dat file
3465: - interpolate - Create faces and edges in the mesh

3467:   Output Parameter:
3468: . dm  - The DM object representing the mesh

3470:   Note: The format is the simplest possible:
3471: $ Ne
3472: $ v0 v1 ... vk
3473: $ Nv
3474: $ x y z marker

3476:   Level: beginner

3478: .seealso: DMPlexCreateFromFile(), DMPlexCreateMedFromFile(), DMPlexCreateGmsh(), DMPlexCreate()
3479: @*/
3480: PetscErrorCode DMPlexCreateCellVertexFromFile(MPI_Comm comm, const char filename[], PetscBool interpolate, DM *dm)
3481: {
3482:   DMLabel         marker;
3483:   PetscViewer     viewer;
3484:   Vec             coordinates;
3485:   PetscSection    coordSection;
3486:   PetscScalar    *coords;
3487:   char            line[PETSC_MAX_PATH_LEN];
3488:   PetscInt        dim = 3, cdim = 3, coordSize, v, c, d;
3489:   PetscMPIInt     rank;
3490:   int             snum, Nv, Nc;
3491:   PetscErrorCode  ierr;

3494:   MPI_Comm_rank(comm, &rank);
3495:   PetscViewerCreate(comm, &viewer);
3496:   PetscViewerSetType(viewer, PETSCVIEWERASCII);
3497:   PetscViewerFileSetMode(viewer, FILE_MODE_READ);
3498:   PetscViewerFileSetName(viewer, filename);
3499:   if (!rank) {
3500:     PetscViewerRead(viewer, line, 2, NULL, PETSC_STRING);
3501:     snum = sscanf(line, "%d %d", &Nc, &Nv);
3502:     if (snum != 2) SETERRQ1(PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Unable to parse cell-vertex file: %s", line);
3503:   } else {
3504:     Nc = Nv = 0;
3505:   }
3506:   DMCreate(comm, dm);
3507:   DMSetType(*dm, DMPLEX);
3508:   DMPlexSetChart(*dm, 0, Nc+Nv);
3509:   DMSetDimension(*dm, dim);
3510:   DMSetCoordinateDim(*dm, cdim);
3511:   /* Read topology */
3512:   if (!rank) {
3513:     PetscInt cone[8], corners = 8;
3514:     int      vbuf[8], v;

3516:     for (c = 0; c < Nc; ++c) {DMPlexSetConeSize(*dm, c, corners);}
3517:     DMSetUp(*dm);
3518:     for (c = 0; c < Nc; ++c) {
3519:       PetscViewerRead(viewer, line, corners, NULL, PETSC_STRING);
3520:       snum = sscanf(line, "%d %d %d %d %d %d %d %d", &vbuf[0], &vbuf[1], &vbuf[2], &vbuf[3], &vbuf[4], &vbuf[5], &vbuf[6], &vbuf[7]);
3521:       if (snum != corners) SETERRQ1(PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Unable to parse cell-vertex file: %s", line);
3522:       for (v = 0; v < corners; ++v) cone[v] = vbuf[v] + Nc;
3523:       /* Hexahedra are inverted */
3524:       {
3525:         PetscInt tmp = cone[1];
3526:         cone[1] = cone[3];
3527:         cone[3] = tmp;
3528:       }
3529:       DMPlexSetCone(*dm, c, cone);
3530:     }
3531:   }
3532:   DMPlexSymmetrize(*dm);
3533:   DMPlexStratify(*dm);
3534:   /* Read coordinates */
3535:   DMGetCoordinateSection(*dm, &coordSection);
3536:   PetscSectionSetNumFields(coordSection, 1);
3537:   PetscSectionSetFieldComponents(coordSection, 0, cdim);
3538:   PetscSectionSetChart(coordSection, Nc, Nc + Nv);
3539:   for (v = Nc; v < Nc+Nv; ++v) {
3540:     PetscSectionSetDof(coordSection, v, cdim);
3541:     PetscSectionSetFieldDof(coordSection, v, 0, cdim);
3542:   }
3543:   PetscSectionSetUp(coordSection);
3544:   PetscSectionGetStorageSize(coordSection, &coordSize);
3545:   VecCreate(PETSC_COMM_SELF, &coordinates);
3546:   PetscObjectSetName((PetscObject) coordinates, "coordinates");
3547:   VecSetSizes(coordinates, coordSize, PETSC_DETERMINE);
3548:   VecSetBlockSize(coordinates, cdim);
3549:   VecSetType(coordinates, VECSTANDARD);
3550:   VecGetArray(coordinates, &coords);
3551:   if (!rank) {
3552:     double x[3];
3553:     int    val;

3555:     DMCreateLabel(*dm, "marker");
3556:     DMGetLabel(*dm, "marker", &marker);
3557:     for (v = 0; v < Nv; ++v) {
3558:       PetscViewerRead(viewer, line, 4, NULL, PETSC_STRING);
3559:       snum = sscanf(line, "%lg %lg %lg %d", &x[0], &x[1], &x[2], &val);
3560:       if (snum != 4) SETERRQ1(PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Unable to parse cell-vertex file: %s", line);
3561:       for (d = 0; d < cdim; ++d) coords[v*cdim+d] = x[d];
3562:       if (val) {DMLabelSetValue(marker, v+Nc, val);}
3563:     }
3564:   }
3565:   VecRestoreArray(coordinates, &coords);
3566:   DMSetCoordinatesLocal(*dm, coordinates);
3567:   VecDestroy(&coordinates);
3568:   PetscViewerDestroy(&viewer);
3569:   if (interpolate) {
3570:     DM      idm;
3571:     DMLabel bdlabel;

3573:     DMPlexInterpolate(*dm, &idm);
3574:     DMDestroy(dm);
3575:     *dm  = idm;

3577:     DMGetLabel(*dm, "marker", &bdlabel);
3578:     DMPlexMarkBoundaryFaces(*dm, PETSC_DETERMINE, bdlabel);
3579:     DMPlexLabelComplete(*dm, bdlabel);
3580:   }
3581:   return(0);
3582: }

3584: /*@C
3585:   DMPlexCreateFromFile - This takes a filename and produces a DM

3587:   Input Parameters:
3588: + comm - The communicator
3589: . filename - A file name
3590: - interpolate - Flag to create intermediate mesh pieces (edges, faces)

3592:   Output Parameter:
3593: . dm - The DM

3595:   Options Database Keys:
3596: . -dm_plex_create_from_hdf5_xdmf - use the PETSC_VIEWER_HDF5_XDMF format for reading HDF5

3598:   Use -dm_plex_create_ prefix to pass options to the internal PetscViewer, e.g.
3599: $ -dm_plex_create_viewer_hdf5_collective

3601:   Level: beginner

3603: .seealso: DMPlexCreateFromDAG(), DMPlexCreateFromCellListPetsc(), DMPlexCreate()
3604: @*/
3605: PetscErrorCode DMPlexCreateFromFile(MPI_Comm comm, const char filename[], PetscBool interpolate, DM *dm)
3606: {
3607:   const char    *extGmsh    = ".msh";
3608:   const char    *extGmsh2   = ".msh2";
3609:   const char    *extGmsh4   = ".msh4";
3610:   const char    *extCGNS    = ".cgns";
3611:   const char    *extExodus  = ".exo";
3612:   const char    *extGenesis = ".gen";
3613:   const char    *extFluent  = ".cas";
3614:   const char    *extHDF5    = ".h5";
3615:   const char    *extMed     = ".med";
3616:   const char    *extPLY     = ".ply";
3617:   const char    *extCV      = ".dat";
3618:   size_t         len;
3619:   PetscBool      isGmsh, isGmsh2, isGmsh4, isCGNS, isExodus, isGenesis, isFluent, isHDF5, isMed, isPLY, isCV;
3620:   PetscMPIInt    rank;

3626:   DMInitializePackage();
3627:   PetscLogEventBegin(DMPLEX_CreateFromFile,0,0,0,0);
3628:   MPI_Comm_rank(comm, &rank);
3629:   PetscStrlen(filename, &len);
3630:   if (!len) SETERRQ(comm, PETSC_ERR_ARG_WRONG, "Filename must be a valid path");
3631:   PetscStrncmp(&filename[PetscMax(0,len-4)], extGmsh,    4, &isGmsh);
3632:   PetscStrncmp(&filename[PetscMax(0,len-5)], extGmsh2,   5, &isGmsh2);
3633:   PetscStrncmp(&filename[PetscMax(0,len-5)], extGmsh4,   5, &isGmsh4);
3634:   PetscStrncmp(&filename[PetscMax(0,len-5)], extCGNS,    5, &isCGNS);
3635:   PetscStrncmp(&filename[PetscMax(0,len-4)], extExodus,  4, &isExodus);
3636:   PetscStrncmp(&filename[PetscMax(0,len-4)], extGenesis, 4, &isGenesis);
3637:   PetscStrncmp(&filename[PetscMax(0,len-4)], extFluent,  4, &isFluent);
3638:   PetscStrncmp(&filename[PetscMax(0,len-3)], extHDF5,    3, &isHDF5);
3639:   PetscStrncmp(&filename[PetscMax(0,len-4)], extMed,     4, &isMed);
3640:   PetscStrncmp(&filename[PetscMax(0,len-4)], extPLY,     4, &isPLY);
3641:   PetscStrncmp(&filename[PetscMax(0,len-4)], extCV,      4, &isCV);
3642:   if (isGmsh || isGmsh2 || isGmsh4) {
3643:     DMPlexCreateGmshFromFile(comm, filename, interpolate, dm);
3644:   } else if (isCGNS) {
3645:     DMPlexCreateCGNSFromFile(comm, filename, interpolate, dm);
3646:   } else if (isExodus || isGenesis) {
3647:     DMPlexCreateExodusFromFile(comm, filename, interpolate, dm);
3648:   } else if (isFluent) {
3649:     DMPlexCreateFluentFromFile(comm, filename, interpolate, dm);
3650:   } else if (isHDF5) {
3651:     PetscBool      load_hdf5_xdmf = PETSC_FALSE;
3652:     PetscViewer viewer;

3654:     /* PETSC_VIEWER_HDF5_XDMF is used if the filename ends with .xdmf.h5, or if -dm_plex_create_from_hdf5_xdmf option is present */
3655:     PetscStrncmp(&filename[PetscMax(0,len-8)], ".xdmf",  5, &load_hdf5_xdmf);
3656:     PetscOptionsGetBool(NULL, NULL, "-dm_plex_create_from_hdf5_xdmf", &load_hdf5_xdmf, NULL);
3657:     PetscViewerCreate(comm, &viewer);
3658:     PetscViewerSetType(viewer, PETSCVIEWERHDF5);
3659:     PetscViewerSetOptionsPrefix(viewer, "dm_plex_create_");
3660:     PetscViewerSetFromOptions(viewer);
3661:     PetscViewerFileSetMode(viewer, FILE_MODE_READ);
3662:     PetscViewerFileSetName(viewer, filename);
3663:     DMCreate(comm, dm);
3664:     DMSetType(*dm, DMPLEX);
3665:     if (load_hdf5_xdmf) {PetscViewerPushFormat(viewer, PETSC_VIEWER_HDF5_XDMF);}
3666:     DMLoad(*dm, viewer);
3667:     if (load_hdf5_xdmf) {PetscViewerPopFormat(viewer);}
3668:     PetscViewerDestroy(&viewer);

3670:     if (interpolate) {
3671:       DM idm;

3673:       DMPlexInterpolate(*dm, &idm);
3674:       DMDestroy(dm);
3675:       *dm  = idm;
3676:     }
3677:   } else if (isMed) {
3678:     DMPlexCreateMedFromFile(comm, filename, interpolate, dm);
3679:   } else if (isPLY) {
3680:     DMPlexCreatePLYFromFile(comm, filename, interpolate, dm);
3681:   } else if (isCV) {
3682:     DMPlexCreateCellVertexFromFile(comm, filename, interpolate, dm);
3683:   } else SETERRQ1(PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Cannot load file %s: unrecognized extension", filename);
3684:   PetscLogEventEnd(DMPLEX_CreateFromFile,0,0,0,0);
3685:   return(0);
3686: }

3688: /*@
3689:   DMPlexCreateReferenceCellByType - Create a DMPLEX with the appropriate FEM reference cell

3691:   Collective

3693:   Input Parameters:
3694: + comm - The communicator
3695: - ct   - The cell type of the reference cell

3697:   Output Parameter:
3698: . refdm - The reference cell

3700:   Level: intermediate

3702: .seealso: DMPlexCreateReferenceCell(), DMPlexCreateBoxMesh()
3703: @*/
3704: PetscErrorCode DMPlexCreateReferenceCellByType(MPI_Comm comm, DMPolytopeType ct, DM *refdm)
3705: {
3706:   DM             rdm;
3707:   Vec            coords;

3711:   DMCreate(comm, &rdm);
3712:   DMSetType(rdm, DMPLEX);
3713:   switch (ct) {
3714:     case DM_POLYTOPE_POINT:
3715:     {
3716:       PetscInt    numPoints[1]        = {1};
3717:       PetscInt    coneSize[1]         = {0};
3718:       PetscInt    cones[1]            = {0};
3719:       PetscInt    coneOrientations[1] = {0};
3720:       PetscScalar vertexCoords[1]     = {0.0};

3722:       DMSetDimension(rdm, 0);
3723:       DMPlexCreateFromDAG(rdm, 0, numPoints, coneSize, cones, coneOrientations, vertexCoords);
3724:     }
3725:     break;
3726:     case DM_POLYTOPE_SEGMENT:
3727:     {
3728:       PetscInt    numPoints[2]        = {2, 1};
3729:       PetscInt    coneSize[3]         = {2, 0, 0};
3730:       PetscInt    cones[2]            = {1, 2};
3731:       PetscInt    coneOrientations[2] = {0, 0};
3732:       PetscScalar vertexCoords[2]     = {-1.0,  1.0};

3734:       DMSetDimension(rdm, 1);
3735:       DMPlexCreateFromDAG(rdm, 1, numPoints, coneSize, cones, coneOrientations, vertexCoords);
3736:     }
3737:     break;
3738:     case DM_POLYTOPE_TRIANGLE:
3739:     {
3740:       PetscInt    numPoints[2]        = {3, 1};
3741:       PetscInt    coneSize[4]         = {3, 0, 0, 0};
3742:       PetscInt    cones[3]            = {1, 2, 3};
3743:       PetscInt    coneOrientations[3] = {0, 0, 0};
3744:       PetscScalar vertexCoords[6]     = {-1.0, -1.0,  1.0, -1.0,  -1.0, 1.0};

3746:       DMSetDimension(rdm, 2);
3747:       DMPlexCreateFromDAG(rdm, 1, numPoints, coneSize, cones, coneOrientations, vertexCoords);
3748:     }
3749:     break;
3750:     case DM_POLYTOPE_QUADRILATERAL:
3751:     {
3752:       PetscInt    numPoints[2]        = {4, 1};
3753:       PetscInt    coneSize[5]         = {4, 0, 0, 0, 0};
3754:       PetscInt    cones[4]            = {1, 2, 3, 4};
3755:       PetscInt    coneOrientations[4] = {0, 0, 0, 0};
3756:       PetscScalar vertexCoords[8]     = {-1.0, -1.0,  1.0, -1.0,  1.0, 1.0,  -1.0, 1.0};

3758:       DMSetDimension(rdm, 2);
3759:       DMPlexCreateFromDAG(rdm, 1, numPoints, coneSize, cones, coneOrientations, vertexCoords);
3760:     }
3761:     break;
3762:     case DM_POLYTOPE_SEG_PRISM_TENSOR:
3763:     {
3764:       PetscInt    numPoints[2]        = {4, 1};
3765:       PetscInt    coneSize[5]         = {4, 0, 0, 0, 0};
3766:       PetscInt    cones[4]            = {1, 2, 3, 4};
3767:       PetscInt    coneOrientations[4] = {0, 0, 0, 0};
3768:       PetscScalar vertexCoords[8]     = {-1.0, -1.0,  1.0, -1.0,  -1.0, 1.0,  1.0, 1.0};

3770:       DMSetDimension(rdm, 2);
3771:       DMPlexCreateFromDAG(rdm, 1, numPoints, coneSize, cones, coneOrientations, vertexCoords);
3772:     }
3773:     break;
3774:     case DM_POLYTOPE_TETRAHEDRON:
3775:     {
3776:       PetscInt    numPoints[2]        = {4, 1};
3777:       PetscInt    coneSize[5]         = {4, 0, 0, 0, 0};
3778:       PetscInt    cones[4]            = {1, 3, 2, 4};
3779:       PetscInt    coneOrientations[4] = {0, 0, 0, 0};
3780:       PetscScalar vertexCoords[12]    = {-1.0, -1.0, -1.0,  1.0, -1.0, -1.0,  -1.0, 1.0, -1.0,  -1.0, -1.0, 1.0};

3782:       DMSetDimension(rdm, 3);
3783:       DMPlexCreateFromDAG(rdm, 1, numPoints, coneSize, cones, coneOrientations, vertexCoords);
3784:     }
3785:     break;
3786:     case DM_POLYTOPE_HEXAHEDRON:
3787:     {
3788:       PetscInt    numPoints[2]        = {8, 1};
3789:       PetscInt    coneSize[9]         = {8, 0, 0, 0, 0, 0, 0, 0, 0};
3790:       PetscInt    cones[8]            = {1, 4, 3, 2, 5, 6, 7, 8};
3791:       PetscInt    coneOrientations[8] = {0, 0, 0, 0, 0, 0, 0, 0};
3792:       PetscScalar vertexCoords[24]    = {-1.0, -1.0, -1.0,  1.0, -1.0, -1.0,  1.0, 1.0, -1.0,  -1.0, 1.0, -1.0,
3793:                                          -1.0, -1.0,  1.0,  1.0, -1.0,  1.0,  1.0, 1.0,  1.0,  -1.0, 1.0,  1.0};

3795:       DMSetDimension(rdm, 3);
3796:       DMPlexCreateFromDAG(rdm, 1, numPoints, coneSize, cones, coneOrientations, vertexCoords);
3797:     }
3798:     break;
3799:     case DM_POLYTOPE_TRI_PRISM:
3800:     {
3801:       PetscInt    numPoints[2]        = {6, 1};
3802:       PetscInt    coneSize[7]         = {6, 0, 0, 0, 0, 0, 0};
3803:       PetscInt    cones[6]            = {1, 3, 2, 4, 5, 6};
3804:       PetscInt    coneOrientations[6] = {0, 0, 0, 0, 0, 0};
3805:       PetscScalar vertexCoords[18]    = {-1.0, -1.0, -1.0,  1.0, -1.0, -1.0,  -1.0, 1.0, -1.0,
3806:                                          -1.0, -1.0,  1.0,  1.0, -1.0,  1.0,  -1.0, 1.0,  1.0};

3808:       DMSetDimension(rdm, 3);
3809:       DMPlexCreateFromDAG(rdm, 1, numPoints, coneSize, cones, coneOrientations, vertexCoords);
3810:     }
3811:     break;
3812:     case DM_POLYTOPE_TRI_PRISM_TENSOR:
3813:     {
3814:       PetscInt    numPoints[2]        = {6, 1};
3815:       PetscInt    coneSize[7]         = {6, 0, 0, 0, 0, 0, 0};
3816:       PetscInt    cones[6]            = {1, 2, 3, 4, 5, 6};
3817:       PetscInt    coneOrientations[6] = {0, 0, 0, 0, 0, 0};
3818:       PetscScalar vertexCoords[18]    = {-1.0, -1.0, -1.0,  1.0, -1.0, -1.0,  -1.0, 1.0, -1.0,
3819:                                          -1.0, -1.0,  1.0,  1.0, -1.0,  1.0,  -1.0, 1.0,  1.0};

3821:       DMSetDimension(rdm, 3);
3822:       DMPlexCreateFromDAG(rdm, 1, numPoints, coneSize, cones, coneOrientations, vertexCoords);
3823:     }
3824:     break;
3825:     case DM_POLYTOPE_QUAD_PRISM_TENSOR:
3826:     {
3827:       PetscInt    numPoints[2]        = {8, 1};
3828:       PetscInt    coneSize[9]         = {8, 0, 0, 0, 0, 0, 0, 0, 0};
3829:       PetscInt    cones[8]            = {1, 2, 3, 4, 5, 6, 7, 8};
3830:       PetscInt    coneOrientations[8] = {0, 0, 0, 0, 0, 0, 0, 0};
3831:       PetscScalar vertexCoords[24]    = {-1.0, -1.0, -1.0,  1.0, -1.0, -1.0,  1.0, 1.0, -1.0,  -1.0, 1.0, -1.0,
3832:                                          -1.0, -1.0,  1.0,  1.0, -1.0,  1.0,  1.0, 1.0,  1.0,  -1.0, 1.0,  1.0};

3834:       DMSetDimension(rdm, 3);
3835:       DMPlexCreateFromDAG(rdm, 1, numPoints, coneSize, cones, coneOrientations, vertexCoords);
3836:     }
3837:     break;
3838:     default: SETERRQ1(comm, PETSC_ERR_ARG_WRONG, "Cannot create reference cell for cell type %s", DMPolytopeTypes[ct]);
3839:   }
3840:   {
3841:     PetscInt Nv, v;

3843:     /* Must create the celltype label here so that we do not automatically try to compute the types */
3844:     DMCreateLabel(rdm, "celltype");
3845:     DMPlexSetCellType(rdm, 0, ct);
3846:     DMPlexGetChart(rdm, NULL, &Nv);
3847:     for (v = 1; v < Nv; ++v) {DMPlexSetCellType(rdm, v, DM_POLYTOPE_POINT);}
3848:   }
3849:   DMPlexInterpolate(rdm, refdm);
3850:   if (rdm->coordinateDM) {
3851:     DM           ncdm;
3852:     PetscSection cs;
3853:     PetscInt     pEnd = -1;

3855:     DMGetLocalSection(rdm->coordinateDM, &cs);
3856:     if (cs) {PetscSectionGetChart(cs, NULL, &pEnd);}
3857:     if (pEnd >= 0) {
3858:       DMClone(*refdm, &ncdm);
3859:       DMCopyDisc(rdm->coordinateDM, ncdm);
3860:       DMSetLocalSection(ncdm, cs);
3861:       DMSetCoordinateDM(*refdm, ncdm);
3862:       DMDestroy(&ncdm);
3863:     }
3864:   }
3865:   DMGetCoordinatesLocal(rdm, &coords);
3866:   if (coords) {
3867:     DMSetCoordinatesLocal(*refdm, coords);
3868:   } else {
3869:     DMGetCoordinates(rdm, &coords);
3870:     if (coords) {DMSetCoordinates(*refdm, coords);}
3871:   }
3872:   DMDestroy(&rdm);
3873:   return(0);
3874: }

3876: /*@
3877:   DMPlexCreateReferenceCell - Create a DMPLEX with the appropriate FEM reference cell

3879:   Collective

3881:   Input Parameters:
3882: + comm    - The communicator
3883: . dim     - The spatial dimension
3884: - simplex - Flag for simplex, otherwise use a tensor-product cell

3886:   Output Parameter:
3887: . refdm - The reference cell

3889:   Level: intermediate

3891: .seealso: DMPlexCreateReferenceCellByType(), DMPlexCreateBoxMesh()
3892: @*/
3893: PetscErrorCode DMPlexCreateReferenceCell(MPI_Comm comm, PetscInt dim, PetscBool simplex, DM *refdm)
3894: {

3898:   switch (dim) {
3899:   case 0: DMPlexCreateReferenceCellByType(comm, DM_POLYTOPE_POINT, refdm);break;
3900:   case 1: DMPlexCreateReferenceCellByType(comm, DM_POLYTOPE_SEGMENT, refdm);break;
3901:   case 2:
3902:     if (simplex) {DMPlexCreateReferenceCellByType(comm, DM_POLYTOPE_TRIANGLE, refdm);}
3903:     else         {DMPlexCreateReferenceCellByType(comm, DM_POLYTOPE_QUADRILATERAL, refdm);}
3904:     break;
3905:   case 3:
3906:     if (simplex) {DMPlexCreateReferenceCellByType(comm, DM_POLYTOPE_TETRAHEDRON, refdm);}
3907:     else         {DMPlexCreateReferenceCellByType(comm, DM_POLYTOPE_HEXAHEDRON, refdm);}
3908:     break;
3909:   default:
3910:     SETERRQ1(comm, PETSC_ERR_ARG_WRONG, "Cannot create reference cell for dimension %D", dim);
3911:   }
3912:   return(0);
3913: }