Actual source code: plex.c

  1: #include <petsc/private/dmpleximpl.h>
  2: #include <petsc/private/dmlabelimpl.h>
  3: #include <petsc/private/isimpl.h>
  4: #include <petsc/private/vecimpl.h>
  5: #include <petsc/private/glvisvecimpl.h>
  6: #include <petscsf.h>
  7: #include <petscds.h>
  8: #include <petscdraw.h>
  9: #include <petscdmfield.h>
 10: #include <petscdmplextransform.h>

 12: /* Logging support */
 13: PetscLogEvent DMPLEX_Interpolate, DMPLEX_Partition, DMPLEX_Distribute, DMPLEX_DistributeCones, DMPLEX_DistributeLabels, DMPLEX_DistributeSF, DMPLEX_DistributeOverlap, DMPLEX_DistributeField, DMPLEX_DistributeData, DMPLEX_Migrate, DMPLEX_InterpolateSF, DMPLEX_GlobalToNaturalBegin, DMPLEX_GlobalToNaturalEnd, DMPLEX_NaturalToGlobalBegin, DMPLEX_NaturalToGlobalEnd, DMPLEX_Stratify, DMPLEX_Symmetrize, DMPLEX_Preallocate, DMPLEX_ResidualFEM, DMPLEX_JacobianFEM, DMPLEX_InterpolatorFEM, DMPLEX_InjectorFEM, DMPLEX_IntegralFEM, DMPLEX_CreateGmsh, DMPLEX_RebalanceSharedPoints, DMPLEX_PartSelf, DMPLEX_PartLabelInvert, DMPLEX_PartLabelCreateSF, DMPLEX_PartStratSF, DMPLEX_CreatePointSF, DMPLEX_LocatePoints, DMPLEX_TopologyView, DMPLEX_LabelsView, DMPLEX_CoordinatesView, DMPLEX_SectionView, DMPLEX_GlobalVectorView, DMPLEX_LocalVectorView, DMPLEX_TopologyLoad, DMPLEX_LabelsLoad, DMPLEX_CoordinatesLoad, DMPLEX_SectionLoad, DMPLEX_GlobalVectorLoad, DMPLEX_LocalVectorLoad;
 14: PetscLogEvent DMPLEX_RebalBuildGraph, DMPLEX_RebalRewriteSF, DMPLEX_RebalGatherGraph, DMPLEX_RebalPartition, DMPLEX_RebalScatterPart;

 16: PETSC_EXTERN PetscErrorCode VecView_MPI(Vec, PetscViewer);

 18: /*@
 19:   DMPlexIsSimplex - Is the first cell in this mesh a simplex?

 21:   Input Parameter:
 22: . dm      - The DMPlex object

 24:   Output Parameter:
 25: . simplex - Flag checking for a simplex

 27:   Note: This just gives the first range of cells found. If the mesh has several cell types, it will only give the first.
 28:   If the mesh has no cells, this returns PETSC_FALSE.

 30:   Level: intermediate

 32: .seealso `DMPlexGetSimplexOrBoxCells()`, `DMPlexGetCellType()`, `DMPlexGetHeightStratum()`, `DMPolytopeTypeGetNumVertices()`
 33: @*/
 34: PetscErrorCode DMPlexIsSimplex(DM dm, PetscBool *simplex)
 35: {
 36:   DMPolytopeType ct;
 37:   PetscInt       cStart, cEnd;

 39:   DMPlexGetHeightStratum(dm, 0, &cStart, &cEnd);
 40:   if (cEnd <= cStart) {
 41:     *simplex = PETSC_FALSE;
 42:     return 0;
 43:   }
 44:   DMPlexGetCellType(dm, cStart, &ct);
 45:   *simplex = DMPolytopeTypeGetNumVertices(ct) == DMPolytopeTypeGetDim(ct) + 1 ? PETSC_TRUE : PETSC_FALSE;
 46:   return 0;
 47: }

 49: /*@
 50:   DMPlexGetSimplexOrBoxCells - Get the range of cells which are neither prisms nor ghost FV cells

 52:   Input Parameters:
 53: + dm     - The DMPlex object
 54: - height - The cell height in the Plex, 0 is the default

 56:   Output Parameters:
 57: + cStart - The first "normal" cell
 58: - cEnd   - The upper bound on "normal"" cells

 60:   Note: This just gives the first range of cells found. If the mesh has several cell types, it will only give the first.

 62:   Level: developer

 64: .seealso `DMPlexConstructGhostCells()`, `DMPlexGetGhostCellStratum()`
 65: @*/
 66: PetscErrorCode DMPlexGetSimplexOrBoxCells(DM dm, PetscInt height, PetscInt *cStart, PetscInt *cEnd)
 67: {
 68:   DMPolytopeType ct = DM_POLYTOPE_UNKNOWN;
 69:   PetscInt       cS, cE, c;

 71:   DMPlexGetHeightStratum(dm, PetscMax(height, 0), &cS, &cE);
 72:   for (c = cS; c < cE; ++c) {
 73:     DMPolytopeType cct;

 75:     DMPlexGetCellType(dm, c, &cct);
 76:     if ((PetscInt)cct < 0) break;
 77:     switch (cct) {
 78:     case DM_POLYTOPE_POINT:
 79:     case DM_POLYTOPE_SEGMENT:
 80:     case DM_POLYTOPE_TRIANGLE:
 81:     case DM_POLYTOPE_QUADRILATERAL:
 82:     case DM_POLYTOPE_TETRAHEDRON:
 83:     case DM_POLYTOPE_HEXAHEDRON:
 84:       ct = cct;
 85:       break;
 86:     default:
 87:       break;
 88:     }
 89:     if (ct != DM_POLYTOPE_UNKNOWN) break;
 90:   }
 91:   if (ct != DM_POLYTOPE_UNKNOWN) {
 92:     DMLabel ctLabel;

 94:     DMPlexGetCellTypeLabel(dm, &ctLabel);
 95:     DMLabelGetStratumBounds(ctLabel, ct, &cS, &cE);
 96:     // Reset label for fast lookup
 97:     DMLabelMakeAllInvalid_Internal(ctLabel);
 98:   }
 99:   if (cStart) *cStart = cS;
100:   if (cEnd) *cEnd = cE;
101:   return 0;
102: }

104: PetscErrorCode DMPlexGetFieldType_Internal(DM dm, PetscSection section, PetscInt field, PetscInt *sStart, PetscInt *sEnd, PetscViewerVTKFieldType *ft)
105: {
106:   PetscInt cdim, pStart, pEnd, vStart, vEnd, cStart, cEnd;
107:   PetscInt vcdof[2] = {0, 0}, globalvcdof[2];

109:   *ft = PETSC_VTK_INVALID;
110:   DMGetCoordinateDim(dm, &cdim);
111:   DMPlexGetDepthStratum(dm, 0, &vStart, &vEnd);
112:   DMPlexGetSimplexOrBoxCells(dm, 0, &cStart, &cEnd);
113:   PetscSectionGetChart(section, &pStart, &pEnd);
114:   if (field >= 0) {
115:     if ((vStart >= pStart) && (vStart < pEnd)) PetscSectionGetFieldDof(section, vStart, field, &vcdof[0]);
116:     if ((cStart >= pStart) && (cStart < pEnd)) PetscSectionGetFieldDof(section, cStart, field, &vcdof[1]);
117:   } else {
118:     if ((vStart >= pStart) && (vStart < pEnd)) PetscSectionGetDof(section, vStart, &vcdof[0]);
119:     if ((cStart >= pStart) && (cStart < pEnd)) PetscSectionGetDof(section, cStart, &vcdof[1]);
120:   }
121:   MPI_Allreduce(vcdof, globalvcdof, 2, MPIU_INT, MPI_MAX, PetscObjectComm((PetscObject)dm));
122:   if (globalvcdof[0]) {
123:     *sStart = vStart;
124:     *sEnd   = vEnd;
125:     if (globalvcdof[0] == cdim) *ft = PETSC_VTK_POINT_VECTOR_FIELD;
126:     else *ft = PETSC_VTK_POINT_FIELD;
127:   } else if (globalvcdof[1]) {
128:     *sStart = cStart;
129:     *sEnd   = cEnd;
130:     if (globalvcdof[1] == cdim) *ft = PETSC_VTK_CELL_VECTOR_FIELD;
131:     else *ft = PETSC_VTK_CELL_FIELD;
132:   } else {
133:     if (field >= 0) {
134:       const char *fieldname;

136:       PetscSectionGetFieldName(section, field, &fieldname);
137:       PetscInfo((PetscObject)dm, "Could not classify VTK output type of section field %" PetscInt_FMT " \"%s\"\n", field, fieldname);
138:     } else {
139:       PetscInfo((PetscObject)dm, "Could not classify VTK output type of section\n");
140:     }
141:   }
142:   return 0;
143: }

145: /*@
146:   DMPlexVecView1D - Plot many 1D solutions on the same line graph

148:   Collective on dm

150:   Input Parameters:
151: + dm - The DMPlex
152: . n  - The number of vectors
153: . u  - The array of local vectors
154: - viewer - The Draw viewer

156:   Level: advanced

158: .seealso: `VecViewFromOptions()`, `VecView()`
159: @*/
160: PetscErrorCode DMPlexVecView1D(DM dm, PetscInt n, Vec u[], PetscViewer viewer)
161: {
162:   PetscDS            ds;
163:   PetscDraw          draw = NULL;
164:   PetscDrawLG        lg;
165:   Vec                coordinates;
166:   const PetscScalar *coords, **sol;
167:   PetscReal         *vals;
168:   PetscInt          *Nc;
169:   PetscInt           Nf, f, c, Nl, l, i, vStart, vEnd, v;
170:   char             **names;

172:   DMGetDS(dm, &ds);
173:   PetscDSGetNumFields(ds, &Nf);
174:   PetscDSGetTotalComponents(ds, &Nl);
175:   PetscDSGetComponents(ds, &Nc);

177:   PetscViewerDrawGetDraw(viewer, 0, &draw);
178:   if (!draw) return 0;
179:   PetscDrawLGCreate(draw, n * Nl, &lg);

181:   PetscMalloc3(n, &sol, n * Nl, &names, n * Nl, &vals);
182:   for (i = 0, l = 0; i < n; ++i) {
183:     const char *vname;

185:     PetscObjectGetName((PetscObject)u[i], &vname);
186:     for (f = 0; f < Nf; ++f) {
187:       PetscObject disc;
188:       const char *fname;
189:       char        tmpname[PETSC_MAX_PATH_LEN];

191:       PetscDSGetDiscretization(ds, f, &disc);
192:       /* TODO Create names for components */
193:       for (c = 0; c < Nc[f]; ++c, ++l) {
194:         PetscObjectGetName(disc, &fname);
195:         PetscStrcpy(tmpname, vname);
196:         PetscStrlcat(tmpname, ":", PETSC_MAX_PATH_LEN);
197:         PetscStrlcat(tmpname, fname, PETSC_MAX_PATH_LEN);
198:         PetscStrallocpy(tmpname, &names[l]);
199:       }
200:     }
201:   }
202:   PetscDrawLGSetLegend(lg, (const char *const *)names);
203:   /* Just add P_1 support for now */
204:   DMPlexGetDepthStratum(dm, 0, &vStart, &vEnd);
205:   DMGetCoordinatesLocal(dm, &coordinates);
206:   VecGetArrayRead(coordinates, &coords);
207:   for (i = 0; i < n; ++i) VecGetArrayRead(u[i], &sol[i]);
208:   for (v = vStart; v < vEnd; ++v) {
209:     PetscScalar *x, *svals;

211:     DMPlexPointLocalRead(dm, v, coords, &x);
212:     for (i = 0; i < n; ++i) {
213:       DMPlexPointLocalRead(dm, v, sol[i], &svals);
214:       for (l = 0; l < Nl; ++l) vals[i * Nl + l] = PetscRealPart(svals[l]);
215:     }
216:     PetscDrawLGAddCommonPoint(lg, PetscRealPart(x[0]), vals);
217:   }
218:   VecRestoreArrayRead(coordinates, &coords);
219:   for (i = 0; i < n; ++i) VecRestoreArrayRead(u[i], &sol[i]);
220:   for (l = 0; l < n * Nl; ++l) PetscFree(names[l]);
221:   PetscFree3(sol, names, vals);

223:   PetscDrawLGDraw(lg);
224:   PetscDrawLGDestroy(&lg);
225:   return 0;
226: }

228: static PetscErrorCode VecView_Plex_Local_Draw_1D(Vec u, PetscViewer viewer)
229: {
230:   DM dm;

232:   VecGetDM(u, &dm);
233:   DMPlexVecView1D(dm, 1, &u, viewer);
234:   return 0;
235: }

237: static PetscErrorCode VecView_Plex_Local_Draw_2D(Vec v, PetscViewer viewer)
238: {
239:   DM                 dm;
240:   PetscSection       s;
241:   PetscDraw          draw, popup;
242:   DM                 cdm;
243:   PetscSection       coordSection;
244:   Vec                coordinates;
245:   const PetscScalar *coords, *array;
246:   PetscReal          bound[4] = {PETSC_MAX_REAL, PETSC_MAX_REAL, PETSC_MIN_REAL, PETSC_MIN_REAL};
247:   PetscReal          vbound[2], time;
248:   PetscBool          flg;
249:   PetscInt           dim, Nf, f, Nc, comp, vStart, vEnd, cStart, cEnd, c, N, level, step, w = 0;
250:   const char        *name;
251:   char               title[PETSC_MAX_PATH_LEN];

253:   PetscViewerDrawGetDraw(viewer, 0, &draw);
254:   VecGetDM(v, &dm);
255:   DMGetCoordinateDim(dm, &dim);
256:   DMGetLocalSection(dm, &s);
257:   PetscSectionGetNumFields(s, &Nf);
258:   DMGetCoarsenLevel(dm, &level);
259:   DMGetCoordinateDM(dm, &cdm);
260:   DMGetLocalSection(cdm, &coordSection);
261:   DMGetCoordinatesLocal(dm, &coordinates);
262:   DMPlexGetDepthStratum(dm, 0, &vStart, &vEnd);
263:   DMPlexGetHeightStratum(dm, 0, &cStart, &cEnd);

265:   PetscObjectGetName((PetscObject)v, &name);
266:   DMGetOutputSequenceNumber(dm, &step, &time);

268:   VecGetLocalSize(coordinates, &N);
269:   VecGetArrayRead(coordinates, &coords);
270:   for (c = 0; c < N; c += dim) {
271:     bound[0] = PetscMin(bound[0], PetscRealPart(coords[c]));
272:     bound[2] = PetscMax(bound[2], PetscRealPart(coords[c]));
273:     bound[1] = PetscMin(bound[1], PetscRealPart(coords[c + 1]));
274:     bound[3] = PetscMax(bound[3], PetscRealPart(coords[c + 1]));
275:   }
276:   VecRestoreArrayRead(coordinates, &coords);
277:   PetscDrawClear(draw);

279:   /* Could implement something like DMDASelectFields() */
280:   for (f = 0; f < Nf; ++f) {
281:     DM          fdm = dm;
282:     Vec         fv  = v;
283:     IS          fis;
284:     char        prefix[PETSC_MAX_PATH_LEN];
285:     const char *fname;

287:     PetscSectionGetFieldComponents(s, f, &Nc);
288:     PetscSectionGetFieldName(s, f, &fname);

290:     if (v->hdr.prefix) PetscStrncpy(prefix, v->hdr.prefix, sizeof(prefix));
291:     else prefix[0] = '\0';
292:     if (Nf > 1) {
293:       DMCreateSubDM(dm, 1, &f, &fis, &fdm);
294:       VecGetSubVector(v, fis, &fv);
295:       PetscStrlcat(prefix, fname, sizeof(prefix));
296:       PetscStrlcat(prefix, "_", sizeof(prefix));
297:     }
298:     for (comp = 0; comp < Nc; ++comp, ++w) {
299:       PetscInt nmax = 2;

301:       PetscViewerDrawGetDraw(viewer, w, &draw);
302:       if (Nc > 1) PetscSNPrintf(title, sizeof(title), "%s:%s_%" PetscInt_FMT " Step: %" PetscInt_FMT " Time: %.4g", name, fname, comp, step, (double)time);
303:       else PetscSNPrintf(title, sizeof(title), "%s:%s Step: %" PetscInt_FMT " Time: %.4g", name, fname, step, (double)time);
304:       PetscDrawSetTitle(draw, title);

306:       /* TODO Get max and min only for this component */
307:       PetscOptionsGetRealArray(NULL, prefix, "-vec_view_bounds", vbound, &nmax, &flg);
308:       if (!flg) {
309:         VecMin(fv, NULL, &vbound[0]);
310:         VecMax(fv, NULL, &vbound[1]);
311:         if (vbound[1] <= vbound[0]) vbound[1] = vbound[0] + 1.0;
312:       }
313:       PetscDrawGetPopup(draw, &popup);
314:       PetscDrawScalePopup(popup, vbound[0], vbound[1]);
315:       PetscDrawSetCoordinates(draw, bound[0], bound[1], bound[2], bound[3]);

317:       VecGetArrayRead(fv, &array);
318:       for (c = cStart; c < cEnd; ++c) {
319:         PetscScalar *coords = NULL, *a   = NULL;
320:         PetscInt     numCoords, color[4] = {-1, -1, -1, -1};

322:         DMPlexPointLocalRead(fdm, c, array, &a);
323:         if (a) {
324:           color[0] = PetscDrawRealToColor(PetscRealPart(a[comp]), vbound[0], vbound[1]);
325:           color[1] = color[2] = color[3] = color[0];
326:         } else {
327:           PetscScalar *vals = NULL;
328:           PetscInt     numVals, va;

330:           DMPlexVecGetClosure(fdm, NULL, fv, c, &numVals, &vals);
332:           switch (numVals / Nc) {
333:           case 3: /* P1 Triangle */
334:           case 4: /* P1 Quadrangle */
335:             for (va = 0; va < numVals / Nc; ++va) color[va] = PetscDrawRealToColor(PetscRealPart(vals[va * Nc + comp]), vbound[0], vbound[1]);
336:             break;
337:           case 6: /* P2 Triangle */
338:           case 8: /* P2 Quadrangle */
339:             for (va = 0; va < numVals / (Nc * 2); ++va) color[va] = PetscDrawRealToColor(PetscRealPart(vals[va * Nc + comp + numVals / (Nc * 2)]), vbound[0], vbound[1]);
340:             break;
341:           default:
342:             SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Number of values for cell closure %" PetscInt_FMT " cannot be handled", numVals / Nc);
343:           }
344:           DMPlexVecRestoreClosure(fdm, NULL, fv, c, &numVals, &vals);
345:         }
346:         DMPlexVecGetClosure(dm, coordSection, coordinates, c, &numCoords, &coords);
347:         switch (numCoords) {
348:         case 6:
349:         case 12: /* Localized triangle */
350:           PetscDrawTriangle(draw, PetscRealPart(coords[0]), PetscRealPart(coords[1]), PetscRealPart(coords[2]), PetscRealPart(coords[3]), PetscRealPart(coords[4]), PetscRealPart(coords[5]), color[0], color[1], color[2]);
351:           break;
352:         case 8:
353:         case 16: /* Localized quadrilateral */
354:           PetscDrawTriangle(draw, PetscRealPart(coords[0]), PetscRealPart(coords[1]), PetscRealPart(coords[2]), PetscRealPart(coords[3]), PetscRealPart(coords[4]), PetscRealPart(coords[5]), color[0], color[1], color[2]);
355:           PetscDrawTriangle(draw, PetscRealPart(coords[4]), PetscRealPart(coords[5]), PetscRealPart(coords[6]), PetscRealPart(coords[7]), PetscRealPart(coords[0]), PetscRealPart(coords[1]), color[2], color[3], color[0]);
356:           break;
357:         default:
358:           SETERRQ(PETSC_COMM_SELF, PETSC_ERR_SUP, "Cannot draw cells with %" PetscInt_FMT " coordinates", numCoords);
359:         }
360:         DMPlexVecRestoreClosure(dm, coordSection, coordinates, c, &numCoords, &coords);
361:       }
362:       VecRestoreArrayRead(fv, &array);
363:       PetscDrawFlush(draw);
364:       PetscDrawPause(draw);
365:       PetscDrawSave(draw);
366:     }
367:     if (Nf > 1) {
368:       VecRestoreSubVector(v, fis, &fv);
369:       ISDestroy(&fis);
370:       DMDestroy(&fdm);
371:     }
372:   }
373:   return 0;
374: }

376: static PetscErrorCode VecView_Plex_Local_Draw(Vec v, PetscViewer viewer)
377: {
378:   DM        dm;
379:   PetscDraw draw;
380:   PetscInt  dim;
381:   PetscBool isnull;

383:   PetscViewerDrawGetDraw(viewer, 0, &draw);
384:   PetscDrawIsNull(draw, &isnull);
385:   if (isnull) return 0;

387:   VecGetDM(v, &dm);
388:   DMGetCoordinateDim(dm, &dim);
389:   switch (dim) {
390:   case 1:
391:     VecView_Plex_Local_Draw_1D(v, viewer);
392:     break;
393:   case 2:
394:     VecView_Plex_Local_Draw_2D(v, viewer);
395:     break;
396:   default:
397:     SETERRQ(PetscObjectComm((PetscObject)v), PETSC_ERR_SUP, "Cannot draw meshes of dimension %" PetscInt_FMT ". Try PETSCVIEWERGLVIS", dim);
398:   }
399:   return 0;
400: }

402: static PetscErrorCode VecView_Plex_Local_VTK(Vec v, PetscViewer viewer)
403: {
404:   DM                      dm;
405:   Vec                     locv;
406:   const char             *name;
407:   PetscSection            section;
408:   PetscInt                pStart, pEnd;
409:   PetscInt                numFields;
410:   PetscViewerVTKFieldType ft;

412:   VecGetDM(v, &dm);
413:   DMCreateLocalVector(dm, &locv); /* VTK viewer requires exclusive ownership of the vector */
414:   PetscObjectGetName((PetscObject)v, &name);
415:   PetscObjectSetName((PetscObject)locv, name);
416:   VecCopy(v, locv);
417:   DMGetLocalSection(dm, &section);
418:   PetscSectionGetNumFields(section, &numFields);
419:   if (!numFields) {
420:     DMPlexGetFieldType_Internal(dm, section, PETSC_DETERMINE, &pStart, &pEnd, &ft);
421:     PetscViewerVTKAddField(viewer, (PetscObject)dm, DMPlexVTKWriteAll, PETSC_DEFAULT, ft, PETSC_TRUE, (PetscObject)locv);
422:   } else {
423:     PetscInt f;

425:     for (f = 0; f < numFields; f++) {
426:       DMPlexGetFieldType_Internal(dm, section, f, &pStart, &pEnd, &ft);
427:       if (ft == PETSC_VTK_INVALID) continue;
428:       PetscObjectReference((PetscObject)locv);
429:       PetscViewerVTKAddField(viewer, (PetscObject)dm, DMPlexVTKWriteAll, f, ft, PETSC_TRUE, (PetscObject)locv);
430:     }
431:     VecDestroy(&locv);
432:   }
433:   return 0;
434: }

436: PetscErrorCode VecView_Plex_Local(Vec v, PetscViewer viewer)
437: {
438:   DM        dm;
439:   PetscBool isvtk, ishdf5, isdraw, isglvis, iscgns;

441:   VecGetDM(v, &dm);
443:   PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERVTK, &isvtk);
444:   PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERHDF5, &ishdf5);
445:   PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERDRAW, &isdraw);
446:   PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERGLVIS, &isglvis);
447:   PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERCGNS, &iscgns);
448:   if (isvtk || ishdf5 || isdraw || isglvis || iscgns) {
449:     PetscInt    i, numFields;
450:     PetscObject fe;
451:     PetscBool   fem  = PETSC_FALSE;
452:     Vec         locv = v;
453:     const char *name;
454:     PetscInt    step;
455:     PetscReal   time;

457:     DMGetNumFields(dm, &numFields);
458:     for (i = 0; i < numFields; i++) {
459:       DMGetField(dm, i, NULL, &fe);
460:       if (fe->classid == PETSCFE_CLASSID) {
461:         fem = PETSC_TRUE;
462:         break;
463:       }
464:     }
465:     if (fem) {
466:       PetscObject isZero;

468:       DMGetLocalVector(dm, &locv);
469:       PetscObjectGetName((PetscObject)v, &name);
470:       PetscObjectSetName((PetscObject)locv, name);
471:       PetscObjectQuery((PetscObject)v, "__Vec_bc_zero__", &isZero);
472:       PetscObjectCompose((PetscObject)locv, "__Vec_bc_zero__", isZero);
473:       VecCopy(v, locv);
474:       DMGetOutputSequenceNumber(dm, NULL, &time);
475:       DMPlexInsertBoundaryValues(dm, PETSC_TRUE, locv, time, NULL, NULL, NULL);
476:     }
477:     if (isvtk) {
478:       VecView_Plex_Local_VTK(locv, viewer);
479:     } else if (ishdf5) {
480: #if defined(PETSC_HAVE_HDF5)
481:       VecView_Plex_Local_HDF5_Internal(locv, viewer);
482: #else
483:       SETERRQ(PetscObjectComm((PetscObject)dm), PETSC_ERR_SUP, "HDF5 not supported in this build.\nPlease reconfigure using --download-hdf5");
484: #endif
485:     } else if (isdraw) {
486:       VecView_Plex_Local_Draw(locv, viewer);
487:     } else if (isglvis) {
488:       DMGetOutputSequenceNumber(dm, &step, NULL);
489:       PetscViewerGLVisSetSnapId(viewer, step);
490:       VecView_GLVis(locv, viewer);
491:     } else if (iscgns) {
492: #if defined(PETSC_HAVE_CGNS)
493:       VecView_Plex_Local_CGNS(locv, viewer);
494: #else
495:       SETERRQ(PetscObjectComm((PetscObject)dm), PETSC_ERR_SUP, "CGNS not supported in this build.\nPlease reconfigure using --download-cgns");
496: #endif
497:     }
498:     if (fem) {
499:       PetscObjectCompose((PetscObject)locv, "__Vec_bc_zero__", NULL);
500:       DMRestoreLocalVector(dm, &locv);
501:     }
502:   } else {
503:     PetscBool isseq;

505:     PetscObjectTypeCompare((PetscObject)v, VECSEQ, &isseq);
506:     if (isseq) VecView_Seq(v, viewer);
507:     else VecView_MPI(v, viewer);
508:   }
509:   return 0;
510: }

512: PetscErrorCode VecView_Plex(Vec v, PetscViewer viewer)
513: {
514:   DM        dm;
515:   PetscBool isvtk, ishdf5, isdraw, isglvis, isexodusii, iscgns;

517:   VecGetDM(v, &dm);
519:   PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERVTK, &isvtk);
520:   PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERHDF5, &ishdf5);
521:   PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERDRAW, &isdraw);
522:   PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERGLVIS, &isglvis);
523:   PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERCGNS, &iscgns);
524:   PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWEREXODUSII, &isexodusii);
525:   if (isvtk || isdraw || isglvis || iscgns) {
526:     Vec         locv;
527:     PetscObject isZero;
528:     const char *name;

530:     DMGetLocalVector(dm, &locv);
531:     PetscObjectGetName((PetscObject)v, &name);
532:     PetscObjectSetName((PetscObject)locv, name);
533:     DMGlobalToLocalBegin(dm, v, INSERT_VALUES, locv);
534:     DMGlobalToLocalEnd(dm, v, INSERT_VALUES, locv);
535:     PetscObjectQuery((PetscObject)v, "__Vec_bc_zero__", &isZero);
536:     PetscObjectCompose((PetscObject)locv, "__Vec_bc_zero__", isZero);
537:     VecView_Plex_Local(locv, viewer);
538:     PetscObjectCompose((PetscObject)locv, "__Vec_bc_zero__", NULL);
539:     DMRestoreLocalVector(dm, &locv);
540:   } else if (ishdf5) {
541: #if defined(PETSC_HAVE_HDF5)
542:     VecView_Plex_HDF5_Internal(v, viewer);
543: #else
544:     SETERRQ(PetscObjectComm((PetscObject)dm), PETSC_ERR_SUP, "HDF5 not supported in this build.\nPlease reconfigure using --download-hdf5");
545: #endif
546:   } else if (isexodusii) {
547: #if defined(PETSC_HAVE_EXODUSII)
548:     VecView_PlexExodusII_Internal(v, viewer);
549: #else
550:     SETERRQ(PetscObjectComm((PetscObject)dm), PETSC_ERR_SUP, "ExodusII not supported in this build.\nPlease reconfigure using --download-exodusii");
551: #endif
552:   } else {
553:     PetscBool isseq;

555:     PetscObjectTypeCompare((PetscObject)v, VECSEQ, &isseq);
556:     if (isseq) VecView_Seq(v, viewer);
557:     else VecView_MPI(v, viewer);
558:   }
559:   return 0;
560: }

562: PetscErrorCode VecView_Plex_Native(Vec originalv, PetscViewer viewer)
563: {
564:   DM                dm;
565:   MPI_Comm          comm;
566:   PetscViewerFormat format;
567:   Vec               v;
568:   PetscBool         isvtk, ishdf5;

570:   VecGetDM(originalv, &dm);
571:   PetscObjectGetComm((PetscObject)originalv, &comm);
573:   PetscViewerGetFormat(viewer, &format);
574:   PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERHDF5, &ishdf5);
575:   PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERVTK, &isvtk);
576:   if (format == PETSC_VIEWER_NATIVE) {
577:     /* Natural ordering is the common case for DMDA, NATIVE means plain vector, for PLEX is the opposite */
578:     /* this need a better fix */
579:     if (dm->useNatural) {
580:       if (dm->sfNatural) {
581:         const char *vecname;
582:         PetscInt    n, nroots;

584:         VecGetLocalSize(originalv, &n);
585:         PetscSFGetGraph(dm->sfNatural, &nroots, NULL, NULL, NULL);
586:         if (n == nroots) {
587:           DMGetGlobalVector(dm, &v);
588:           DMPlexGlobalToNaturalBegin(dm, originalv, v);
589:           DMPlexGlobalToNaturalEnd(dm, originalv, v);
590:           PetscObjectGetName((PetscObject)originalv, &vecname);
591:           PetscObjectSetName((PetscObject)v, vecname);
592:         } else SETERRQ(comm, PETSC_ERR_ARG_WRONG, "DM global to natural SF only handles global vectors");
593:       } else SETERRQ(comm, PETSC_ERR_ARG_WRONGSTATE, "DM global to natural SF was not created");
594:     } else v = originalv;
595:   } else v = originalv;

597:   if (ishdf5) {
598: #if defined(PETSC_HAVE_HDF5)
599:     VecView_Plex_HDF5_Native_Internal(v, viewer);
600: #else
601:     SETERRQ(comm, PETSC_ERR_SUP, "HDF5 not supported in this build.\nPlease reconfigure using --download-hdf5");
602: #endif
603:   } else if (isvtk) {
604:     SETERRQ(comm, PETSC_ERR_SUP, "VTK format does not support viewing in natural order. Please switch to HDF5.");
605:   } else {
606:     PetscBool isseq;

608:     PetscObjectTypeCompare((PetscObject)v, VECSEQ, &isseq);
609:     if (isseq) VecView_Seq(v, viewer);
610:     else VecView_MPI(v, viewer);
611:   }
612:   if (v != originalv) DMRestoreGlobalVector(dm, &v);
613:   return 0;
614: }

616: PetscErrorCode VecLoad_Plex_Local(Vec v, PetscViewer viewer)
617: {
618:   DM        dm;
619:   PetscBool ishdf5;

621:   VecGetDM(v, &dm);
623:   PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERHDF5, &ishdf5);
624:   if (ishdf5) {
625:     DM          dmBC;
626:     Vec         gv;
627:     const char *name;

629:     DMGetOutputDM(dm, &dmBC);
630:     DMGetGlobalVector(dmBC, &gv);
631:     PetscObjectGetName((PetscObject)v, &name);
632:     PetscObjectSetName((PetscObject)gv, name);
633:     VecLoad_Default(gv, viewer);
634:     DMGlobalToLocalBegin(dmBC, gv, INSERT_VALUES, v);
635:     DMGlobalToLocalEnd(dmBC, gv, INSERT_VALUES, v);
636:     DMRestoreGlobalVector(dmBC, &gv);
637:   } else VecLoad_Default(v, viewer);
638:   return 0;
639: }

641: PetscErrorCode VecLoad_Plex(Vec v, PetscViewer viewer)
642: {
643:   DM        dm;
644:   PetscBool ishdf5, isexodusii;

646:   VecGetDM(v, &dm);
648:   PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERHDF5, &ishdf5);
649:   PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWEREXODUSII, &isexodusii);
650:   if (ishdf5) {
651: #if defined(PETSC_HAVE_HDF5)
652:     VecLoad_Plex_HDF5_Internal(v, viewer);
653: #else
654:     SETERRQ(PetscObjectComm((PetscObject)dm), PETSC_ERR_SUP, "HDF5 not supported in this build.\nPlease reconfigure using --download-hdf5");
655: #endif
656:   } else if (isexodusii) {
657: #if defined(PETSC_HAVE_EXODUSII)
658:     VecLoad_PlexExodusII_Internal(v, viewer);
659: #else
660:     SETERRQ(PetscObjectComm((PetscObject)dm), PETSC_ERR_SUP, "ExodusII not supported in this build.\nPlease reconfigure using --download-exodusii");
661: #endif
662:   } else VecLoad_Default(v, viewer);
663:   return 0;
664: }

666: PetscErrorCode VecLoad_Plex_Native(Vec originalv, PetscViewer viewer)
667: {
668:   DM                dm;
669:   PetscViewerFormat format;
670:   PetscBool         ishdf5;

672:   VecGetDM(originalv, &dm);
674:   PetscViewerGetFormat(viewer, &format);
675:   PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERHDF5, &ishdf5);
676:   if (format == PETSC_VIEWER_NATIVE) {
677:     if (dm->useNatural) {
678:       if (dm->sfNatural) {
679:         if (ishdf5) {
680: #if defined(PETSC_HAVE_HDF5)
681:           Vec         v;
682:           const char *vecname;

684:           DMGetGlobalVector(dm, &v);
685:           PetscObjectGetName((PetscObject)originalv, &vecname);
686:           PetscObjectSetName((PetscObject)v, vecname);
687:           VecLoad_Plex_HDF5_Native_Internal(v, viewer);
688:           DMPlexNaturalToGlobalBegin(dm, v, originalv);
689:           DMPlexNaturalToGlobalEnd(dm, v, originalv);
690:           DMRestoreGlobalVector(dm, &v);
691: #else
692:           SETERRQ(PetscObjectComm((PetscObject)dm), PETSC_ERR_SUP, "HDF5 not supported in this build.\nPlease reconfigure using --download-hdf5");
693: #endif
694:         } else SETERRQ(PetscObjectComm((PetscObject)dm), PETSC_ERR_SUP, "Reading in natural order is not supported for anything but HDF5.");
695:       }
696:     } else VecLoad_Default(originalv, viewer);
697:   }
698:   return 0;
699: }

701: PETSC_UNUSED static PetscErrorCode DMPlexView_Ascii_Geometry(DM dm, PetscViewer viewer)
702: {
703:   PetscSection       coordSection;
704:   Vec                coordinates;
705:   DMLabel            depthLabel, celltypeLabel;
706:   const char        *name[4];
707:   const PetscScalar *a;
708:   PetscInt           dim, pStart, pEnd, cStart, cEnd, c;

710:   DMGetDimension(dm, &dim);
711:   DMGetCoordinatesLocal(dm, &coordinates);
712:   DMGetCoordinateSection(dm, &coordSection);
713:   DMPlexGetDepthLabel(dm, &depthLabel);
714:   DMPlexGetCellTypeLabel(dm, &celltypeLabel);
715:   DMPlexGetHeightStratum(dm, 0, &cStart, &cEnd);
716:   PetscSectionGetChart(coordSection, &pStart, &pEnd);
717:   VecGetArrayRead(coordinates, &a);
718:   name[0]       = "vertex";
719:   name[1]       = "edge";
720:   name[dim - 1] = "face";
721:   name[dim]     = "cell";
722:   for (c = cStart; c < cEnd; ++c) {
723:     PetscInt *closure = NULL;
724:     PetscInt  closureSize, cl, ct;

726:     DMLabelGetValue(celltypeLabel, c, &ct);
727:     PetscViewerASCIIPrintf(viewer, "Geometry for cell %" PetscInt_FMT " polytope type %s:\n", c, DMPolytopeTypes[ct]);
728:     DMPlexGetTransitiveClosure(dm, c, PETSC_TRUE, &closureSize, &closure);
729:     PetscViewerASCIIPushTab(viewer);
730:     for (cl = 0; cl < closureSize * 2; cl += 2) {
731:       PetscInt point = closure[cl], depth, dof, off, d, p;

733:       if ((point < pStart) || (point >= pEnd)) continue;
734:       PetscSectionGetDof(coordSection, point, &dof);
735:       if (!dof) continue;
736:       DMLabelGetValue(depthLabel, point, &depth);
737:       PetscSectionGetOffset(coordSection, point, &off);
738:       PetscViewerASCIIPrintf(viewer, "%s %" PetscInt_FMT " coords:", name[depth], point);
739:       for (p = 0; p < dof / dim; ++p) {
740:         PetscViewerASCIIPrintf(viewer, " (");
741:         for (d = 0; d < dim; ++d) {
742:           if (d > 0) PetscViewerASCIIPrintf(viewer, ", ");
743:           PetscViewerASCIIPrintf(viewer, "%g", (double)PetscRealPart(a[off + p * dim + d]));
744:         }
745:         PetscViewerASCIIPrintf(viewer, ")");
746:       }
747:       PetscViewerASCIIPrintf(viewer, "\n");
748:     }
749:     DMPlexRestoreTransitiveClosure(dm, c, PETSC_TRUE, &closureSize, &closure);
750:     PetscViewerASCIIPopTab(viewer);
751:   }
752:   VecRestoreArrayRead(coordinates, &a);
753:   return 0;
754: }

756: typedef enum {
757:   CS_CARTESIAN,
758:   CS_POLAR,
759:   CS_CYLINDRICAL,
760:   CS_SPHERICAL
761: } CoordSystem;
762: const char *CoordSystems[] = {"cartesian", "polar", "cylindrical", "spherical", "CoordSystem", "CS_", NULL};

764: static PetscErrorCode DMPlexView_Ascii_Coordinates(PetscViewer viewer, CoordSystem cs, PetscInt dim, const PetscScalar x[])
765: {
766:   PetscInt i;

768:   if (dim > 3) {
769:     for (i = 0; i < dim; ++i) PetscViewerASCIISynchronizedPrintf(viewer, " %g", (double)PetscRealPart(x[i]));
770:   } else {
771:     PetscReal coords[3], trcoords[3] = {0., 0., 0.};

773:     for (i = 0; i < dim; ++i) coords[i] = PetscRealPart(x[i]);
774:     switch (cs) {
775:     case CS_CARTESIAN:
776:       for (i = 0; i < dim; ++i) trcoords[i] = coords[i];
777:       break;
778:     case CS_POLAR:
780:       trcoords[0] = PetscSqrtReal(PetscSqr(coords[0]) + PetscSqr(coords[1]));
781:       trcoords[1] = PetscAtan2Real(coords[1], coords[0]);
782:       break;
783:     case CS_CYLINDRICAL:
785:       trcoords[0] = PetscSqrtReal(PetscSqr(coords[0]) + PetscSqr(coords[1]));
786:       trcoords[1] = PetscAtan2Real(coords[1], coords[0]);
787:       trcoords[2] = coords[2];
788:       break;
789:     case CS_SPHERICAL:
791:       trcoords[0] = PetscSqrtReal(PetscSqr(coords[0]) + PetscSqr(coords[1]) + PetscSqr(coords[2]));
792:       trcoords[1] = PetscAtan2Real(PetscSqrtReal(PetscSqr(coords[0]) + PetscSqr(coords[1])), coords[2]);
793:       trcoords[2] = PetscAtan2Real(coords[1], coords[0]);
794:       break;
795:     }
796:     for (i = 0; i < dim; ++i) PetscViewerASCIISynchronizedPrintf(viewer, " %g", (double)trcoords[i]);
797:   }
798:   return 0;
799: }

801: static PetscErrorCode DMPlexView_Ascii(DM dm, PetscViewer viewer)
802: {
803:   DM_Plex          *mesh = (DM_Plex *)dm->data;
804:   DM                cdm, cdmCell;
805:   PetscSection      coordSection, coordSectionCell;
806:   Vec               coordinates, coordinatesCell;
807:   PetscViewerFormat format;

809:   DMGetCoordinateDM(dm, &cdm);
810:   DMGetCoordinateSection(dm, &coordSection);
811:   DMGetCoordinatesLocal(dm, &coordinates);
812:   DMGetCellCoordinateDM(dm, &cdmCell);
813:   DMGetCellCoordinateSection(dm, &coordSectionCell);
814:   DMGetCellCoordinatesLocal(dm, &coordinatesCell);
815:   PetscViewerGetFormat(viewer, &format);
816:   if (format == PETSC_VIEWER_ASCII_INFO_DETAIL) {
817:     const char *name;
818:     PetscInt    dim, cellHeight, maxConeSize, maxSupportSize;
819:     PetscInt    pStart, pEnd, p, numLabels, l;
820:     PetscMPIInt rank, size;

822:     MPI_Comm_rank(PetscObjectComm((PetscObject)dm), &rank);
823:     MPI_Comm_size(PetscObjectComm((PetscObject)dm), &size);
824:     PetscObjectGetName((PetscObject)dm, &name);
825:     DMPlexGetChart(dm, &pStart, &pEnd);
826:     DMPlexGetMaxSizes(dm, &maxConeSize, &maxSupportSize);
827:     DMGetDimension(dm, &dim);
828:     DMPlexGetVTKCellHeight(dm, &cellHeight);
829:     if (name) PetscViewerASCIIPrintf(viewer, "%s in %" PetscInt_FMT " dimension%s:\n", name, dim, dim == 1 ? "" : "s");
830:     else PetscViewerASCIIPrintf(viewer, "Mesh in %" PetscInt_FMT " dimension%s:\n", dim, dim == 1 ? "" : "s");
831:     if (cellHeight) PetscViewerASCIIPrintf(viewer, "  Cells are at height %" PetscInt_FMT "\n", cellHeight);
832:     PetscViewerASCIIPrintf(viewer, "Supports:\n");
833:     PetscViewerASCIIPushSynchronized(viewer);
834:     PetscViewerASCIISynchronizedPrintf(viewer, "[%d] Max support size: %" PetscInt_FMT "\n", rank, maxSupportSize);
835:     for (p = pStart; p < pEnd; ++p) {
836:       PetscInt dof, off, s;

838:       PetscSectionGetDof(mesh->supportSection, p, &dof);
839:       PetscSectionGetOffset(mesh->supportSection, p, &off);
840:       for (s = off; s < off + dof; ++s) PetscViewerASCIISynchronizedPrintf(viewer, "[%d]: %" PetscInt_FMT " ----> %" PetscInt_FMT "\n", rank, p, mesh->supports[s]);
841:     }
842:     PetscViewerFlush(viewer);
843:     PetscViewerASCIIPrintf(viewer, "Cones:\n");
844:     PetscViewerASCIISynchronizedPrintf(viewer, "[%d] Max cone size: %" PetscInt_FMT "\n", rank, maxConeSize);
845:     for (p = pStart; p < pEnd; ++p) {
846:       PetscInt dof, off, c;

848:       PetscSectionGetDof(mesh->coneSection, p, &dof);
849:       PetscSectionGetOffset(mesh->coneSection, p, &off);
850:       for (c = off; c < off + dof; ++c) PetscViewerASCIISynchronizedPrintf(viewer, "[%d]: %" PetscInt_FMT " <---- %" PetscInt_FMT " (%" PetscInt_FMT ")\n", rank, p, mesh->cones[c], mesh->coneOrientations[c]);
851:     }
852:     PetscViewerFlush(viewer);
853:     PetscViewerASCIIPopSynchronized(viewer);
854:     if (coordSection && coordinates) {
855:       CoordSystem        cs = CS_CARTESIAN;
856:       const PetscScalar *array, *arrayCell = NULL;
857:       PetscInt           Nf, Nc, pvStart, pvEnd, pcStart = PETSC_MAX_INT, pcEnd = PETSC_MIN_INT, pStart, pEnd, p;
858:       PetscMPIInt        rank;
859:       const char        *name;

861:       PetscOptionsGetEnum(((PetscObject)viewer)->options, ((PetscObject)viewer)->prefix, "-dm_plex_view_coord_system", CoordSystems, (PetscEnum *)&cs, NULL);
862:       MPI_Comm_rank(PetscObjectComm((PetscObject)viewer), &rank);
863:       PetscSectionGetNumFields(coordSection, &Nf);
865:       PetscSectionGetFieldComponents(coordSection, 0, &Nc);
866:       PetscSectionGetChart(coordSection, &pvStart, &pvEnd);
867:       if (coordSectionCell) PetscSectionGetChart(coordSectionCell, &pcStart, &pcEnd);
868:       pStart = PetscMin(pvStart, pcStart);
869:       pEnd   = PetscMax(pvEnd, pcEnd);
870:       PetscObjectGetName((PetscObject)coordinates, &name);
871:       PetscViewerASCIIPrintf(viewer, "%s with %" PetscInt_FMT " fields\n", name, Nf);
872:       PetscViewerASCIIPrintf(viewer, "  field 0 with %" PetscInt_FMT " components\n", Nc);
873:       if (cs != CS_CARTESIAN) PetscViewerASCIIPrintf(viewer, "  output coordinate system: %s\n", CoordSystems[cs]);

875:       VecGetArrayRead(coordinates, &array);
876:       if (coordinatesCell) VecGetArrayRead(coordinatesCell, &arrayCell);
877:       PetscViewerASCIIPushSynchronized(viewer);
878:       PetscViewerASCIISynchronizedPrintf(viewer, "Process %d:\n", rank);
879:       for (p = pStart; p < pEnd; ++p) {
880:         PetscInt dof, off;

882:         if (p >= pvStart && p < pvEnd) {
883:           PetscSectionGetDof(coordSection, p, &dof);
884:           PetscSectionGetOffset(coordSection, p, &off);
885:           if (dof) {
886:             PetscViewerASCIISynchronizedPrintf(viewer, "  (%4" PetscInt_FMT ") dim %2" PetscInt_FMT " offset %3" PetscInt_FMT, p, dof, off);
887:             DMPlexView_Ascii_Coordinates(viewer, cs, dof, &array[off]);
888:             PetscViewerASCIISynchronizedPrintf(viewer, "\n");
889:           }
890:         }
891:         if (cdmCell && p >= pcStart && p < pcEnd) {
892:           PetscSectionGetDof(coordSectionCell, p, &dof);
893:           PetscSectionGetOffset(coordSectionCell, p, &off);
894:           if (dof) {
895:             PetscViewerASCIISynchronizedPrintf(viewer, "  (%4" PetscInt_FMT ") dim %2" PetscInt_FMT " offset %3" PetscInt_FMT, p, dof, off);
896:             DMPlexView_Ascii_Coordinates(viewer, cs, dof, &arrayCell[off]);
897:             PetscViewerASCIISynchronizedPrintf(viewer, "\n");
898:           }
899:         }
900:       }
901:       PetscViewerFlush(viewer);
902:       PetscViewerASCIIPopSynchronized(viewer);
903:       VecRestoreArrayRead(coordinates, &array);
904:       if (coordinatesCell) VecRestoreArrayRead(coordinatesCell, &arrayCell);
905:     }
906:     DMGetNumLabels(dm, &numLabels);
907:     if (numLabels) PetscViewerASCIIPrintf(viewer, "Labels:\n");
908:     for (l = 0; l < numLabels; ++l) {
909:       DMLabel     label;
910:       PetscBool   isdepth;
911:       const char *name;

913:       DMGetLabelName(dm, l, &name);
914:       PetscStrcmp(name, "depth", &isdepth);
915:       if (isdepth) continue;
916:       DMGetLabel(dm, name, &label);
917:       DMLabelView(label, viewer);
918:     }
919:     if (size > 1) {
920:       PetscSF sf;

922:       DMGetPointSF(dm, &sf);
923:       PetscSFView(sf, viewer);
924:     }
925:     PetscViewerFlush(viewer);
926:   } else if (format == PETSC_VIEWER_ASCII_LATEX) {
927:     const char  *name, *color;
928:     const char  *defcolors[3]  = {"gray", "orange", "green"};
929:     const char  *deflcolors[4] = {"blue", "cyan", "red", "magenta"};
930:     char         lname[PETSC_MAX_PATH_LEN];
931:     PetscReal    scale      = 2.0;
932:     PetscReal    tikzscale  = 1.0;
933:     PetscBool    useNumbers = PETSC_TRUE, drawNumbers[4], drawColors[4], useLabels, useColors, plotEdges, drawHasse = PETSC_FALSE;
934:     double       tcoords[3];
935:     PetscScalar *coords;
936:     PetscInt     numLabels, l, numColors, numLColors, dim, d, depth, cStart, cEnd, c, vStart, vEnd, v, eStart = 0, eEnd = 0, e, p, n;
937:     PetscMPIInt  rank, size;
938:     char       **names, **colors, **lcolors;
939:     PetscBool    flg, lflg;
940:     PetscBT      wp = NULL;
941:     PetscInt     pEnd, pStart;

943:     DMGetDimension(dm, &dim);
944:     DMPlexGetDepth(dm, &depth);
945:     DMGetNumLabels(dm, &numLabels);
946:     numLabels  = PetscMax(numLabels, 10);
947:     numColors  = 10;
948:     numLColors = 10;
949:     PetscCalloc3(numLabels, &names, numColors, &colors, numLColors, &lcolors);
950:     PetscOptionsGetReal(((PetscObject)viewer)->options, ((PetscObject)viewer)->prefix, "-dm_plex_view_scale", &scale, NULL);
951:     PetscOptionsGetReal(((PetscObject)viewer)->options, ((PetscObject)viewer)->prefix, "-dm_plex_view_tikzscale", &tikzscale, NULL);
952:     PetscOptionsGetBool(((PetscObject)viewer)->options, ((PetscObject)viewer)->prefix, "-dm_plex_view_numbers", &useNumbers, NULL);
953:     for (d = 0; d < 4; ++d) drawNumbers[d] = useNumbers;
954:     for (d = 0; d < 4; ++d) drawColors[d] = PETSC_TRUE;
955:     n = 4;
956:     PetscOptionsGetBoolArray(((PetscObject)viewer)->options, ((PetscObject)viewer)->prefix, "-dm_plex_view_numbers_depth", drawNumbers, &n, &flg);
958:     PetscOptionsGetBoolArray(((PetscObject)viewer)->options, ((PetscObject)viewer)->prefix, "-dm_plex_view_colors_depth", drawColors, &n, &flg);
960:     PetscOptionsGetStringArray(((PetscObject)viewer)->options, ((PetscObject)viewer)->prefix, "-dm_plex_view_labels", names, &numLabels, &useLabels);
961:     if (!useLabels) numLabels = 0;
962:     PetscOptionsGetStringArray(((PetscObject)viewer)->options, ((PetscObject)viewer)->prefix, "-dm_plex_view_colors", colors, &numColors, &useColors);
963:     if (!useColors) {
964:       numColors = 3;
965:       for (c = 0; c < numColors; ++c) PetscStrallocpy(defcolors[c], &colors[c]);
966:     }
967:     PetscOptionsGetStringArray(((PetscObject)viewer)->options, ((PetscObject)viewer)->prefix, "-dm_plex_view_lcolors", lcolors, &numLColors, &useColors);
968:     if (!useColors) {
969:       numLColors = 4;
970:       for (c = 0; c < numLColors; ++c) PetscStrallocpy(deflcolors[c], &lcolors[c]);
971:     }
972:     PetscOptionsGetString(((PetscObject)viewer)->options, ((PetscObject)viewer)->prefix, "-dm_plex_view_label_filter", lname, sizeof(lname), &lflg);
973:     plotEdges = (PetscBool)(depth > 1 && drawNumbers[1] && dim < 3);
974:     PetscOptionsGetBool(((PetscObject)viewer)->options, ((PetscObject)viewer)->prefix, "-dm_plex_view_edges", &plotEdges, &flg);
976:     if (depth < dim) plotEdges = PETSC_FALSE;
977:     PetscOptionsGetBool(((PetscObject)viewer)->options, ((PetscObject)viewer)->prefix, "-dm_plex_view_hasse", &drawHasse, NULL);

979:     /* filter points with labelvalue != labeldefaultvalue */
980:     DMPlexGetChart(dm, &pStart, &pEnd);
981:     DMPlexGetDepthStratum(dm, 0, &vStart, &vEnd);
982:     DMPlexGetDepthStratum(dm, 1, &eStart, &eEnd);
983:     DMPlexGetHeightStratum(dm, 0, &cStart, &cEnd);
984:     if (lflg) {
985:       DMLabel lbl;

987:       DMGetLabel(dm, lname, &lbl);
988:       if (lbl) {
989:         PetscInt val, defval;

991:         DMLabelGetDefaultValue(lbl, &defval);
992:         PetscBTCreate(pEnd - pStart, &wp);
993:         for (c = pStart; c < pEnd; c++) {
994:           PetscInt *closure = NULL;
995:           PetscInt  closureSize;

997:           DMLabelGetValue(lbl, c, &val);
998:           if (val == defval) continue;

1000:           DMPlexGetTransitiveClosure(dm, c, PETSC_TRUE, &closureSize, &closure);
1001:           for (p = 0; p < closureSize * 2; p += 2) PetscBTSet(wp, closure[p] - pStart);
1002:           DMPlexRestoreTransitiveClosure(dm, c, PETSC_TRUE, &closureSize, &closure);
1003:         }
1004:       }
1005:     }

1007:     MPI_Comm_rank(PetscObjectComm((PetscObject)dm), &rank);
1008:     MPI_Comm_size(PetscObjectComm((PetscObject)dm), &size);
1009:     PetscObjectGetName((PetscObject)dm, &name);
1010:     PetscCall(PetscViewerASCIIPrintf(viewer, "\
1011: \\documentclass[tikz]{standalone}\n\n\
1012: \\usepackage{pgflibraryshapes}\n\
1013: \\usetikzlibrary{backgrounds}\n\
1014: \\usetikzlibrary{arrows}\n\
1015: \\begin{document}\n"));
1016:     if (size > 1) {
1017:       PetscViewerASCIIPrintf(viewer, "%s for process ", name);
1018:       for (p = 0; p < size; ++p) {
1019:         if (p) PetscViewerASCIIPrintf(viewer, (p == size - 1) ? ", and " : ", ");
1020:         PetscViewerASCIIPrintf(viewer, "{\\textcolor{%s}%" PetscInt_FMT "}", colors[p % numColors], p);
1021:       }
1022:       PetscViewerASCIIPrintf(viewer, ".\n\n\n");
1023:     }
1024:     if (drawHasse) {
1025:       PetscInt maxStratum = PetscMax(vEnd - vStart, PetscMax(eEnd - eStart, cEnd - cStart));

1027:       PetscViewerASCIIPrintf(viewer, "\\newcommand{\\vStart}{%" PetscInt_FMT "}\n", vStart);
1028:       PetscViewerASCIIPrintf(viewer, "\\newcommand{\\vEnd}{%" PetscInt_FMT "}\n", vEnd - 1);
1029:       PetscViewerASCIIPrintf(viewer, "\\newcommand{\\numVertices}{%" PetscInt_FMT "}\n", vEnd - vStart);
1030:       PetscViewerASCIIPrintf(viewer, "\\newcommand{\\vShift}{%.2f}\n", 3 + (maxStratum - (vEnd - vStart)) / 2.);
1031:       PetscViewerASCIIPrintf(viewer, "\\newcommand{\\eStart}{%" PetscInt_FMT "}\n", eStart);
1032:       PetscViewerASCIIPrintf(viewer, "\\newcommand{\\eEnd}{%" PetscInt_FMT "}\n", eEnd - 1);
1033:       PetscViewerASCIIPrintf(viewer, "\\newcommand{\\eShift}{%.2f}\n", 3 + (maxStratum - (eEnd - eStart)) / 2.);
1034:       PetscViewerASCIIPrintf(viewer, "\\newcommand{\\numEdges}{%" PetscInt_FMT "}\n", eEnd - eStart);
1035:       PetscViewerASCIIPrintf(viewer, "\\newcommand{\\cStart}{%" PetscInt_FMT "}\n", cStart);
1036:       PetscViewerASCIIPrintf(viewer, "\\newcommand{\\cEnd}{%" PetscInt_FMT "}\n", cEnd - 1);
1037:       PetscViewerASCIIPrintf(viewer, "\\newcommand{\\numCells}{%" PetscInt_FMT "}\n", cEnd - cStart);
1038:       PetscViewerASCIIPrintf(viewer, "\\newcommand{\\cShift}{%.2f}\n", 3 + (maxStratum - (cEnd - cStart)) / 2.);
1039:     }
1040:     PetscViewerASCIIPrintf(viewer, "\\begin{tikzpicture}[scale = %g,font=\\fontsize{8}{8}\\selectfont]\n", (double)tikzscale);

1042:     /* Plot vertices */
1043:     VecGetArray(coordinates, &coords);
1044:     PetscViewerASCIIPushSynchronized(viewer);
1045:     for (v = vStart; v < vEnd; ++v) {
1046:       PetscInt  off, dof, d;
1047:       PetscBool isLabeled = PETSC_FALSE;

1049:       if (wp && !PetscBTLookup(wp, v - pStart)) continue;
1050:       PetscSectionGetDof(coordSection, v, &dof);
1051:       PetscSectionGetOffset(coordSection, v, &off);
1052:       PetscViewerASCIISynchronizedPrintf(viewer, "\\path (");
1054:       for (d = 0; d < dof; ++d) {
1055:         tcoords[d] = (double)(scale * PetscRealPart(coords[off + d]));
1056:         tcoords[d] = PetscAbs(tcoords[d]) < 1e-10 ? 0.0 : tcoords[d];
1057:       }
1058:       /* Rotate coordinates since PGF makes z point out of the page instead of up */
1059:       if (dim == 3) {
1060:         PetscReal tmp = tcoords[1];
1061:         tcoords[1]    = tcoords[2];
1062:         tcoords[2]    = -tmp;
1063:       }
1064:       for (d = 0; d < dof; ++d) {
1065:         if (d > 0) PetscViewerASCIISynchronizedPrintf(viewer, ",");
1066:         PetscViewerASCIISynchronizedPrintf(viewer, "%g", (double)tcoords[d]);
1067:       }
1068:       if (drawHasse) color = colors[0 % numColors];
1069:       else color = colors[rank % numColors];
1070:       for (l = 0; l < numLabels; ++l) {
1071:         PetscInt val;
1072:         DMGetLabelValue(dm, names[l], v, &val);
1073:         if (val >= 0) {
1074:           color     = lcolors[l % numLColors];
1075:           isLabeled = PETSC_TRUE;
1076:           break;
1077:         }
1078:       }
1079:       if (drawNumbers[0]) {
1080:         PetscViewerASCIISynchronizedPrintf(viewer, ") node(%" PetscInt_FMT "_%d) [draw,shape=circle,color=%s] {%" PetscInt_FMT "};\n", v, rank, color, v);
1081:       } else if (drawColors[0]) {
1082:         PetscViewerASCIISynchronizedPrintf(viewer, ") node(%" PetscInt_FMT "_%d) [fill,inner sep=%dpt,shape=circle,color=%s] {};\n", v, rank, !isLabeled ? 1 : 2, color);
1083:       } else PetscViewerASCIISynchronizedPrintf(viewer, ") node(%" PetscInt_FMT "_%d) [] {};\n", v, rank);
1084:     }
1085:     VecRestoreArray(coordinates, &coords);
1086:     PetscViewerFlush(viewer);
1087:     /* Plot edges */
1088:     if (plotEdges) {
1089:       VecGetArray(coordinates, &coords);
1090:       PetscViewerASCIIPrintf(viewer, "\\path\n");
1091:       for (e = eStart; e < eEnd; ++e) {
1092:         const PetscInt *cone;
1093:         PetscInt        coneSize, offA, offB, dof, d;

1095:         if (wp && !PetscBTLookup(wp, e - pStart)) continue;
1096:         DMPlexGetConeSize(dm, e, &coneSize);
1098:         DMPlexGetCone(dm, e, &cone);
1099:         PetscSectionGetDof(coordSection, cone[0], &dof);
1100:         PetscSectionGetOffset(coordSection, cone[0], &offA);
1101:         PetscSectionGetOffset(coordSection, cone[1], &offB);
1102:         PetscViewerASCIISynchronizedPrintf(viewer, "(");
1103:         for (d = 0; d < dof; ++d) {
1104:           tcoords[d] = (double)(0.5 * scale * PetscRealPart(coords[offA + d] + coords[offB + d]));
1105:           tcoords[d] = PetscAbs(tcoords[d]) < 1e-10 ? 0.0 : tcoords[d];
1106:         }
1107:         /* Rotate coordinates since PGF makes z point out of the page instead of up */
1108:         if (dim == 3) {
1109:           PetscReal tmp = tcoords[1];
1110:           tcoords[1]    = tcoords[2];
1111:           tcoords[2]    = -tmp;
1112:         }
1113:         for (d = 0; d < dof; ++d) {
1114:           if (d > 0) PetscViewerASCIISynchronizedPrintf(viewer, ",");
1115:           PetscViewerASCIISynchronizedPrintf(viewer, "%g", (double)tcoords[d]);
1116:         }
1117:         if (drawHasse) color = colors[1 % numColors];
1118:         else color = colors[rank % numColors];
1119:         for (l = 0; l < numLabels; ++l) {
1120:           PetscInt val;
1121:           DMGetLabelValue(dm, names[l], v, &val);
1122:           if (val >= 0) {
1123:             color = lcolors[l % numLColors];
1124:             break;
1125:           }
1126:         }
1127:         PetscViewerASCIISynchronizedPrintf(viewer, ") node(%" PetscInt_FMT "_%d) [draw,shape=circle,color=%s] {%" PetscInt_FMT "} --\n", e, rank, color, e);
1128:       }
1129:       VecRestoreArray(coordinates, &coords);
1130:       PetscViewerFlush(viewer);
1131:       PetscViewerASCIIPrintf(viewer, "(0,0);\n");
1132:     }
1133:     /* Plot cells */
1134:     if (dim == 3 || !drawNumbers[1]) {
1135:       for (e = eStart; e < eEnd; ++e) {
1136:         const PetscInt *cone;

1138:         if (wp && !PetscBTLookup(wp, e - pStart)) continue;
1139:         color = colors[rank % numColors];
1140:         for (l = 0; l < numLabels; ++l) {
1141:           PetscInt val;
1142:           DMGetLabelValue(dm, names[l], e, &val);
1143:           if (val >= 0) {
1144:             color = lcolors[l % numLColors];
1145:             break;
1146:           }
1147:         }
1148:         DMPlexGetCone(dm, e, &cone);
1149:         PetscViewerASCIISynchronizedPrintf(viewer, "\\draw[color=%s] (%" PetscInt_FMT "_%d) -- (%" PetscInt_FMT "_%d);\n", color, cone[0], rank, cone[1], rank);
1150:       }
1151:     } else {
1152:       DMPolytopeType ct;

1154:       /* Drawing a 2D polygon */
1155:       for (c = cStart; c < cEnd; ++c) {
1156:         if (wp && !PetscBTLookup(wp, c - pStart)) continue;
1157:         DMPlexGetCellType(dm, c, &ct);
1158:         if (ct == DM_POLYTOPE_SEG_PRISM_TENSOR || ct == DM_POLYTOPE_TRI_PRISM_TENSOR || ct == DM_POLYTOPE_QUAD_PRISM_TENSOR) {
1159:           const PetscInt *cone;
1160:           PetscInt        coneSize, e;

1162:           DMPlexGetCone(dm, c, &cone);
1163:           DMPlexGetConeSize(dm, c, &coneSize);
1164:           for (e = 0; e < coneSize; ++e) {
1165:             const PetscInt *econe;

1167:             DMPlexGetCone(dm, cone[e], &econe);
1168:             PetscViewerASCIISynchronizedPrintf(viewer, "\\draw[color=%s] (%" PetscInt_FMT "_%d) -- (%" PetscInt_FMT "_%d) -- (%" PetscInt_FMT "_%d);\n", colors[rank % numColors], econe[0], rank, cone[e], rank, econe[1], rank);
1169:           }
1170:         } else {
1171:           PetscInt *closure = NULL;
1172:           PetscInt  closureSize, Nv = 0, v;

1174:           DMPlexGetTransitiveClosure(dm, c, PETSC_TRUE, &closureSize, &closure);
1175:           for (p = 0; p < closureSize * 2; p += 2) {
1176:             const PetscInt point = closure[p];

1178:             if ((point >= vStart) && (point < vEnd)) closure[Nv++] = point;
1179:           }
1180:           PetscViewerASCIISynchronizedPrintf(viewer, "\\draw[color=%s] ", colors[rank % numColors]);
1181:           for (v = 0; v <= Nv; ++v) {
1182:             const PetscInt vertex = closure[v % Nv];

1184:             if (v > 0) {
1185:               if (plotEdges) {
1186:                 const PetscInt *edge;
1187:                 PetscInt        endpoints[2], ne;

1189:                 endpoints[0] = closure[v - 1];
1190:                 endpoints[1] = vertex;
1191:                 DMPlexGetJoin(dm, 2, endpoints, &ne, &edge);
1193:                 PetscViewerASCIISynchronizedPrintf(viewer, " -- (%" PetscInt_FMT "_%d) -- ", edge[0], rank);
1194:                 DMPlexRestoreJoin(dm, 2, endpoints, &ne, &edge);
1195:               } else PetscViewerASCIISynchronizedPrintf(viewer, " -- ");
1196:             }
1197:             PetscViewerASCIISynchronizedPrintf(viewer, "(%" PetscInt_FMT "_%d)", vertex, rank);
1198:           }
1199:           PetscViewerASCIISynchronizedPrintf(viewer, ";\n");
1200:           DMPlexRestoreTransitiveClosure(dm, c, PETSC_TRUE, &closureSize, &closure);
1201:         }
1202:       }
1203:     }
1204:     for (c = cStart; c < cEnd; ++c) {
1205:       double             ccoords[3] = {0.0, 0.0, 0.0};
1206:       PetscBool          isLabeled  = PETSC_FALSE;
1207:       PetscScalar       *cellCoords = NULL;
1208:       const PetscScalar *array;
1209:       PetscInt           numCoords, cdim, d;
1210:       PetscBool          isDG;

1212:       if (wp && !PetscBTLookup(wp, c - pStart)) continue;
1213:       DMGetCoordinateDim(dm, &cdim);
1214:       DMPlexGetCellCoordinates(dm, c, &isDG, &numCoords, &array, &cellCoords);
1216:       PetscViewerASCIISynchronizedPrintf(viewer, "\\path (");
1217:       for (p = 0; p < numCoords / cdim; ++p) {
1218:         for (d = 0; d < cdim; ++d) {
1219:           tcoords[d] = (double)(scale * PetscRealPart(cellCoords[p * cdim + d]));
1220:           tcoords[d] = PetscAbs(tcoords[d]) < 1e-10 ? 0.0 : tcoords[d];
1221:         }
1222:         /* Rotate coordinates since PGF makes z point out of the page instead of up */
1223:         if (cdim == 3) {
1224:           PetscReal tmp = tcoords[1];
1225:           tcoords[1]    = tcoords[2];
1226:           tcoords[2]    = -tmp;
1227:         }
1228:         for (d = 0; d < dim; ++d) ccoords[d] += tcoords[d];
1229:       }
1230:       for (d = 0; d < cdim; ++d) ccoords[d] /= (numCoords / cdim);
1231:       DMPlexRestoreCellCoordinates(dm, c, &isDG, &numCoords, &array, &cellCoords);
1232:       for (d = 0; d < cdim; ++d) {
1233:         if (d > 0) PetscViewerASCIISynchronizedPrintf(viewer, ",");
1234:         PetscViewerASCIISynchronizedPrintf(viewer, "%g", (double)ccoords[d]);
1235:       }
1236:       if (drawHasse) color = colors[depth % numColors];
1237:       else color = colors[rank % numColors];
1238:       for (l = 0; l < numLabels; ++l) {
1239:         PetscInt val;
1240:         DMGetLabelValue(dm, names[l], c, &val);
1241:         if (val >= 0) {
1242:           color     = lcolors[l % numLColors];
1243:           isLabeled = PETSC_TRUE;
1244:           break;
1245:         }
1246:       }
1247:       if (drawNumbers[dim]) {
1248:         PetscViewerASCIISynchronizedPrintf(viewer, ") node(%" PetscInt_FMT "_%d) [draw,shape=circle,color=%s] {%" PetscInt_FMT "};\n", c, rank, color, c);
1249:       } else if (drawColors[dim]) {
1250:         PetscViewerASCIISynchronizedPrintf(viewer, ") node(%" PetscInt_FMT "_%d) [fill,inner sep=%dpt,shape=circle,color=%s] {};\n", c, rank, !isLabeled ? 1 : 2, color);
1251:       } else PetscViewerASCIISynchronizedPrintf(viewer, ") node(%" PetscInt_FMT "_%d) [] {};\n", c, rank);
1252:     }
1253:     if (drawHasse) {
1254:       color = colors[depth % numColors];
1255:       PetscViewerASCIIPrintf(viewer, "%% Cells\n");
1256:       PetscViewerASCIIPrintf(viewer, "\\foreach \\c in {\\cStart,...,\\cEnd}\n");
1257:       PetscViewerASCIIPrintf(viewer, "{\n");
1258:       PetscViewerASCIIPrintf(viewer, "  \\node(\\c_%d) [draw,shape=circle,color=%s,minimum size = 6mm] at (\\cShift+\\c-\\cStart,0) {\\c};\n", rank, color);
1259:       PetscViewerASCIIPrintf(viewer, "}\n");

1261:       color = colors[1 % numColors];
1262:       PetscViewerASCIIPrintf(viewer, "%% Edges\n");
1263:       PetscViewerASCIIPrintf(viewer, "\\foreach \\e in {\\eStart,...,\\eEnd}\n");
1264:       PetscViewerASCIIPrintf(viewer, "{\n");
1265:       PetscViewerASCIIPrintf(viewer, "  \\node(\\e_%d) [draw,shape=circle,color=%s,minimum size = 6mm] at (\\eShift+\\e-\\eStart,1) {\\e};\n", rank, color);
1266:       PetscViewerASCIIPrintf(viewer, "}\n");

1268:       color = colors[0 % numColors];
1269:       PetscViewerASCIIPrintf(viewer, "%% Vertices\n");
1270:       PetscViewerASCIIPrintf(viewer, "\\foreach \\v in {\\vStart,...,\\vEnd}\n");
1271:       PetscViewerASCIIPrintf(viewer, "{\n");
1272:       PetscViewerASCIIPrintf(viewer, "  \\node(\\v_%d) [draw,shape=circle,color=%s,minimum size = 6mm] at (\\vShift+\\v-\\vStart,2) {\\v};\n", rank, color);
1273:       PetscViewerASCIIPrintf(viewer, "}\n");

1275:       for (p = pStart; p < pEnd; ++p) {
1276:         const PetscInt *cone;
1277:         PetscInt        coneSize, cp;

1279:         DMPlexGetCone(dm, p, &cone);
1280:         DMPlexGetConeSize(dm, p, &coneSize);
1281:         for (cp = 0; cp < coneSize; ++cp) PetscViewerASCIIPrintf(viewer, "\\draw[->, shorten >=1pt] (%" PetscInt_FMT "_%d) -- (%" PetscInt_FMT "_%d);\n", cone[cp], rank, p, rank);
1282:       }
1283:     }
1284:     PetscViewerFlush(viewer);
1285:     PetscViewerASCIIPopSynchronized(viewer);
1286:     PetscViewerASCIIPrintf(viewer, "\\end{tikzpicture}\n");
1287:     PetscViewerASCIIPrintf(viewer, "\\end{document}\n");
1288:     for (l = 0; l < numLabels; ++l) PetscFree(names[l]);
1289:     for (c = 0; c < numColors; ++c) PetscFree(colors[c]);
1290:     for (c = 0; c < numLColors; ++c) PetscFree(lcolors[c]);
1291:     PetscFree3(names, colors, lcolors);
1292:     PetscBTDestroy(&wp);
1293:   } else if (format == PETSC_VIEWER_LOAD_BALANCE) {
1294:     Vec                    cown, acown;
1295:     VecScatter             sct;
1296:     ISLocalToGlobalMapping g2l;
1297:     IS                     gid, acis;
1298:     MPI_Comm               comm, ncomm = MPI_COMM_NULL;
1299:     MPI_Group              ggroup, ngroup;
1300:     PetscScalar           *array, nid;
1301:     const PetscInt        *idxs;
1302:     PetscInt              *idxs2, *start, *adjacency, *work;
1303:     PetscInt64             lm[3], gm[3];
1304:     PetscInt               i, c, cStart, cEnd, cum, numVertices, ect, ectn, cellHeight;
1305:     PetscMPIInt            d1, d2, rank;

1307:     PetscObjectGetComm((PetscObject)dm, &comm);
1308:     MPI_Comm_rank(comm, &rank);
1309: #if defined(PETSC_HAVE_MPI_PROCESS_SHARED_MEMORY)
1310:     MPI_Comm_split_type(comm, MPI_COMM_TYPE_SHARED, rank, MPI_INFO_NULL, &ncomm);
1311: #endif
1312:     if (ncomm != MPI_COMM_NULL) {
1313:       MPI_Comm_group(comm, &ggroup);
1314:       MPI_Comm_group(ncomm, &ngroup);
1315:       d1 = 0;
1316:       MPI_Group_translate_ranks(ngroup, 1, &d1, ggroup, &d2);
1317:       nid = d2;
1318:       MPI_Group_free(&ggroup);
1319:       MPI_Group_free(&ngroup);
1320:       MPI_Comm_free(&ncomm);
1321:     } else nid = 0.0;

1323:     /* Get connectivity */
1324:     DMPlexGetVTKCellHeight(dm, &cellHeight);
1325:     DMPlexCreatePartitionerGraph(dm, cellHeight, &numVertices, &start, &adjacency, &gid);

1327:     /* filter overlapped local cells */
1328:     DMPlexGetHeightStratum(dm, cellHeight, &cStart, &cEnd);
1329:     ISGetIndices(gid, &idxs);
1330:     ISGetLocalSize(gid, &cum);
1331:     PetscMalloc1(cum, &idxs2);
1332:     for (c = cStart, cum = 0; c < cEnd; c++) {
1333:       if (idxs[c - cStart] < 0) continue;
1334:       idxs2[cum++] = idxs[c - cStart];
1335:     }
1336:     ISRestoreIndices(gid, &idxs);
1338:     ISDestroy(&gid);
1339:     ISCreateGeneral(comm, numVertices, idxs2, PETSC_OWN_POINTER, &gid);

1341:     /* support for node-aware cell locality */
1342:     ISCreateGeneral(comm, start[numVertices], adjacency, PETSC_USE_POINTER, &acis);
1343:     VecCreateSeq(PETSC_COMM_SELF, start[numVertices], &acown);
1344:     VecCreateMPI(comm, numVertices, PETSC_DECIDE, &cown);
1345:     VecGetArray(cown, &array);
1346:     for (c = 0; c < numVertices; c++) array[c] = nid;
1347:     VecRestoreArray(cown, &array);
1348:     VecScatterCreate(cown, acis, acown, NULL, &sct);
1349:     VecScatterBegin(sct, cown, acown, INSERT_VALUES, SCATTER_FORWARD);
1350:     VecScatterEnd(sct, cown, acown, INSERT_VALUES, SCATTER_FORWARD);
1351:     ISDestroy(&acis);
1352:     VecScatterDestroy(&sct);
1353:     VecDestroy(&cown);

1355:     /* compute edgeCut */
1356:     for (c = 0, cum = 0; c < numVertices; c++) cum = PetscMax(cum, start[c + 1] - start[c]);
1357:     PetscMalloc1(cum, &work);
1358:     ISLocalToGlobalMappingCreateIS(gid, &g2l);
1359:     ISLocalToGlobalMappingSetType(g2l, ISLOCALTOGLOBALMAPPINGHASH);
1360:     ISDestroy(&gid);
1361:     VecGetArray(acown, &array);
1362:     for (c = 0, ect = 0, ectn = 0; c < numVertices; c++) {
1363:       PetscInt totl;

1365:       totl = start[c + 1] - start[c];
1366:       ISGlobalToLocalMappingApply(g2l, IS_GTOLM_MASK, totl, adjacency + start[c], NULL, work);
1367:       for (i = 0; i < totl; i++) {
1368:         if (work[i] < 0) {
1369:           ect += 1;
1370:           ectn += (array[i + start[c]] != nid) ? 0 : 1;
1371:         }
1372:       }
1373:     }
1374:     PetscFree(work);
1375:     VecRestoreArray(acown, &array);
1376:     lm[0] = numVertices > 0 ? numVertices : PETSC_MAX_INT;
1377:     lm[1] = -numVertices;
1378:     MPIU_Allreduce(lm, gm, 2, MPIU_INT64, MPI_MIN, comm);
1379:     PetscViewerASCIIPrintf(viewer, "  Cell balance: %.2f (max %" PetscInt_FMT ", min %" PetscInt_FMT, -((double)gm[1]) / ((double)gm[0]), -(PetscInt)gm[1], (PetscInt)gm[0]);
1380:     lm[0] = ect;                     /* edgeCut */
1381:     lm[1] = ectn;                    /* node-aware edgeCut */
1382:     lm[2] = numVertices > 0 ? 0 : 1; /* empty processes */
1383:     MPIU_Allreduce(lm, gm, 3, MPIU_INT64, MPI_SUM, comm);
1384:     PetscViewerASCIIPrintf(viewer, ", empty %" PetscInt_FMT ")\n", (PetscInt)gm[2]);
1385: #if defined(PETSC_HAVE_MPI_PROCESS_SHARED_MEMORY)
1386:     PetscViewerASCIIPrintf(viewer, "  Edge Cut: %" PetscInt_FMT " (on node %.3f)\n", (PetscInt)(gm[0] / 2), gm[0] ? ((double)(gm[1])) / ((double)gm[0]) : 1.);
1387: #else
1388:     PetscViewerASCIIPrintf(viewer, "  Edge Cut: %" PetscInt_FMT " (on node %.3f)\n", (PetscInt)(gm[0] / 2), 0.0);
1389: #endif
1390:     ISLocalToGlobalMappingDestroy(&g2l);
1391:     PetscFree(start);
1392:     PetscFree(adjacency);
1393:     VecDestroy(&acown);
1394:   } else {
1395:     const char    *name;
1396:     PetscInt      *sizes, *hybsizes, *ghostsizes;
1397:     PetscInt       locDepth, depth, cellHeight, dim, d;
1398:     PetscInt       pStart, pEnd, p, gcStart, gcEnd, gcNum;
1399:     PetscInt       numLabels, l, maxSize = 17;
1400:     DMPolytopeType ct0 = DM_POLYTOPE_UNKNOWN;
1401:     MPI_Comm       comm;
1402:     PetscMPIInt    size, rank;

1404:     PetscObjectGetComm((PetscObject)dm, &comm);
1405:     MPI_Comm_size(comm, &size);
1406:     MPI_Comm_rank(comm, &rank);
1407:     DMGetDimension(dm, &dim);
1408:     DMPlexGetVTKCellHeight(dm, &cellHeight);
1409:     PetscObjectGetName((PetscObject)dm, &name);
1410:     if (name) PetscViewerASCIIPrintf(viewer, "%s in %" PetscInt_FMT " dimension%s:\n", name, dim, dim == 1 ? "" : "s");
1411:     else PetscViewerASCIIPrintf(viewer, "Mesh in %" PetscInt_FMT " dimension%s:\n", dim, dim == 1 ? "" : "s");
1412:     if (cellHeight) PetscViewerASCIIPrintf(viewer, "  Cells are at height %" PetscInt_FMT "\n", cellHeight);
1413:     DMPlexGetDepth(dm, &locDepth);
1414:     MPIU_Allreduce(&locDepth, &depth, 1, MPIU_INT, MPI_MAX, comm);
1415:     DMPlexGetGhostCellStratum(dm, &gcStart, &gcEnd);
1416:     gcNum = gcEnd - gcStart;
1417:     if (size < maxSize) PetscCalloc3(size, &sizes, size, &hybsizes, size, &ghostsizes);
1418:     else PetscCalloc3(3, &sizes, 3, &hybsizes, 3, &ghostsizes);
1419:     for (d = 0; d <= depth; d++) {
1420:       PetscInt Nc[2] = {0, 0}, ict;

1422:       DMPlexGetDepthStratum(dm, d, &pStart, &pEnd);
1423:       if (pStart < pEnd) DMPlexGetCellType(dm, pStart, &ct0);
1424:       ict = ct0;
1425:       MPI_Bcast(&ict, 1, MPIU_INT, 0, comm);
1426:       ct0 = (DMPolytopeType)ict;
1427:       for (p = pStart; p < pEnd; ++p) {
1428:         DMPolytopeType ct;

1430:         DMPlexGetCellType(dm, p, &ct);
1431:         if (ct == ct0) ++Nc[0];
1432:         else ++Nc[1];
1433:       }
1434:       if (size < maxSize) {
1435:         MPI_Gather(&Nc[0], 1, MPIU_INT, sizes, 1, MPIU_INT, 0, comm);
1436:         MPI_Gather(&Nc[1], 1, MPIU_INT, hybsizes, 1, MPIU_INT, 0, comm);
1437:         if (d == depth) MPI_Gather(&gcNum, 1, MPIU_INT, ghostsizes, 1, MPIU_INT, 0, comm);
1438:         PetscViewerASCIIPrintf(viewer, "  Number of %" PetscInt_FMT "-cells per rank:", (depth == 1) && d ? dim : d);
1439:         for (p = 0; p < size; ++p) {
1440:           if (rank == 0) {
1441:             PetscViewerASCIIPrintf(viewer, " %" PetscInt_FMT, sizes[p] + hybsizes[p]);
1442:             if (hybsizes[p] > 0) PetscViewerASCIIPrintf(viewer, " (%" PetscInt_FMT ")", hybsizes[p]);
1443:             if (ghostsizes[p] > 0) PetscViewerASCIIPrintf(viewer, " [%" PetscInt_FMT "]", ghostsizes[p]);
1444:           }
1445:         }
1446:       } else {
1447:         PetscInt locMinMax[2];

1449:         locMinMax[0] = Nc[0] + Nc[1];
1450:         locMinMax[1] = Nc[0] + Nc[1];
1451:         PetscGlobalMinMaxInt(comm, locMinMax, sizes);
1452:         locMinMax[0] = Nc[1];
1453:         locMinMax[1] = Nc[1];
1454:         PetscGlobalMinMaxInt(comm, locMinMax, hybsizes);
1455:         if (d == depth) {
1456:           locMinMax[0] = gcNum;
1457:           locMinMax[1] = gcNum;
1458:           PetscGlobalMinMaxInt(comm, locMinMax, ghostsizes);
1459:         }
1460:         PetscViewerASCIIPrintf(viewer, "  Min/Max of %" PetscInt_FMT "-cells per rank:", (depth == 1) && d ? dim : d);
1461:         PetscViewerASCIIPrintf(viewer, " %" PetscInt_FMT "/%" PetscInt_FMT, sizes[0], sizes[1]);
1462:         if (hybsizes[0] > 0) PetscViewerASCIIPrintf(viewer, " (%" PetscInt_FMT "/%" PetscInt_FMT ")", hybsizes[0], hybsizes[1]);
1463:         if (ghostsizes[0] > 0) PetscViewerASCIIPrintf(viewer, " [%" PetscInt_FMT "/%" PetscInt_FMT "]", ghostsizes[0], ghostsizes[1]);
1464:       }
1465:       PetscViewerASCIIPrintf(viewer, "\n");
1466:     }
1467:     PetscFree3(sizes, hybsizes, ghostsizes);
1468:     {
1469:       const PetscReal *maxCell;
1470:       const PetscReal *L;
1471:       PetscBool        localized;

1473:       DMGetPeriodicity(dm, &maxCell, NULL, &L);
1474:       DMGetCoordinatesLocalized(dm, &localized);
1475:       if (L || localized) {
1476:         PetscViewerASCIIPrintf(viewer, "Periodic mesh");
1477:         PetscViewerASCIIUseTabs(viewer, PETSC_FALSE);
1478:         if (L) {
1479:           PetscViewerASCIIPrintf(viewer, " (");
1480:           for (d = 0; d < dim; ++d) {
1481:             if (d > 0) PetscViewerASCIIPrintf(viewer, ", ");
1482:             PetscViewerASCIIPrintf(viewer, "%s", L[d] > 0.0 ? "PERIODIC" : "NONE");
1483:           }
1484:           PetscViewerASCIIPrintf(viewer, ")");
1485:         }
1486:         PetscViewerASCIIPrintf(viewer, " coordinates %s\n", localized ? "localized" : "not localized");
1487:         PetscViewerASCIIUseTabs(viewer, PETSC_TRUE);
1488:       }
1489:     }
1490:     DMGetNumLabels(dm, &numLabels);
1491:     if (numLabels) PetscViewerASCIIPrintf(viewer, "Labels:\n");
1492:     for (l = 0; l < numLabels; ++l) {
1493:       DMLabel         label;
1494:       const char     *name;
1495:       IS              valueIS;
1496:       const PetscInt *values;
1497:       PetscInt        numValues, v;

1499:       DMGetLabelName(dm, l, &name);
1500:       DMGetLabel(dm, name, &label);
1501:       DMLabelGetNumValues(label, &numValues);
1502:       PetscViewerASCIIPrintf(viewer, "  %s: %" PetscInt_FMT " strata with value/size (", name, numValues);
1503:       DMLabelGetValueIS(label, &valueIS);
1504:       ISGetIndices(valueIS, &values);
1505:       PetscViewerASCIIUseTabs(viewer, PETSC_FALSE);
1506:       for (v = 0; v < numValues; ++v) {
1507:         PetscInt size;

1509:         DMLabelGetStratumSize(label, values[v], &size);
1510:         if (v > 0) PetscViewerASCIIPrintf(viewer, ", ");
1511:         PetscViewerASCIIPrintf(viewer, "%" PetscInt_FMT " (%" PetscInt_FMT ")", values[v], size);
1512:       }
1513:       PetscViewerASCIIPrintf(viewer, ")\n");
1514:       PetscViewerASCIIUseTabs(viewer, PETSC_TRUE);
1515:       ISRestoreIndices(valueIS, &values);
1516:       ISDestroy(&valueIS);
1517:     }
1518:     {
1519:       char    **labelNames;
1520:       PetscInt  Nl = numLabels;
1521:       PetscBool flg;

1523:       PetscMalloc1(Nl, &labelNames);
1524:       PetscOptionsGetStringArray(((PetscObject)dm)->options, ((PetscObject)dm)->prefix, "-dm_plex_view_labels", labelNames, &Nl, &flg);
1525:       for (l = 0; l < Nl; ++l) {
1526:         DMLabel label;

1528:         DMHasLabel(dm, labelNames[l], &flg);
1529:         if (flg) {
1530:           DMGetLabel(dm, labelNames[l], &label);
1531:           DMLabelView(label, viewer);
1532:         }
1533:         PetscFree(labelNames[l]);
1534:       }
1535:       PetscFree(labelNames);
1536:     }
1537:     /* If no fields are specified, people do not want to see adjacency */
1538:     if (dm->Nf) {
1539:       PetscInt f;

1541:       for (f = 0; f < dm->Nf; ++f) {
1542:         const char *name;

1544:         PetscObjectGetName(dm->fields[f].disc, &name);
1545:         if (numLabels) PetscViewerASCIIPrintf(viewer, "Field %s:\n", name);
1546:         PetscViewerASCIIPushTab(viewer);
1547:         if (dm->fields[f].label) DMLabelView(dm->fields[f].label, viewer);
1548:         if (dm->fields[f].adjacency[0]) {
1549:           if (dm->fields[f].adjacency[1]) PetscViewerASCIIPrintf(viewer, "adjacency FVM++\n");
1550:           else PetscViewerASCIIPrintf(viewer, "adjacency FVM\n");
1551:         } else {
1552:           if (dm->fields[f].adjacency[1]) PetscViewerASCIIPrintf(viewer, "adjacency FEM\n");
1553:           else PetscViewerASCIIPrintf(viewer, "adjacency FUNKY\n");
1554:         }
1555:         PetscViewerASCIIPopTab(viewer);
1556:       }
1557:     }
1558:     DMGetCoarseDM(dm, &cdm);
1559:     if (cdm) {
1560:       PetscViewerASCIIPushTab(viewer);
1561:       DMPlexView_Ascii(cdm, viewer);
1562:       PetscViewerASCIIPopTab(viewer);
1563:     }
1564:   }
1565:   return 0;
1566: }

1568: static PetscErrorCode DMPlexDrawCell(DM dm, PetscDraw draw, PetscInt cell, const PetscScalar coords[])
1569: {
1570:   DMPolytopeType ct;
1571:   PetscMPIInt    rank;
1572:   PetscInt       cdim;

1574:   MPI_Comm_rank(PetscObjectComm((PetscObject)dm), &rank);
1575:   DMPlexGetCellType(dm, cell, &ct);
1576:   DMGetCoordinateDim(dm, &cdim);
1577:   switch (ct) {
1578:   case DM_POLYTOPE_SEGMENT:
1579:   case DM_POLYTOPE_POINT_PRISM_TENSOR:
1580:     switch (cdim) {
1581:     case 1: {
1582:       const PetscReal y  = 0.5;  /* TODO Put it in the middle of the viewport */
1583:       const PetscReal dy = 0.05; /* TODO Make it a fraction of the total length */

1585:       PetscDrawLine(draw, PetscRealPart(coords[0]), y, PetscRealPart(coords[1]), y, PETSC_DRAW_BLACK);
1586:       PetscDrawLine(draw, PetscRealPart(coords[0]), y + dy, PetscRealPart(coords[0]), y - dy, PETSC_DRAW_BLACK);
1587:       PetscDrawLine(draw, PetscRealPart(coords[1]), y + dy, PetscRealPart(coords[1]), y - dy, PETSC_DRAW_BLACK);
1588:     } break;
1589:     case 2: {
1590:       const PetscReal dx = (PetscRealPart(coords[3]) - PetscRealPart(coords[1]));
1591:       const PetscReal dy = (PetscRealPart(coords[2]) - PetscRealPart(coords[0]));
1592:       const PetscReal l  = 0.1 / PetscSqrtReal(dx * dx + dy * dy);

1594:       PetscDrawLine(draw, PetscRealPart(coords[0]), PetscRealPart(coords[1]), PetscRealPart(coords[2]), PetscRealPart(coords[3]), PETSC_DRAW_BLACK);
1595:       PetscDrawLine(draw, PetscRealPart(coords[0]) + l * dx, PetscRealPart(coords[1]) + l * dy, PetscRealPart(coords[0]) - l * dx, PetscRealPart(coords[1]) - l * dy, PETSC_DRAW_BLACK);
1596:       PetscDrawLine(draw, PetscRealPart(coords[2]) + l * dx, PetscRealPart(coords[3]) + l * dy, PetscRealPart(coords[2]) - l * dx, PetscRealPart(coords[3]) - l * dy, PETSC_DRAW_BLACK);
1597:     } break;
1598:     default:
1599:       SETERRQ(PETSC_COMM_SELF, PETSC_ERR_SUP, "Cannot draw cells of dimension %" PetscInt_FMT, cdim);
1600:     }
1601:     break;
1602:   case DM_POLYTOPE_TRIANGLE:
1603:     PetscDrawTriangle(draw, PetscRealPart(coords[0]), PetscRealPart(coords[1]), PetscRealPart(coords[2]), PetscRealPart(coords[3]), PetscRealPart(coords[4]), PetscRealPart(coords[5]), PETSC_DRAW_WHITE + rank % (PETSC_DRAW_BASIC_COLORS - 2) + 2, PETSC_DRAW_WHITE + rank % (PETSC_DRAW_BASIC_COLORS - 2) + 2, PETSC_DRAW_WHITE + rank % (PETSC_DRAW_BASIC_COLORS - 2) + 2);
1604:     PetscDrawLine(draw, PetscRealPart(coords[0]), PetscRealPart(coords[1]), PetscRealPart(coords[2]), PetscRealPart(coords[3]), PETSC_DRAW_BLACK);
1605:     PetscDrawLine(draw, PetscRealPart(coords[2]), PetscRealPart(coords[3]), PetscRealPart(coords[4]), PetscRealPart(coords[5]), PETSC_DRAW_BLACK);
1606:     PetscDrawLine(draw, PetscRealPart(coords[4]), PetscRealPart(coords[5]), PetscRealPart(coords[0]), PetscRealPart(coords[1]), PETSC_DRAW_BLACK);
1607:     break;
1608:   case DM_POLYTOPE_QUADRILATERAL:
1609:     PetscDrawTriangle(draw, PetscRealPart(coords[0]), PetscRealPart(coords[1]), PetscRealPart(coords[2]), PetscRealPart(coords[3]), PetscRealPart(coords[4]), PetscRealPart(coords[5]), PETSC_DRAW_WHITE + rank % (PETSC_DRAW_BASIC_COLORS - 2) + 2, PETSC_DRAW_WHITE + rank % (PETSC_DRAW_BASIC_COLORS - 2) + 2, PETSC_DRAW_WHITE + rank % (PETSC_DRAW_BASIC_COLORS - 2) + 2);
1610:     PetscDrawTriangle(draw, PetscRealPart(coords[0]), PetscRealPart(coords[1]), PetscRealPart(coords[4]), PetscRealPart(coords[5]), PetscRealPart(coords[6]), PetscRealPart(coords[7]), PETSC_DRAW_WHITE + rank % (PETSC_DRAW_BASIC_COLORS - 2) + 2, PETSC_DRAW_WHITE + rank % (PETSC_DRAW_BASIC_COLORS - 2) + 2, PETSC_DRAW_WHITE + rank % (PETSC_DRAW_BASIC_COLORS - 2) + 2);
1611:     PetscDrawLine(draw, PetscRealPart(coords[0]), PetscRealPart(coords[1]), PetscRealPart(coords[2]), PetscRealPart(coords[3]), PETSC_DRAW_BLACK);
1612:     PetscDrawLine(draw, PetscRealPart(coords[2]), PetscRealPart(coords[3]), PetscRealPart(coords[4]), PetscRealPart(coords[5]), PETSC_DRAW_BLACK);
1613:     PetscDrawLine(draw, PetscRealPart(coords[4]), PetscRealPart(coords[5]), PetscRealPart(coords[6]), PetscRealPart(coords[7]), PETSC_DRAW_BLACK);
1614:     PetscDrawLine(draw, PetscRealPart(coords[6]), PetscRealPart(coords[7]), PetscRealPart(coords[0]), PetscRealPart(coords[1]), PETSC_DRAW_BLACK);
1615:     break;
1616:   case DM_POLYTOPE_FV_GHOST:
1617:     break;
1618:   default:
1619:     SETERRQ(PETSC_COMM_SELF, PETSC_ERR_SUP, "Cannot draw cells of type %s", DMPolytopeTypes[ct]);
1620:   }
1621:   return 0;
1622: }

1624: static PetscErrorCode DMPlexDrawCellHighOrder(DM dm, PetscDraw draw, PetscInt cell, const PetscScalar coords[], PetscInt edgeDiv, PetscReal refCoords[], PetscReal edgeCoords[])
1625: {
1626:   DMPolytopeType ct;
1627:   PetscReal      centroid[2] = {0., 0.};
1628:   PetscMPIInt    rank;
1629:   PetscInt       fillColor, v, e, d;

1631:   MPI_Comm_rank(PetscObjectComm((PetscObject)dm), &rank);
1632:   DMPlexGetCellType(dm, cell, &ct);
1633:   fillColor = PETSC_DRAW_WHITE + rank % (PETSC_DRAW_BASIC_COLORS - 2) + 2;
1634:   switch (ct) {
1635:   case DM_POLYTOPE_TRIANGLE: {
1636:     PetscReal refVertices[6] = {-1., -1., 1., -1., -1., 1.};

1638:     for (v = 0; v < 3; ++v) {
1639:       centroid[0] += PetscRealPart(coords[v * 2 + 0]) / 3.;
1640:       centroid[1] += PetscRealPart(coords[v * 2 + 1]) / 3.;
1641:     }
1642:     for (e = 0; e < 3; ++e) {
1643:       refCoords[0] = refVertices[e * 2 + 0];
1644:       refCoords[1] = refVertices[e * 2 + 1];
1645:       for (d = 1; d <= edgeDiv; ++d) {
1646:         refCoords[d * 2 + 0] = refCoords[0] + (refVertices[(e + 1) % 3 * 2 + 0] - refCoords[0]) * d / edgeDiv;
1647:         refCoords[d * 2 + 1] = refCoords[1] + (refVertices[(e + 1) % 3 * 2 + 1] - refCoords[1]) * d / edgeDiv;
1648:       }
1649:       DMPlexReferenceToCoordinates(dm, cell, edgeDiv + 1, refCoords, edgeCoords);
1650:       for (d = 0; d < edgeDiv; ++d) {
1651:         PetscDrawTriangle(draw, centroid[0], centroid[1], edgeCoords[d * 2 + 0], edgeCoords[d * 2 + 1], edgeCoords[(d + 1) * 2 + 0], edgeCoords[(d + 1) * 2 + 1], fillColor, fillColor, fillColor);
1652:         PetscDrawLine(draw, edgeCoords[d * 2 + 0], edgeCoords[d * 2 + 1], edgeCoords[(d + 1) * 2 + 0], edgeCoords[(d + 1) * 2 + 1], PETSC_DRAW_BLACK);
1653:       }
1654:     }
1655:   } break;
1656:   default:
1657:     SETERRQ(PETSC_COMM_SELF, PETSC_ERR_SUP, "Cannot draw cells of type %s", DMPolytopeTypes[ct]);
1658:   }
1659:   return 0;
1660: }

1662: static PetscErrorCode DMPlexView_Draw(DM dm, PetscViewer viewer)
1663: {
1664:   PetscDraw          draw;
1665:   DM                 cdm;
1666:   PetscSection       coordSection;
1667:   Vec                coordinates;
1668:   const PetscScalar *coords;
1669:   PetscReal          xyl[2], xyr[2], bound[4] = {PETSC_MAX_REAL, PETSC_MAX_REAL, PETSC_MIN_REAL, PETSC_MIN_REAL};
1670:   PetscReal         *refCoords, *edgeCoords;
1671:   PetscBool          isnull, drawAffine = PETSC_TRUE;
1672:   PetscInt           dim, vStart, vEnd, cStart, cEnd, c, N, edgeDiv = 4;

1674:   DMGetCoordinateDim(dm, &dim);
1676:   PetscOptionsGetBool(((PetscObject)dm)->options, ((PetscObject)dm)->prefix, "-dm_view_draw_affine", &drawAffine, NULL);
1677:   if (!drawAffine) PetscMalloc2((edgeDiv + 1) * dim, &refCoords, (edgeDiv + 1) * dim, &edgeCoords);
1678:   DMGetCoordinateDM(dm, &cdm);
1679:   DMGetLocalSection(cdm, &coordSection);
1680:   DMGetCoordinatesLocal(dm, &coordinates);
1681:   DMPlexGetDepthStratum(dm, 0, &vStart, &vEnd);
1682:   DMPlexGetHeightStratum(dm, 0, &cStart, &cEnd);

1684:   PetscViewerDrawGetDraw(viewer, 0, &draw);
1685:   PetscDrawIsNull(draw, &isnull);
1686:   if (isnull) return 0;
1687:   PetscDrawSetTitle(draw, "Mesh");

1689:   VecGetLocalSize(coordinates, &N);
1690:   VecGetArrayRead(coordinates, &coords);
1691:   for (c = 0; c < N; c += dim) {
1692:     bound[0] = PetscMin(bound[0], PetscRealPart(coords[c]));
1693:     bound[2] = PetscMax(bound[2], PetscRealPart(coords[c]));
1694:     bound[1] = PetscMin(bound[1], PetscRealPart(coords[c + 1]));
1695:     bound[3] = PetscMax(bound[3], PetscRealPart(coords[c + 1]));
1696:   }
1697:   VecRestoreArrayRead(coordinates, &coords);
1698:   MPIU_Allreduce(&bound[0], xyl, 2, MPIU_REAL, MPIU_MIN, PetscObjectComm((PetscObject)dm));
1699:   MPIU_Allreduce(&bound[2], xyr, 2, MPIU_REAL, MPIU_MAX, PetscObjectComm((PetscObject)dm));
1700:   PetscDrawSetCoordinates(draw, xyl[0], xyl[1], xyr[0], xyr[1]);
1701:   PetscDrawClear(draw);

1703:   for (c = cStart; c < cEnd; ++c) {
1704:     PetscScalar *coords = NULL;
1705:     PetscInt     numCoords;

1707:     DMPlexVecGetClosureAtDepth_Internal(dm, coordSection, coordinates, c, 0, &numCoords, &coords);
1708:     if (drawAffine) DMPlexDrawCell(dm, draw, c, coords);
1709:     else DMPlexDrawCellHighOrder(dm, draw, c, coords, edgeDiv, refCoords, edgeCoords);
1710:     DMPlexVecRestoreClosure(dm, coordSection, coordinates, c, &numCoords, &coords);
1711:   }
1712:   if (!drawAffine) PetscFree2(refCoords, edgeCoords);
1713:   PetscDrawFlush(draw);
1714:   PetscDrawPause(draw);
1715:   PetscDrawSave(draw);
1716:   return 0;
1717: }

1719: #if defined(PETSC_HAVE_EXODUSII)
1720:   #include <exodusII.h>
1721: #include <petscviewerexodusii.h>
1722: #endif

1724: PetscErrorCode DMView_Plex(DM dm, PetscViewer viewer)
1725: {
1726:   PetscBool iascii, ishdf5, isvtk, isdraw, flg, isglvis, isexodus, iscgns;
1727:   char      name[PETSC_MAX_PATH_LEN];

1731:   PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERASCII, &iascii);
1732:   PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERVTK, &isvtk);
1733:   PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERHDF5, &ishdf5);
1734:   PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERDRAW, &isdraw);
1735:   PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERGLVIS, &isglvis);
1736:   PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWEREXODUSII, &isexodus);
1737:   PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERCGNS, &iscgns);
1738:   if (iascii) {
1739:     PetscViewerFormat format;
1740:     PetscViewerGetFormat(viewer, &format);
1741:     if (format == PETSC_VIEWER_ASCII_GLVIS) DMPlexView_GLVis(dm, viewer);
1742:     else DMPlexView_Ascii(dm, viewer);
1743:   } else if (ishdf5) {
1744: #if defined(PETSC_HAVE_HDF5)
1745:     DMPlexView_HDF5_Internal(dm, viewer);
1746: #else
1747:     SETERRQ(PetscObjectComm((PetscObject)dm), PETSC_ERR_SUP, "HDF5 not supported in this build.\nPlease reconfigure using --download-hdf5");
1748: #endif
1749:   } else if (isvtk) {
1750:     DMPlexVTKWriteAll((PetscObject)dm, viewer);
1751:   } else if (isdraw) {
1752:     DMPlexView_Draw(dm, viewer);
1753:   } else if (isglvis) {
1754:     DMPlexView_GLVis(dm, viewer);
1755: #if defined(PETSC_HAVE_EXODUSII)
1756:   } else if (isexodus) {
1757:     /*
1758:       exodusII requires that all sets be part of exactly one cell set.
1759:       If the dm does not have a "Cell Sets" label defined, we create one
1760:       with ID 1, containig all cells.
1761:       Note that if the Cell Sets label is defined but does not cover all cells,
1762:       we may still have a problem. This should probably be checked here or in the viewer;
1763:     */
1764:     PetscInt numCS;
1765:     DMGetLabelSize(dm, "Cell Sets", &numCS);
1766:     if (!numCS) {
1767:       PetscInt cStart, cEnd, c;
1768:       DMCreateLabel(dm, "Cell Sets");
1769:       DMPlexGetHeightStratum(dm, 0, &cStart, &cEnd);
1770:       for (c = cStart; c < cEnd; ++c) DMSetLabelValue(dm, "Cell Sets", c, 1);
1771:     }
1772:     DMView_PlexExodusII(dm, viewer);
1773: #endif
1774: #if defined(PETSC_HAVE_CGNS)
1775:   } else if (iscgns) {
1776:     DMView_PlexCGNS(dm, viewer);
1777: #endif
1778:   } else SETERRQ(PetscObjectComm((PetscObject)dm), PETSC_ERR_SUP, "Viewer type %s not yet supported for DMPlex writing", ((PetscObject)viewer)->type_name);
1779:   /* Optionally view the partition */
1780:   PetscOptionsHasName(((PetscObject)dm)->options, ((PetscObject)dm)->prefix, "-dm_partition_view", &flg);
1781:   if (flg) {
1782:     Vec ranks;
1783:     DMPlexCreateRankField(dm, &ranks);
1784:     VecView(ranks, viewer);
1785:     VecDestroy(&ranks);
1786:   }
1787:   /* Optionally view a label */
1788:   PetscOptionsGetString(((PetscObject)dm)->options, ((PetscObject)dm)->prefix, "-dm_label_view", name, sizeof(name), &flg);
1789:   if (flg) {
1790:     DMLabel label;
1791:     Vec     val;

1793:     DMGetLabel(dm, name, &label);
1795:     DMPlexCreateLabelField(dm, label, &val);
1796:     VecView(val, viewer);
1797:     VecDestroy(&val);
1798:   }
1799:   return 0;
1800: }

1802: /*@
1803:   DMPlexTopologyView - Saves a DMPlex topology into a file

1805:   Collective on DM

1807:   Input Parameters:
1808: + dm                - The DM whose topology is to be saved
1809: - viewer            - The PetscViewer for saving

1811:   Level: advanced

1813: .seealso: `DMView()`, `DMPlexCoordinatesView()`, `DMPlexLabelsView()`, `DMPlexTopologyLoad()`
1814: @*/
1815: PetscErrorCode DMPlexTopologyView(DM dm, PetscViewer viewer)
1816: {
1817:   PetscBool ishdf5;

1821:   PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERHDF5, &ishdf5);
1822:   PetscLogEventBegin(DMPLEX_TopologyView, viewer, 0, 0, 0);
1823:   if (ishdf5) {
1824: #if defined(PETSC_HAVE_HDF5)
1825:     PetscViewerFormat format;
1826:     PetscViewerGetFormat(viewer, &format);
1827:     if (format == PETSC_VIEWER_HDF5_PETSC || format == PETSC_VIEWER_DEFAULT || format == PETSC_VIEWER_NATIVE) {
1828:       IS globalPointNumbering;

1830:       DMPlexCreatePointNumbering(dm, &globalPointNumbering);
1831:       DMPlexTopologyView_HDF5_Internal(dm, globalPointNumbering, viewer);
1832:       ISDestroy(&globalPointNumbering);
1833:     } else SETERRQ(PetscObjectComm((PetscObject)dm), PETSC_ERR_SUP, "PetscViewerFormat %s not supported for HDF5 output.", PetscViewerFormats[format]);
1834: #else
1835:     SETERRQ(PetscObjectComm((PetscObject)dm), PETSC_ERR_SUP, "HDF5 not supported in this build.\nPlease reconfigure using --download-hdf5");
1836: #endif
1837:   }
1838:   PetscLogEventEnd(DMPLEX_TopologyView, viewer, 0, 0, 0);
1839:   return 0;
1840: }

1842: /*@
1843:   DMPlexCoordinatesView - Saves DMPlex coordinates into a file

1845:   Collective on DM

1847:   Input Parameters:
1848: + dm     - The DM whose coordinates are to be saved
1849: - viewer - The PetscViewer for saving

1851:   Level: advanced

1853: .seealso: `DMView()`, `DMPlexTopologyView()`, `DMPlexLabelsView()`, `DMPlexCoordinatesLoad()`
1854: @*/
1855: PetscErrorCode DMPlexCoordinatesView(DM dm, PetscViewer viewer)
1856: {
1857:   PetscBool ishdf5;

1861:   PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERHDF5, &ishdf5);
1862:   PetscLogEventBegin(DMPLEX_CoordinatesView, viewer, 0, 0, 0);
1863:   if (ishdf5) {
1864: #if defined(PETSC_HAVE_HDF5)
1865:     PetscViewerFormat format;
1866:     PetscViewerGetFormat(viewer, &format);
1867:     if (format == PETSC_VIEWER_HDF5_PETSC || format == PETSC_VIEWER_DEFAULT || format == PETSC_VIEWER_NATIVE) {
1868:       DMPlexCoordinatesView_HDF5_Internal(dm, viewer);
1869:     } else SETERRQ(PetscObjectComm((PetscObject)dm), PETSC_ERR_SUP, "PetscViewerFormat %s not supported for HDF5 output.", PetscViewerFormats[format]);
1870: #else
1871:     SETERRQ(PetscObjectComm((PetscObject)dm), PETSC_ERR_SUP, "HDF5 not supported in this build.\nPlease reconfigure using --download-hdf5");
1872: #endif
1873:   }
1874:   PetscLogEventEnd(DMPLEX_CoordinatesView, viewer, 0, 0, 0);
1875:   return 0;
1876: }

1878: /*@
1879:   DMPlexLabelsView - Saves DMPlex labels into a file

1881:   Collective on DM

1883:   Input Parameters:
1884: + dm     - The DM whose labels are to be saved
1885: - viewer - The PetscViewer for saving

1887:   Level: advanced

1889: .seealso: `DMView()`, `DMPlexTopologyView()`, `DMPlexCoordinatesView()`, `DMPlexLabelsLoad()`
1890: @*/
1891: PetscErrorCode DMPlexLabelsView(DM dm, PetscViewer viewer)
1892: {
1893:   PetscBool ishdf5;

1897:   PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERHDF5, &ishdf5);
1898:   PetscLogEventBegin(DMPLEX_LabelsView, viewer, 0, 0, 0);
1899:   if (ishdf5) {
1900: #if defined(PETSC_HAVE_HDF5)
1901:     IS                globalPointNumbering;
1902:     PetscViewerFormat format;

1904:     PetscViewerGetFormat(viewer, &format);
1905:     if (format == PETSC_VIEWER_HDF5_PETSC || format == PETSC_VIEWER_DEFAULT || format == PETSC_VIEWER_NATIVE) {
1906:       DMPlexCreatePointNumbering(dm, &globalPointNumbering);
1907:       DMPlexLabelsView_HDF5_Internal(dm, globalPointNumbering, viewer);
1908:       ISDestroy(&globalPointNumbering);
1909:     } else SETERRQ(PetscObjectComm((PetscObject)dm), PETSC_ERR_SUP, "PetscViewerFormat %s not supported for HDF5 input.", PetscViewerFormats[format]);
1910: #else
1911:     SETERRQ(PetscObjectComm((PetscObject)dm), PETSC_ERR_SUP, "HDF5 not supported in this build.\nPlease reconfigure using --download-hdf5");
1912: #endif
1913:   }
1914:   PetscLogEventEnd(DMPLEX_LabelsView, viewer, 0, 0, 0);
1915:   return 0;
1916: }

1918: /*@
1919:   DMPlexSectionView - Saves a section associated with a DMPlex

1921:   Collective on DM

1923:   Input Parameters:
1924: + dm         - The DM that contains the topology on which the section to be saved is defined
1925: . viewer     - The PetscViewer for saving
1926: - sectiondm  - The DM that contains the section to be saved

1928:   Level: advanced

1930:   Notes:
1931:   This function is a wrapper around PetscSectionView(); in addition to the raw section, it saves information that associates the section points to the topology (dm) points. When the topology (dm) and the section are later loaded with DMPlexTopologyLoad() and DMPlexSectionLoad(), respectively, this information is used to match section points with topology points.

1933:   In general dm and sectiondm are two different objects, the former carrying the topology and the latter carrying the section, and have been given a topology name and a section name, respectively, with PetscObjectSetName(). In practice, however, they can be the same object if it carries both topology and section; in that case the name of the object is used as both the topology name and the section name.

1935: .seealso: `DMView()`, `DMPlexTopologyView()`, `DMPlexCoordinatesView()`, `DMPlexLabelsView()`, `DMPlexGlobalVectorView()`, `DMPlexLocalVectorView()`, `PetscSectionView()`, `DMPlexSectionLoad()`
1936: @*/
1937: PetscErrorCode DMPlexSectionView(DM dm, PetscViewer viewer, DM sectiondm)
1938: {
1939:   PetscBool ishdf5;

1944:   PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERHDF5, &ishdf5);
1945:   PetscLogEventBegin(DMPLEX_SectionView, viewer, 0, 0, 0);
1946:   if (ishdf5) {
1947: #if defined(PETSC_HAVE_HDF5)
1948:     DMPlexSectionView_HDF5_Internal(dm, viewer, sectiondm);
1949: #else
1950:     SETERRQ(PetscObjectComm((PetscObject)dm), PETSC_ERR_SUP, "HDF5 not supported in this build.\nPlease reconfigure using --download-hdf5");
1951: #endif
1952:   }
1953:   PetscLogEventEnd(DMPLEX_SectionView, viewer, 0, 0, 0);
1954:   return 0;
1955: }

1957: /*@
1958:   DMPlexGlobalVectorView - Saves a global vector

1960:   Collective on DM

1962:   Input Parameters:
1963: + dm        - The DM that represents the topology
1964: . viewer    - The PetscViewer to save data with
1965: . sectiondm - The DM that contains the global section on which vec is defined
1966: - vec       - The global vector to be saved

1968:   Level: advanced

1970:   Notes:
1971:   In general dm and sectiondm are two different objects, the former carrying the topology and the latter carrying the section, and have been given a topology name and a section name, respectively, with PetscObjectSetName(). In practice, however, they can be the same object if it carries both topology and section; in that case the name of the object is used as both the topology name and the section name.

1973:   Typical calling sequence
1974: $       DMCreate(PETSC_COMM_WORLD, &dm);
1975: $       DMSetType(dm, DMPLEX);
1976: $       PetscObjectSetName((PetscObject)dm, "topologydm_name");
1977: $       DMClone(dm, &sectiondm);
1978: $       PetscObjectSetName((PetscObject)sectiondm, "sectiondm_name");
1979: $       PetscSectionCreate(PETSC_COMM_WORLD, &section);
1980: $       DMPlexGetChart(sectiondm, &pStart, &pEnd);
1981: $       PetscSectionSetChart(section, pStart, pEnd);
1982: $       PetscSectionSetUp(section);
1983: $       DMSetLocalSection(sectiondm, section);
1984: $       PetscSectionDestroy(&section);
1985: $       DMGetGlobalVector(sectiondm, &vec);
1986: $       PetscObjectSetName((PetscObject)vec, "vec_name");
1987: $       DMPlexTopologyView(dm, viewer);
1988: $       DMPlexSectionView(dm, viewer, sectiondm);
1989: $       DMPlexGlobalVectorView(dm, viewer, sectiondm, vec);
1990: $       DMRestoreGlobalVector(sectiondm, &vec);
1991: $       DMDestroy(&sectiondm);
1992: $       DMDestroy(&dm);

1994: .seealso: `DMPlexTopologyView()`, `DMPlexSectionView()`, `DMPlexLocalVectorView()`, `DMPlexGlobalVectorLoad()`, `DMPlexLocalVectorLoad()`
1995: @*/
1996: PetscErrorCode DMPlexGlobalVectorView(DM dm, PetscViewer viewer, DM sectiondm, Vec vec)
1997: {
1998:   PetscBool ishdf5;

2004:   /* Check consistency */
2005:   {
2006:     PetscSection section;
2007:     PetscBool    includesConstraints;
2008:     PetscInt     m, m1;

2010:     VecGetLocalSize(vec, &m1);
2011:     DMGetGlobalSection(sectiondm, &section);
2012:     PetscSectionGetIncludesConstraints(section, &includesConstraints);
2013:     if (includesConstraints) PetscSectionGetStorageSize(section, &m);
2014:     else PetscSectionGetConstrainedStorageSize(section, &m);
2016:   }
2017:   PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERHDF5, &ishdf5);
2018:   PetscLogEventBegin(DMPLEX_GlobalVectorView, viewer, 0, 0, 0);
2019:   if (ishdf5) {
2020: #if defined(PETSC_HAVE_HDF5)
2021:     DMPlexGlobalVectorView_HDF5_Internal(dm, viewer, sectiondm, vec);
2022: #else
2023:     SETERRQ(PetscObjectComm((PetscObject)dm), PETSC_ERR_SUP, "HDF5 not supported in this build.\nPlease reconfigure using --download-hdf5");
2024: #endif
2025:   }
2026:   PetscLogEventEnd(DMPLEX_GlobalVectorView, viewer, 0, 0, 0);
2027:   return 0;
2028: }

2030: /*@
2031:   DMPlexLocalVectorView - Saves a local vector

2033:   Collective on DM

2035:   Input Parameters:
2036: + dm        - The DM that represents the topology
2037: . viewer    - The PetscViewer to save data with
2038: . sectiondm - The DM that contains the local section on which vec is defined; may be the same as dm
2039: - vec       - The local vector to be saved

2041:   Level: advanced

2043:   Notes:
2044:   In general dm and sectiondm are two different objects, the former carrying the topology and the latter carrying the section, and have been given a topology name and a section name, respectively, with PetscObjectSetName(). In practice, however, they can be the same object if it carries both topology and section; in that case the name of the object is used as both the topology name and the section name.

2046:   Typical calling sequence
2047: $       DMCreate(PETSC_COMM_WORLD, &dm);
2048: $       DMSetType(dm, DMPLEX);
2049: $       PetscObjectSetName((PetscObject)dm, "topologydm_name");
2050: $       DMClone(dm, &sectiondm);
2051: $       PetscObjectSetName((PetscObject)sectiondm, "sectiondm_name");
2052: $       PetscSectionCreate(PETSC_COMM_WORLD, &section);
2053: $       DMPlexGetChart(sectiondm, &pStart, &pEnd);
2054: $       PetscSectionSetChart(section, pStart, pEnd);
2055: $       PetscSectionSetUp(section);
2056: $       DMSetLocalSection(sectiondm, section);
2057: $       DMGetLocalVector(sectiondm, &vec);
2058: $       PetscObjectSetName((PetscObject)vec, "vec_name");
2059: $       DMPlexTopologyView(dm, viewer);
2060: $       DMPlexSectionView(dm, viewer, sectiondm);
2061: $       DMPlexLocalVectorView(dm, viewer, sectiondm, vec);
2062: $       DMRestoreLocalVector(sectiondm, &vec);
2063: $       DMDestroy(&sectiondm);
2064: $       DMDestroy(&dm);

2066: .seealso: `DMPlexTopologyView()`, `DMPlexSectionView()`, `DMPlexGlobalVectorView()`, `DMPlexGlobalVectorLoad()`, `DMPlexLocalVectorLoad()`
2067: @*/
2068: PetscErrorCode DMPlexLocalVectorView(DM dm, PetscViewer viewer, DM sectiondm, Vec vec)
2069: {
2070:   PetscBool ishdf5;

2076:   /* Check consistency */
2077:   {
2078:     PetscSection section;
2079:     PetscBool    includesConstraints;
2080:     PetscInt     m, m1;

2082:     VecGetLocalSize(vec, &m1);
2083:     DMGetLocalSection(sectiondm, &section);
2084:     PetscSectionGetIncludesConstraints(section, &includesConstraints);
2085:     if (includesConstraints) PetscSectionGetStorageSize(section, &m);
2086:     else PetscSectionGetConstrainedStorageSize(section, &m);
2088:   }
2089:   PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERHDF5, &ishdf5);
2090:   PetscLogEventBegin(DMPLEX_LocalVectorView, viewer, 0, 0, 0);
2091:   if (ishdf5) {
2092: #if defined(PETSC_HAVE_HDF5)
2093:     DMPlexLocalVectorView_HDF5_Internal(dm, viewer, sectiondm, vec);
2094: #else
2095:     SETERRQ(PetscObjectComm((PetscObject)dm), PETSC_ERR_SUP, "HDF5 not supported in this build.\nPlease reconfigure using --download-hdf5");
2096: #endif
2097:   }
2098:   PetscLogEventEnd(DMPLEX_LocalVectorView, viewer, 0, 0, 0);
2099:   return 0;
2100: }

2102: PetscErrorCode DMLoad_Plex(DM dm, PetscViewer viewer)
2103: {
2104:   PetscBool ishdf5;

2108:   PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERHDF5, &ishdf5);
2109:   if (ishdf5) {
2110: #if defined(PETSC_HAVE_HDF5)
2111:     PetscViewerFormat format;
2112:     PetscViewerGetFormat(viewer, &format);
2113:     if (format == PETSC_VIEWER_HDF5_XDMF || format == PETSC_VIEWER_HDF5_VIZ) {
2114:       DMPlexLoad_HDF5_Xdmf_Internal(dm, viewer);
2115:     } else if (format == PETSC_VIEWER_HDF5_PETSC || format == PETSC_VIEWER_DEFAULT || format == PETSC_VIEWER_NATIVE) {
2116:       DMPlexLoad_HDF5_Internal(dm, viewer);
2117:     } else SETERRQ(PetscObjectComm((PetscObject)dm), PETSC_ERR_SUP, "PetscViewerFormat %s not supported for HDF5 input.", PetscViewerFormats[format]);
2118:     return 0;
2119: #else
2120:     SETERRQ(PetscObjectComm((PetscObject)dm), PETSC_ERR_SUP, "HDF5 not supported in this build.\nPlease reconfigure using --download-hdf5");
2121: #endif
2122:   } else SETERRQ(PetscObjectComm((PetscObject)dm), PETSC_ERR_SUP, "Viewer type %s not yet supported for DMPlex loading", ((PetscObject)viewer)->type_name);
2123: }

2125: /*@
2126:   DMPlexTopologyLoad - Loads a topology into a DMPlex

2128:   Collective on DM

2130:   Input Parameters:
2131: + dm                - The DM into which the topology is loaded
2132: - viewer            - The PetscViewer for the saved topology

2134:   Output Parameters:
2135: . globalToLocalPointSF - The PetscSF that pushes points in [0, N) to the associated points in the loaded plex, where N is the global number of points; NULL if unneeded

2137:   Level: advanced

2139: .seealso: `DMLoad()`, `DMPlexCoordinatesLoad()`, `DMPlexLabelsLoad()`, `DMView()`, `PetscViewerHDF5Open()`, `PetscViewerPushFormat()`
2140: @*/
2141: PetscErrorCode DMPlexTopologyLoad(DM dm, PetscViewer viewer, PetscSF *globalToLocalPointSF)
2142: {
2143:   PetscBool ishdf5;

2148:   PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERHDF5, &ishdf5);
2149:   PetscLogEventBegin(DMPLEX_TopologyLoad, viewer, 0, 0, 0);
2150:   if (ishdf5) {
2151: #if defined(PETSC_HAVE_HDF5)
2152:     PetscViewerFormat format;
2153:     PetscViewerGetFormat(viewer, &format);
2154:     if (format == PETSC_VIEWER_HDF5_PETSC || format == PETSC_VIEWER_DEFAULT || format == PETSC_VIEWER_NATIVE) {
2155:       DMPlexTopologyLoad_HDF5_Internal(dm, viewer, globalToLocalPointSF);
2156:     } else SETERRQ(PetscObjectComm((PetscObject)dm), PETSC_ERR_SUP, "PetscViewerFormat %s not supported for HDF5 input.", PetscViewerFormats[format]);
2157: #else
2158:     SETERRQ(PetscObjectComm((PetscObject)dm), PETSC_ERR_SUP, "HDF5 not supported in this build.\nPlease reconfigure using --download-hdf5");
2159: #endif
2160:   }
2161:   PetscLogEventEnd(DMPLEX_TopologyLoad, viewer, 0, 0, 0);
2162:   return 0;
2163: }

2165: /*@
2166:   DMPlexCoordinatesLoad - Loads coordinates into a DMPlex

2168:   Collective on DM

2170:   Input Parameters:
2171: + dm     - The DM into which the coordinates are loaded
2172: . viewer - The PetscViewer for the saved coordinates
2173: - globalToLocalPointSF - The SF returned by DMPlexTopologyLoad() when loading dm from viewer

2175:   Level: advanced

2177: .seealso: `DMLoad()`, `DMPlexTopologyLoad()`, `DMPlexLabelsLoad()`, `DMView()`, `PetscViewerHDF5Open()`, `PetscViewerPushFormat()`
2178: @*/
2179: PetscErrorCode DMPlexCoordinatesLoad(DM dm, PetscViewer viewer, PetscSF globalToLocalPointSF)
2180: {
2181:   PetscBool ishdf5;

2186:   PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERHDF5, &ishdf5);
2187:   PetscLogEventBegin(DMPLEX_CoordinatesLoad, viewer, 0, 0, 0);
2188:   if (ishdf5) {
2189: #if defined(PETSC_HAVE_HDF5)
2190:     PetscViewerFormat format;
2191:     PetscViewerGetFormat(viewer, &format);
2192:     if (format == PETSC_VIEWER_HDF5_PETSC || format == PETSC_VIEWER_DEFAULT || format == PETSC_VIEWER_NATIVE) {
2193:       DMPlexCoordinatesLoad_HDF5_Internal(dm, viewer, globalToLocalPointSF);
2194:     } else SETERRQ(PetscObjectComm((PetscObject)dm), PETSC_ERR_SUP, "PetscViewerFormat %s not supported for HDF5 input.", PetscViewerFormats[format]);
2195: #else
2196:     SETERRQ(PetscObjectComm((PetscObject)dm), PETSC_ERR_SUP, "HDF5 not supported in this build.\nPlease reconfigure using --download-hdf5");
2197: #endif
2198:   }
2199:   PetscLogEventEnd(DMPLEX_CoordinatesLoad, viewer, 0, 0, 0);
2200:   return 0;
2201: }

2203: /*@
2204:   DMPlexLabelsLoad - Loads labels into a DMPlex

2206:   Collective on DM

2208:   Input Parameters:
2209: + dm     - The DM into which the labels are loaded
2210: . viewer - The PetscViewer for the saved labels
2211: - globalToLocalPointSF - The SF returned by DMPlexTopologyLoad() when loading dm from viewer

2213:   Level: advanced

2215:   Notes:
2216:   The PetscSF argument must not be NULL if the DM is distributed, otherwise an error occurs.

2218: .seealso: `DMLoad()`, `DMPlexTopologyLoad()`, `DMPlexCoordinatesLoad()`, `DMView()`, `PetscViewerHDF5Open()`, `PetscViewerPushFormat()`
2219: @*/
2220: PetscErrorCode DMPlexLabelsLoad(DM dm, PetscViewer viewer, PetscSF globalToLocalPointSF)
2221: {
2222:   PetscBool ishdf5;

2227:   PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERHDF5, &ishdf5);
2228:   PetscLogEventBegin(DMPLEX_LabelsLoad, viewer, 0, 0, 0);
2229:   if (ishdf5) {
2230: #if defined(PETSC_HAVE_HDF5)
2231:     PetscViewerFormat format;

2233:     PetscViewerGetFormat(viewer, &format);
2234:     if (format == PETSC_VIEWER_HDF5_PETSC || format == PETSC_VIEWER_DEFAULT || format == PETSC_VIEWER_NATIVE) {
2235:       DMPlexLabelsLoad_HDF5_Internal(dm, viewer, globalToLocalPointSF);
2236:     } else SETERRQ(PetscObjectComm((PetscObject)dm), PETSC_ERR_SUP, "PetscViewerFormat %s not supported for HDF5 input.", PetscViewerFormats[format]);
2237: #else
2238:     SETERRQ(PetscObjectComm((PetscObject)dm), PETSC_ERR_SUP, "HDF5 not supported in this build.\nPlease reconfigure using --download-hdf5");
2239: #endif
2240:   }
2241:   PetscLogEventEnd(DMPLEX_LabelsLoad, viewer, 0, 0, 0);
2242:   return 0;
2243: }

2245: /*@
2246:   DMPlexSectionLoad - Loads section into a DMPlex

2248:   Collective on DM

2250:   Input Parameters:
2251: + dm          - The DM that represents the topology
2252: . viewer      - The PetscViewer that represents the on-disk section (sectionA)
2253: . sectiondm   - The DM into which the on-disk section (sectionA) is migrated
2254: - globalToLocalPointSF - The SF returned by DMPlexTopologyLoad() when loading dm from viewer

2256:   Output Parameters
2257: + globalDofSF - The SF that migrates any on-disk Vec data associated with sectionA into a global Vec associated with the sectiondm's global section (NULL if not needed)
2258: - localDofSF  - The SF that migrates any on-disk Vec data associated with sectionA into a local Vec associated with the sectiondm's local section (NULL if not needed)

2260:   Level: advanced

2262:   Notes:
2263:   This function is a wrapper around PetscSectionLoad(); it loads, in addition to the raw section, a list of global point numbers that associates each on-disk section point with a global point number in [0, NX), where NX is the number of topology points in dm. Noting that globalToLocalPointSF associates each topology point in dm with a global number in [0, NX), one can readily establish an association of the on-disk section points with the topology points.

2265:   In general dm and sectiondm are two different objects, the former carrying the topology and the latter carrying the section, and have been given a topology name and a section name, respectively, with PetscObjectSetName(). In practice, however, they can be the same object if it carries both topology and section; in that case the name of the object is used as both the topology name and the section name.

2267:   The output parameter, globalDofSF (localDofSF), can later be used with DMPlexGlobalVectorLoad() (DMPlexLocalVectorLoad()) to load on-disk vectors into global (local) vectors associated with sectiondm's global (local) section.

2269:   Example using 2 processes:
2270: $  NX (number of points on dm): 4
2271: $  sectionA                   : the on-disk section
2272: $  vecA                       : a vector associated with sectionA
2273: $  sectionB                   : sectiondm's local section constructed in this function
2274: $  vecB (local)               : a vector associated with sectiondm's local section
2275: $  vecB (global)              : a vector associated with sectiondm's global section
2276: $
2277: $                                     rank 0    rank 1
2278: $  vecA (global)                  : [.0 .4 .1 | .2 .3]        <- to be loaded in DMPlexGlobalVectorLoad() or DMPlexLocalVectorLoad()
2279: $  sectionA->atlasOff             :       0 2 | 1             <- loaded in PetscSectionLoad()
2280: $  sectionA->atlasDof             :       1 3 | 1             <- loaded in PetscSectionLoad()
2281: $  sectionA's global point numbers:       0 2 | 3             <- loaded in DMPlexSectionLoad()
2282: $  [0, NX)                        :       0 1 | 2 3           <- conceptual partition used in globalToLocalPointSF
2283: $  sectionB's global point numbers:     0 1 3 | 3 2           <- associated with [0, NX) by globalToLocalPointSF
2284: $  sectionB->atlasDof             :     1 0 1 | 1 3
2285: $  sectionB->atlasOff (no perm)   :     0 1 1 | 0 1
2286: $  vecB (local)                   :   [.0 .4] | [.4 .1 .2 .3] <- to be constructed by calling DMPlexLocalVectorLoad() with localDofSF
2287: $  vecB (global)                  :    [.0 .4 | .1 .2 .3]     <- to be constructed by calling DMPlexGlobalVectorLoad() with globalDofSF
2288: $
2289: $  where "|" represents a partition of loaded data, and global point 3 is assumed to be owned by rank 0.

2291: .seealso: `DMLoad()`, `DMPlexTopologyLoad()`, `DMPlexCoordinatesLoad()`, `DMPlexLabelsLoad()`, `DMPlexGlobalVectorLoad()`, `DMPlexLocalVectorLoad()`, `PetscSectionLoad()`, `DMPlexSectionView()`
2292: @*/
2293: PetscErrorCode DMPlexSectionLoad(DM dm, PetscViewer viewer, DM sectiondm, PetscSF globalToLocalPointSF, PetscSF *globalDofSF, PetscSF *localDofSF)
2294: {
2295:   PetscBool ishdf5;

2303:   PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERHDF5, &ishdf5);
2304:   PetscLogEventBegin(DMPLEX_SectionLoad, viewer, 0, 0, 0);
2305:   if (ishdf5) {
2306: #if defined(PETSC_HAVE_HDF5)
2307:     DMPlexSectionLoad_HDF5_Internal(dm, viewer, sectiondm, globalToLocalPointSF, globalDofSF, localDofSF);
2308: #else
2309:     SETERRQ(PetscObjectComm((PetscObject)dm), PETSC_ERR_SUP, "HDF5 not supported in this build.\nPlease reconfigure using --download-hdf5");
2310: #endif
2311:   }
2312:   PetscLogEventEnd(DMPLEX_SectionLoad, viewer, 0, 0, 0);
2313:   return 0;
2314: }

2316: /*@
2317:   DMPlexGlobalVectorLoad - Loads on-disk vector data into a global vector

2319:   Collective on DM

2321:   Input Parameters:
2322: + dm        - The DM that represents the topology
2323: . viewer    - The PetscViewer that represents the on-disk vector data
2324: . sectiondm - The DM that contains the global section on which vec is defined
2325: . sf        - The SF that migrates the on-disk vector data into vec
2326: - vec       - The global vector to set values of

2328:   Level: advanced

2330:   Notes:
2331:   In general dm and sectiondm are two different objects, the former carrying the topology and the latter carrying the section, and have been given a topology name and a section name, respectively, with PetscObjectSetName(). In practice, however, they can be the same object if it carries both topology and section; in that case the name of the object is used as both the topology name and the section name.

2333:   Typical calling sequence
2334: $       DMCreate(PETSC_COMM_WORLD, &dm);
2335: $       DMSetType(dm, DMPLEX);
2336: $       PetscObjectSetName((PetscObject)dm, "topologydm_name");
2337: $       DMPlexTopologyLoad(dm, viewer, &sfX);
2338: $       DMClone(dm, &sectiondm);
2339: $       PetscObjectSetName((PetscObject)sectiondm, "sectiondm_name");
2340: $       DMPlexSectionLoad(dm, viewer, sectiondm, sfX, &gsf, NULL);
2341: $       DMGetGlobalVector(sectiondm, &vec);
2342: $       PetscObjectSetName((PetscObject)vec, "vec_name");
2343: $       DMPlexGlobalVectorLoad(dm, viewer, sectiondm, gsf, vec);
2344: $       DMRestoreGlobalVector(sectiondm, &vec);
2345: $       PetscSFDestroy(&gsf);
2346: $       PetscSFDestroy(&sfX);
2347: $       DMDestroy(&sectiondm);
2348: $       DMDestroy(&dm);

2350: .seealso: `DMPlexTopologyLoad()`, `DMPlexSectionLoad()`, `DMPlexLocalVectorLoad()`, `DMPlexGlobalVectorView()`, `DMPlexLocalVectorView()`
2351: @*/
2352: PetscErrorCode DMPlexGlobalVectorLoad(DM dm, PetscViewer viewer, DM sectiondm, PetscSF sf, Vec vec)
2353: {
2354:   PetscBool ishdf5;

2361:   /* Check consistency */
2362:   {
2363:     PetscSection section;
2364:     PetscBool    includesConstraints;
2365:     PetscInt     m, m1;

2367:     VecGetLocalSize(vec, &m1);
2368:     DMGetGlobalSection(sectiondm, &section);
2369:     PetscSectionGetIncludesConstraints(section, &includesConstraints);
2370:     if (includesConstraints) PetscSectionGetStorageSize(section, &m);
2371:     else PetscSectionGetConstrainedStorageSize(section, &m);
2373:   }
2374:   PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERHDF5, &ishdf5);
2375:   PetscLogEventBegin(DMPLEX_GlobalVectorLoad, viewer, 0, 0, 0);
2376:   if (ishdf5) {
2377: #if defined(PETSC_HAVE_HDF5)
2378:     DMPlexVecLoad_HDF5_Internal(dm, viewer, sectiondm, sf, vec);
2379: #else
2380:     SETERRQ(PetscObjectComm((PetscObject)dm), PETSC_ERR_SUP, "HDF5 not supported in this build.\nPlease reconfigure using --download-hdf5");
2381: #endif
2382:   }
2383:   PetscLogEventEnd(DMPLEX_GlobalVectorLoad, viewer, 0, 0, 0);
2384:   return 0;
2385: }

2387: /*@
2388:   DMPlexLocalVectorLoad - Loads on-disk vector data into a local vector

2390:   Collective on DM

2392:   Input Parameters:
2393: + dm        - The DM that represents the topology
2394: . viewer    - The PetscViewer that represents the on-disk vector data
2395: . sectiondm - The DM that contains the local section on which vec is defined
2396: . sf        - The SF that migrates the on-disk vector data into vec
2397: - vec       - The local vector to set values of

2399:   Level: advanced

2401:   Notes:
2402:   In general dm and sectiondm are two different objects, the former carrying the topology and the latter carrying the section, and have been given a topology name and a section name, respectively, with PetscObjectSetName(). In practice, however, they can be the same object if it carries both topology and section; in that case the name of the object is used as both the topology name and the section name.

2404:   Typical calling sequence
2405: $       DMCreate(PETSC_COMM_WORLD, &dm);
2406: $       DMSetType(dm, DMPLEX);
2407: $       PetscObjectSetName((PetscObject)dm, "topologydm_name");
2408: $       DMPlexTopologyLoad(dm, viewer, &sfX);
2409: $       DMClone(dm, &sectiondm);
2410: $       PetscObjectSetName((PetscObject)sectiondm, "sectiondm_name");
2411: $       DMPlexSectionLoad(dm, viewer, sectiondm, sfX, NULL, &lsf);
2412: $       DMGetLocalVector(sectiondm, &vec);
2413: $       PetscObjectSetName((PetscObject)vec, "vec_name");
2414: $       DMPlexLocalVectorLoad(dm, viewer, sectiondm, lsf, vec);
2415: $       DMRestoreLocalVector(sectiondm, &vec);
2416: $       PetscSFDestroy(&lsf);
2417: $       PetscSFDestroy(&sfX);
2418: $       DMDestroy(&sectiondm);
2419: $       DMDestroy(&dm);

2421: .seealso: `DMPlexTopologyLoad()`, `DMPlexSectionLoad()`, `DMPlexGlobalVectorLoad()`, `DMPlexGlobalVectorView()`, `DMPlexLocalVectorView()`
2422: @*/
2423: PetscErrorCode DMPlexLocalVectorLoad(DM dm, PetscViewer viewer, DM sectiondm, PetscSF sf, Vec vec)
2424: {
2425:   PetscBool ishdf5;

2432:   /* Check consistency */
2433:   {
2434:     PetscSection section;
2435:     PetscBool    includesConstraints;
2436:     PetscInt     m, m1;

2438:     VecGetLocalSize(vec, &m1);
2439:     DMGetLocalSection(sectiondm, &section);
2440:     PetscSectionGetIncludesConstraints(section, &includesConstraints);
2441:     if (includesConstraints) PetscSectionGetStorageSize(section, &m);
2442:     else PetscSectionGetConstrainedStorageSize(section, &m);
2444:   }
2445:   PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERHDF5, &ishdf5);
2446:   PetscLogEventBegin(DMPLEX_LocalVectorLoad, viewer, 0, 0, 0);
2447:   if (ishdf5) {
2448: #if defined(PETSC_HAVE_HDF5)
2449:     DMPlexVecLoad_HDF5_Internal(dm, viewer, sectiondm, sf, vec);
2450: #else
2451:     SETERRQ(PetscObjectComm((PetscObject)dm), PETSC_ERR_SUP, "HDF5 not supported in this build.\nPlease reconfigure using --download-hdf5");
2452: #endif
2453:   }
2454:   PetscLogEventEnd(DMPLEX_LocalVectorLoad, viewer, 0, 0, 0);
2455:   return 0;
2456: }

2458: PetscErrorCode DMDestroy_Plex(DM dm)
2459: {
2460:   DM_Plex *mesh = (DM_Plex *)dm->data;

2462:   PetscObjectComposeFunction((PetscObject)dm, "DMSetUpGLVisViewer_C", NULL);
2463:   PetscObjectComposeFunction((PetscObject)dm, "DMPlexInsertBoundaryValues_C", NULL);
2464:   PetscObjectComposeFunction((PetscObject)dm, "DMCreateNeumannOverlap_C", NULL);
2465:   PetscObjectComposeFunction((PetscObject)dm, "DMInterpolateSolution_C", NULL);
2466:   PetscObjectComposeFunction((PetscObject)dm, "DMPlexInsertTimeDerviativeBoundaryValues_C", NULL);
2467:   PetscObjectComposeFunction((PetscObject)dm, "DMPlexGetOverlap_C", NULL);
2468:   PetscObjectComposeFunction((PetscObject)dm, "DMPlexDistributeGetDefault_C", NULL);
2469:   PetscObjectComposeFunction((PetscObject)dm, "DMPlexDistributeSetDefault_C", NULL);
2470:   PetscObjectComposeFunction((PetscObject)dm, "MatComputeNeumannOverlap_C", NULL);
2471:   PetscObjectComposeFunction((PetscObject)dm, "DMPlexReorderGetDefault_C", NULL);
2472:   PetscObjectComposeFunction((PetscObject)dm, "DMPlexReorderSetDefault_C", NULL);
2473:   PetscObjectComposeFunction((PetscObject)dm, "DMPlexGetOverlap_C", NULL);
2474:   PetscObjectComposeFunction((PetscObject)dm, "DMPlexSetOverlap_C", NULL);
2475:   if (--mesh->refct > 0) return 0;
2476:   PetscSectionDestroy(&mesh->coneSection);
2477:   PetscFree(mesh->cones);
2478:   PetscFree(mesh->coneOrientations);
2479:   PetscSectionDestroy(&mesh->supportSection);
2480:   PetscSectionDestroy(&mesh->subdomainSection);
2481:   PetscFree(mesh->supports);
2482:   PetscFree(mesh->facesTmp);
2483:   PetscFree(mesh->tetgenOpts);
2484:   PetscFree(mesh->triangleOpts);
2485:   PetscFree(mesh->transformType);
2486:   PetscFree(mesh->distributionName);
2487:   PetscPartitionerDestroy(&mesh->partitioner);
2488:   DMLabelDestroy(&mesh->subpointMap);
2489:   ISDestroy(&mesh->subpointIS);
2490:   ISDestroy(&mesh->globalVertexNumbers);
2491:   ISDestroy(&mesh->globalCellNumbers);
2492:   PetscSectionDestroy(&mesh->anchorSection);
2493:   ISDestroy(&mesh->anchorIS);
2494:   PetscSectionDestroy(&mesh->parentSection);
2495:   PetscFree(mesh->parents);
2496:   PetscFree(mesh->childIDs);
2497:   PetscSectionDestroy(&mesh->childSection);
2498:   PetscFree(mesh->children);
2499:   DMDestroy(&mesh->referenceTree);
2500:   PetscGridHashDestroy(&mesh->lbox);
2501:   PetscFree(mesh->neighbors);
2502:   if (mesh->metricCtx) PetscFree(mesh->metricCtx);
2503:   /* This was originally freed in DMDestroy(), but that prevents reference counting of backend objects */
2504:   PetscFree(mesh);
2505:   return 0;
2506: }

2508: PetscErrorCode DMCreateMatrix_Plex(DM dm, Mat *J)
2509: {
2510:   PetscSection           sectionGlobal;
2511:   PetscInt               bs = -1, mbs;
2512:   PetscInt               localSize, localStart = 0;
2513:   PetscBool              isShell, isBlock, isSeqBlock, isMPIBlock, isSymBlock, isSymSeqBlock, isSymMPIBlock, isMatIS;
2514:   MatType                mtype;
2515:   ISLocalToGlobalMapping ltog;

2517:   MatInitializePackage();
2518:   mtype = dm->mattype;
2519:   DMGetGlobalSection(dm, &sectionGlobal);
2520:   /* PetscSectionGetStorageSize(sectionGlobal, &localSize); */
2521:   PetscSectionGetConstrainedStorageSize(sectionGlobal, &localSize);
2522:   MPI_Exscan(&localSize, &localStart, 1, MPIU_INT, MPI_SUM, PetscObjectComm((PetscObject)dm));
2523:   MatCreate(PetscObjectComm((PetscObject)dm), J);
2524:   MatSetSizes(*J, localSize, localSize, PETSC_DETERMINE, PETSC_DETERMINE);
2525:   MatSetType(*J, mtype);
2526:   MatSetFromOptions(*J);
2527:   MatGetBlockSize(*J, &mbs);
2528:   if (mbs > 1) bs = mbs;
2529:   PetscStrcmp(mtype, MATSHELL, &isShell);
2530:   PetscStrcmp(mtype, MATBAIJ, &isBlock);
2531:   PetscStrcmp(mtype, MATSEQBAIJ, &isSeqBlock);
2532:   PetscStrcmp(mtype, MATMPIBAIJ, &isMPIBlock);
2533:   PetscStrcmp(mtype, MATSBAIJ, &isSymBlock);
2534:   PetscStrcmp(mtype, MATSEQSBAIJ, &isSymSeqBlock);
2535:   PetscStrcmp(mtype, MATMPISBAIJ, &isSymMPIBlock);
2536:   PetscStrcmp(mtype, MATIS, &isMatIS);
2537:   if (!isShell) {
2538:     PetscBool fillMatrix = (PetscBool)(!dm->prealloc_only && !isMatIS);
2539:     PetscInt *dnz, *onz, *dnzu, *onzu, bsLocal[2], bsMinMax[2], *pblocks;
2540:     PetscInt  pStart, pEnd, p, dof, cdof;

2542:     DMGetLocalToGlobalMapping(dm, &ltog);

2544:     PetscCalloc1(localSize, &pblocks);
2545:     PetscSectionGetChart(sectionGlobal, &pStart, &pEnd);
2546:     for (p = pStart; p < pEnd; ++p) {
2547:       PetscInt bdof, offset;

2549:       PetscSectionGetDof(sectionGlobal, p, &dof);
2550:       PetscSectionGetOffset(sectionGlobal, p, &offset);
2551:       PetscSectionGetConstraintDof(sectionGlobal, p, &cdof);
2552:       for (PetscInt i = 0; i < dof - cdof; i++) pblocks[offset - localStart + i] = dof - cdof;
2553:       dof  = dof < 0 ? -(dof + 1) : dof;
2554:       bdof = cdof && (dof - cdof) ? 1 : dof;
2555:       if (dof) {
2556:         if (bs < 0) {
2557:           bs = bdof;
2558:         } else if (bs != bdof) {
2559:           bs = 1;
2560:         }
2561:       }
2562:     }
2563:     /* Must have same blocksize on all procs (some might have no points) */
2564:     bsLocal[0] = bs < 0 ? PETSC_MAX_INT : bs;
2565:     bsLocal[1] = bs;
2566:     PetscGlobalMinMaxInt(PetscObjectComm((PetscObject)dm), bsLocal, bsMinMax);
2567:     if (bsMinMax[0] != bsMinMax[1]) bs = 1;
2568:     else bs = bsMinMax[0];
2569:     bs = PetscMax(1, bs);
2570:     MatSetLocalToGlobalMapping(*J, ltog, ltog);
2571:     if (dm->prealloc_skip) { // User will likely use MatSetPreallocationCOO(), but still set structural parameters
2572:       MatSetBlockSize(*J, bs);
2573:       MatSetUp(*J);
2574:     } else {
2575:       PetscCalloc4(localSize / bs, &dnz, localSize / bs, &onz, localSize / bs, &dnzu, localSize / bs, &onzu);
2576:       DMPlexPreallocateOperator(dm, bs, dnz, onz, dnzu, onzu, *J, fillMatrix);
2577:       PetscFree4(dnz, onz, dnzu, onzu);
2578:     }
2579:     { // Consolidate blocks
2580:       PetscInt nblocks = 0;
2581:       for (PetscInt i = 0; i < localSize; i += PetscMax(1, pblocks[i])) {
2582:         if (pblocks[i] == 0) continue;
2583:         pblocks[nblocks++] = pblocks[i]; // nblocks always <= i
2585:       }
2586:       MatSetVariableBlockSizes(*J, nblocks, pblocks);
2587:     }
2588:     PetscFree(pblocks);
2589:   }
2590:   MatSetDM(*J, dm);
2591:   return 0;
2592: }

2594: /*@
2595:   DMPlexGetSubdomainSection - Returns the section associated with the subdomain

2597:   Not collective

2599:   Input Parameter:
2600: . mesh - The DMPlex

2602:   Output Parameters:
2603: . subsection - The subdomain section

2605:   Level: developer

2607: .seealso:
2608: @*/
2609: PetscErrorCode DMPlexGetSubdomainSection(DM dm, PetscSection *subsection)
2610: {
2611:   DM_Plex *mesh = (DM_Plex *)dm->data;

2614:   if (!mesh->subdomainSection) {
2615:     PetscSection section;
2616:     PetscSF      sf;

2618:     PetscSFCreate(PETSC_COMM_SELF, &sf);
2619:     DMGetLocalSection(dm, &section);
2620:     PetscSectionCreateGlobalSection(section, sf, PETSC_FALSE, PETSC_TRUE, &mesh->subdomainSection);
2621:     PetscSFDestroy(&sf);
2622:   }
2623:   *subsection = mesh->subdomainSection;
2624:   return 0;
2625: }

2627: /*@
2628:   DMPlexGetChart - Return the interval for all mesh points [pStart, pEnd)

2630:   Not collective

2632:   Input Parameter:
2633: . mesh - The DMPlex

2635:   Output Parameters:
2636: + pStart - The first mesh point
2637: - pEnd   - The upper bound for mesh points

2639:   Level: beginner

2641: .seealso: `DMPlexCreate()`, `DMPlexSetChart()`
2642: @*/
2643: PetscErrorCode DMPlexGetChart(DM dm, PetscInt *pStart, PetscInt *pEnd)
2644: {
2645:   DM_Plex *mesh = (DM_Plex *)dm->data;

2648:   PetscSectionGetChart(mesh->coneSection, pStart, pEnd);
2649:   return 0;
2650: }

2652: /*@
2653:   DMPlexSetChart - Set the interval for all mesh points [pStart, pEnd)

2655:   Not collective

2657:   Input Parameters:
2658: + mesh - The DMPlex
2659: . pStart - The first mesh point
2660: - pEnd   - The upper bound for mesh points

2662:   Output Parameters:

2664:   Level: beginner

2666: .seealso: `DMPlexCreate()`, `DMPlexGetChart()`
2667: @*/
2668: PetscErrorCode DMPlexSetChart(DM dm, PetscInt pStart, PetscInt pEnd)
2669: {
2670:   DM_Plex *mesh = (DM_Plex *)dm->data;

2673:   PetscSectionSetChart(mesh->coneSection, pStart, pEnd);
2674:   PetscSectionSetChart(mesh->supportSection, pStart, pEnd);
2675:   return 0;
2676: }

2678: /*@
2679:   DMPlexGetConeSize - Return the number of in-edges for this point in the DAG

2681:   Not collective

2683:   Input Parameters:
2684: + mesh - The DMPlex
2685: - p - The point, which must lie in the chart set with DMPlexSetChart()

2687:   Output Parameter:
2688: . size - The cone size for point p

2690:   Level: beginner

2692: .seealso: `DMPlexCreate()`, `DMPlexSetConeSize()`, `DMPlexSetChart()`
2693: @*/
2694: PetscErrorCode DMPlexGetConeSize(DM dm, PetscInt p, PetscInt *size)
2695: {
2696:   DM_Plex *mesh = (DM_Plex *)dm->data;

2700:   PetscSectionGetDof(mesh->coneSection, p, size);
2701:   return 0;
2702: }

2704: /*@
2705:   DMPlexSetConeSize - Set the number of in-edges for this point in the DAG

2707:   Not collective

2709:   Input Parameters:
2710: + mesh - The DMPlex
2711: . p - The point, which must lie in the chart set with DMPlexSetChart()
2712: - size - The cone size for point p

2714:   Output Parameter:

2716:   Note:
2717:   This should be called after DMPlexSetChart().

2719:   Level: beginner

2721: .seealso: `DMPlexCreate()`, `DMPlexGetConeSize()`, `DMPlexSetChart()`
2722: @*/
2723: PetscErrorCode DMPlexSetConeSize(DM dm, PetscInt p, PetscInt size)
2724: {
2725:   DM_Plex *mesh = (DM_Plex *)dm->data;

2728:   PetscSectionSetDof(mesh->coneSection, p, size);
2729:   return 0;
2730: }

2732: /*@
2733:   DMPlexAddConeSize - Add the given number of in-edges to this point in the DAG

2735:   Not collective

2737:   Input Parameters:
2738: + mesh - The DMPlex
2739: . p - The point, which must lie in the chart set with DMPlexSetChart()
2740: - size - The additional cone size for point p

2742:   Output Parameter:

2744:   Note:
2745:   This should be called after DMPlexSetChart().

2747:   Level: beginner

2749: .seealso: `DMPlexCreate()`, `DMPlexSetConeSize()`, `DMPlexGetConeSize()`, `DMPlexSetChart()`
2750: @*/
2751: PetscErrorCode DMPlexAddConeSize(DM dm, PetscInt p, PetscInt size)
2752: {
2753:   DM_Plex *mesh = (DM_Plex *)dm->data;
2755:   PetscSectionAddDof(mesh->coneSection, p, size);
2756:   return 0;
2757: }

2759: /*@C
2760:   DMPlexGetCone - Return the points on the in-edges for this point in the DAG

2762:   Not collective

2764:   Input Parameters:
2765: + dm - The DMPlex
2766: - p - The point, which must lie in the chart set with DMPlexSetChart()

2768:   Output Parameter:
2769: . cone - An array of points which are on the in-edges for point p

2771:   Level: beginner

2773:   Fortran Notes:
2774:   Since it returns an array, this routine is only available in Fortran 90, and you must
2775:   include petsc.h90 in your code.
2776:   You must also call DMPlexRestoreCone() after you finish using the returned array.
2777:   DMPlexRestoreCone() is not needed/available in C.

2779: .seealso: `DMPlexGetConeSize()`, `DMPlexSetCone()`, `DMPlexGetConeTuple()`, `DMPlexSetChart()`
2780: @*/
2781: PetscErrorCode DMPlexGetCone(DM dm, PetscInt p, const PetscInt *cone[])
2782: {
2783:   DM_Plex *mesh = (DM_Plex *)dm->data;
2784:   PetscInt off;

2788:   PetscSectionGetOffset(mesh->coneSection, p, &off);
2789:   *cone = &mesh->cones[off];
2790:   return 0;
2791: }

2793: /*@C
2794:   DMPlexGetConeTuple - Return the points on the in-edges of several points in the DAG

2796:   Not collective

2798:   Input Parameters:
2799: + dm - The DMPlex
2800: - p - The IS of points, which must lie in the chart set with DMPlexSetChart()

2802:   Output Parameters:
2803: + pConesSection - PetscSection describing the layout of pCones
2804: - pCones - An array of points which are on the in-edges for the point set p

2806:   Level: intermediate

2808: .seealso: `DMPlexCreate()`, `DMPlexGetCone()`, `DMPlexGetConeRecursive()`, `DMPlexSetChart()`
2809: @*/
2810: PetscErrorCode DMPlexGetConeTuple(DM dm, IS p, PetscSection *pConesSection, IS *pCones)
2811: {
2812:   PetscSection cs, newcs;
2813:   PetscInt    *cones;
2814:   PetscInt    *newarr = NULL;
2815:   PetscInt     n;

2817:   DMPlexGetCones(dm, &cones);
2818:   DMPlexGetConeSection(dm, &cs);
2819:   PetscSectionExtractDofsFromArray(cs, MPIU_INT, cones, p, &newcs, pCones ? ((void **)&newarr) : NULL);
2820:   if (pConesSection) *pConesSection = newcs;
2821:   if (pCones) {
2822:     PetscSectionGetStorageSize(newcs, &n);
2823:     ISCreateGeneral(PetscObjectComm((PetscObject)p), n, newarr, PETSC_OWN_POINTER, pCones);
2824:   }
2825:   return 0;
2826: }

2828: /*@
2829:   DMPlexGetConeRecursiveVertices - Expand each given point into its cone points and do that recursively until we end up just with vertices.

2831:   Not collective

2833:   Input Parameters:
2834: + dm - The DMPlex
2835: - points - The IS of points, which must lie in the chart set with DMPlexSetChart()

2837:   Output Parameter:
2838: . expandedPoints - An array of vertices recursively expanded from input points

2840:   Level: advanced

2842:   Notes:
2843:   Like DMPlexGetConeRecursive but returns only the 0-depth IS (i.e. vertices only) and no sections.
2844:   There is no corresponding Restore function, just call ISDestroy() on the returned IS to deallocate.

2846: .seealso: `DMPlexCreate()`, `DMPlexGetCone()`, `DMPlexGetConeTuple()`, `DMPlexGetConeRecursive()`, `DMPlexRestoreConeRecursive()`, `DMPlexGetDepth()`
2847: @*/
2848: PetscErrorCode DMPlexGetConeRecursiveVertices(DM dm, IS points, IS *expandedPoints)
2849: {
2850:   IS      *expandedPointsAll;
2851:   PetscInt depth;

2856:   DMPlexGetConeRecursive(dm, points, &depth, &expandedPointsAll, NULL);
2857:   *expandedPoints = expandedPointsAll[0];
2858:   PetscObjectReference((PetscObject)expandedPointsAll[0]);
2859:   DMPlexRestoreConeRecursive(dm, points, &depth, &expandedPointsAll, NULL);
2860:   return 0;
2861: }

2863: /*@
2864:   DMPlexGetConeRecursive - Expand each given point into its cone points and do that recursively until we end up just with vertices (DAG points of depth 0, i.e. without cones).

2866:   Not collective

2868:   Input Parameters:
2869: + dm - The DMPlex
2870: - points - The IS of points, which must lie in the chart set with DMPlexSetChart()

2872:   Output Parameters:
2873: + depth - (optional) Size of the output arrays, equal to DMPlex depth, returned by DMPlexGetDepth()
2874: . expandedPoints - (optional) An array of index sets with recursively expanded cones
2875: - sections - (optional) An array of sections which describe mappings from points to their cone points

2877:   Level: advanced

2879:   Notes:
2880:   Like DMPlexGetConeTuple() but recursive.

2882:   Array expandedPoints has size equal to depth. Each expandedPoints[d] contains DAG points with maximum depth d, recursively cone-wise expanded from the input points.
2883:   For example, for d=0 it contains only vertices, for d=1 it can contain vertices and edges, etc.

2885:   Array section has size equal to depth.  Each PetscSection sections[d] realizes mapping from expandedPoints[d+1] (section points) to expandedPoints[d] (section dofs) as follows:
2886:   (1) DAG points in expandedPoints[d+1] with depth d+1 to their cone points in expandedPoints[d];
2887:   (2) DAG points in expandedPoints[d+1] with depth in [0,d] to the same points in expandedPoints[d].

2889: .seealso: `DMPlexCreate()`, `DMPlexGetCone()`, `DMPlexGetConeTuple()`, `DMPlexRestoreConeRecursive()`, `DMPlexGetConeRecursiveVertices()`, `DMPlexGetDepth()`
2890: @*/
2891: PetscErrorCode DMPlexGetConeRecursive(DM dm, IS points, PetscInt *depth, IS *expandedPoints[], PetscSection *sections[])
2892: {
2893:   const PetscInt *arr0 = NULL, *cone = NULL;
2894:   PetscInt       *arr = NULL, *newarr = NULL;
2895:   PetscInt        d, depth_, i, n, newn, cn, co, start, end;
2896:   IS             *expandedPoints_;
2897:   PetscSection   *sections_;

2904:   ISGetLocalSize(points, &n);
2905:   ISGetIndices(points, &arr0);
2906:   DMPlexGetDepth(dm, &depth_);
2907:   PetscCalloc1(depth_, &expandedPoints_);
2908:   PetscCalloc1(depth_, &sections_);
2909:   arr = (PetscInt *)arr0; /* this is ok because first generation of arr is not modified */
2910:   for (d = depth_ - 1; d >= 0; d--) {
2911:     PetscSectionCreate(PETSC_COMM_SELF, &sections_[d]);
2912:     PetscSectionSetChart(sections_[d], 0, n);
2913:     for (i = 0; i < n; i++) {
2914:       DMPlexGetDepthStratum(dm, d + 1, &start, &end);
2915:       if (arr[i] >= start && arr[i] < end) {
2916:         DMPlexGetConeSize(dm, arr[i], &cn);
2917:         PetscSectionSetDof(sections_[d], i, cn);
2918:       } else {
2919:         PetscSectionSetDof(sections_[d], i, 1);
2920:       }
2921:     }
2922:     PetscSectionSetUp(sections_[d]);
2923:     PetscSectionGetStorageSize(sections_[d], &newn);
2924:     PetscMalloc1(newn, &newarr);
2925:     for (i = 0; i < n; i++) {
2926:       PetscSectionGetDof(sections_[d], i, &cn);
2927:       PetscSectionGetOffset(sections_[d], i, &co);
2928:       if (cn > 1) {
2929:         DMPlexGetCone(dm, arr[i], &cone);
2930:         PetscMemcpy(&newarr[co], cone, cn * sizeof(PetscInt));
2931:       } else {
2932:         newarr[co] = arr[i];
2933:       }
2934:     }
2935:     ISCreateGeneral(PETSC_COMM_SELF, newn, newarr, PETSC_OWN_POINTER, &expandedPoints_[d]);
2936:     arr = newarr;
2937:     n   = newn;
2938:   }
2939:   ISRestoreIndices(points, &arr0);
2940:   *depth = depth_;
2941:   if (expandedPoints) *expandedPoints = expandedPoints_;
2942:   else {
2943:     for (d = 0; d < depth_; d++) ISDestroy(&expandedPoints_[d]);
2944:     PetscFree(expandedPoints_);
2945:   }
2946:   if (sections) *sections = sections_;
2947:   else {
2948:     for (d = 0; d < depth_; d++) PetscSectionDestroy(&sections_[d]);
2949:     PetscFree(sections_);
2950:   }
2951:   return 0;
2952: }

2954: /*@
2955:   DMPlexRestoreConeRecursive - Deallocates arrays created by DMPlexGetConeRecursive

2957:   Not collective

2959:   Input Parameters:
2960: + dm - The DMPlex
2961: - points - The IS of points, which must lie in the chart set with DMPlexSetChart()

2963:   Output Parameters:
2964: + depth - (optional) Size of the output arrays, equal to DMPlex depth, returned by DMPlexGetDepth()
2965: . expandedPoints - (optional) An array of recursively expanded cones
2966: - sections - (optional) An array of sections which describe mappings from points to their cone points

2968:   Level: advanced

2970:   Notes:
2971:   See DMPlexGetConeRecursive() for details.

2973: .seealso: `DMPlexCreate()`, `DMPlexGetCone()`, `DMPlexGetConeTuple()`, `DMPlexGetConeRecursive()`, `DMPlexGetConeRecursiveVertices()`, `DMPlexGetDepth()`
2974: @*/
2975: PetscErrorCode DMPlexRestoreConeRecursive(DM dm, IS points, PetscInt *depth, IS *expandedPoints[], PetscSection *sections[])
2976: {
2977:   PetscInt d, depth_;

2979:   DMPlexGetDepth(dm, &depth_);
2981:   if (depth) *depth = 0;
2982:   if (expandedPoints) {
2983:     for (d = 0; d < depth_; d++) ISDestroy(&((*expandedPoints)[d]));
2984:     PetscFree(*expandedPoints);
2985:   }
2986:   if (sections) {
2987:     for (d = 0; d < depth_; d++) PetscSectionDestroy(&((*sections)[d]));
2988:     PetscFree(*sections);
2989:   }
2990:   return 0;
2991: }

2993: /*@
2994:   DMPlexSetCone - Set the points on the in-edges for this point in the DAG; that is these are the points that cover the specific point

2996:   Not collective

2998:   Input Parameters:
2999: + mesh - The DMPlex
3000: . p - The point, which must lie in the chart set with DMPlexSetChart()
3001: - cone - An array of points which are on the in-edges for point p

3003:   Output Parameter:

3005:   Note:
3006:   This should be called after all calls to DMPlexSetConeSize() and DMSetUp().

3008:   Level: beginner

3010: .seealso: `DMPlexCreate()`, `DMPlexGetCone()`, `DMPlexSetChart()`, `DMPlexSetConeSize()`, `DMSetUp()`, `DMPlexSetSupport()`, `DMPlexSetSupportSize()`
3011: @*/
3012: PetscErrorCode DMPlexSetCone(DM dm, PetscInt p, const PetscInt cone[])
3013: {
3014:   DM_Plex *mesh = (DM_Plex *)dm->data;
3015:   PetscInt pStart, pEnd;
3016:   PetscInt dof, off, c;

3019:   PetscSectionGetChart(mesh->coneSection, &pStart, &pEnd);
3020:   PetscSectionGetDof(mesh->coneSection, p, &dof);
3022:   PetscSectionGetOffset(mesh->coneSection, p, &off);
3024:   for (c = 0; c < dof; ++c) {
3026:     mesh->cones[off + c] = cone[c];
3027:   }
3028:   return 0;
3029: }

3031: /*@C
3032:   DMPlexGetConeOrientation - Return the orientations on the in-edges for this point in the DAG

3034:   Not collective

3036:   Input Parameters:
3037: + mesh - The DMPlex
3038: - p - The point, which must lie in the chart set with DMPlexSetChart()

3040:   Output Parameter:
3041: . coneOrientation - An array of orientations which are on the in-edges for point p. An orientation is an
3042:                     integer giving the prescription for cone traversal.

3044:   Level: beginner

3046:   Notes:
3047:   The number indexes the symmetry transformations for the cell type (see manual). Orientation 0 is always
3048:   the identity transformation. Negative orientation indicates reflection so that -(o+1) is the reflection
3049:   of o, however it is not necessarily the inverse. To get the inverse, use DMPolytopeTypeComposeOrientationInv()
3050:   with the identity.

3052:   Fortran Notes:
3053:   Since it returns an array, this routine is only available in Fortran 90, and you must
3054:   include petsc.h90 in your code.
3055:   You must also call DMPlexRestoreConeOrientation() after you finish using the returned array.
3056:   DMPlexRestoreConeOrientation() is not needed/available in C.

3058: .seealso: `DMPolytopeTypeComposeOrientation()`, `DMPolytopeTypeComposeOrientationInv()`, `DMPlexCreate()`, `DMPlexGetCone()`, `DMPlexSetCone()`, `DMPlexSetChart()`
3059: @*/
3060: PetscErrorCode DMPlexGetConeOrientation(DM dm, PetscInt p, const PetscInt *coneOrientation[])
3061: {
3062:   DM_Plex *mesh = (DM_Plex *)dm->data;
3063:   PetscInt off;

3066:   if (PetscDefined(USE_DEBUG)) {
3067:     PetscInt dof;
3068:     PetscSectionGetDof(mesh->coneSection, p, &dof);
3070:   }
3071:   PetscSectionGetOffset(mesh->coneSection, p, &off);

3073:   *coneOrientation = &mesh->coneOrientations[off];
3074:   return 0;
3075: }

3077: /*@
3078:   DMPlexSetConeOrientation - Set the orientations on the in-edges for this point in the DAG

3080:   Not collective

3082:   Input Parameters:
3083: + mesh - The DMPlex
3084: . p - The point, which must lie in the chart set with DMPlexSetChart()
3085: - coneOrientation - An array of orientations
3086:   Output Parameter:

3088:   Notes:
3089:   This should be called after all calls to DMPlexSetConeSize() and DMSetUp().

3091:   The meaning of coneOrientation is detailed in DMPlexGetConeOrientation().

3093:   Level: beginner

3095: .seealso: `DMPlexCreate()`, `DMPlexGetConeOrientation()`, `DMPlexSetCone()`, `DMPlexSetChart()`, `DMPlexSetConeSize()`, `DMSetUp()`
3096: @*/
3097: PetscErrorCode DMPlexSetConeOrientation(DM dm, PetscInt p, const PetscInt coneOrientation[])
3098: {
3099:   DM_Plex *mesh = (DM_Plex *)dm->data;
3100:   PetscInt pStart, pEnd;
3101:   PetscInt dof, off, c;

3104:   PetscSectionGetChart(mesh->coneSection, &pStart, &pEnd);
3105:   PetscSectionGetDof(mesh->coneSection, p, &dof);
3107:   PetscSectionGetOffset(mesh->coneSection, p, &off);
3109:   for (c = 0; c < dof; ++c) {
3110:     PetscInt cdof, o = coneOrientation[c];

3112:     PetscSectionGetDof(mesh->coneSection, mesh->cones[off + c], &cdof);
3114:     mesh->coneOrientations[off + c] = o;
3115:   }
3116:   return 0;
3117: }

3119: /*@
3120:   DMPlexInsertCone - Insert a point into the in-edges for the point p in the DAG

3122:   Not collective

3124:   Input Parameters:
3125: + mesh - The DMPlex
3126: . p - The point, which must lie in the chart set with DMPlexSetChart()
3127: . conePos - The local index in the cone where the point should be put
3128: - conePoint - The mesh point to insert

3130:   Level: beginner

3132: .seealso: `DMPlexCreate()`, `DMPlexGetCone()`, `DMPlexSetChart()`, `DMPlexSetConeSize()`, `DMSetUp()`
3133: @*/
3134: PetscErrorCode DMPlexInsertCone(DM dm, PetscInt p, PetscInt conePos, PetscInt conePoint)
3135: {
3136:   DM_Plex *mesh = (DM_Plex *)dm->data;
3137:   PetscInt pStart, pEnd;
3138:   PetscInt dof, off;

3141:   PetscSectionGetChart(mesh->coneSection, &pStart, &pEnd);
3144:   PetscSectionGetDof(mesh->coneSection, p, &dof);
3145:   PetscSectionGetOffset(mesh->coneSection, p, &off);
3147:   mesh->cones[off + conePos] = conePoint;
3148:   return 0;
3149: }

3151: /*@
3152:   DMPlexInsertConeOrientation - Insert a point orientation for the in-edge for the point p in the DAG

3154:   Not collective

3156:   Input Parameters:
3157: + mesh - The DMPlex
3158: . p - The point, which must lie in the chart set with DMPlexSetChart()
3159: . conePos - The local index in the cone where the point should be put
3160: - coneOrientation - The point orientation to insert

3162:   Level: beginner

3164:   Notes:
3165:   The meaning of coneOrientation values is detailed in DMPlexGetConeOrientation().

3167: .seealso: `DMPlexCreate()`, `DMPlexGetCone()`, `DMPlexSetChart()`, `DMPlexSetConeSize()`, `DMSetUp()`
3168: @*/
3169: PetscErrorCode DMPlexInsertConeOrientation(DM dm, PetscInt p, PetscInt conePos, PetscInt coneOrientation)
3170: {
3171:   DM_Plex *mesh = (DM_Plex *)dm->data;
3172:   PetscInt pStart, pEnd;
3173:   PetscInt dof, off;

3176:   PetscSectionGetChart(mesh->coneSection, &pStart, &pEnd);
3178:   PetscSectionGetDof(mesh->coneSection, p, &dof);
3179:   PetscSectionGetOffset(mesh->coneSection, p, &off);
3181:   mesh->coneOrientations[off + conePos] = coneOrientation;
3182:   return 0;
3183: }

3185: /*@
3186:   DMPlexGetSupportSize - Return the number of out-edges for this point in the DAG

3188:   Not collective

3190:   Input Parameters:
3191: + mesh - The DMPlex
3192: - p - The point, which must lie in the chart set with DMPlexSetChart()

3194:   Output Parameter:
3195: . size - The support size for point p

3197:   Level: beginner

3199: .seealso: `DMPlexCreate()`, `DMPlexSetConeSize()`, `DMPlexSetChart()`, `DMPlexGetConeSize()`
3200: @*/
3201: PetscErrorCode DMPlexGetSupportSize(DM dm, PetscInt p, PetscInt *size)
3202: {
3203:   DM_Plex *mesh = (DM_Plex *)dm->data;

3207:   PetscSectionGetDof(mesh->supportSection, p, size);
3208:   return 0;
3209: }

3211: /*@
3212:   DMPlexSetSupportSize - Set the number of out-edges for this point in the DAG

3214:   Not collective

3216:   Input Parameters:
3217: + mesh - The DMPlex
3218: . p - The point, which must lie in the chart set with DMPlexSetChart()
3219: - size - The support size for point p

3221:   Output Parameter:

3223:   Note:
3224:   This should be called after DMPlexSetChart().

3226:   Level: beginner

3228: .seealso: `DMPlexCreate()`, `DMPlexGetSupportSize()`, `DMPlexSetChart()`
3229: @*/
3230: PetscErrorCode DMPlexSetSupportSize(DM dm, PetscInt p, PetscInt size)
3231: {
3232:   DM_Plex *mesh = (DM_Plex *)dm->data;

3235:   PetscSectionSetDof(mesh->supportSection, p, size);
3236:   return 0;
3237: }

3239: /*@C
3240:   DMPlexGetSupport - Return the points on the out-edges for this point in the DAG

3242:   Not collective

3244:   Input Parameters:
3245: + mesh - The DMPlex
3246: - p - The point, which must lie in the chart set with DMPlexSetChart()

3248:   Output Parameter:
3249: . support - An array of points which are on the out-edges for point p

3251:   Level: beginner

3253:   Fortran Notes:
3254:   Since it returns an array, this routine is only available in Fortran 90, and you must
3255:   include petsc.h90 in your code.
3256:   You must also call DMPlexRestoreSupport() after you finish using the returned array.
3257:   DMPlexRestoreSupport() is not needed/available in C.

3259: .seealso: `DMPlexGetSupportSize()`, `DMPlexSetSupport()`, `DMPlexGetCone()`, `DMPlexSetChart()`
3260: @*/
3261: PetscErrorCode DMPlexGetSupport(DM dm, PetscInt p, const PetscInt *support[])
3262: {
3263:   DM_Plex *mesh = (DM_Plex *)dm->data;
3264:   PetscInt off;

3268:   PetscSectionGetOffset(mesh->supportSection, p, &off);
3269:   *support = &mesh->supports[off];
3270:   return 0;
3271: }

3273: /*@
3274:   DMPlexSetSupport - Set the points on the out-edges for this point in the DAG, that is the list of points that this point covers

3276:   Not collective

3278:   Input Parameters:
3279: + mesh - The DMPlex
3280: . p - The point, which must lie in the chart set with DMPlexSetChart()
3281: - support - An array of points which are on the out-edges for point p

3283:   Output Parameter:

3285:   Note:
3286:   This should be called after all calls to DMPlexSetSupportSize() and DMSetUp().

3288:   Level: beginner

3290: .seealso: `DMPlexSetCone()`, `DMPlexSetConeSize()`, `DMPlexCreate()`, `DMPlexGetSupport()`, `DMPlexSetChart()`, `DMPlexSetSupportSize()`, `DMSetUp()`
3291: @*/
3292: PetscErrorCode DMPlexSetSupport(DM dm, PetscInt p, const PetscInt support[])
3293: {
3294:   DM_Plex *mesh = (DM_Plex *)dm->data;
3295:   PetscInt pStart, pEnd;
3296:   PetscInt dof, off, c;

3299:   PetscSectionGetChart(mesh->supportSection, &pStart, &pEnd);
3300:   PetscSectionGetDof(mesh->supportSection, p, &dof);
3302:   PetscSectionGetOffset(mesh->supportSection, p, &off);
3304:   for (c = 0; c < dof; ++c) {
3306:     mesh->supports[off + c] = support[c];
3307:   }
3308:   return 0;
3309: }

3311: /*@
3312:   DMPlexInsertSupport - Insert a point into the out-edges for the point p in the DAG

3314:   Not collective

3316:   Input Parameters:
3317: + mesh - The DMPlex
3318: . p - The point, which must lie in the chart set with DMPlexSetChart()
3319: . supportPos - The local index in the cone where the point should be put
3320: - supportPoint - The mesh point to insert

3322:   Level: beginner

3324: .seealso: `DMPlexCreate()`, `DMPlexGetCone()`, `DMPlexSetChart()`, `DMPlexSetConeSize()`, `DMSetUp()`
3325: @*/
3326: PetscErrorCode DMPlexInsertSupport(DM dm, PetscInt p, PetscInt supportPos, PetscInt supportPoint)
3327: {
3328:   DM_Plex *mesh = (DM_Plex *)dm->data;
3329:   PetscInt pStart, pEnd;
3330:   PetscInt dof, off;

3333:   PetscSectionGetChart(mesh->supportSection, &pStart, &pEnd);
3334:   PetscSectionGetDof(mesh->supportSection, p, &dof);
3335:   PetscSectionGetOffset(mesh->supportSection, p, &off);
3339:   mesh->supports[off + supportPos] = supportPoint;
3340:   return 0;
3341: }

3343: /* Converts an orientation o in the current numbering to the previous scheme used in Plex */
3344: PetscInt DMPolytopeConvertNewOrientation_Internal(DMPolytopeType ct, PetscInt o)
3345: {
3346:   switch (ct) {
3347:   case DM_POLYTOPE_SEGMENT:
3348:     if (o == -1) return -2;
3349:     break;
3350:   case DM_POLYTOPE_TRIANGLE:
3351:     if (o == -3) return -1;
3352:     if (o == -2) return -3;
3353:     if (o == -1) return -2;
3354:     break;
3355:   case DM_POLYTOPE_QUADRILATERAL:
3356:     if (o == -4) return -2;
3357:     if (o == -3) return -1;
3358:     if (o == -2) return -4;
3359:     if (o == -1) return -3;
3360:     break;
3361:   default:
3362:     return o;
3363:   }
3364:   return o;
3365: }

3367: /* Converts an orientation o in the previous scheme used in Plex to the current numbering */
3368: PetscInt DMPolytopeConvertOldOrientation_Internal(DMPolytopeType ct, PetscInt o)
3369: {
3370:   switch (ct) {
3371:   case DM_POLYTOPE_SEGMENT:
3372:     if ((o == -2) || (o == 1)) return -1;
3373:     if (o == -1) return 0;
3374:     break;
3375:   case DM_POLYTOPE_TRIANGLE:
3376:     if (o == -3) return -2;
3377:     if (o == -2) return -1;
3378:     if (o == -1) return -3;
3379:     break;
3380:   case DM_POLYTOPE_QUADRILATERAL:
3381:     if (o == -4) return -2;
3382:     if (o == -3) return -1;
3383:     if (o == -2) return -4;
3384:     if (o == -1) return -3;
3385:     break;
3386:   default:
3387:     return o;
3388:   }
3389:   return o;
3390: }

3392: /* Takes in a mesh whose orientations are in the previous scheme and converts them all to the current numbering */
3393: PetscErrorCode DMPlexConvertOldOrientations_Internal(DM dm)
3394: {
3395:   PetscInt pStart, pEnd, p;

3397:   DMPlexGetChart(dm, &pStart, &pEnd);
3398:   for (p = pStart; p < pEnd; ++p) {
3399:     const PetscInt *cone, *ornt;
3400:     PetscInt        coneSize, c;

3402:     DMPlexGetConeSize(dm, p, &coneSize);
3403:     DMPlexGetCone(dm, p, &cone);
3404:     DMPlexGetConeOrientation(dm, p, &ornt);
3405:     for (c = 0; c < coneSize; ++c) {
3406:       DMPolytopeType ct;
3407:       const PetscInt o = ornt[c];

3409:       DMPlexGetCellType(dm, cone[c], &ct);
3410:       switch (ct) {
3411:       case DM_POLYTOPE_SEGMENT:
3412:         if ((o == -2) || (o == 1)) DMPlexInsertConeOrientation(dm, p, c, -1);
3413:         if (o == -1) DMPlexInsertConeOrientation(dm, p, c, 0);
3414:         break;
3415:       case DM_POLYTOPE_TRIANGLE:
3416:         if (o == -3) DMPlexInsertConeOrientation(dm, p, c, -2);
3417:         if (o == -2) DMPlexInsertConeOrientation(dm, p, c, -1);
3418:         if (o == -1) DMPlexInsertConeOrientation(dm, p, c, -3);
3419:         break;
3420:       case DM_POLYTOPE_QUADRILATERAL:
3421:         if (o == -4) DMPlexInsertConeOrientation(dm, p, c, -2);
3422:         if (o == -3) DMPlexInsertConeOrientation(dm, p, c, -1);
3423:         if (o == -2) DMPlexInsertConeOrientation(dm, p, c, -4);
3424:         if (o == -1) DMPlexInsertConeOrientation(dm, p, c, -3);
3425:         break;
3426:       default:
3427:         break;
3428:       }
3429:     }
3430:   }
3431:   return 0;
3432: }

3434: static PetscErrorCode DMPlexGetTransitiveClosure_Depth1_Private(DM dm, PetscInt p, PetscInt ornt, PetscBool useCone, PetscInt *numPoints, PetscInt *points[])
3435: {
3436:   DMPolytopeType  ct = DM_POLYTOPE_UNKNOWN;
3437:   PetscInt       *closure;
3438:   const PetscInt *tmp = NULL, *tmpO = NULL;
3439:   PetscInt        off = 0, tmpSize, t;

3442:   if (ornt) {
3443:     DMPlexGetCellType(dm, p, &ct);
3444:     if (ct == DM_POLYTOPE_FV_GHOST || ct == DM_POLYTOPE_INTERIOR_GHOST || ct == DM_POLYTOPE_UNKNOWN) ct = DM_POLYTOPE_UNKNOWN;
3445:   }
3446:   if (*points) {
3447:     closure = *points;
3448:   } else {
3449:     PetscInt maxConeSize, maxSupportSize;
3450:     DMPlexGetMaxSizes(dm, &maxConeSize, &maxSupportSize);
3451:     DMGetWorkArray(dm, 2 * (PetscMax(maxConeSize, maxSupportSize) + 1), MPIU_INT, &closure);
3452:   }
3453:   if (useCone) {
3454:     DMPlexGetConeSize(dm, p, &tmpSize);
3455:     DMPlexGetCone(dm, p, &tmp);
3456:     DMPlexGetConeOrientation(dm, p, &tmpO);
3457:   } else {
3458:     DMPlexGetSupportSize(dm, p, &tmpSize);
3459:     DMPlexGetSupport(dm, p, &tmp);
3460:   }
3461:   if (ct == DM_POLYTOPE_UNKNOWN) {
3462:     closure[off++] = p;
3463:     closure[off++] = 0;
3464:     for (t = 0; t < tmpSize; ++t) {
3465:       closure[off++] = tmp[t];
3466:       closure[off++] = tmpO ? tmpO[t] : 0;
3467:     }
3468:   } else {
3469:     const PetscInt *arr = DMPolytopeTypeGetArrangment(ct, ornt);

3471:     /* We assume that cells with a valid type have faces with a valid type */
3472:     closure[off++] = p;
3473:     closure[off++] = ornt;
3474:     for (t = 0; t < tmpSize; ++t) {
3475:       DMPolytopeType ft;

3477:       DMPlexGetCellType(dm, tmp[t], &ft);
3478:       closure[off++] = tmp[arr[t]];
3479:       closure[off++] = tmpO ? DMPolytopeTypeComposeOrientation(ft, ornt, tmpO[t]) : 0;
3480:     }
3481:   }
3482:   if (numPoints) *numPoints = tmpSize + 1;
3483:   if (points) *points = closure;
3484:   return 0;
3485: }

3487: /* We need a special tensor verison becasue we want to allow duplicate points in the endcaps for hybrid cells */
3488: static PetscErrorCode DMPlexTransitiveClosure_Tensor_Internal(DM dm, PetscInt point, DMPolytopeType ct, PetscInt o, PetscBool useCone, PetscInt *numPoints, PetscInt **points)
3489: {
3490:   const PetscInt *arr = DMPolytopeTypeGetArrangment(ct, o);
3491:   const PetscInt *cone, *ornt;
3492:   PetscInt       *pts, *closure = NULL;
3493:   DMPolytopeType  ft;
3494:   PetscInt        maxConeSize, maxSupportSize, coneSeries, supportSeries, maxSize;
3495:   PetscInt        dim, coneSize, c, d, clSize, cl;

3498:   DMGetDimension(dm, &dim);
3499:   DMPlexGetConeSize(dm, point, &coneSize);
3500:   DMPlexGetCone(dm, point, &cone);
3501:   DMPlexGetConeOrientation(dm, point, &ornt);
3502:   DMPlexGetMaxSizes(dm, &maxConeSize, &maxSupportSize);
3503:   coneSeries    = (maxConeSize > 1) ? ((PetscPowInt(maxConeSize, dim + 1) - 1) / (maxConeSize - 1)) : dim + 1;
3504:   supportSeries = (maxSupportSize > 1) ? ((PetscPowInt(maxSupportSize, dim + 1) - 1) / (maxSupportSize - 1)) : dim + 1;
3505:   maxSize       = PetscMax(coneSeries, supportSeries);
3506:   if (*points) {
3507:     pts = *points;
3508:   } else DMGetWorkArray(dm, 2 * maxSize, MPIU_INT, &pts);
3509:   c        = 0;
3510:   pts[c++] = point;
3511:   pts[c++] = o;
3512:   DMPlexGetCellType(dm, cone[arr[0 * 2 + 0]], &ft);
3513:   DMPlexGetTransitiveClosure_Internal(dm, cone[arr[0 * 2 + 0]], DMPolytopeTypeComposeOrientation(ft, arr[0 * 2 + 1], ornt[0]), useCone, &clSize, &closure);
3514:   for (cl = 0; cl < clSize * 2; cl += 2) {
3515:     pts[c++] = closure[cl];
3516:     pts[c++] = closure[cl + 1];
3517:   }
3518:   DMPlexGetTransitiveClosure_Internal(dm, cone[arr[1 * 2 + 0]], DMPolytopeTypeComposeOrientation(ft, arr[1 * 2 + 1], ornt[1]), useCone, &clSize, &closure);
3519:   for (cl = 0; cl < clSize * 2; cl += 2) {
3520:     pts[c++] = closure[cl];
3521:     pts[c++] = closure[cl + 1];
3522:   }
3523:   DMPlexRestoreTransitiveClosure(dm, cone[0], useCone, &clSize, &closure);
3524:   for (d = 2; d < coneSize; ++d) {
3525:     DMPlexGetCellType(dm, cone[arr[d * 2 + 0]], &ft);
3526:     pts[c++] = cone[arr[d * 2 + 0]];
3527:     pts[c++] = DMPolytopeTypeComposeOrientation(ft, arr[d * 2 + 1], ornt[d]);
3528:   }
3529:   if (dim >= 3) {
3530:     for (d = 2; d < coneSize; ++d) {
3531:       const PetscInt  fpoint = cone[arr[d * 2 + 0]];
3532:       const PetscInt *fcone, *fornt;
3533:       PetscInt        fconeSize, fc, i;

3535:       DMPlexGetCellType(dm, fpoint, &ft);
3536:       const PetscInt *farr = DMPolytopeTypeGetArrangment(ft, DMPolytopeTypeComposeOrientation(ft, arr[d * 2 + 1], ornt[d]));
3537:       DMPlexGetConeSize(dm, fpoint, &fconeSize);
3538:       DMPlexGetCone(dm, fpoint, &fcone);
3539:       DMPlexGetConeOrientation(dm, fpoint, &fornt);
3540:       for (fc = 0; fc < fconeSize; ++fc) {
3541:         const PetscInt cp = fcone[farr[fc * 2 + 0]];
3542:         const PetscInt co = farr[fc * 2 + 1];

3544:         for (i = 0; i < c; i += 2)
3545:           if (pts[i] == cp) break;
3546:         if (i == c) {
3547:           DMPlexGetCellType(dm, cp, &ft);
3548:           pts[c++] = cp;
3549:           pts[c++] = DMPolytopeTypeComposeOrientation(ft, co, fornt[farr[fc * 2 + 0]]);
3550:         }
3551:       }
3552:     }
3553:   }
3554:   *numPoints = c / 2;
3555:   *points    = pts;
3556:   return 0;
3557: }

3559: PetscErrorCode DMPlexGetTransitiveClosure_Internal(DM dm, PetscInt p, PetscInt ornt, PetscBool useCone, PetscInt *numPoints, PetscInt *points[])
3560: {
3561:   DMPolytopeType ct;
3562:   PetscInt      *closure, *fifo;
3563:   PetscInt       closureSize = 0, fifoStart = 0, fifoSize = 0;
3564:   PetscInt       maxConeSize, maxSupportSize, coneSeries, supportSeries;
3565:   PetscInt       depth, maxSize;

3568:   DMPlexGetDepth(dm, &depth);
3569:   if (depth == 1) {
3570:     DMPlexGetTransitiveClosure_Depth1_Private(dm, p, ornt, useCone, numPoints, points);
3571:     return 0;
3572:   }
3573:   DMPlexGetCellType(dm, p, &ct);
3574:   if (ct == DM_POLYTOPE_FV_GHOST || ct == DM_POLYTOPE_INTERIOR_GHOST || ct == DM_POLYTOPE_UNKNOWN) ct = DM_POLYTOPE_UNKNOWN;
3575:   if (ct == DM_POLYTOPE_SEG_PRISM_TENSOR || ct == DM_POLYTOPE_TRI_PRISM_TENSOR || ct == DM_POLYTOPE_QUAD_PRISM_TENSOR) {
3576:     DMPlexTransitiveClosure_Tensor_Internal(dm, p, ct, ornt, useCone, numPoints, points);
3577:     return 0;
3578:   }
3579:   DMPlexGetMaxSizes(dm, &maxConeSize, &maxSupportSize);
3580:   coneSeries    = (maxConeSize > 1) ? ((PetscPowInt(maxConeSize, depth + 1) - 1) / (maxConeSize - 1)) : depth + 1;
3581:   supportSeries = (maxSupportSize > 1) ? ((PetscPowInt(maxSupportSize, depth + 1) - 1) / (maxSupportSize - 1)) : depth + 1;
3582:   maxSize       = PetscMax(coneSeries, supportSeries);
3583:   DMGetWorkArray(dm, 3 * maxSize, MPIU_INT, &fifo);
3584:   if (*points) {
3585:     closure = *points;
3586:   } else DMGetWorkArray(dm, 2 * maxSize, MPIU_INT, &closure);
3587:   closure[closureSize++] = p;
3588:   closure[closureSize++] = ornt;
3589:   fifo[fifoSize++]       = p;
3590:   fifo[fifoSize++]       = ornt;
3591:   fifo[fifoSize++]       = ct;
3592:   /* Should kick out early when depth is reached, rather than checking all vertices for empty cones */
3593:   while (fifoSize - fifoStart) {
3594:     const PetscInt       q    = fifo[fifoStart++];
3595:     const PetscInt       o    = fifo[fifoStart++];
3596:     const DMPolytopeType qt   = (DMPolytopeType)fifo[fifoStart++];
3597:     const PetscInt      *qarr = DMPolytopeTypeGetArrangment(qt, o);
3598:     const PetscInt      *tmp, *tmpO;
3599:     PetscInt             tmpSize, t;

3601:     if (PetscDefined(USE_DEBUG)) {
3602:       PetscInt nO = DMPolytopeTypeGetNumArrangments(qt) / 2;
3604:     }
3605:     if (useCone) {
3606:       DMPlexGetConeSize(dm, q, &tmpSize);
3607:       DMPlexGetCone(dm, q, &tmp);
3608:       DMPlexGetConeOrientation(dm, q, &tmpO);
3609:     } else {
3610:       DMPlexGetSupportSize(dm, q, &tmpSize);
3611:       DMPlexGetSupport(dm, q, &tmp);
3612:       tmpO = NULL;
3613:     }
3614:     for (t = 0; t < tmpSize; ++t) {
3615:       const PetscInt ip = useCone && qarr ? qarr[t * 2] : t;
3616:       const PetscInt io = useCone && qarr ? qarr[t * 2 + 1] : 0;
3617:       const PetscInt cp = tmp[ip];
3618:       DMPlexGetCellType(dm, cp, &ct);
3619:       const PetscInt co = tmpO ? DMPolytopeTypeComposeOrientation(ct, io, tmpO[ip]) : 0;
3620:       PetscInt       c;

3622:       /* Check for duplicate */
3623:       for (c = 0; c < closureSize; c += 2) {
3624:         if (closure[c] == cp) break;
3625:       }
3626:       if (c == closureSize) {
3627:         closure[closureSize++] = cp;
3628:         closure[closureSize++] = co;
3629:         fifo[fifoSize++]       = cp;
3630:         fifo[fifoSize++]       = co;
3631:         fifo[fifoSize++]       = ct;
3632:       }
3633:     }
3634:   }
3635:   DMRestoreWorkArray(dm, 3 * maxSize, MPIU_INT, &fifo);
3636:   if (numPoints) *numPoints = closureSize / 2;
3637:   if (points) *points = closure;
3638:   return 0;
3639: }

3641: /*@C
3642:   DMPlexGetTransitiveClosure - Return the points on the transitive closure of the in-edges or out-edges for this point in the DAG

3644:   Not collective

3646:   Input Parameters:
3647: + dm      - The DMPlex
3648: . p       - The mesh point
3649: - useCone - PETSC_TRUE for the closure, otherwise return the star

3651:   Input/Output Parameter:
3652: . points - The points and point orientations, interleaved as pairs [p0, o0, p1, o1, ...];
3653:            if NULL on input, internal storage will be returned, otherwise the provided array is used

3655:   Output Parameter:
3656: . numPoints - The number of points in the closure, so points[] is of size 2*numPoints

3658:   Note:
3659:   If using internal storage (points is NULL on input), each call overwrites the last output.

3661:   Fortran Note:
3662:   The numPoints argument is not present in the Fortran 90 binding since it is internal to the array.

3664:   Level: beginner

3666: .seealso: `DMPlexRestoreTransitiveClosure()`, `DMPlexCreate()`, `DMPlexSetCone()`, `DMPlexSetChart()`, `DMPlexGetCone()`
3667: @*/
3668: PetscErrorCode DMPlexGetTransitiveClosure(DM dm, PetscInt p, PetscBool useCone, PetscInt *numPoints, PetscInt *points[])
3669: {
3674:   DMPlexGetTransitiveClosure_Internal(dm, p, 0, useCone, numPoints, points);
3675:   return 0;
3676: }

3678: /*@C
3679:   DMPlexRestoreTransitiveClosure - Restore the array of points on the transitive closure of the in-edges or out-edges for this point in the DAG

3681:   Not collective

3683:   Input Parameters:
3684: + dm        - The DMPlex
3685: . p         - The mesh point
3686: . useCone   - PETSC_TRUE for the closure, otherwise return the star
3687: . numPoints - The number of points in the closure, so points[] is of size 2*numPoints
3688: - points    - The points and point orientations, interleaved as pairs [p0, o0, p1, o1, ...]

3690:   Note:
3691:   If not using internal storage (points is not NULL on input), this call is unnecessary

3693:   Level: beginner

3695: .seealso: `DMPlexGetTransitiveClosure()`, `DMPlexCreate()`, `DMPlexSetCone()`, `DMPlexSetChart()`, `DMPlexGetCone()`
3696: @*/
3697: PetscErrorCode DMPlexRestoreTransitiveClosure(DM dm, PetscInt p, PetscBool useCone, PetscInt *numPoints, PetscInt *points[])
3698: {
3701:   if (numPoints) *numPoints = 0;
3702:   DMRestoreWorkArray(dm, 0, MPIU_INT, points);
3703:   return 0;
3704: }

3706: /*@
3707:   DMPlexGetMaxSizes - Return the maximum number of in-edges (cone) and out-edges (support) for any point in the DAG

3709:   Not collective

3711:   Input Parameter:
3712: . mesh - The DMPlex

3714:   Output Parameters:
3715: + maxConeSize - The maximum number of in-edges
3716: - maxSupportSize - The maximum number of out-edges

3718:   Level: beginner

3720: .seealso: `DMPlexCreate()`, `DMPlexSetConeSize()`, `DMPlexSetChart()`
3721: @*/
3722: PetscErrorCode DMPlexGetMaxSizes(DM dm, PetscInt *maxConeSize, PetscInt *maxSupportSize)
3723: {
3724:   DM_Plex *mesh = (DM_Plex *)dm->data;

3727:   if (maxConeSize) PetscSectionGetMaxDof(mesh->coneSection, maxConeSize);
3728:   if (maxSupportSize) PetscSectionGetMaxDof(mesh->supportSection, maxSupportSize);
3729:   return 0;
3730: }

3732: PetscErrorCode DMSetUp_Plex(DM dm)
3733: {
3734:   DM_Plex *mesh = (DM_Plex *)dm->data;
3735:   PetscInt size, maxSupportSize;

3738:   PetscSectionSetUp(mesh->coneSection);
3739:   PetscSectionGetStorageSize(mesh->coneSection, &size);
3740:   PetscMalloc1(size, &mesh->cones);
3741:   PetscCalloc1(size, &mesh->coneOrientations);
3742:   PetscSectionGetMaxDof(mesh->supportSection, &maxSupportSize);
3743:   if (maxSupportSize) {
3744:     PetscSectionSetUp(mesh->supportSection);
3745:     PetscSectionGetStorageSize(mesh->supportSection, &size);
3746:     PetscMalloc1(size, &mesh->supports);
3747:   }
3748:   return 0;
3749: }

3751: PetscErrorCode DMCreateSubDM_Plex(DM dm, PetscInt numFields, const PetscInt fields[], IS *is, DM *subdm)
3752: {
3753:   if (subdm) DMClone(dm, subdm);
3754:   DMCreateSectionSubDM(dm, numFields, fields, is, subdm);
3755:   if (subdm) (*subdm)->useNatural = dm->useNatural;
3756:   if (dm->useNatural && dm->sfMigration) {
3757:     PetscSF sfNatural;

3759:     (*subdm)->sfMigration = dm->sfMigration;
3760:     PetscObjectReference((PetscObject)dm->sfMigration);
3761:     DMPlexCreateGlobalToNaturalSF(*subdm, NULL, (*subdm)->sfMigration, &sfNatural);
3762:     (*subdm)->sfNatural = sfNatural;
3763:   }
3764:   return 0;
3765: }

3767: PetscErrorCode DMCreateSuperDM_Plex(DM dms[], PetscInt len, IS **is, DM *superdm)
3768: {
3769:   PetscInt i = 0;

3771:   DMClone(dms[0], superdm);
3772:   DMCreateSectionSuperDM(dms, len, is, superdm);
3773:   (*superdm)->useNatural = PETSC_FALSE;
3774:   for (i = 0; i < len; i++) {
3775:     if (dms[i]->useNatural && dms[i]->sfMigration) {
3776:       PetscSF sfNatural;

3778:       (*superdm)->sfMigration = dms[i]->sfMigration;
3779:       PetscObjectReference((PetscObject)dms[i]->sfMigration);
3780:       (*superdm)->useNatural = PETSC_TRUE;
3781:       DMPlexCreateGlobalToNaturalSF(*superdm, NULL, (*superdm)->sfMigration, &sfNatural);
3782:       (*superdm)->sfNatural = sfNatural;
3783:       break;
3784:     }
3785:   }
3786:   return 0;
3787: }

3789: /*@
3790:   DMPlexSymmetrize - Create support (out-edge) information from cone (in-edge) information

3792:   Not collective

3794:   Input Parameter:
3795: . mesh - The DMPlex

3797:   Output Parameter:

3799:   Note:
3800:   This should be called after all calls to DMPlexSetCone()

3802:   Level: beginner

3804: .seealso: `DMPlexCreate()`, `DMPlexSetChart()`, `DMPlexSetConeSize()`, `DMPlexSetCone()`
3805: @*/
3806: PetscErrorCode DMPlexSymmetrize(DM dm)
3807: {
3808:   DM_Plex  *mesh = (DM_Plex *)dm->data;
3809:   PetscInt *offsets;
3810:   PetscInt  supportSize;
3811:   PetscInt  pStart, pEnd, p;

3815:   PetscLogEventBegin(DMPLEX_Symmetrize, dm, 0, 0, 0);
3816:   /* Calculate support sizes */
3817:   DMPlexGetChart(dm, &pStart, &pEnd);
3818:   for (p = pStart; p < pEnd; ++p) {
3819:     PetscInt dof, off, c;

3821:     PetscSectionGetDof(mesh->coneSection, p, &dof);
3822:     PetscSectionGetOffset(mesh->coneSection, p, &off);
3823:     for (c = off; c < off + dof; ++c) PetscSectionAddDof(mesh->supportSection, mesh->cones[c], 1);
3824:   }
3825:   PetscSectionSetUp(mesh->supportSection);
3826:   /* Calculate supports */
3827:   PetscSectionGetStorageSize(mesh->supportSection, &supportSize);
3828:   PetscMalloc1(supportSize, &mesh->supports);
3829:   PetscCalloc1(pEnd - pStart, &offsets);
3830:   for (p = pStart; p < pEnd; ++p) {
3831:     PetscInt dof, off, c;

3833:     PetscSectionGetDof(mesh->coneSection, p, &dof);
3834:     PetscSectionGetOffset(mesh->coneSection, p, &off);
3835:     for (c = off; c < off + dof; ++c) {
3836:       const PetscInt q = mesh->cones[c];
3837:       PetscInt       offS;

3839:       PetscSectionGetOffset(mesh->supportSection, q, &offS);

3841:       mesh->supports[offS + offsets[q]] = p;
3842:       ++offsets[q];
3843:     }
3844:   }
3845:   PetscFree(offsets);
3846:   PetscLogEventEnd(DMPLEX_Symmetrize, dm, 0, 0, 0);
3847:   return 0;
3848: }

3850: static PetscErrorCode DMPlexCreateDepthStratum(DM dm, DMLabel label, PetscInt depth, PetscInt pStart, PetscInt pEnd)
3851: {
3852:   IS stratumIS;

3854:   if (pStart >= pEnd) return 0;
3855:   if (PetscDefined(USE_DEBUG)) {
3856:     PetscInt  qStart, qEnd, numLevels, level;
3857:     PetscBool overlap = PETSC_FALSE;
3858:     DMLabelGetNumValues(label, &numLevels);
3859:     for (level = 0; level < numLevels; level++) {
3860:       DMLabelGetStratumBounds(label, level, &qStart, &qEnd);
3861:       if ((pStart >= qStart && pStart < qEnd) || (pEnd > qStart && pEnd <= qEnd)) {
3862:         overlap = PETSC_TRUE;
3863:         break;
3864:       }
3865:     }
3867:   }
3868:   ISCreateStride(PETSC_COMM_SELF, pEnd - pStart, pStart, 1, &stratumIS);
3869:   DMLabelSetStratumIS(label, depth, stratumIS);
3870:   ISDestroy(&stratumIS);
3871:   return 0;
3872: }

3874: /*@
3875:   DMPlexStratify - The DAG for most topologies is a graded poset (https://en.wikipedia.org/wiki/Graded_poset), and
3876:   can be illustrated by a Hasse Diagram (https://en.wikipedia.org/wiki/Hasse_diagram). The strata group all points of the
3877:   same grade, and this function calculates the strata. This grade can be seen as the height (or depth) of the point in
3878:   the DAG.

3880:   Collective on dm

3882:   Input Parameter:
3883: . mesh - The DMPlex

3885:   Output Parameter:

3887:   Notes:
3888:   Concretely, DMPlexStratify() creates a new label named "depth" containing the depth in the DAG of each point. For cell-vertex
3889:   meshes, vertices are depth 0 and cells are depth 1. For fully interpolated meshes, depth 0 for vertices, 1 for edges, and so on
3890:   until cells have depth equal to the dimension of the mesh. The depth label can be accessed through DMPlexGetDepthLabel() or DMPlexGetDepthStratum(), or
3891:   manually via DMGetLabel().  The height is defined implicitly by height = maxDimension - depth, and can be accessed
3892:   via DMPlexGetHeightStratum().  For example, cells have height 0 and faces have height 1.

3894:   The depth of a point is calculated by executing a breadth-first search (BFS) on the DAG. This could produce surprising results
3895:   if run on a partially interpolated mesh, meaning one that had some edges and faces, but not others. For example, suppose that
3896:   we had a mesh consisting of one triangle (c0) and three vertices (v0, v1, v2), and only one edge is on the boundary so we choose
3897:   to interpolate only that one (e0), so that
3898: $  cone(c0) = {e0, v2}
3899: $  cone(e0) = {v0, v1}
3900:   If DMPlexStratify() is run on this mesh, it will give depths
3901: $  depth 0 = {v0, v1, v2}
3902: $  depth 1 = {e0, c0}
3903:   where the triangle has been given depth 1, instead of 2, because it is reachable from vertex v2.

3905:   DMPlexStratify() should be called after all calls to DMPlexSymmetrize()

3907:   Level: beginner

3909: .seealso: `DMPlexCreate()`, `DMPlexSymmetrize()`, `DMPlexComputeCellTypes()`
3910: @*/
3911: PetscErrorCode DMPlexStratify(DM dm)
3912: {
3913:   DM_Plex *mesh = (DM_Plex *)dm->data;
3914:   DMLabel  label;
3915:   PetscInt pStart, pEnd, p;
3916:   PetscInt numRoots = 0, numLeaves = 0;

3919:   PetscLogEventBegin(DMPLEX_Stratify, dm, 0, 0, 0);

3921:   /* Create depth label */
3922:   DMPlexGetChart(dm, &pStart, &pEnd);
3923:   DMCreateLabel(dm, "depth");
3924:   DMPlexGetDepthLabel(dm, &label);

3926:   {
3927:     /* Initialize roots and count leaves */
3928:     PetscInt sMin = PETSC_MAX_INT;
3929:     PetscInt sMax = PETSC_MIN_INT;
3930:     PetscInt coneSize, supportSize;

3932:     for (p = pStart; p < pEnd; ++p) {
3933:       DMPlexGetConeSize(dm, p, &coneSize);
3934:       DMPlexGetSupportSize(dm, p, &supportSize);
3935:       if (!coneSize && supportSize) {
3936:         sMin = PetscMin(p, sMin);
3937:         sMax = PetscMax(p, sMax);
3938:         ++numRoots;
3939:       } else if (!supportSize && coneSize) {
3940:         ++numLeaves;
3941:       } else if (!supportSize && !coneSize) {
3942:         /* Isolated points */
3943:         sMin = PetscMin(p, sMin);
3944:         sMax = PetscMax(p, sMax);
3945:       }
3946:     }
3947:     DMPlexCreateDepthStratum(dm, label, 0, sMin, sMax + 1);
3948:   }

3950:   if (numRoots + numLeaves == (pEnd - pStart)) {
3951:     PetscInt sMin = PETSC_MAX_INT;
3952:     PetscInt sMax = PETSC_MIN_INT;
3953:     PetscInt coneSize, supportSize;

3955:     for (p = pStart; p < pEnd; ++p) {
3956:       DMPlexGetConeSize(dm, p, &coneSize);
3957:       DMPlexGetSupportSize(dm, p, &supportSize);
3958:       if (!supportSize && coneSize) {
3959:         sMin = PetscMin(p, sMin);
3960:         sMax = PetscMax(p, sMax);
3961:       }
3962:     }
3963:     DMPlexCreateDepthStratum(dm, label, 1, sMin, sMax + 1);
3964:   } else {
3965:     PetscInt level = 0;
3966:     PetscInt qStart, qEnd, q;

3968:     DMLabelGetStratumBounds(label, level, &qStart, &qEnd);
3969:     while (qEnd > qStart) {
3970:       PetscInt sMin = PETSC_MAX_INT;
3971:       PetscInt sMax = PETSC_MIN_INT;

3973:       for (q = qStart; q < qEnd; ++q) {
3974:         const PetscInt *support;
3975:         PetscInt        supportSize, s;

3977:         DMPlexGetSupportSize(dm, q, &supportSize);
3978:         DMPlexGetSupport(dm, q, &support);
3979:         for (s = 0; s < supportSize; ++s) {
3980:           sMin = PetscMin(support[s], sMin);
3981:           sMax = PetscMax(support[s], sMax);
3982:         }
3983:       }
3984:       DMLabelGetNumValues(label, &level);
3985:       DMPlexCreateDepthStratum(dm, label, level, sMin, sMax + 1);
3986:       DMLabelGetStratumBounds(label, level, &qStart, &qEnd);
3987:     }
3988:   }
3989:   { /* just in case there is an empty process */
3990:     PetscInt numValues, maxValues = 0, v;

3992:     DMLabelGetNumValues(label, &numValues);
3993:     MPI_Allreduce(&numValues, &maxValues, 1, MPIU_INT, MPI_MAX, PetscObjectComm((PetscObject)dm));
3994:     for (v = numValues; v < maxValues; v++) DMLabelAddStratum(label, v);
3995:   }
3996:   PetscObjectStateGet((PetscObject)label, &mesh->depthState);
3997:   PetscLogEventEnd(DMPLEX_Stratify, dm, 0, 0, 0);
3998:   return 0;
3999: }

4001: PetscErrorCode DMPlexComputeCellType_Internal(DM dm, PetscInt p, PetscInt pdepth, DMPolytopeType *pt)
4002: {
4003:   DMPolytopeType ct = DM_POLYTOPE_UNKNOWN;
4004:   PetscInt       dim, depth, pheight, coneSize;

4007:   DMGetDimension(dm, &dim);
4008:   DMPlexGetDepth(dm, &depth);
4009:   DMPlexGetConeSize(dm, p, &coneSize);
4010:   pheight = depth - pdepth;
4011:   if (depth <= 1) {
4012:     switch (pdepth) {
4013:     case 0:
4014:       ct = DM_POLYTOPE_POINT;
4015:       break;
4016:     case 1:
4017:       switch (coneSize) {
4018:       case 2:
4019:         ct = DM_POLYTOPE_SEGMENT;
4020:         break;
4021:       case 3:
4022:         ct = DM_POLYTOPE_TRIANGLE;
4023:         break;
4024:       case 4:
4025:         switch (dim) {
4026:         case 2:
4027:           ct = DM_POLYTOPE_QUADRILATERAL;
4028:           break;
4029:         case 3:
4030:           ct = DM_POLYTOPE_TETRAHEDRON;
4031:           break;
4032:         default:
4033:           break;
4034:         }
4035:         break;
4036:       case 5:
4037:         ct = DM_POLYTOPE_PYRAMID;
4038:         break;
4039:       case 6:
4040:         ct = DM_POLYTOPE_TRI_PRISM_TENSOR;
4041:         break;
4042:       case 8:
4043:         ct = DM_POLYTOPE_HEXAHEDRON;
4044:         break;
4045:       default:
4046:         break;
4047:       }
4048:     }
4049:   } else {
4050:     if (pdepth == 0) {
4051:       ct = DM_POLYTOPE_POINT;
4052:     } else if (pheight == 0) {
4053:       switch (dim) {
4054:       case 1:
4055:         switch (coneSize) {
4056:         case 2:
4057:           ct = DM_POLYTOPE_SEGMENT;
4058:           break;
4059:         default:
4060:           break;
4061:         }
4062:         break;
4063:       case 2:
4064:         switch (coneSize) {
4065:         case 3:
4066:           ct = DM_POLYTOPE_TRIANGLE;
4067:           break;
4068:         case 4:
4069:           ct = DM_POLYTOPE_QUADRILATERAL;
4070:           break;
4071:         default:
4072:           break;
4073:         }
4074:         break;
4075:       case 3:
4076:         switch (coneSize) {
4077:         case 4:
4078:           ct = DM_POLYTOPE_TETRAHEDRON;
4079:           break;
4080:         case 5: {
4081:           const PetscInt *cone;
4082:           PetscInt        faceConeSize;

4084:           DMPlexGetCone(dm, p, &cone);
4085:           DMPlexGetConeSize(dm, cone[0], &faceConeSize);
4086:           switch (faceConeSize) {
4087:           case 3:
4088:             ct = DM_POLYTOPE_TRI_PRISM_TENSOR;
4089:             break;
4090:           case 4:
4091:             ct = DM_POLYTOPE_PYRAMID;
4092:             break;
4093:           }
4094:         } break;
4095:         case 6:
4096:           ct = DM_POLYTOPE_HEXAHEDRON;
4097:           break;
4098:         default:
4099:           break;
4100:         }
4101:         break;
4102:       default:
4103:         break;
4104:       }
4105:     } else if (pheight > 0) {
4106:       switch (coneSize) {
4107:       case 2:
4108:         ct = DM_POLYTOPE_SEGMENT;
4109:         break;
4110:       case 3:
4111:         ct = DM_POLYTOPE_TRIANGLE;
4112:         break;
4113:       case 4:
4114:         ct = DM_POLYTOPE_QUADRILATERAL;
4115:         break;
4116:       default:
4117:         break;
4118:       }
4119:     }
4120:   }
4121:   *pt = ct;
4122:   return 0;
4123: }

4125: /*@
4126:   DMPlexComputeCellTypes - Infer the polytope type of every cell using its dimension and cone size.

4128:   Collective on dm

4130:   Input Parameter:
4131: . mesh - The DMPlex

4133:   DMPlexComputeCellTypes() should be called after all calls to DMPlexSymmetrize() and DMPlexStratify()

4135:   Level: developer

4137:   Note: This function is normally called automatically by Plex when a cell type is requested. It creates an
4138:   internal DMLabel named "celltype" which can be directly accessed using DMGetLabel(). A user may disable
4139:   automatic creation by creating the label manually, using DMCreateLabel(dm, "celltype").

4141: .seealso: `DMPlexCreate()`, `DMPlexSymmetrize()`, `DMPlexStratify()`, `DMGetLabel()`, `DMCreateLabel()`
4142: @*/
4143: PetscErrorCode DMPlexComputeCellTypes(DM dm)
4144: {
4145:   DM_Plex *mesh;
4146:   DMLabel  ctLabel;
4147:   PetscInt pStart, pEnd, p;

4150:   mesh = (DM_Plex *)dm->data;
4151:   DMCreateLabel(dm, "celltype");
4152:   DMPlexGetCellTypeLabel(dm, &ctLabel);
4153:   DMPlexGetChart(dm, &pStart, &pEnd);
4154:   for (p = pStart; p < pEnd; ++p) {
4155:     DMPolytopeType ct = DM_POLYTOPE_UNKNOWN;
4156:     PetscInt       pdepth;

4158:     DMPlexGetPointDepth(dm, p, &pdepth);
4159:     DMPlexComputeCellType_Internal(dm, p, pdepth, &ct);
4161:     DMLabelSetValue(ctLabel, p, ct);
4162:   }
4163:   PetscObjectStateGet((PetscObject)ctLabel, &mesh->celltypeState);
4164:   PetscObjectViewFromOptions((PetscObject)ctLabel, NULL, "-dm_plex_celltypes_view");
4165:   return 0;
4166: }

4168: /*@C
4169:   DMPlexGetJoin - Get an array for the join of the set of points

4171:   Not Collective

4173:   Input Parameters:
4174: + dm - The DMPlex object
4175: . numPoints - The number of input points for the join
4176: - points - The input points

4178:   Output Parameters:
4179: + numCoveredPoints - The number of points in the join
4180: - coveredPoints - The points in the join

4182:   Level: intermediate

4184:   Note: Currently, this is restricted to a single level join

4186:   Fortran Notes:
4187:   Since it returns an array, this routine is only available in Fortran 90, and you must
4188:   include petsc.h90 in your code.

4190:   The numCoveredPoints argument is not present in the Fortran 90 binding since it is internal to the array.

4192: .seealso: `DMPlexRestoreJoin()`, `DMPlexGetMeet()`
4193: @*/
4194: PetscErrorCode DMPlexGetJoin(DM dm, PetscInt numPoints, const PetscInt points[], PetscInt *numCoveredPoints, const PetscInt **coveredPoints)
4195: {
4196:   DM_Plex  *mesh = (DM_Plex *)dm->data;
4197:   PetscInt *join[2];
4198:   PetscInt  joinSize, i = 0;
4199:   PetscInt  dof, off, p, c, m;
4200:   PetscInt  maxSupportSize;

4206:   PetscSectionGetMaxDof(mesh->supportSection, &maxSupportSize);
4207:   DMGetWorkArray(dm, maxSupportSize, MPIU_INT, &join[0]);
4208:   DMGetWorkArray(dm, maxSupportSize, MPIU_INT, &join[1]);
4209:   /* Copy in support of first point */
4210:   PetscSectionGetDof(mesh->supportSection, points[0], &dof);
4211:   PetscSectionGetOffset(mesh->supportSection, points[0], &off);
4212:   for (joinSize = 0; joinSize < dof; ++joinSize) join[i][joinSize] = mesh->supports[off + joinSize];
4213:   /* Check each successive support */
4214:   for (p = 1; p < numPoints; ++p) {
4215:     PetscInt newJoinSize = 0;

4217:     PetscSectionGetDof(mesh->supportSection, points[p], &dof);
4218:     PetscSectionGetOffset(mesh->supportSection, points[p], &off);
4219:     for (c = 0; c < dof; ++c) {
4220:       const PetscInt point = mesh->supports[off + c];

4222:       for (m = 0; m < joinSize; ++m) {
4223:         if (point == join[i][m]) {
4224:           join[1 - i][newJoinSize++] = point;
4225:           break;
4226:         }
4227:       }
4228:     }
4229:     joinSize = newJoinSize;
4230:     i        = 1 - i;
4231:   }
4232:   *numCoveredPoints = joinSize;
4233:   *coveredPoints    = join[i];
4234:   DMRestoreWorkArray(dm, maxSupportSize, MPIU_INT, &join[1 - i]);
4235:   return 0;
4236: }

4238: /*@C
4239:   DMPlexRestoreJoin - Restore an array for the join of the set of points

4241:   Not Collective

4243:   Input Parameters:
4244: + dm - The DMPlex object
4245: . numPoints - The number of input points for the join
4246: - points - The input points

4248:   Output Parameters:
4249: + numCoveredPoints - The number of points in the join
4250: - coveredPoints - The points in the join

4252:   Fortran Notes:
4253:   Since it returns an array, this routine is only available in Fortran 90, and you must
4254:   include petsc.h90 in your code.

4256:   The numCoveredPoints argument is not present in the Fortran 90 binding since it is internal to the array.

4258:   Level: intermediate

4260: .seealso: `DMPlexGetJoin()`, `DMPlexGetFullJoin()`, `DMPlexGetMeet()`
4261: @*/
4262: PetscErrorCode DMPlexRestoreJoin(DM dm, PetscInt numPoints, const PetscInt points[], PetscInt *numCoveredPoints, const PetscInt **coveredPoints)
4263: {
4268:   DMRestoreWorkArray(dm, 0, MPIU_INT, (void *)coveredPoints);
4269:   if (numCoveredPoints) *numCoveredPoints = 0;
4270:   return 0;
4271: }

4273: /*@C
4274:   DMPlexGetFullJoin - Get an array for the join of the set of points

4276:   Not Collective

4278:   Input Parameters:
4279: + dm - The DMPlex object
4280: . numPoints - The number of input points for the join
4281: - points - The input points

4283:   Output Parameters:
4284: + numCoveredPoints - The number of points in the join
4285: - coveredPoints - The points in the join

4287:   Fortran Notes:
4288:   Since it returns an array, this routine is only available in Fortran 90, and you must
4289:   include petsc.h90 in your code.

4291:   The numCoveredPoints argument is not present in the Fortran 90 binding since it is internal to the array.

4293:   Level: intermediate

4295: .seealso: `DMPlexGetJoin()`, `DMPlexRestoreJoin()`, `DMPlexGetMeet()`
4296: @*/
4297: PetscErrorCode DMPlexGetFullJoin(DM dm, PetscInt numPoints, const PetscInt points[], PetscInt *numCoveredPoints, const PetscInt **coveredPoints)
4298: {
4299:   PetscInt *offsets, **closures;
4300:   PetscInt *join[2];
4301:   PetscInt  depth = 0, maxSize, joinSize = 0, i = 0;
4302:   PetscInt  p, d, c, m, ms;


4309:   DMPlexGetDepth(dm, &depth);
4310:   PetscCalloc1(numPoints, &closures);
4311:   DMGetWorkArray(dm, numPoints * (depth + 2), MPIU_INT, &offsets);
4312:   DMPlexGetMaxSizes(dm, NULL, &ms);
4313:   maxSize = (ms > 1) ? ((PetscPowInt(ms, depth + 1) - 1) / (ms - 1)) : depth + 1;
4314:   DMGetWorkArray(dm, maxSize, MPIU_INT, &join[0]);
4315:   DMGetWorkArray(dm, maxSize, MPIU_INT, &join[1]);

4317:   for (p = 0; p < numPoints; ++p) {
4318:     PetscInt closureSize;

4320:     DMPlexGetTransitiveClosure(dm, points[p], PETSC_FALSE, &closureSize, &closures[p]);

4322:     offsets[p * (depth + 2) + 0] = 0;
4323:     for (d = 0; d < depth + 1; ++d) {
4324:       PetscInt pStart, pEnd, i;

4326:       DMPlexGetDepthStratum(dm, d, &pStart, &pEnd);
4327:       for (i = offsets[p * (depth + 2) + d]; i < closureSize; ++i) {
4328:         if ((pStart > closures[p][i * 2]) || (pEnd <= closures[p][i * 2])) {
4329:           offsets[p * (depth + 2) + d + 1] = i;
4330:           break;
4331:         }
4332:       }
4333:       if (i == closureSize) offsets[p * (depth + 2) + d + 1] = i;
4334:     }
4336:   }
4337:   for (d = 0; d < depth + 1; ++d) {
4338:     PetscInt dof;

4340:     /* Copy in support of first point */
4341:     dof = offsets[d + 1] - offsets[d];
4342:     for (joinSize = 0; joinSize < dof; ++joinSize) join[i][joinSize] = closures[0][(offsets[d] + joinSize) * 2];
4343:     /* Check each successive cone */
4344:     for (p = 1; p < numPoints && joinSize; ++p) {
4345:       PetscInt newJoinSize = 0;

4347:       dof = offsets[p * (depth + 2) + d + 1] - offsets[p * (depth + 2) + d];
4348:       for (c = 0; c < dof; ++c) {
4349:         const PetscInt point = closures[p][(offsets[p * (depth + 2) + d] + c) * 2];

4351:         for (m = 0; m < joinSize; ++m) {
4352:           if (point == join[i][m]) {
4353:             join[1 - i][newJoinSize++] = point;
4354:             break;
4355:           }
4356:         }
4357:       }
4358:       joinSize = newJoinSize;
4359:       i        = 1 - i;
4360:     }
4361:     if (joinSize) break;
4362:   }
4363:   *numCoveredPoints = joinSize;
4364:   *coveredPoints    = join[i];
4365:   for (p = 0; p < numPoints; ++p) DMPlexRestoreTransitiveClosure(dm, points[p], PETSC_FALSE, NULL, &closures[p]);
4366:   PetscFree(closures);
4367:   DMRestoreWorkArray(dm, numPoints * (depth + 2), MPIU_INT, &offsets);
4368:   DMRestoreWorkArray(dm, ms, MPIU_INT, &join[1 - i]);
4369:   return 0;
4370: }

4372: /*@C
4373:   DMPlexGetMeet - Get an array for the meet of the set of points

4375:   Not Collective

4377:   Input Parameters:
4378: + dm - The DMPlex object
4379: . numPoints - The number of input points for the meet
4380: - points - The input points

4382:   Output Parameters:
4383: + numCoveredPoints - The number of points in the meet
4384: - coveredPoints - The points in the meet

4386:   Level: intermediate

4388:   Note: Currently, this is restricted to a single level meet

4390:   Fortran Notes:
4391:   Since it returns an array, this routine is only available in Fortran 90, and you must
4392:   include petsc.h90 in your code.

4394:   The numCoveredPoints argument is not present in the Fortran 90 binding since it is internal to the array.

4396: .seealso: `DMPlexRestoreMeet()`, `DMPlexGetJoin()`
4397: @*/
4398: PetscErrorCode DMPlexGetMeet(DM dm, PetscInt numPoints, const PetscInt points[], PetscInt *numCoveringPoints, const PetscInt **coveringPoints)
4399: {
4400:   DM_Plex  *mesh = (DM_Plex *)dm->data;
4401:   PetscInt *meet[2];
4402:   PetscInt  meetSize, i = 0;
4403:   PetscInt  dof, off, p, c, m;
4404:   PetscInt  maxConeSize;

4410:   PetscSectionGetMaxDof(mesh->coneSection, &maxConeSize);
4411:   DMGetWorkArray(dm, maxConeSize, MPIU_INT, &meet[0]);
4412:   DMGetWorkArray(dm, maxConeSize, MPIU_INT, &meet[1]);
4413:   /* Copy in cone of first point */
4414:   PetscSectionGetDof(mesh->coneSection, points[0], &dof);
4415:   PetscSectionGetOffset(mesh->coneSection, points[0], &off);
4416:   for (meetSize = 0; meetSize < dof; ++meetSize) meet[i][meetSize] = mesh->cones[off + meetSize];
4417:   /* Check each successive cone */
4418:   for (p = 1; p < numPoints; ++p) {
4419:     PetscInt newMeetSize = 0;

4421:     PetscSectionGetDof(mesh->coneSection, points[p], &dof);
4422:     PetscSectionGetOffset(mesh->coneSection, points[p], &off);
4423:     for (c = 0; c < dof; ++c) {
4424:       const PetscInt point = mesh->cones[off + c];

4426:       for (m = 0; m < meetSize; ++m) {
4427:         if (point == meet[i][m]) {
4428:           meet[1 - i][newMeetSize++] = point;
4429:           break;
4430:         }
4431:       }
4432:     }
4433:     meetSize = newMeetSize;
4434:     i        = 1 - i;
4435:   }
4436:   *numCoveringPoints = meetSize;
4437:   *coveringPoints    = meet[i];
4438:   DMRestoreWorkArray(dm, maxConeSize, MPIU_INT, &meet[1 - i]);
4439:   return 0;
4440: }

4442: /*@C
4443:   DMPlexRestoreMeet - Restore an array for the meet of the set of points

4445:   Not Collective

4447:   Input Parameters:
4448: + dm - The DMPlex object
4449: . numPoints - The number of input points for the meet
4450: - points - The input points

4452:   Output Parameters:
4453: + numCoveredPoints - The number of points in the meet
4454: - coveredPoints - The points in the meet

4456:   Level: intermediate

4458:   Fortran Notes:
4459:   Since it returns an array, this routine is only available in Fortran 90, and you must
4460:   include petsc.h90 in your code.

4462:   The numCoveredPoints argument is not present in the Fortran 90 binding since it is internal to the array.

4464: .seealso: `DMPlexGetMeet()`, `DMPlexGetFullMeet()`, `DMPlexGetJoin()`
4465: @*/
4466: PetscErrorCode DMPlexRestoreMeet(DM dm, PetscInt numPoints, const PetscInt points[], PetscInt *numCoveredPoints, const PetscInt **coveredPoints)
4467: {
4472:   DMRestoreWorkArray(dm, 0, MPIU_INT, (void *)coveredPoints);
4473:   if (numCoveredPoints) *numCoveredPoints = 0;
4474:   return 0;
4475: }

4477: /*@C
4478:   DMPlexGetFullMeet - Get an array for the meet of the set of points

4480:   Not Collective

4482:   Input Parameters:
4483: + dm - The DMPlex object
4484: . numPoints - The number of input points for the meet
4485: - points - The input points

4487:   Output Parameters:
4488: + numCoveredPoints - The number of points in the meet
4489: - coveredPoints - The points in the meet

4491:   Level: intermediate

4493:   Fortran Notes:
4494:   Since it returns an array, this routine is only available in Fortran 90, and you must
4495:   include petsc.h90 in your code.

4497:   The numCoveredPoints argument is not present in the Fortran 90 binding since it is internal to the array.

4499: .seealso: `DMPlexGetMeet()`, `DMPlexRestoreMeet()`, `DMPlexGetJoin()`
4500: @*/
4501: PetscErrorCode DMPlexGetFullMeet(DM dm, PetscInt numPoints, const PetscInt points[], PetscInt *numCoveredPoints, const PetscInt **coveredPoints)
4502: {
4503:   PetscInt *offsets, **closures;
4504:   PetscInt *meet[2];
4505:   PetscInt  height = 0, maxSize, meetSize = 0, i = 0;
4506:   PetscInt  p, h, c, m, mc;


4513:   DMPlexGetDepth(dm, &height);
4514:   PetscMalloc1(numPoints, &closures);
4515:   DMGetWorkArray(dm, numPoints * (height + 2), MPIU_INT, &offsets);
4516:   DMPlexGetMaxSizes(dm, &mc, NULL);
4517:   maxSize = (mc > 1) ? ((PetscPowInt(mc, height + 1) - 1) / (mc - 1)) : height + 1;
4518:   DMGetWorkArray(dm, maxSize, MPIU_INT, &meet[0]);
4519:   DMGetWorkArray(dm, maxSize, MPIU_INT, &meet[1]);

4521:   for (p = 0; p < numPoints; ++p) {
4522:     PetscInt closureSize;

4524:     DMPlexGetTransitiveClosure(dm, points[p], PETSC_TRUE, &closureSize, &closures[p]);

4526:     offsets[p * (height + 2) + 0] = 0;
4527:     for (h = 0; h < height + 1; ++h) {
4528:       PetscInt pStart, pEnd, i;

4530:       DMPlexGetHeightStratum(dm, h, &pStart, &pEnd);
4531:       for (i = offsets[p * (height + 2) + h]; i < closureSize; ++i) {
4532:         if ((pStart > closures[p][i * 2]) || (pEnd <= closures[p][i * 2])) {
4533:           offsets[p * (height + 2) + h + 1] = i;
4534:           break;
4535:         }
4536:       }
4537:       if (i == closureSize) offsets[p * (height + 2) + h + 1] = i;
4538:     }
4540:   }
4541:   for (h = 0; h < height + 1; ++h) {
4542:     PetscInt dof;

4544:     /* Copy in cone of first point */
4545:     dof = offsets[h + 1] - offsets[h];
4546:     for (meetSize = 0; meetSize < dof; ++meetSize) meet[i][meetSize] = closures[0][(offsets[h] + meetSize) * 2];
4547:     /* Check each successive cone */
4548:     for (p = 1; p < numPoints && meetSize; ++p) {
4549:       PetscInt newMeetSize = 0;

4551:       dof = offsets[p * (height + 2) + h + 1] - offsets[p * (height + 2) + h];
4552:       for (c = 0; c < dof; ++c) {
4553:         const PetscInt point = closures[p][(offsets[p * (height + 2) + h] + c) * 2];

4555:         for (m = 0; m < meetSize; ++m) {
4556:           if (point == meet[i][m]) {
4557:             meet[1 - i][newMeetSize++] = point;
4558:             break;
4559:           }
4560:         }
4561:       }
4562:       meetSize = newMeetSize;
4563:       i        = 1 - i;
4564:     }
4565:     if (meetSize) break;
4566:   }
4567:   *numCoveredPoints = meetSize;
4568:   *coveredPoints    = meet[i];
4569:   for (p = 0; p < numPoints; ++p) DMPlexRestoreTransitiveClosure(dm, points[p], PETSC_TRUE, NULL, &closures[p]);
4570:   PetscFree(closures);
4571:   DMRestoreWorkArray(dm, numPoints * (height + 2), MPIU_INT, &offsets);
4572:   DMRestoreWorkArray(dm, mc, MPIU_INT, &meet[1 - i]);
4573:   return 0;
4574: }

4576: /*@C
4577:   DMPlexEqual - Determine if two DMs have the same topology

4579:   Not Collective

4581:   Input Parameters:
4582: + dmA - A DMPlex object
4583: - dmB - A DMPlex object

4585:   Output Parameters:
4586: . equal - PETSC_TRUE if the topologies are identical

4588:   Level: intermediate

4590:   Notes:
4591:   We are not solving graph isomorphism, so we do not permutation.

4593: .seealso: `DMPlexGetCone()`
4594: @*/
4595: PetscErrorCode DMPlexEqual(DM dmA, DM dmB, PetscBool *equal)
4596: {
4597:   PetscInt depth, depthB, pStart, pEnd, pStartB, pEndB, p;


4603:   *equal = PETSC_FALSE;
4604:   DMPlexGetDepth(dmA, &depth);
4605:   DMPlexGetDepth(dmB, &depthB);
4606:   if (depth != depthB) return 0;
4607:   DMPlexGetChart(dmA, &pStart, &pEnd);
4608:   DMPlexGetChart(dmB, &pStartB, &pEndB);
4609:   if ((pStart != pStartB) || (pEnd != pEndB)) return 0;
4610:   for (p = pStart; p < pEnd; ++p) {
4611:     const PetscInt *cone, *coneB, *ornt, *orntB, *support, *supportB;
4612:     PetscInt        coneSize, coneSizeB, c, supportSize, supportSizeB, s;

4614:     DMPlexGetConeSize(dmA, p, &coneSize);
4615:     DMPlexGetCone(dmA, p, &cone);
4616:     DMPlexGetConeOrientation(dmA, p, &ornt);
4617:     DMPlexGetConeSize(dmB, p, &coneSizeB);
4618:     DMPlexGetCone(dmB, p, &coneB);
4619:     DMPlexGetConeOrientation(dmB, p, &orntB);
4620:     if (coneSize != coneSizeB) return 0;
4621:     for (c = 0; c < coneSize; ++c) {
4622:       if (cone[c] != coneB[c]) return 0;
4623:       if (ornt[c] != orntB[c]) return 0;
4624:     }
4625:     DMPlexGetSupportSize(dmA, p, &supportSize);
4626:     DMPlexGetSupport(dmA, p, &support);
4627:     DMPlexGetSupportSize(dmB, p, &supportSizeB);
4628:     DMPlexGetSupport(dmB, p, &supportB);
4629:     if (supportSize != supportSizeB) return 0;
4630:     for (s = 0; s < supportSize; ++s) {
4631:       if (support[s] != supportB[s]) return 0;
4632:     }
4633:   }
4634:   *equal = PETSC_TRUE;
4635:   return 0;
4636: }

4638: /*@C
4639:   DMPlexGetNumFaceVertices - Returns the number of vertices on a face

4641:   Not Collective

4643:   Input Parameters:
4644: + dm         - The DMPlex
4645: . cellDim    - The cell dimension
4646: - numCorners - The number of vertices on a cell

4648:   Output Parameters:
4649: . numFaceVertices - The number of vertices on a face

4651:   Level: developer

4653:   Notes:
4654:   Of course this can only work for a restricted set of symmetric shapes

4656: .seealso: `DMPlexGetCone()`
4657: @*/
4658: PetscErrorCode DMPlexGetNumFaceVertices(DM dm, PetscInt cellDim, PetscInt numCorners, PetscInt *numFaceVertices)
4659: {
4660:   MPI_Comm comm;

4662:   PetscObjectGetComm((PetscObject)dm, &comm);
4664:   switch (cellDim) {
4665:   case 0:
4666:     *numFaceVertices = 0;
4667:     break;
4668:   case 1:
4669:     *numFaceVertices = 1;
4670:     break;
4671:   case 2:
4672:     switch (numCorners) {
4673:     case 3:                 /* triangle */
4674:       *numFaceVertices = 2; /* Edge has 2 vertices */
4675:       break;
4676:     case 4:                 /* quadrilateral */
4677:       *numFaceVertices = 2; /* Edge has 2 vertices */
4678:       break;
4679:     case 6:                 /* quadratic triangle, tri and quad cohesive Lagrange cells */
4680:       *numFaceVertices = 3; /* Edge has 3 vertices */
4681:       break;
4682:     case 9:                 /* quadratic quadrilateral, quadratic quad cohesive Lagrange cells */
4683:       *numFaceVertices = 3; /* Edge has 3 vertices */
4684:       break;
4685:     default:
4686:       SETERRQ(comm, PETSC_ERR_ARG_OUTOFRANGE, "Invalid number of face corners %" PetscInt_FMT " for dimension %" PetscInt_FMT, numCorners, cellDim);
4687:     }
4688:     break;
4689:   case 3:
4690:     switch (numCorners) {
4691:     case 4:                 /* tetradehdron */
4692:       *numFaceVertices = 3; /* Face has 3 vertices */
4693:       break;
4694:     case 6:                 /* tet cohesive cells */
4695:       *numFaceVertices = 4; /* Face has 4 vertices */
4696:       break;
4697:     case 8:                 /* hexahedron */
4698:       *numFaceVertices = 4; /* Face has 4 vertices */
4699:       break;
4700:     case 9:                 /* tet cohesive Lagrange cells */
4701:       *numFaceVertices = 6; /* Face has 6 vertices */
4702:       break;
4703:     case 10:                /* quadratic tetrahedron */
4704:       *numFaceVertices = 6; /* Face has 6 vertices */
4705:       break;
4706:     case 12:                /* hex cohesive Lagrange cells */
4707:       *numFaceVertices = 6; /* Face has 6 vertices */
4708:       break;
4709:     case 18:                /* quadratic tet cohesive Lagrange cells */
4710:       *numFaceVertices = 6; /* Face has 6 vertices */
4711:       break;
4712:     case 27:                /* quadratic hexahedron, quadratic hex cohesive Lagrange cells */
4713:       *numFaceVertices = 9; /* Face has 9 vertices */
4714:       break;
4715:     default:
4716:       SETERRQ(comm, PETSC_ERR_ARG_OUTOFRANGE, "Invalid number of face corners %" PetscInt_FMT " for dimension %" PetscInt_FMT, numCorners, cellDim);
4717:     }
4718:     break;
4719:   default:
4720:     SETERRQ(comm, PETSC_ERR_ARG_OUTOFRANGE, "Invalid cell dimension %" PetscInt_FMT, cellDim);
4721:   }
4722:   return 0;
4723: }

4725: /*@
4726:   DMPlexGetDepthLabel - Get the DMLabel recording the depth of each point

4728:   Not Collective

4730:   Input Parameter:
4731: . dm    - The DMPlex object

4733:   Output Parameter:
4734: . depthLabel - The DMLabel recording point depth

4736:   Level: developer

4738: .seealso: `DMPlexGetDepth()`, `DMPlexGetHeightStratum()`, `DMPlexGetDepthStratum()`, `DMPlexGetPointDepth()`,
4739: @*/
4740: PetscErrorCode DMPlexGetDepthLabel(DM dm, DMLabel *depthLabel)
4741: {
4744:   *depthLabel = dm->depthLabel;
4745:   return 0;
4746: }

4748: /*@
4749:   DMPlexGetDepth - Get the depth of the DAG representing this mesh

4751:   Not Collective

4753:   Input Parameter:
4754: . dm    - The DMPlex object

4756:   Output Parameter:
4757: . depth - The number of strata (breadth first levels) in the DAG

4759:   Level: developer

4761:   Notes:
4762:   This returns maximum of point depths over all points, i.e. maximum value of the label returned by DMPlexGetDepthLabel().
4763:   The point depth is described more in detail in DMPlexGetDepthStratum().
4764:   An empty mesh gives -1.

4766: .seealso: `DMPlexGetDepthLabel()`, `DMPlexGetDepthStratum()`, `DMPlexGetPointDepth()`, `DMPlexSymmetrize()`
4767: @*/
4768: PetscErrorCode DMPlexGetDepth(DM dm, PetscInt *depth)
4769: {
4770:   DMLabel  label;
4771:   PetscInt d = 0;

4775:   DMPlexGetDepthLabel(dm, &label);
4776:   if (label) DMLabelGetNumValues(label, &d);
4777:   *depth = d - 1;
4778:   return 0;
4779: }

4781: /*@
4782:   DMPlexGetDepthStratum - Get the bounds [start, end) for all points at a certain depth.

4784:   Not Collective

4786:   Input Parameters:
4787: + dm    - The DMPlex object
4788: - depth - The requested depth

4790:   Output Parameters:
4791: + start - The first point at this depth
4792: - end   - One beyond the last point at this depth

4794:   Notes:
4795:   Depth indexing is related to topological dimension.  Depth stratum 0 contains the lowest topological dimension points,
4796:   often "vertices".  If the mesh is "interpolated" (see DMPlexInterpolate()), then depth stratum 1 contains the next
4797:   higher dimension, e.g., "edges".

4799:   Level: developer

4801: .seealso: `DMPlexGetHeightStratum()`, `DMPlexGetDepth()`, `DMPlexGetDepthLabel()`, `DMPlexGetPointDepth()`, `DMPlexSymmetrize()`, `DMPlexInterpolate()`
4802: @*/
4803: PetscErrorCode DMPlexGetDepthStratum(DM dm, PetscInt depth, PetscInt *start, PetscInt *end)
4804: {
4805:   DMLabel  label;
4806:   PetscInt pStart, pEnd;

4809:   if (start) {
4811:     *start = 0;
4812:   }
4813:   if (end) {
4815:     *end = 0;
4816:   }
4817:   DMPlexGetChart(dm, &pStart, &pEnd);
4818:   if (pStart == pEnd) return 0;
4819:   if (depth < 0) {
4820:     if (start) *start = pStart;
4821:     if (end) *end = pEnd;
4822:     return 0;
4823:   }
4824:   DMPlexGetDepthLabel(dm, &label);
4826:   DMLabelGetStratumBounds(label, depth, start, end);
4827:   return 0;
4828: }

4830: /*@
4831:   DMPlexGetHeightStratum - Get the bounds [start, end) for all points at a certain height.

4833:   Not Collective

4835:   Input Parameters:
4836: + dm     - The DMPlex object
4837: - height - The requested height

4839:   Output Parameters:
4840: + start - The first point at this height
4841: - end   - One beyond the last point at this height

4843:   Notes:
4844:   Height indexing is related to topological codimension.  Height stratum 0 contains the highest topological dimension
4845:   points, often called "cells" or "elements".  If the mesh is "interpolated" (see DMPlexInterpolate()), then height
4846:   stratum 1 contains the boundary of these "cells", often called "faces" or "facets".

4848:   Level: developer

4850: .seealso: `DMPlexGetDepthStratum()`, `DMPlexGetDepth()`, `DMPlexGetPointHeight()`
4851: @*/
4852: PetscErrorCode DMPlexGetHeightStratum(DM dm, PetscInt height, PetscInt *start, PetscInt *end)
4853: {
4854:   DMLabel  label;
4855:   PetscInt depth, pStart, pEnd;

4858:   if (start) {
4860:     *start = 0;
4861:   }
4862:   if (end) {
4864:     *end = 0;
4865:   }
4866:   DMPlexGetChart(dm, &pStart, &pEnd);
4867:   if (pStart == pEnd) return 0;
4868:   if (height < 0) {
4869:     if (start) *start = pStart;
4870:     if (end) *end = pEnd;
4871:     return 0;
4872:   }
4873:   DMPlexGetDepthLabel(dm, &label);
4875:   DMLabelGetNumValues(label, &depth);
4876:   DMLabelGetStratumBounds(label, depth - 1 - height, start, end);
4877:   return 0;
4878: }

4880: /*@
4881:   DMPlexGetPointDepth - Get the depth of a given point

4883:   Not Collective

4885:   Input Parameters:
4886: + dm    - The DMPlex object
4887: - point - The point

4889:   Output Parameter:
4890: . depth - The depth of the point

4892:   Level: intermediate

4894: .seealso: `DMPlexGetCellType()`, `DMPlexGetDepthLabel()`, `DMPlexGetDepth()`, `DMPlexGetPointHeight()`
4895: @*/
4896: PetscErrorCode DMPlexGetPointDepth(DM dm, PetscInt point, PetscInt *depth)
4897: {
4900:   DMLabelGetValue(dm->depthLabel, point, depth);
4901:   return 0;
4902: }

4904: /*@
4905:   DMPlexGetPointHeight - Get the height of a given point

4907:   Not Collective

4909:   Input Parameters:
4910: + dm    - The DMPlex object
4911: - point - The point

4913:   Output Parameter:
4914: . height - The height of the point

4916:   Level: intermediate

4918: .seealso: `DMPlexGetCellType()`, `DMPlexGetDepthLabel()`, `DMPlexGetDepth()`, `DMPlexGetPointDepth()`
4919: @*/
4920: PetscErrorCode DMPlexGetPointHeight(DM dm, PetscInt point, PetscInt *height)
4921: {
4922:   PetscInt n, pDepth;

4926:   DMLabelGetNumValues(dm->depthLabel, &n);
4927:   DMLabelGetValue(dm->depthLabel, point, &pDepth);
4928:   *height = n - 1 - pDepth; /* DAG depth is n-1 */
4929:   return 0;
4930: }

4932: /*@
4933:   DMPlexGetCellTypeLabel - Get the DMLabel recording the polytope type of each cell

4935:   Not Collective

4937:   Input Parameter:
4938: . dm - The DMPlex object

4940:   Output Parameter:
4941: . celltypeLabel - The DMLabel recording cell polytope type

4943:   Note: This function will trigger automatica computation of cell types. This can be disabled by calling
4944:   DMCreateLabel(dm, "celltype") beforehand.

4946:   Level: developer

4948: .seealso: `DMPlexGetCellType()`, `DMPlexGetDepthLabel()`, `DMCreateLabel()`
4949: @*/
4950: PetscErrorCode DMPlexGetCellTypeLabel(DM dm, DMLabel *celltypeLabel)
4951: {
4954:   if (!dm->celltypeLabel) DMPlexComputeCellTypes(dm);
4955:   *celltypeLabel = dm->celltypeLabel;
4956:   return 0;
4957: }

4959: /*@
4960:   DMPlexGetCellType - Get the polytope type of a given cell

4962:   Not Collective

4964:   Input Parameters:
4965: + dm   - The DMPlex object
4966: - cell - The cell

4968:   Output Parameter:
4969: . celltype - The polytope type of the cell

4971:   Level: intermediate

4973: .seealso: `DMPlexGetCellTypeLabel()`, `DMPlexGetDepthLabel()`, `DMPlexGetDepth()`
4974: @*/
4975: PetscErrorCode DMPlexGetCellType(DM dm, PetscInt cell, DMPolytopeType *celltype)
4976: {
4977:   DMLabel  label;
4978:   PetscInt ct;

4982:   DMPlexGetCellTypeLabel(dm, &label);
4983:   DMLabelGetValue(label, cell, &ct);
4985:   *celltype = (DMPolytopeType)ct;
4986:   return 0;
4987: }

4989: /*@
4990:   DMPlexSetCellType - Set the polytope type of a given cell

4992:   Not Collective

4994:   Input Parameters:
4995: + dm   - The DMPlex object
4996: . cell - The cell
4997: - celltype - The polytope type of the cell

4999:   Note: By default, cell types will be automatically computed using DMPlexComputeCellTypes() before this function
5000:   is executed. This function will override the computed type. However, if automatic classification will not succeed
5001:   and a user wants to manually specify all types, the classification must be disabled by calling
5002:   DMCreaateLabel(dm, "celltype") before getting or setting any cell types.

5004:   Level: advanced

5006: .seealso: `DMPlexGetCellTypeLabel()`, `DMPlexGetDepthLabel()`, `DMPlexGetDepth()`, `DMPlexComputeCellTypes()`, `DMCreateLabel()`
5007: @*/
5008: PetscErrorCode DMPlexSetCellType(DM dm, PetscInt cell, DMPolytopeType celltype)
5009: {
5010:   DMLabel label;

5013:   DMPlexGetCellTypeLabel(dm, &label);
5014:   DMLabelSetValue(label, cell, celltype);
5015:   return 0;
5016: }

5018: PetscErrorCode DMCreateCoordinateDM_Plex(DM dm, DM *cdm)
5019: {
5020:   PetscSection section, s;
5021:   Mat          m;
5022:   PetscInt     maxHeight;

5024:   DMClone(dm, cdm);
5025:   DMPlexGetMaxProjectionHeight(dm, &maxHeight);
5026:   DMPlexSetMaxProjectionHeight(*cdm, maxHeight);
5027:   PetscSectionCreate(PetscObjectComm((PetscObject)dm), &section);
5028:   DMSetLocalSection(*cdm, section);
5029:   PetscSectionDestroy(&section);
5030:   PetscSectionCreate(PETSC_COMM_SELF, &s);
5031:   MatCreate(PETSC_COMM_SELF, &m);
5032:   DMSetDefaultConstraints(*cdm, s, m, NULL);
5033:   PetscSectionDestroy(&s);
5034:   MatDestroy(&m);

5036:   DMSetNumFields(*cdm, 1);
5037:   DMCreateDS(*cdm);
5038:   return 0;
5039: }

5041: PetscErrorCode DMCreateCoordinateField_Plex(DM dm, DMField *field)
5042: {
5043:   Vec coordsLocal, cellCoordsLocal;
5044:   DM  coordsDM, cellCoordsDM;

5046:   *field = NULL;
5047:   DMGetCoordinatesLocal(dm, &coordsLocal);
5048:   DMGetCoordinateDM(dm, &coordsDM);
5049:   DMGetCellCoordinatesLocal(dm, &cellCoordsLocal);
5050:   DMGetCellCoordinateDM(dm, &cellCoordsDM);
5051:   if (coordsLocal && coordsDM) {
5052:     if (cellCoordsLocal && cellCoordsDM) DMFieldCreateDSWithDG(coordsDM, cellCoordsDM, 0, coordsLocal, cellCoordsLocal, field);
5053:     else DMFieldCreateDS(coordsDM, 0, coordsLocal, field);
5054:   }
5055:   return 0;
5056: }

5058: /*@C
5059:   DMPlexGetConeSection - Return a section which describes the layout of cone data

5061:   Not Collective

5063:   Input Parameters:
5064: . dm        - The DMPlex object

5066:   Output Parameter:
5067: . section - The PetscSection object

5069:   Level: developer

5071: .seealso: `DMPlexGetSupportSection()`, `DMPlexGetCones()`, `DMPlexGetConeOrientations()`
5072: @*/
5073: PetscErrorCode DMPlexGetConeSection(DM dm, PetscSection *section)
5074: {
5075:   DM_Plex *mesh = (DM_Plex *)dm->data;

5078:   if (section) *section = mesh->coneSection;
5079:   return 0;
5080: }

5082: /*@C
5083:   DMPlexGetSupportSection - Return a section which describes the layout of support data

5085:   Not Collective

5087:   Input Parameters:
5088: . dm        - The DMPlex object

5090:   Output Parameter:
5091: . section - The PetscSection object

5093:   Level: developer

5095: .seealso: `DMPlexGetConeSection()`
5096: @*/
5097: PetscErrorCode DMPlexGetSupportSection(DM dm, PetscSection *section)
5098: {
5099:   DM_Plex *mesh = (DM_Plex *)dm->data;

5102:   if (section) *section = mesh->supportSection;
5103:   return 0;
5104: }

5106: /*@C
5107:   DMPlexGetCones - Return cone data

5109:   Not Collective

5111:   Input Parameters:
5112: . dm        - The DMPlex object

5114:   Output Parameter:
5115: . cones - The cone for each point

5117:   Level: developer

5119: .seealso: `DMPlexGetConeSection()`
5120: @*/
5121: PetscErrorCode DMPlexGetCones(DM dm, PetscInt *cones[])
5122: {
5123:   DM_Plex *mesh = (DM_Plex *)dm->data;

5126:   if (cones) *cones = mesh->cones;
5127:   return 0;
5128: }

5130: /*@C
5131:   DMPlexGetConeOrientations - Return cone orientation data

5133:   Not Collective

5135:   Input Parameters:
5136: . dm        - The DMPlex object

5138:   Output Parameter:
5139: . coneOrientations - The array of cone orientations for all points

5141:   Level: developer

5143:   Notes:
5144:   The PetscSection returned by DMPlexGetConeSection() partitions coneOrientations into cone orientations of particular points as returned by DMPlexGetConeOrientation().

5146:   The meaning of coneOrientations values is detailed in DMPlexGetConeOrientation().

5148: .seealso: `DMPlexGetConeSection()`, `DMPlexGetConeOrientation()`
5149: @*/
5150: PetscErrorCode DMPlexGetConeOrientations(DM dm, PetscInt *coneOrientations[])
5151: {
5152:   DM_Plex *mesh = (DM_Plex *)dm->data;

5155:   if (coneOrientations) *coneOrientations = mesh->coneOrientations;
5156:   return 0;
5157: }

5159: /******************************** FEM Support **********************************/

5161: /*
5162:  Returns number of components and tensor degree for the field.  For interpolated meshes, line should be a point
5163:  representing a line in the section.
5164: */
5165: static PetscErrorCode PetscSectionFieldGetTensorDegree_Private(PetscSection section, PetscInt field, PetscInt line, PetscBool vertexchart, PetscInt *Nc, PetscInt *k)
5166: {
5168:   PetscSectionGetFieldComponents(section, field, Nc);
5169:   if (line < 0) {
5170:     *k  = 0;
5171:     *Nc = 0;
5172:   } else if (vertexchart) { /* If we only have a vertex chart, we must have degree k=1 */
5173:     *k = 1;
5174:   } else { /* Assume the full interpolated mesh is in the chart; lines in particular */
5175:     /* An order k SEM disc has k-1 dofs on an edge */
5176:     PetscSectionGetFieldDof(section, line, field, k);
5177:     *k = *k / *Nc + 1;
5178:   }
5179:   return 0;
5180: }

5182: /*@

5184:   DMPlexSetClosurePermutationTensor - Create a permutation from the default (BFS) point ordering in the closure, to a
5185:   lexicographic ordering over the tensor product cell (i.e., line, quad, hex, etc.), and set this permutation in the
5186:   section provided (or the section of the DM).

5188:   Input Parameters:
5189: + dm      - The DM
5190: . point   - Either a cell (highest dim point) or an edge (dim 1 point), or PETSC_DETERMINE
5191: - section - The PetscSection to reorder, or NULL for the default section

5193:   Note: The point is used to determine the number of dofs/field on an edge. For SEM, this is related to the polynomial
5194:   degree of the basis.

5196:   Example:
5197:   A typical interpolated single-quad mesh might order points as
5198: .vb
5199:   [c0, v1, v2, v3, v4, e5, e6, e7, e8]

5201:   v4 -- e6 -- v3
5202:   |           |
5203:   e7    c0    e8
5204:   |           |
5205:   v1 -- e5 -- v2
5206: .ve

5208:   (There is no significance to the ordering described here.)  The default section for a Q3 quad might typically assign
5209:   dofs in the order of points, e.g.,
5210: .vb
5211:     c0 -> [0,1,2,3]
5212:     v1 -> [4]
5213:     ...
5214:     e5 -> [8, 9]
5215: .ve

5217:   which corresponds to the dofs
5218: .vb
5219:     6   10  11  7
5220:     13  2   3   15
5221:     12  0   1   14
5222:     4   8   9   5
5223: .ve

5225:   The closure in BFS ordering works through height strata (cells, edges, vertices) to produce the ordering
5226: .vb
5227:   0 1 2 3 8 9 14 15 11 10 13 12 4 5 7 6
5228: .ve

5230:   After calling DMPlexSetClosurePermutationTensor(), the closure will be ordered lexicographically,
5231: .vb
5232:    4 8 9 5 12 0 1 14 13 2 3 15 6 10 11 7
5233: .ve

5235:   Level: developer

5237: .seealso: `DMGetLocalSection()`, `PetscSectionSetClosurePermutation()`, `DMSetGlobalSection()`
5238: @*/
5239: PetscErrorCode DMPlexSetClosurePermutationTensor(DM dm, PetscInt point, PetscSection section)
5240: {
5241:   DMLabel   label;
5242:   PetscInt  dim, depth = -1, eStart = -1, Nf;
5243:   PetscBool vertexchart;

5245:   DMGetDimension(dm, &dim);
5246:   if (dim < 1) return 0;
5247:   if (point < 0) {
5248:     PetscInt sStart, sEnd;

5250:     DMPlexGetDepthStratum(dm, 1, &sStart, &sEnd);
5251:     point = sEnd - sStart ? sStart : point;
5252:   }
5253:   DMPlexGetDepthLabel(dm, &label);
5254:   if (point >= 0) DMLabelGetValue(label, point, &depth);
5255:   if (!section) DMGetLocalSection(dm, &section);
5256:   if (depth == 1) {
5257:     eStart = point;
5258:   } else if (depth == dim) {
5259:     const PetscInt *cone;

5261:     DMPlexGetCone(dm, point, &cone);
5262:     if (dim == 2) eStart = cone[0];
5263:     else if (dim == 3) {
5264:       const PetscInt *cone2;
5265:       DMPlexGetCone(dm, cone[0], &cone2);
5266:       eStart = cone2[0];
5267:     } else SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Point %" PetscInt_FMT " of depth %" PetscInt_FMT " cannot be used to bootstrap spectral ordering for dim %" PetscInt_FMT, point, depth, dim);
5269:   { /* Determine whether the chart covers all points or just vertices. */
5270:     PetscInt pStart, pEnd, cStart, cEnd;
5271:     DMPlexGetDepthStratum(dm, 0, &pStart, &pEnd);
5272:     PetscSectionGetChart(section, &cStart, &cEnd);
5273:     if (pStart == cStart && pEnd == cEnd) vertexchart = PETSC_TRUE;      /* Only vertices are in the chart */
5274:     else if (cStart <= point && point < cEnd) vertexchart = PETSC_FALSE; /* Some interpolated points exist in the chart */
5275:     else vertexchart = PETSC_TRUE;                                       /* Some interpolated points are not in chart; assume dofs only at cells and vertices */
5276:   }
5277:   PetscSectionGetNumFields(section, &Nf);
5278:   for (PetscInt d = 1; d <= dim; d++) {
5279:     PetscInt  k, f, Nc, c, i, j, size = 0, offset = 0, foffset = 0;
5280:     PetscInt *perm;

5282:     for (f = 0; f < Nf; ++f) {
5283:       PetscSectionFieldGetTensorDegree_Private(section, f, eStart, vertexchart, &Nc, &k);
5284:       size += PetscPowInt(k + 1, d) * Nc;
5285:     }
5286:     PetscMalloc1(size, &perm);
5287:     for (f = 0; f < Nf; ++f) {
5288:       switch (d) {
5289:       case 1:
5290:         PetscSectionFieldGetTensorDegree_Private(section, f, eStart, vertexchart, &Nc, &k);
5291:         /*
5292:          Original ordering is [ edge of length k-1; vtx0; vtx1 ]
5293:          We want              [ vtx0; edge of length k-1; vtx1 ]
5294:          */
5295:         for (c = 0; c < Nc; c++, offset++) perm[offset] = (k - 1) * Nc + c + foffset;
5296:         for (i = 0; i < k - 1; i++)
5297:           for (c = 0; c < Nc; c++, offset++) perm[offset] = i * Nc + c + foffset;
5298:         for (c = 0; c < Nc; c++, offset++) perm[offset] = k * Nc + c + foffset;
5299:         foffset = offset;
5300:         break;
5301:       case 2:
5302:         /* The original quad closure is oriented clockwise, {f, e_b, e_r, e_t, e_l, v_lb, v_rb, v_tr, v_tl} */
5303:         PetscSectionFieldGetTensorDegree_Private(section, f, eStart, vertexchart, &Nc, &k);
5304:         /* The SEM order is

5306:          v_lb, {e_b}, v_rb,
5307:          e^{(k-1)-i}_l, {f^{i*(k-1)}}, e^i_r,
5308:          v_lt, reverse {e_t}, v_rt
5309:          */
5310:         {
5311:           const PetscInt of   = 0;
5312:           const PetscInt oeb  = of + PetscSqr(k - 1);
5313:           const PetscInt oer  = oeb + (k - 1);
5314:           const PetscInt oet  = oer + (k - 1);
5315:           const PetscInt oel  = oet + (k - 1);
5316:           const PetscInt ovlb = oel + (k - 1);
5317:           const PetscInt ovrb = ovlb + 1;
5318:           const PetscInt ovrt = ovrb + 1;
5319:           const PetscInt ovlt = ovrt + 1;
5320:           PetscInt       o;

5322:           /* bottom */
5323:           for (c = 0; c < Nc; ++c, ++offset) perm[offset] = ovlb * Nc + c + foffset;
5324:           for (o = oeb; o < oer; ++o)
5325:             for (c = 0; c < Nc; ++c, ++offset) perm[offset] = o * Nc + c + foffset;
5326:           for (c = 0; c < Nc; ++c, ++offset) perm[offset] = ovrb * Nc + c + foffset;
5327:           /* middle */
5328:           for (i = 0; i < k - 1; ++i) {
5329:             for (c = 0; c < Nc; ++c, ++offset) perm[offset] = (oel + (k - 2) - i) * Nc + c + foffset;
5330:             for (o = of + (k - 1) * i; o < of + (k - 1) * (i + 1); ++o)
5331:               for (c = 0; c < Nc; ++c, ++offset) perm[offset] = o * Nc + c + foffset;
5332:             for (c = 0; c < Nc; ++c, ++offset) perm[offset] = (oer + i) * Nc + c + foffset;
5333:           }
5334:           /* top */
5335:           for (c = 0; c < Nc; ++c, ++offset) perm[offset] = ovlt * Nc + c + foffset;
5336:           for (o = oel - 1; o >= oet; --o)
5337:             for (c = 0; c < Nc; ++c, ++offset) perm[offset] = o * Nc + c + foffset;
5338:           for (c = 0; c < Nc; ++c, ++offset) perm[offset] = ovrt * Nc + c + foffset;
5339:           foffset = offset;
5340:         }
5341:         break;
5342:       case 3:
5343:         /* The original hex closure is

5345:          {c,
5346:          f_b, f_t, f_f, f_b, f_r, f_l,
5347:          e_bl, e_bb, e_br, e_bf,  e_tf, e_tr, e_tb, e_tl,  e_rf, e_lf, e_lb, e_rb,
5348:          v_blf, v_blb, v_brb, v_brf, v_tlf, v_trf, v_trb, v_tlb}
5349:          */
5350:         PetscSectionFieldGetTensorDegree_Private(section, f, eStart, vertexchart, &Nc, &k);
5351:         /* The SEM order is
5352:          Bottom Slice
5353:          v_blf, {e^{(k-1)-n}_bf}, v_brf,
5354:          e^{i}_bl, f^{n*(k-1)+(k-1)-i}_b, e^{(k-1)-i}_br,
5355:          v_blb, {e_bb}, v_brb,

5357:          Middle Slice (j)
5358:          {e^{(k-1)-j}_lf}, {f^{j*(k-1)+n}_f}, e^j_rf,
5359:          f^{i*(k-1)+j}_l, {c^{(j*(k-1) + i)*(k-1)+n}_t}, f^{j*(k-1)+i}_r,
5360:          e^j_lb, {f^{j*(k-1)+(k-1)-n}_b}, e^{(k-1)-j}_rb,

5362:          Top Slice
5363:          v_tlf, {e_tf}, v_trf,
5364:          e^{(k-1)-i}_tl, {f^{i*(k-1)}_t}, e^{i}_tr,
5365:          v_tlb, {e^{(k-1)-n}_tb}, v_trb,
5366:          */
5367:         {
5368:           const PetscInt oc    = 0;
5369:           const PetscInt ofb   = oc + PetscSqr(k - 1) * (k - 1);
5370:           const PetscInt oft   = ofb + PetscSqr(k - 1);
5371:           const PetscInt off   = oft + PetscSqr(k - 1);
5372:           const PetscInt ofk   = off + PetscSqr(k - 1);
5373:           const PetscInt ofr   = ofk + PetscSqr(k - 1);
5374:           const PetscInt ofl   = ofr + PetscSqr(k - 1);
5375:           const PetscInt oebl  = ofl + PetscSqr(k - 1);
5376:           const PetscInt oebb  = oebl + (k - 1);
5377:           const PetscInt oebr  = oebb + (k - 1);
5378:           const PetscInt oebf  = oebr + (k - 1);
5379:           const PetscInt oetf  = oebf + (k - 1);
5380:           const PetscInt oetr  = oetf + (k - 1);
5381:           const PetscInt oetb  = oetr + (k - 1);
5382:           const PetscInt oetl  = oetb + (k - 1);
5383:           const PetscInt oerf  = oetl + (k - 1);
5384:           const PetscInt oelf  = oerf + (k - 1);
5385:           const PetscInt oelb  = oelf + (k - 1);
5386:           const PetscInt oerb  = oelb + (k - 1);
5387:           const PetscInt ovblf = oerb + (k - 1);
5388:           const PetscInt ovblb = ovblf + 1;
5389:           const PetscInt ovbrb = ovblb + 1;
5390:           const PetscInt ovbrf = ovbrb + 1;
5391:           const PetscInt ovtlf = ovbrf + 1;
5392:           const PetscInt ovtrf = ovtlf + 1;
5393:           const PetscInt ovtrb = ovtrf + 1;
5394:           const PetscInt ovtlb = ovtrb + 1;
5395:           PetscInt       o, n;

5397:           /* Bottom Slice */
5398:           /*   bottom */
5399:           for (c = 0; c < Nc; ++c, ++offset) perm[offset] = ovblf * Nc + c + foffset;
5400:           for (o = oetf - 1; o >= oebf; --o)
5401:             for (c = 0; c < Nc; ++c, ++offset) perm[offset] = o * Nc + c + foffset;
5402:           for (c = 0; c < Nc; ++c, ++offset) perm[offset] = ovbrf * Nc + c + foffset;
5403:           /*   middle */
5404:           for (i = 0; i < k - 1; ++i) {
5405:             for (c = 0; c < Nc; ++c, ++offset) perm[offset] = (oebl + i) * Nc + c + foffset;
5406:             for (n = 0; n < k - 1; ++n) {
5407:               o = ofb + n * (k - 1) + i;
5408:               for (c = 0; c < Nc; ++c, ++offset) perm[offset] = o * Nc + c + foffset;
5409:             }
5410:             for (c = 0; c < Nc; ++c, ++offset) perm[offset] = (oebr + (k - 2) - i) * Nc + c + foffset;
5411:           }
5412:           /*   top */
5413:           for (c = 0; c < Nc; ++c, ++offset) perm[offset] = ovblb * Nc + c + foffset;
5414:           for (o = oebb; o < oebr; ++o)
5415:             for (c = 0; c < Nc; ++c, ++offset) perm[offset] = o * Nc + c + foffset;
5416:           for (c = 0; c < Nc; ++c, ++offset) perm[offset] = ovbrb * Nc + c + foffset;

5418:           /* Middle Slice */
5419:           for (j = 0; j < k - 1; ++j) {
5420:             /*   bottom */
5421:             for (c = 0; c < Nc; ++c, ++offset) perm[offset] = (oelf + (k - 2) - j) * Nc + c + foffset;
5422:             for (o = off + j * (k - 1); o < off + (j + 1) * (k - 1); ++o)
5423:               for (c = 0; c < Nc; ++c, ++offset) perm[offset] = o * Nc + c + foffset;
5424:             for (c = 0; c < Nc; ++c, ++offset) perm[offset] = (oerf + j) * Nc + c + foffset;
5425:             /*   middle */
5426:             for (i = 0; i < k - 1; ++i) {
5427:               for (c = 0; c < Nc; ++c, ++offset) perm[offset] = (ofl + i * (k - 1) + j) * Nc + c + foffset;
5428:               for (n = 0; n < k - 1; ++n)
5429:                 for (c = 0; c < Nc; ++c, ++offset) perm[offset] = (oc + (j * (k - 1) + i) * (k - 1) + n) * Nc + c + foffset;
5430:               for (c = 0; c < Nc; ++c, ++offset) perm[offset] = (ofr + j * (k - 1) + i) * Nc + c + foffset;
5431:             }
5432:             /*   top */
5433:             for (c = 0; c < Nc; ++c, ++offset) perm[offset] = (oelb + j) * Nc + c + foffset;
5434:             for (o = ofk + j * (k - 1) + (k - 2); o >= ofk + j * (k - 1); --o)
5435:               for (c = 0; c < Nc; ++c, ++offset) perm[offset] = o * Nc + c + foffset;
5436:             for (c = 0; c < Nc; ++c, ++offset) perm[offset] = (oerb + (k - 2) - j) * Nc + c + foffset;
5437:           }

5439:           /* Top Slice */
5440:           /*   bottom */
5441:           for (c = 0; c < Nc; ++c, ++offset) perm[offset] = ovtlf * Nc + c + foffset;
5442:           for (o = oetf; o < oetr; ++o)
5443:             for (c = 0; c < Nc; ++c, ++offset) perm[offset] = o * Nc + c + foffset;
5444:           for (c = 0; c < Nc; ++c, ++offset) perm[offset] = ovtrf * Nc + c + foffset;
5445:           /*   middle */
5446:           for (i = 0; i < k - 1; ++i) {
5447:             for (c = 0; c < Nc; ++c, ++offset) perm[offset] = (oetl + (k - 2) - i) * Nc + c + foffset;
5448:             for (n = 0; n < k - 1; ++n)
5449:               for (c = 0; c < Nc; ++c, ++offset) perm[offset] = (oft + i * (k - 1) + n) * Nc + c + foffset;
5450:             for (c = 0; c < Nc; ++c, ++offset) perm[offset] = (oetr + i) * Nc + c + foffset;
5451:           }
5452:           /*   top */
5453:           for (c = 0; c < Nc; ++c, ++offset) perm[offset] = ovtlb * Nc + c + foffset;
5454:           for (o = oetl - 1; o >= oetb; --o)
5455:             for (c = 0; c < Nc; ++c, ++offset) perm[offset] = o * Nc + c + foffset;
5456:           for (c = 0; c < Nc; ++c, ++offset) perm[offset] = ovtrb * Nc + c + foffset;

5458:           foffset = offset;
5459:         }
5460:         break;
5461:       default:
5462:         SETERRQ(PetscObjectComm((PetscObject)dm), PETSC_ERR_ARG_OUTOFRANGE, "No spectral ordering for dimension %" PetscInt_FMT, d);
5463:       }
5464:     }
5466:     /* Check permutation */
5467:     {
5468:       PetscInt *check;

5470:       PetscMalloc1(size, &check);
5471:       for (i = 0; i < size; ++i) {
5472:         check[i] = -1;
5474:       }
5475:       for (i = 0; i < size; ++i) check[perm[i]] = i;
5477:       PetscFree(check);
5478:     }
5479:     PetscSectionSetClosurePermutation_Internal(section, (PetscObject)dm, d, size, PETSC_OWN_POINTER, perm);
5480:     if (d == dim) { // Add permutation for localized (in case this is a coordinate DM)
5481:       PetscInt *loc_perm;
5482:       PetscMalloc1(size * 2, &loc_perm);
5483:       for (PetscInt i = 0; i < size; i++) {
5484:         loc_perm[i]        = perm[i];
5485:         loc_perm[size + i] = size + perm[i];
5486:       }
5487:       PetscSectionSetClosurePermutation_Internal(section, (PetscObject)dm, d, size * 2, PETSC_OWN_POINTER, loc_perm);
5488:     }
5489:   }
5490:   return 0;
5491: }

5493: PetscErrorCode DMPlexGetPointDualSpaceFEM(DM dm, PetscInt point, PetscInt field, PetscDualSpace *dspace)
5494: {
5495:   PetscDS  prob;
5496:   PetscInt depth, Nf, h;
5497:   DMLabel  label;

5500:   DMGetDS(dm, &prob);
5501:   Nf      = prob->Nf;
5502:   label   = dm->depthLabel;
5503:   *dspace = NULL;
5504:   if (field < Nf) {
5505:     PetscObject disc = prob->disc[field];

5507:     if (disc->classid == PETSCFE_CLASSID) {
5508:       PetscDualSpace dsp;

5510:       PetscFEGetDualSpace((PetscFE)disc, &dsp);
5511:       DMLabelGetNumValues(label, &depth);
5512:       DMLabelGetValue(label, point, &h);
5513:       h = depth - 1 - h;
5514:       if (h) {
5515:         PetscDualSpaceGetHeightSubspace(dsp, h, dspace);
5516:       } else {
5517:         *dspace = dsp;
5518:       }
5519:     }
5520:   }
5521:   return 0;
5522: }

5524: static inline PetscErrorCode DMPlexVecGetClosure_Depth1_Static(DM dm, PetscSection section, Vec v, PetscInt point, PetscInt *csize, PetscScalar *values[])
5525: {
5526:   PetscScalar       *array;
5527:   const PetscScalar *vArray;
5528:   const PetscInt    *cone, *coneO;
5529:   PetscInt           pStart, pEnd, p, numPoints, size = 0, offset = 0;

5532:   PetscSectionGetChart(section, &pStart, &pEnd);
5533:   DMPlexGetConeSize(dm, point, &numPoints);
5534:   DMPlexGetCone(dm, point, &cone);
5535:   DMPlexGetConeOrientation(dm, point, &coneO);
5536:   if (!values || !*values) {
5537:     if ((point >= pStart) && (point < pEnd)) {
5538:       PetscInt dof;

5540:       PetscSectionGetDof(section, point, &dof);
5541:       size += dof;
5542:     }
5543:     for (p = 0; p < numPoints; ++p) {
5544:       const PetscInt cp = cone[p];
5545:       PetscInt       dof;

5547:       if ((cp < pStart) || (cp >= pEnd)) continue;
5548:       PetscSectionGetDof(section, cp, &dof);
5549:       size += dof;
5550:     }
5551:     if (!values) {
5552:       if (csize) *csize = size;
5553:       return 0;
5554:     }
5555:     DMGetWorkArray(dm, size, MPIU_SCALAR, &array);
5556:   } else {
5557:     array = *values;
5558:   }
5559:   size = 0;
5560:   VecGetArrayRead(v, &vArray);
5561:   if ((point >= pStart) && (point < pEnd)) {
5562:     PetscInt           dof, off, d;
5563:     const PetscScalar *varr;

5565:     PetscSectionGetDof(section, point, &dof);
5566:     PetscSectionGetOffset(section, point, &off);
5567:     varr = &vArray[off];
5568:     for (d = 0; d < dof; ++d, ++offset) array[offset] = varr[d];
5569:     size += dof;
5570:   }
5571:   for (p = 0; p < numPoints; ++p) {
5572:     const PetscInt     cp = cone[p];
5573:     PetscInt           o  = coneO[p];
5574:     PetscInt           dof, off, d;
5575:     const PetscScalar *varr;

5577:     if ((cp < pStart) || (cp >= pEnd)) continue;
5578:     PetscSectionGetDof(section, cp, &dof);
5579:     PetscSectionGetOffset(section, cp, &off);
5580:     varr = &vArray[off];
5581:     if (o >= 0) {
5582:       for (d = 0; d < dof; ++d, ++offset) array[offset] = varr[d];
5583:     } else {
5584:       for (d = dof - 1; d >= 0; --d, ++offset) array[offset] = varr[d];
5585:     }
5586:     size += dof;
5587:   }
5588:   VecRestoreArrayRead(v, &vArray);
5589:   if (!*values) {
5590:     if (csize) *csize = size;
5591:     *values = array;
5592:   } else {
5594:     *csize = size;
5595:   }
5596:   return 0;
5597: }

5599: /* Compress out points not in the section */
5600: static inline PetscErrorCode CompressPoints_Private(PetscSection section, PetscInt *numPoints, PetscInt points[])
5601: {
5602:   const PetscInt np = *numPoints;
5603:   PetscInt       pStart, pEnd, p, q;

5605:   PetscSectionGetChart(section, &pStart, &pEnd);
5606:   for (p = 0, q = 0; p < np; ++p) {
5607:     const PetscInt r = points[p * 2];
5608:     if ((r >= pStart) && (r < pEnd)) {
5609:       points[q * 2]     = r;
5610:       points[q * 2 + 1] = points[p * 2 + 1];
5611:       ++q;
5612:     }
5613:   }
5614:   *numPoints = q;
5615:   return 0;
5616: }

5618: /* Compressed closure does not apply closure permutation */
5619: PetscErrorCode DMPlexGetCompressedClosure(DM dm, PetscSection section, PetscInt point, PetscInt *numPoints, PetscInt **points, PetscSection *clSec, IS *clPoints, const PetscInt **clp)
5620: {
5621:   const PetscInt *cla = NULL;
5622:   PetscInt        np, *pts = NULL;

5625:   PetscSectionGetClosureIndex(section, (PetscObject)dm, clSec, clPoints);
5626:   if (*clPoints) {
5627:     PetscInt dof, off;

5629:     PetscSectionGetDof(*clSec, point, &dof);
5630:     PetscSectionGetOffset(*clSec, point, &off);
5631:     ISGetIndices(*clPoints, &cla);
5632:     np  = dof / 2;
5633:     pts = (PetscInt *)&cla[off];
5634:   } else {
5635:     DMPlexGetTransitiveClosure(dm, point, PETSC_TRUE, &np, &pts);
5636:     CompressPoints_Private(section, &np, pts);
5637:   }
5638:   *numPoints = np;
5639:   *points    = pts;
5640:   *clp       = cla;
5641:   return 0;
5642: }

5644: PetscErrorCode DMPlexRestoreCompressedClosure(DM dm, PetscSection section, PetscInt point, PetscInt *numPoints, PetscInt **points, PetscSection *clSec, IS *clPoints, const PetscInt **clp)
5645: {
5647:   if (!*clPoints) {
5648:     DMPlexRestoreTransitiveClosure(dm, point, PETSC_TRUE, numPoints, points);
5649:   } else {
5650:     ISRestoreIndices(*clPoints, clp);
5651:   }
5652:   *numPoints = 0;
5653:   *points    = NULL;
5654:   *clSec     = NULL;
5655:   *clPoints  = NULL;
5656:   *clp       = NULL;
5657:   return 0;
5658: }

5660: static inline PetscErrorCode DMPlexVecGetClosure_Static(DM dm, PetscSection section, PetscInt numPoints, const PetscInt points[], const PetscInt clperm[], const PetscScalar vArray[], PetscInt *size, PetscScalar array[])
5661: {
5662:   PetscInt            offset = 0, p;
5663:   const PetscInt    **perms  = NULL;
5664:   const PetscScalar **flips  = NULL;

5667:   *size = 0;
5668:   PetscSectionGetPointSyms(section, numPoints, points, &perms, &flips);
5669:   for (p = 0; p < numPoints; p++) {
5670:     const PetscInt     point = points[2 * p];
5671:     const PetscInt    *perm  = perms ? perms[p] : NULL;
5672:     const PetscScalar *flip  = flips ? flips[p] : NULL;
5673:     PetscInt           dof, off, d;
5674:     const PetscScalar *varr;

5676:     PetscSectionGetDof(section, point, &dof);
5677:     PetscSectionGetOffset(section, point, &off);
5678:     varr = &vArray[off];
5679:     if (clperm) {
5680:       if (perm) {
5681:         for (d = 0; d < dof; d++) array[clperm[offset + perm[d]]] = varr[d];
5682:       } else {
5683:         for (d = 0; d < dof; d++) array[clperm[offset + d]] = varr[d];
5684:       }
5685:       if (flip) {
5686:         for (d = 0; d < dof; d++) array[clperm[offset + d]] *= flip[d];
5687:       }
5688:     } else {
5689:       if (perm) {
5690:         for (d = 0; d < dof; d++) array[offset + perm[d]] = varr[d];
5691:       } else {
5692:         for (d = 0; d < dof; d++) array[offset + d] = varr[d];
5693:       }
5694:       if (flip) {
5695:         for (d = 0; d < dof; d++) array[offset + d] *= flip[d];
5696:       }
5697:     }
5698:     offset += dof;
5699:   }
5700:   PetscSectionRestorePointSyms(section, numPoints, points, &perms, &flips);
5701:   *size = offset;
5702:   return 0;
5703: }

5705: static inline PetscErrorCode DMPlexVecGetClosure_Fields_Static(DM dm, PetscSection section, PetscInt numPoints, const PetscInt points[], PetscInt numFields, const PetscInt clperm[], const PetscScalar vArray[], PetscInt *size, PetscScalar array[])
5706: {
5707:   PetscInt offset = 0, f;

5710:   *size = 0;
5711:   for (f = 0; f < numFields; ++f) {
5712:     PetscInt            p;
5713:     const PetscInt    **perms = NULL;
5714:     const PetscScalar **flips = NULL;

5716:     PetscSectionGetFieldPointSyms(section, f, numPoints, points, &perms, &flips);
5717:     for (p = 0; p < numPoints; p++) {
5718:       const PetscInt     point = points[2 * p];
5719:       PetscInt           fdof, foff, b;
5720:       const PetscScalar *varr;
5721:       const PetscInt    *perm = perms ? perms[p] : NULL;
5722:       const PetscScalar *flip = flips ? flips[p] : NULL;

5724:       PetscSectionGetFieldDof(section, point, f, &fdof);
5725:       PetscSectionGetFieldOffset(section, point, f, &foff);
5726:       varr = &vArray[foff];
5727:       if (clperm) {
5728:         if (perm) {
5729:           for (b = 0; b < fdof; b++) array[clperm[offset + perm[b]]] = varr[b];
5730:         } else {
5731:           for (b = 0; b < fdof; b++) array[clperm[offset + b]] = varr[b];
5732:         }
5733:         if (flip) {
5734:           for (b = 0; b < fdof; b++) array[clperm[offset + b]] *= flip[b];
5735:         }
5736:       } else {
5737:         if (perm) {
5738:           for (b = 0; b < fdof; b++) array[offset + perm[b]] = varr[b];
5739:         } else {
5740:           for (b = 0; b < fdof; b++) array[offset + b] = varr[b];
5741:         }
5742:         if (flip) {
5743:           for (b = 0; b < fdof; b++) array[offset + b] *= flip[b];
5744:         }
5745:       }
5746:       offset += fdof;
5747:     }
5748:     PetscSectionRestoreFieldPointSyms(section, f, numPoints, points, &perms, &flips);
5749:   }
5750:   *size = offset;
5751:   return 0;
5752: }

5754: /*@C
5755:   DMPlexVecGetClosure - Get an array of the values on the closure of 'point'

5757:   Not collective

5759:   Input Parameters:
5760: + dm - The DM
5761: . section - The section describing the layout in v, or NULL to use the default section
5762: . v - The local vector
5763: - point - The point in the DM

5765:   Input/Output Parameters:
5766: + csize  - The size of the input values array, or NULL; on output the number of values in the closure
5767: - values - An array to use for the values, or NULL to have it allocated automatically;
5768:            if the user provided NULL, it is a borrowed array and should not be freed

5770: $ Note that DMPlexVecGetClosure/DMPlexVecRestoreClosure only allocates the values array if it set to NULL in the
5771: $ calling function. This is because DMPlexVecGetClosure() is typically called in the inner loop of a Vec or Mat
5772: $ assembly function, and a user may already have allocated storage for this operation.
5773: $
5774: $ A typical use could be
5775: $
5776: $  values = NULL;
5777: $  DMPlexVecGetClosure(dm, NULL, v, p, &clSize, &values);
5778: $  for (cl = 0; cl < clSize; ++cl) {
5779: $    <Compute on closure>
5780: $  }
5781: $  DMPlexVecRestoreClosure(dm, NULL, v, p, &clSize, &values);
5782: $
5783: $ or
5784: $
5785: $  PetscMalloc1(clMaxSize, &values);
5786: $  for (p = pStart; p < pEnd; ++p) {
5787: $    clSize = clMaxSize;
5788: $    DMPlexVecGetClosure(dm, NULL, v, p, &clSize, &values);
5789: $    for (cl = 0; cl < clSize; ++cl) {
5790: $      <Compute on closure>
5791: $    }
5792: $  }
5793: $  PetscFree(values);

5795:   Fortran Notes:
5796:   Since it returns an array, this routine is only available in Fortran 90, and you must
5797:   include petsc.h90 in your code.

5799:   The csize argument is not present in the Fortran 90 binding since it is internal to the array.

5801:   Level: intermediate

5803: .seealso `DMPlexVecRestoreClosure()`, `DMPlexVecSetClosure()`, `DMPlexMatSetClosure()`
5804: @*/
5805: PetscErrorCode DMPlexVecGetClosure(DM dm, PetscSection section, Vec v, PetscInt point, PetscInt *csize, PetscScalar *values[])
5806: {
5807:   PetscSection    clSection;
5808:   IS              clPoints;
5809:   PetscInt       *points = NULL;
5810:   const PetscInt *clp, *perm;
5811:   PetscInt        depth, numFields, numPoints, asize;

5815:   if (!section) DMGetLocalSection(dm, &section);
5818:   DMPlexGetDepth(dm, &depth);
5819:   PetscSectionGetNumFields(section, &numFields);
5820:   if (depth == 1 && numFields < 2) {
5821:     DMPlexVecGetClosure_Depth1_Static(dm, section, v, point, csize, values);
5822:     return 0;
5823:   }
5824:   /* Get points */
5825:   DMPlexGetCompressedClosure(dm, section, point, &numPoints, &points, &clSection, &clPoints, &clp);
5826:   /* Get sizes */
5827:   asize = 0;
5828:   for (PetscInt p = 0; p < numPoints * 2; p += 2) {
5829:     PetscInt dof;
5830:     PetscSectionGetDof(section, points[p], &dof);
5831:     asize += dof;
5832:   }
5833:   if (values) {
5834:     const PetscScalar *vArray;
5835:     PetscInt           size;

5837:     if (*values) {
5839:     } else DMGetWorkArray(dm, asize, MPIU_SCALAR, values);
5840:     PetscSectionGetClosureInversePermutation_Internal(section, (PetscObject)dm, depth, asize, &perm);
5841:     VecGetArrayRead(v, &vArray);
5842:     /* Get values */
5843:     if (numFields > 0) DMPlexVecGetClosure_Fields_Static(dm, section, numPoints, points, numFields, perm, vArray, &size, *values);
5844:     else DMPlexVecGetClosure_Static(dm, section, numPoints, points, perm, vArray, &size, *values);
5846:     /* Cleanup array */
5847:     VecRestoreArrayRead(v, &vArray);
5848:   }
5849:   if (csize) *csize = asize;
5850:   /* Cleanup points */
5851:   DMPlexRestoreCompressedClosure(dm, section, point, &numPoints, &points, &clSection, &clPoints, &clp);
5852:   return 0;
5853: }

5855: PetscErrorCode DMPlexVecGetClosureAtDepth_Internal(DM dm, PetscSection section, Vec v, PetscInt point, PetscInt depth, PetscInt *csize, PetscScalar *values[])
5856: {
5857:   DMLabel            depthLabel;
5858:   PetscSection       clSection;
5859:   IS                 clPoints;
5860:   PetscScalar       *array;
5861:   const PetscScalar *vArray;
5862:   PetscInt          *points = NULL;
5863:   const PetscInt    *clp, *perm = NULL;
5864:   PetscInt           mdepth, numFields, numPoints, Np = 0, p, clsize, size;

5868:   if (!section) DMGetLocalSection(dm, &section);
5871:   DMPlexGetDepth(dm, &mdepth);
5872:   DMPlexGetDepthLabel(dm, &depthLabel);
5873:   PetscSectionGetNumFields(section, &numFields);
5874:   if (mdepth == 1 && numFields < 2) {
5875:     DMPlexVecGetClosure_Depth1_Static(dm, section, v, point, csize, values);
5876:     return 0;
5877:   }
5878:   /* Get points */
5879:   DMPlexGetCompressedClosure(dm, section, point, &numPoints, &points, &clSection, &clPoints, &clp);
5880:   for (clsize = 0, p = 0; p < Np; p++) {
5881:     PetscInt dof;
5882:     PetscSectionGetDof(section, points[2 * p], &dof);
5883:     clsize += dof;
5884:   }
5885:   PetscSectionGetClosureInversePermutation_Internal(section, (PetscObject)dm, depth, clsize, &perm);
5886:   /* Filter points */
5887:   for (p = 0; p < numPoints * 2; p += 2) {
5888:     PetscInt dep;

5890:     DMLabelGetValue(depthLabel, points[p], &dep);
5891:     if (dep != depth) continue;
5892:     points[Np * 2 + 0] = points[p];
5893:     points[Np * 2 + 1] = points[p + 1];
5894:     ++Np;
5895:   }
5896:   /* Get array */
5897:   if (!values || !*values) {
5898:     PetscInt asize = 0, dof;

5900:     for (p = 0; p < Np * 2; p += 2) {
5901:       PetscSectionGetDof(section, points[p], &dof);
5902:       asize += dof;
5903:     }
5904:     if (!values) {
5905:       DMPlexRestoreCompressedClosure(dm, section, point, &numPoints, &points, &clSection, &clPoints, &clp);
5906:       if (csize) *csize = asize;
5907:       return 0;
5908:     }
5909:     DMGetWorkArray(dm, asize, MPIU_SCALAR, &array);
5910:   } else {
5911:     array = *values;
5912:   }
5913:   VecGetArrayRead(v, &vArray);
5914:   /* Get values */
5915:   if (numFields > 0) DMPlexVecGetClosure_Fields_Static(dm, section, Np, points, numFields, perm, vArray, &size, array);
5916:   else DMPlexVecGetClosure_Static(dm, section, Np, points, perm, vArray, &size, array);
5917:   /* Cleanup points */
5918:   DMPlexRestoreCompressedClosure(dm, section, point, &numPoints, &points, &clSection, &clPoints, &clp);
5919:   /* Cleanup array */
5920:   VecRestoreArrayRead(v, &vArray);
5921:   if (!*values) {
5922:     if (csize) *csize = size;
5923:     *values = array;
5924:   } else {
5926:     *csize = size;
5927:   }
5928:   return 0;
5929: }

5931: /*@C
5932:   DMPlexVecRestoreClosure - Restore the array of the values on the closure of 'point'

5934:   Not collective

5936:   Input Parameters:
5937: + dm - The DM
5938: . section - The section describing the layout in v, or NULL to use the default section
5939: . v - The local vector
5940: . point - The point in the DM
5941: . csize - The number of values in the closure, or NULL
5942: - values - The array of values, which is a borrowed array and should not be freed

5944:   Note that the array values are discarded and not copied back into v. In order to copy values back to v, use DMPlexVecSetClosure()

5946:   Fortran Notes:
5947:   Since it returns an array, this routine is only available in Fortran 90, and you must
5948:   include petsc.h90 in your code.

5950:   The csize argument is not present in the Fortran 90 binding since it is internal to the array.

5952:   Level: intermediate

5954: .seealso `DMPlexVecGetClosure()`, `DMPlexVecSetClosure()`, `DMPlexMatSetClosure()`
5955: @*/
5956: PetscErrorCode DMPlexVecRestoreClosure(DM dm, PetscSection section, Vec v, PetscInt point, PetscInt *csize, PetscScalar *values[])
5957: {
5958:   PetscInt size = 0;

5960:   /* Should work without recalculating size */
5961:   DMRestoreWorkArray(dm, size, MPIU_SCALAR, (void *)values);
5962:   *values = NULL;
5963:   return 0;
5964: }

5966: static inline void add(PetscScalar *x, PetscScalar y)
5967: {
5968:   *x += y;
5969: }
5970: static inline void insert(PetscScalar *x, PetscScalar y)
5971: {
5972:   *x = y;
5973: }

5975: static inline PetscErrorCode updatePoint_private(PetscSection section, PetscInt point, PetscInt dof, void (*fuse)(PetscScalar *, PetscScalar), PetscBool setBC, const PetscInt perm[], const PetscScalar flip[], const PetscInt clperm[], const PetscScalar values[], PetscInt offset, PetscScalar array[])
5976: {
5977:   PetscInt        cdof;  /* The number of constraints on this point */
5978:   const PetscInt *cdofs; /* The indices of the constrained dofs on this point */
5979:   PetscScalar    *a;
5980:   PetscInt        off, cind = 0, k;

5982:   PetscSectionGetConstraintDof(section, point, &cdof);
5983:   PetscSectionGetOffset(section, point, &off);
5984:   a = &array[off];
5985:   if (!cdof || setBC) {
5986:     if (clperm) {
5987:       if (perm) {
5988:         for (k = 0; k < dof; ++k) fuse(&a[k], values[clperm[offset + perm[k]]] * (flip ? flip[perm[k]] : 1.));
5989:       } else {
5990:         for (k = 0; k < dof; ++k) fuse(&a[k], values[clperm[offset + k]] * (flip ? flip[k] : 1.));
5991:       }
5992:     } else {
5993:       if (perm) {
5994:         for (k = 0; k < dof; ++k) fuse(&a[k], values[offset + perm[k]] * (flip ? flip[perm[k]] : 1.));
5995:       } else {
5996:         for (k = 0; k < dof; ++k) fuse(&a[k], values[offset + k] * (flip ? flip[k] : 1.));
5997:       }
5998:     }
5999:   } else {
6000:     PetscSectionGetConstraintIndices(section, point, &cdofs);
6001:     if (clperm) {
6002:       if (perm) {
6003:         for (k = 0; k < dof; ++k) {
6004:           if ((cind < cdof) && (k == cdofs[cind])) {
6005:             ++cind;
6006:             continue;
6007:           }
6008:           fuse(&a[k], values[clperm[offset + perm[k]]] * (flip ? flip[perm[k]] : 1.));
6009:         }
6010:       } else {
6011:         for (k = 0; k < dof; ++k) {
6012:           if ((cind < cdof) && (k == cdofs[cind])) {
6013:             ++cind;
6014:             continue;
6015:           }
6016:           fuse(&a[k], values[clperm[offset + k]] * (flip ? flip[k] : 1.));
6017:         }
6018:       }
6019:     } else {
6020:       if (perm) {
6021:         for (k = 0; k < dof; ++k) {
6022:           if ((cind < cdof) && (k == cdofs[cind])) {
6023:             ++cind;
6024:             continue;
6025:           }
6026:           fuse(&a[k], values[offset + perm[k]] * (flip ? flip[perm[k]] : 1.));
6027:         }
6028:       } else {
6029:         for (k = 0; k < dof; ++k) {
6030:           if ((cind < cdof) && (k == cdofs[cind])) {
6031:             ++cind;
6032:             continue;
6033:           }
6034:           fuse(&a[k], values[offset + k] * (flip ? flip[k] : 1.));
6035:         }
6036:       }
6037:     }
6038:   }
6039:   return 0;
6040: }

6042: static inline PetscErrorCode updatePointBC_private(PetscSection section, PetscInt point, PetscInt dof, void (*fuse)(PetscScalar *, PetscScalar), const PetscInt perm[], const PetscScalar flip[], const PetscInt clperm[], const PetscScalar values[], PetscInt offset, PetscScalar array[])
6043: {
6044:   PetscInt        cdof;  /* The number of constraints on this point */
6045:   const PetscInt *cdofs; /* The indices of the constrained dofs on this point */
6046:   PetscScalar    *a;
6047:   PetscInt        off, cind = 0, k;

6049:   PetscSectionGetConstraintDof(section, point, &cdof);
6050:   PetscSectionGetOffset(section, point, &off);
6051:   a = &array[off];
6052:   if (cdof) {
6053:     PetscSectionGetConstraintIndices(section, point, &cdofs);
6054:     if (clperm) {
6055:       if (perm) {
6056:         for (k = 0; k < dof; ++k) {
6057:           if ((cind < cdof) && (k == cdofs[cind])) {
6058:             fuse(&a[k], values[clperm[offset + perm[k]]] * (flip ? flip[perm[k]] : 1.));
6059:             cind++;
6060:           }
6061:         }
6062:       } else {
6063:         for (k = 0; k < dof; ++k) {
6064:           if ((cind < cdof) && (k == cdofs[cind])) {
6065:             fuse(&a[k], values[clperm[offset + k]] * (flip ? flip[k] : 1.));
6066:             cind++;
6067:           }
6068:         }
6069:       }
6070:     } else {
6071:       if (perm) {
6072:         for (k = 0; k < dof; ++k) {
6073:           if ((cind < cdof) && (k == cdofs[cind])) {
6074:             fuse(&a[k], values[offset + perm[k]] * (flip ? flip[perm[k]] : 1.));
6075:             cind++;
6076:           }
6077:         }
6078:       } else {
6079:         for (k = 0; k < dof; ++k) {
6080:           if ((cind < cdof) && (k == cdofs[cind])) {
6081:             fuse(&a[k], values[offset + k] * (flip ? flip[k] : 1.));
6082:             cind++;
6083:           }
6084:         }
6085:       }
6086:     }
6087:   }
6088:   return 0;
6089: }

6091: static inline PetscErrorCode updatePointFields_private(PetscSection section, PetscInt point, const PetscInt *perm, const PetscScalar *flip, PetscInt f, void (*fuse)(PetscScalar *, PetscScalar), PetscBool setBC, const PetscInt clperm[], const PetscScalar values[], PetscInt *offset, PetscScalar array[])
6092: {
6093:   PetscScalar    *a;
6094:   PetscInt        fdof, foff, fcdof, foffset = *offset;
6095:   const PetscInt *fcdofs; /* The indices of the constrained dofs for field f on this point */
6096:   PetscInt        cind = 0, b;

6098:   PetscSectionGetFieldDof(section, point, f, &fdof);
6099:   PetscSectionGetFieldConstraintDof(section, point, f, &fcdof);
6100:   PetscSectionGetFieldOffset(section, point, f, &foff);
6101:   a = &array[foff];
6102:   if (!fcdof || setBC) {
6103:     if (clperm) {
6104:       if (perm) {
6105:         for (b = 0; b < fdof; b++) fuse(&a[b], values[clperm[foffset + perm[b]]] * (flip ? flip[perm[b]] : 1.));
6106:       } else {
6107:         for (b = 0; b < fdof; b++) fuse(&a[b], values[clperm[foffset + b]] * (flip ? flip[b] : 1.));
6108:       }
6109:     } else {
6110:       if (perm) {
6111:         for (b = 0; b < fdof; b++) fuse(&a[b], values[foffset + perm[b]] * (flip ? flip[perm[b]] : 1.));
6112:       } else {
6113:         for (b = 0; b < fdof; b++) fuse(&a[b], values[foffset + b] * (flip ? flip[b] : 1.));
6114:       }
6115:     }
6116:   } else {
6117:     PetscSectionGetFieldConstraintIndices(section, point, f, &fcdofs);
6118:     if (clperm) {
6119:       if (perm) {
6120:         for (b = 0; b < fdof; b++) {
6121:           if ((cind < fcdof) && (b == fcdofs[cind])) {
6122:             ++cind;
6123:             continue;
6124:           }
6125:           fuse(&a[b], values[clperm[foffset + perm[b]]] * (flip ? flip[perm[b]] : 1.));
6126:         }
6127:       } else {
6128:         for (b = 0; b < fdof; b++) {
6129:           if ((cind < fcdof) && (b == fcdofs[cind])) {
6130:             ++cind;
6131:             continue;
6132:           }
6133:           fuse(&a[b], values[clperm[foffset + b]] * (flip ? flip[b] : 1.));
6134:         }
6135:       }
6136:     } else {
6137:       if (perm) {
6138:         for (b = 0; b < fdof; b++) {
6139:           if ((cind < fcdof) && (b == fcdofs[cind])) {
6140:             ++cind;
6141:             continue;
6142:           }
6143:           fuse(&a[b], values[foffset + perm[b]] * (flip ? flip[perm[b]] : 1.));
6144:         }
6145:       } else {
6146:         for (b = 0; b < fdof; b++) {
6147:           if ((cind < fcdof) && (b == fcdofs[cind])) {
6148:             ++cind;
6149:             continue;
6150:           }
6151:           fuse(&a[b], values[foffset + b] * (flip ? flip[b] : 1.));
6152:         }
6153:       }
6154:     }
6155:   }
6156:   *offset += fdof;
6157:   return 0;
6158: }

6160: static inline PetscErrorCode updatePointFieldsBC_private(PetscSection section, PetscInt point, const PetscInt perm[], const PetscScalar flip[], PetscInt f, PetscInt Ncc, const PetscInt comps[], void (*fuse)(PetscScalar *, PetscScalar), const PetscInt clperm[], const PetscScalar values[], PetscInt *offset, PetscScalar array[])
6161: {
6162:   PetscScalar    *a;
6163:   PetscInt        fdof, foff, fcdof, foffset = *offset;
6164:   const PetscInt *fcdofs; /* The indices of the constrained dofs for field f on this point */
6165:   PetscInt        Nc, cind = 0, ncind = 0, b;
6166:   PetscBool       ncSet, fcSet;

6168:   PetscSectionGetFieldComponents(section, f, &Nc);
6169:   PetscSectionGetFieldDof(section, point, f, &fdof);
6170:   PetscSectionGetFieldConstraintDof(section, point, f, &fcdof);
6171:   PetscSectionGetFieldOffset(section, point, f, &foff);
6172:   a = &array[foff];
6173:   if (fcdof) {
6174:     /* We just override fcdof and fcdofs with Ncc and comps */
6175:     PetscSectionGetFieldConstraintIndices(section, point, f, &fcdofs);
6176:     if (clperm) {
6177:       if (perm) {
6178:         if (comps) {
6179:           for (b = 0; b < fdof; b++) {
6180:             ncSet = fcSet = PETSC_FALSE;
6181:             if (b % Nc == comps[ncind]) {
6182:               ncind = (ncind + 1) % Ncc;
6183:               ncSet = PETSC_TRUE;
6184:             }
6185:             if ((cind < fcdof) && (b == fcdofs[cind])) {
6186:               ++cind;
6187:               fcSet = PETSC_TRUE;
6188:             }
6189:             if (ncSet && fcSet) fuse(&a[b], values[clperm[foffset + perm[b]]] * (flip ? flip[perm[b]] : 1.));
6190:           }
6191:         } else {
6192:           for (b = 0; b < fdof; b++) {
6193:             if ((cind < fcdof) && (b == fcdofs[cind])) {
6194:               fuse(&a[b], values[clperm[foffset + perm[b]]] * (flip ? flip[perm[b]] : 1.));
6195:               ++cind;
6196:             }
6197:           }
6198:         }
6199:       } else {
6200:         if (comps) {
6201:           for (b = 0; b < fdof; b++) {
6202:             ncSet = fcSet = PETSC_FALSE;
6203:             if (b % Nc == comps[ncind]) {
6204:               ncind = (ncind + 1) % Ncc;
6205:               ncSet = PETSC_TRUE;
6206:             }
6207:             if ((cind < fcdof) && (b == fcdofs[cind])) {
6208:               ++cind;
6209:               fcSet = PETSC_TRUE;
6210:             }
6211:             if (ncSet && fcSet) fuse(&a[b], values[clperm[foffset + b]] * (flip ? flip[b] : 1.));
6212:           }
6213:         } else {
6214:           for (b = 0; b < fdof; b++) {
6215:             if ((cind < fcdof) && (b == fcdofs[cind])) {
6216:               fuse(&a[b], values[clperm[foffset + b]] * (flip ? flip[b] : 1.));
6217:               ++cind;
6218:             }
6219:           }
6220:         }
6221:       }
6222:     } else {
6223:       if (perm) {
6224:         if (comps) {
6225:           for (b = 0; b < fdof; b++) {
6226:             ncSet = fcSet = PETSC_FALSE;
6227:             if (b % Nc == comps[ncind]) {
6228:               ncind = (ncind + 1) % Ncc;
6229:               ncSet = PETSC_TRUE;
6230:             }
6231:             if ((cind < fcdof) && (b == fcdofs[cind])) {
6232:               ++cind;
6233:               fcSet = PETSC_TRUE;
6234:             }
6235:             if (ncSet && fcSet) fuse(&a[b], values[foffset + perm[b]] * (flip ? flip[perm[b]] : 1.));
6236:           }
6237:         } else {
6238:           for (b = 0; b < fdof; b++) {
6239:             if ((cind < fcdof) && (b == fcdofs[cind])) {
6240:               fuse(&a[b], values[foffset + perm[b]] * (flip ? flip[perm[b]] : 1.));
6241:               ++cind;
6242:             }
6243:           }
6244:         }
6245:       } else {
6246:         if (comps) {
6247:           for (b = 0; b < fdof; b++) {
6248:             ncSet = fcSet = PETSC_FALSE;
6249:             if (b % Nc == comps[ncind]) {
6250:               ncind = (ncind + 1) % Ncc;
6251:               ncSet = PETSC_TRUE;
6252:             }
6253:             if ((cind < fcdof) && (b == fcdofs[cind])) {
6254:               ++cind;
6255:               fcSet = PETSC_TRUE;
6256:             }
6257:             if (ncSet && fcSet) fuse(&a[b], values[foffset + b] * (flip ? flip[b] : 1.));
6258:           }
6259:         } else {
6260:           for (b = 0; b < fdof; b++) {
6261:             if ((cind < fcdof) && (b == fcdofs[cind])) {
6262:               fuse(&a[b], values[foffset + b] * (flip ? flip[b] : 1.));
6263:               ++cind;
6264:             }
6265:           }
6266:         }
6267:       }
6268:     }
6269:   }
6270:   *offset += fdof;
6271:   return 0;
6272: }

6274: static inline PetscErrorCode DMPlexVecSetClosure_Depth1_Static(DM dm, PetscSection section, Vec v, PetscInt point, const PetscScalar values[], InsertMode mode)
6275: {
6276:   PetscScalar    *array;
6277:   const PetscInt *cone, *coneO;
6278:   PetscInt        pStart, pEnd, p, numPoints, off, dof;

6281:   PetscSectionGetChart(section, &pStart, &pEnd);
6282:   DMPlexGetConeSize(dm, point, &numPoints);
6283:   DMPlexGetCone(dm, point, &cone);
6284:   DMPlexGetConeOrientation(dm, point, &coneO);
6285:   VecGetArray(v, &array);
6286:   for (p = 0, off = 0; p <= numPoints; ++p, off += dof) {
6287:     const PetscInt cp = !p ? point : cone[p - 1];
6288:     const PetscInt o  = !p ? 0 : coneO[p - 1];

6290:     if ((cp < pStart) || (cp >= pEnd)) {
6291:       dof = 0;
6292:       continue;
6293:     }
6294:     PetscSectionGetDof(section, cp, &dof);
6295:     /* ADD_VALUES */
6296:     {
6297:       const PetscInt *cdofs; /* The indices of the constrained dofs on this point */
6298:       PetscScalar    *a;
6299:       PetscInt        cdof, coff, cind = 0, k;

6301:       PetscSectionGetConstraintDof(section, cp, &cdof);
6302:       PetscSectionGetOffset(section, cp, &coff);
6303:       a = &array[coff];
6304:       if (!cdof) {
6305:         if (o >= 0) {
6306:           for (k = 0; k < dof; ++k) a[k] += values[off + k];
6307:         } else {
6308:           for (k = 0; k < dof; ++k) a[k] += values[off + dof - k - 1];
6309:         }
6310:       } else {
6311:         PetscSectionGetConstraintIndices(section, cp, &cdofs);
6312:         if (o >= 0) {
6313:           for (k = 0; k < dof; ++k) {
6314:             if ((cind < cdof) && (k == cdofs[cind])) {
6315:               ++cind;
6316:               continue;
6317:             }
6318:             a[k] += values[off + k];
6319:           }
6320:         } else {
6321:           for (k = 0; k < dof; ++k) {
6322:             if ((cind < cdof) && (k == cdofs[cind])) {
6323:               ++cind;
6324:               continue;
6325:             }
6326:             a[k] += values[off + dof - k - 1];
6327:           }
6328:         }
6329:       }
6330:     }
6331:   }
6332:   VecRestoreArray(v, &array);
6333:   return 0;
6334: }

6336: /*@C
6337:   DMPlexVecSetClosure - Set an array of the values on the closure of 'point'

6339:   Not collective

6341:   Input Parameters:
6342: + dm - The DM
6343: . section - The section describing the layout in v, or NULL to use the default section
6344: . v - The local vector
6345: . point - The point in the DM
6346: . values - The array of values
6347: - mode - The insert mode. One of INSERT_ALL_VALUES, ADD_ALL_VALUES, INSERT_VALUES, ADD_VALUES, INSERT_BC_VALUES, and ADD_BC_VALUES,
6348:          where INSERT_ALL_VALUES and ADD_ALL_VALUES also overwrite boundary conditions.

6350:   Fortran Notes:
6351:   This routine is only available in Fortran 90, and you must include petsc.h90 in your code.

6353:   Level: intermediate

6355: .seealso `DMPlexVecGetClosure()`, `DMPlexMatSetClosure()`
6356: @*/
6357: PetscErrorCode DMPlexVecSetClosure(DM dm, PetscSection section, Vec v, PetscInt point, const PetscScalar values[], InsertMode mode)
6358: {
6359:   PetscSection    clSection;
6360:   IS              clPoints;
6361:   PetscScalar    *array;
6362:   PetscInt       *points = NULL;
6363:   const PetscInt *clp, *clperm = NULL;
6364:   PetscInt        depth, numFields, numPoints, p, clsize;

6368:   if (!section) DMGetLocalSection(dm, &section);
6371:   DMPlexGetDepth(dm, &depth);
6372:   PetscSectionGetNumFields(section, &numFields);
6373:   if (depth == 1 && numFields < 2 && mode == ADD_VALUES) {
6374:     DMPlexVecSetClosure_Depth1_Static(dm, section, v, point, values, mode);
6375:     return 0;
6376:   }
6377:   /* Get points */
6378:   DMPlexGetCompressedClosure(dm, section, point, &numPoints, &points, &clSection, &clPoints, &clp);
6379:   for (clsize = 0, p = 0; p < numPoints; p++) {
6380:     PetscInt dof;
6381:     PetscSectionGetDof(section, points[2 * p], &dof);
6382:     clsize += dof;
6383:   }
6384:   PetscSectionGetClosureInversePermutation_Internal(section, (PetscObject)dm, depth, clsize, &clperm);
6385:   /* Get array */
6386:   VecGetArray(v, &array);
6387:   /* Get values */
6388:   if (numFields > 0) {
6389:     PetscInt offset = 0, f;
6390:     for (f = 0; f < numFields; ++f) {
6391:       const PetscInt    **perms = NULL;
6392:       const PetscScalar **flips = NULL;

6394:       PetscSectionGetFieldPointSyms(section, f, numPoints, points, &perms, &flips);
6395:       switch (mode) {
6396:       case INSERT_VALUES:
6397:         for (p = 0; p < numPoints; p++) {
6398:           const PetscInt     point = points[2 * p];
6399:           const PetscInt    *perm  = perms ? perms[p] : NULL;
6400:           const PetscScalar *flip  = flips ? flips[p] : NULL;
6401:           updatePointFields_private(section, point, perm, flip, f, insert, PETSC_FALSE, clperm, values, &offset, array);
6402:         }
6403:         break;
6404:       case INSERT_ALL_VALUES:
6405:         for (p = 0; p < numPoints; p++) {
6406:           const PetscInt     point = points[2 * p];
6407:           const PetscInt    *perm  = perms ? perms[p] : NULL;
6408:           const PetscScalar *flip  = flips ? flips[p] : NULL;
6409:           updatePointFields_private(section, point, perm, flip, f, insert, PETSC_TRUE, clperm, values, &offset, array);
6410:         }
6411:         break;
6412:       case INSERT_BC_VALUES:
6413:         for (p = 0; p < numPoints; p++) {
6414:           const PetscInt     point = points[2 * p];
6415:           const PetscInt    *perm  = perms ? perms[p] : NULL;
6416:           const PetscScalar *flip  = flips ? flips[p] : NULL;
6417:           updatePointFieldsBC_private(section, point, perm, flip, f, -1, NULL, insert, clperm, values, &offset, array);
6418:         }
6419:         break;
6420:       case ADD_VALUES:
6421:         for (p = 0; p < numPoints; p++) {
6422:           const PetscInt     point = points[2 * p];
6423:           const PetscInt    *perm  = perms ? perms[p] : NULL;
6424:           const PetscScalar *flip  = flips ? flips[p] : NULL;
6425:           updatePointFields_private(section, point, perm, flip, f, add, PETSC_FALSE, clperm, values, &offset, array);
6426:         }
6427:         break;
6428:       case ADD_ALL_VALUES:
6429:         for (p = 0; p < numPoints; p++) {
6430:           const PetscInt     point = points[2 * p];
6431:           const PetscInt    *perm  = perms ? perms[p] : NULL;
6432:           const PetscScalar *flip  = flips ? flips[p] : NULL;
6433:           updatePointFields_private(section, point, perm, flip, f, add, PETSC_TRUE, clperm, values, &offset, array);
6434:         }
6435:         break;
6436:       case ADD_BC_VALUES:
6437:         for (p = 0; p < numPoints; p++) {
6438:           const PetscInt     point = points[2 * p];
6439:           const PetscInt    *perm  = perms ? perms[p] : NULL;
6440:           const PetscScalar *flip  = flips ? flips[p] : NULL;
6441:           updatePointFieldsBC_private(section, point, perm, flip, f, -1, NULL, add, clperm, values, &offset, array);
6442:         }
6443:         break;
6444:       default:
6445:         SETERRQ(PetscObjectComm((PetscObject)dm), PETSC_ERR_ARG_OUTOFRANGE, "Invalid insert mode %d", mode);
6446:       }
6447:       PetscSectionRestoreFieldPointSyms(section, f, numPoints, points, &perms, &flips);
6448:     }
6449:   } else {
6450:     PetscInt            dof, off;
6451:     const PetscInt    **perms = NULL;
6452:     const PetscScalar **flips = NULL;

6454:     PetscSectionGetPointSyms(section, numPoints, points, &perms, &flips);
6455:     switch (mode) {
6456:     case INSERT_VALUES:
6457:       for (p = 0, off = 0; p < numPoints; p++, off += dof) {
6458:         const PetscInt     point = points[2 * p];
6459:         const PetscInt    *perm  = perms ? perms[p] : NULL;
6460:         const PetscScalar *flip  = flips ? flips[p] : NULL;
6461:         PetscSectionGetDof(section, point, &dof);
6462:         updatePoint_private(section, point, dof, insert, PETSC_FALSE, perm, flip, clperm, values, off, array);
6463:       }
6464:       break;
6465:     case INSERT_ALL_VALUES:
6466:       for (p = 0, off = 0; p < numPoints; p++, off += dof) {
6467:         const PetscInt     point = points[2 * p];
6468:         const PetscInt    *perm  = perms ? perms[p] : NULL;
6469:         const PetscScalar *flip  = flips ? flips[p] : NULL;
6470:         PetscSectionGetDof(section, point, &dof);
6471:         updatePoint_private(section, point, dof, insert, PETSC_TRUE, perm, flip, clperm, values, off, array);
6472:       }
6473:       break;
6474:     case INSERT_BC_VALUES:
6475:       for (p = 0, off = 0; p < numPoints; p++, off += dof) {
6476:         const PetscInt     point = points[2 * p];
6477:         const PetscInt    *perm  = perms ? perms[p] : NULL;
6478:         const PetscScalar *flip  = flips ? flips[p] : NULL;
6479:         PetscSectionGetDof(section, point, &dof);
6480:         updatePointBC_private(section, point, dof, insert, perm, flip, clperm, values, off, array);
6481:       }
6482:       break;
6483:     case ADD_VALUES:
6484:       for (p = 0, off = 0; p < numPoints; p++, off += dof) {
6485:         const PetscInt     point = points[2 * p];
6486:         const PetscInt    *perm  = perms ? perms[p] : NULL;
6487:         const PetscScalar *flip  = flips ? flips[p] : NULL;
6488:         PetscSectionGetDof(section, point, &dof);
6489:         updatePoint_private(section, point, dof, add, PETSC_FALSE, perm, flip, clperm, values, off, array);
6490:       }
6491:       break;
6492:     case ADD_ALL_VALUES:
6493:       for (p = 0, off = 0; p < numPoints; p++, off += dof) {
6494:         const PetscInt     point = points[2 * p];
6495:         const PetscInt    *perm  = perms ? perms[p] : NULL;
6496:         const PetscScalar *flip  = flips ? flips[p] : NULL;
6497:         PetscSectionGetDof(section, point, &dof);
6498:         updatePoint_private(section, point, dof, add, PETSC_TRUE, perm, flip, clperm, values, off, array);
6499:       }
6500:       break;
6501:     case ADD_BC_VALUES:
6502:       for (p = 0, off = 0; p < numPoints; p++, off += dof) {
6503:         const PetscInt     point = points[2 * p];
6504:         const PetscInt    *perm  = perms ? perms[p] : NULL;
6505:         const PetscScalar *flip  = flips ? flips[p] : NULL;
6506:         PetscSectionGetDof(section, point, &dof);
6507:         updatePointBC_private(section, point, dof, add, perm, flip, clperm, values, off, array);
6508:       }
6509:       break;
6510:     default:
6511:       SETERRQ(PetscObjectComm((PetscObject)dm), PETSC_ERR_ARG_OUTOFRANGE, "Invalid insert mode %d", mode);
6512:     }
6513:     PetscSectionRestorePointSyms(section, numPoints, points, &perms, &flips);
6514:   }
6515:   /* Cleanup points */
6516:   DMPlexRestoreCompressedClosure(dm, section, point, &numPoints, &points, &clSection, &clPoints, &clp);
6517:   /* Cleanup array */
6518:   VecRestoreArray(v, &array);
6519:   return 0;
6520: }

6522: /* Check whether the given point is in the label. If not, update the offset to skip this point */
6523: static inline PetscErrorCode CheckPoint_Private(DMLabel label, PetscInt labelId, PetscSection section, PetscInt point, PetscInt f, PetscInt *offset, PetscBool *contains)
6524: {
6525:   *contains = PETSC_TRUE;
6526:   if (label) {
6527:     PetscInt fdof;

6529:     DMLabelStratumHasPoint(label, labelId, point, contains);
6530:     if (!*contains) {
6531:       PetscSectionGetFieldDof(section, point, f, &fdof);
6532:       *offset += fdof;
6533:       return 0;
6534:     }
6535:   }
6536:   return 0;
6537: }

6539: /* Unlike DMPlexVecSetClosure(), this uses plex-native closure permutation, not a user-specified permutation such as DMPlexSetClosurePermutationTensor(). */
6540: PetscErrorCode DMPlexVecSetFieldClosure_Internal(DM dm, PetscSection section, Vec v, PetscBool fieldActive[], PetscInt point, PetscInt Ncc, const PetscInt comps[], DMLabel label, PetscInt labelId, const PetscScalar values[], InsertMode mode)
6541: {
6542:   PetscSection    clSection;
6543:   IS              clPoints;
6544:   PetscScalar    *array;
6545:   PetscInt       *points = NULL;
6546:   const PetscInt *clp;
6547:   PetscInt        numFields, numPoints, p;
6548:   PetscInt        offset = 0, f;

6552:   if (!section) DMGetLocalSection(dm, &section);
6555:   PetscSectionGetNumFields(section, &numFields);
6556:   /* Get points */
6557:   DMPlexGetCompressedClosure(dm, section, point, &numPoints, &points, &clSection, &clPoints, &clp);
6558:   /* Get array */
6559:   VecGetArray(v, &array);
6560:   /* Get values */
6561:   for (f = 0; f < numFields; ++f) {
6562:     const PetscInt    **perms = NULL;
6563:     const PetscScalar **flips = NULL;
6564:     PetscBool           contains;

6566:     if (!fieldActive[f]) {
6567:       for (p = 0; p < numPoints * 2; p += 2) {
6568:         PetscInt fdof;
6569:         PetscSectionGetFieldDof(section, points[p], f, &fdof);
6570:         offset += fdof;
6571:       }
6572:       continue;
6573:     }
6574:     PetscSectionGetFieldPointSyms(section, f, numPoints, points, &perms, &flips);
6575:     switch (mode) {
6576:     case INSERT_VALUES:
6577:       for (p = 0; p < numPoints; p++) {
6578:         const PetscInt     point = points[2 * p];
6579:         const PetscInt    *perm  = perms ? perms[p] : NULL;
6580:         const PetscScalar *flip  = flips ? flips[p] : NULL;
6581:         CheckPoint_Private(label, labelId, section, point, f, &offset, &contains);
6582:         if (!contains) continue;
6583:         updatePointFields_private(section, point, perm, flip, f, insert, PETSC_FALSE, NULL, values, &offset, array);
6584:       }
6585:       break;
6586:     case INSERT_ALL_VALUES:
6587:       for (p = 0; p < numPoints; p++) {
6588:         const PetscInt     point = points[2 * p];
6589:         const PetscInt    *perm  = perms ? perms[p] : NULL;
6590:         const PetscScalar *flip  = flips ? flips[p] : NULL;
6591:         CheckPoint_Private(label, labelId, section, point, f, &offset, &contains);
6592:         if (!contains) continue;
6593:         updatePointFields_private(section, point, perm, flip, f, insert, PETSC_TRUE, NULL, values, &offset, array);
6594:       }
6595:       break;
6596:     case INSERT_BC_VALUES:
6597:       for (p = 0; p < numPoints; p++) {
6598:         const PetscInt     point = points[2 * p];
6599:         const PetscInt    *perm  = perms ? perms[p] : NULL;
6600:         const PetscScalar *flip  = flips ? flips[p] : NULL;
6601:         CheckPoint_Private(label, labelId, section, point, f, &offset, &contains);
6602:         if (!contains) continue;
6603:         updatePointFieldsBC_private(section, point, perm, flip, f, Ncc, comps, insert, NULL, values, &offset, array);
6604:       }
6605:       break;
6606:     case ADD_VALUES:
6607:       for (p = 0; p < numPoints; p++) {
6608:         const PetscInt     point = points[2 * p];
6609:         const PetscInt    *perm  = perms ? perms[p] : NULL;
6610:         const PetscScalar *flip  = flips ? flips[p] : NULL;
6611:         CheckPoint_Private(label, labelId, section, point, f, &offset, &contains);
6612:         if (!contains) continue;
6613:         updatePointFields_private(section, point, perm, flip, f, add, PETSC_FALSE, NULL, values, &offset, array);
6614:       }
6615:       break;
6616:     case ADD_ALL_VALUES:
6617:       for (p = 0; p < numPoints; p++) {
6618:         const PetscInt     point = points[2 * p];
6619:         const PetscInt    *perm  = perms ? perms[p] : NULL;
6620:         const PetscScalar *flip  = flips ? flips[p] : NULL;
6621:         CheckPoint_Private(label, labelId, section, point, f, &offset, &contains);
6622:         if (!contains) continue;
6623:         updatePointFields_private(section, point, perm, flip, f, add, PETSC_TRUE, NULL, values, &offset, array);
6624:       }
6625:       break;
6626:     default:
6627:       SETERRQ(PetscObjectComm((PetscObject)dm), PETSC_ERR_ARG_OUTOFRANGE, "Invalid insert mode %d", mode);
6628:     }
6629:     PetscSectionRestoreFieldPointSyms(section, f, numPoints, points, &perms, &flips);
6630:   }
6631:   /* Cleanup points */
6632:   DMPlexRestoreCompressedClosure(dm, section, point, &numPoints, &points, &clSection, &clPoints, &clp);
6633:   /* Cleanup array */
6634:   VecRestoreArray(v, &array);
6635:   return 0;
6636: }

6638: static PetscErrorCode DMPlexPrintMatSetValues(PetscViewer viewer, Mat A, PetscInt point, PetscInt numRIndices, const PetscInt rindices[], PetscInt numCIndices, const PetscInt cindices[], const PetscScalar values[])
6639: {
6640:   PetscMPIInt rank;
6641:   PetscInt    i, j;

6643:   MPI_Comm_rank(PetscObjectComm((PetscObject)A), &rank);
6644:   PetscViewerASCIIPrintf(viewer, "[%d]mat for point %" PetscInt_FMT "\n", rank, point);
6645:   for (i = 0; i < numRIndices; i++) PetscViewerASCIIPrintf(viewer, "[%d]mat row indices[%" PetscInt_FMT "] = %" PetscInt_FMT "\n", rank, i, rindices[i]);
6646:   for (i = 0; i < numCIndices; i++) PetscViewerASCIIPrintf(viewer, "[%d]mat col indices[%" PetscInt_FMT "] = %" PetscInt_FMT "\n", rank, i, cindices[i]);
6647:   numCIndices = numCIndices ? numCIndices : numRIndices;
6648:   if (!values) return 0;
6649:   for (i = 0; i < numRIndices; i++) {
6650:     PetscViewerASCIIPrintf(viewer, "[%d]", rank);
6651:     for (j = 0; j < numCIndices; j++) {
6652: #if defined(PETSC_USE_COMPLEX)
6653:       PetscViewerASCIIPrintf(viewer, " (%g,%g)", (double)PetscRealPart(values[i * numCIndices + j]), (double)PetscImaginaryPart(values[i * numCIndices + j]));
6654: #else
6655:       PetscViewerASCIIPrintf(viewer, " %g", (double)values[i * numCIndices + j]);
6656: #endif
6657:     }
6658:     PetscViewerASCIIPrintf(viewer, "\n");
6659:   }
6660:   return 0;
6661: }

6663: /*
6664:   DMPlexGetIndicesPoint_Internal - Add the indices for dofs on a point to an index array

6666:   Input Parameters:
6667: + section - The section for this data layout
6668: . islocal - Is the section (and thus indices being requested) local or global?
6669: . point   - The point contributing dofs with these indices
6670: . off     - The global offset of this point
6671: . loff    - The local offset of each field
6672: . setBC   - The flag determining whether to include indices of boundary values
6673: . perm    - A permutation of the dofs on this point, or NULL
6674: - indperm - A permutation of the entire indices array, or NULL

6676:   Output Parameter:
6677: . indices - Indices for dofs on this point

6679:   Level: developer

6681:   Note: The indices could be local or global, depending on the value of 'off'.
6682: */
6683: PetscErrorCode DMPlexGetIndicesPoint_Internal(PetscSection section, PetscBool islocal, PetscInt point, PetscInt off, PetscInt *loff, PetscBool setBC, const PetscInt perm[], const PetscInt indperm[], PetscInt indices[])
6684: {
6685:   PetscInt        dof;   /* The number of unknowns on this point */
6686:   PetscInt        cdof;  /* The number of constraints on this point */
6687:   const PetscInt *cdofs; /* The indices of the constrained dofs on this point */
6688:   PetscInt        cind = 0, k;

6691:   PetscSectionGetDof(section, point, &dof);
6692:   PetscSectionGetConstraintDof(section, point, &cdof);
6693:   if (!cdof || setBC) {
6694:     for (k = 0; k < dof; ++k) {
6695:       const PetscInt preind = perm ? *loff + perm[k] : *loff + k;
6696:       const PetscInt ind    = indperm ? indperm[preind] : preind;

6698:       indices[ind] = off + k;
6699:     }
6700:   } else {
6701:     PetscSectionGetConstraintIndices(section, point, &cdofs);
6702:     for (k = 0; k < dof; ++k) {
6703:       const PetscInt preind = perm ? *loff + perm[k] : *loff + k;
6704:       const PetscInt ind    = indperm ? indperm[preind] : preind;

6706:       if ((cind < cdof) && (k == cdofs[cind])) {
6707:         /* Insert check for returning constrained indices */
6708:         indices[ind] = -(off + k + 1);
6709:         ++cind;
6710:       } else {
6711:         indices[ind] = off + k - (islocal ? 0 : cind);
6712:       }
6713:     }
6714:   }
6715:   *loff += dof;
6716:   return 0;
6717: }

6719: /*
6720:  DMPlexGetIndicesPointFields_Internal - gets section indices for a point in its canonical ordering.

6722:  Input Parameters:
6723: + section - a section (global or local)
6724: - islocal - PETSC_TRUE if requesting local indices (i.e., section is local); PETSC_FALSE for global
6725: . point - point within section
6726: . off - The offset of this point in the (local or global) indexed space - should match islocal and (usually) the section
6727: . foffs - array of length numFields containing the offset in canonical point ordering (the location in indices) of each field
6728: . setBC - identify constrained (boundary condition) points via involution.
6729: . perms - perms[f][permsoff][:] is a permutation of dofs within each field
6730: . permsoff - offset
6731: - indperm - index permutation

6733:  Output Parameter:
6734: . foffs - each entry is incremented by the number of (unconstrained if setBC=FALSE) dofs in that field
6735: . indices - array to hold indices (as defined by section) of each dof associated with point

6737:  Notes:
6738:  If section is local and setBC=true, there is no distinction between constrained and unconstrained dofs.
6739:  If section is local and setBC=false, the indices for constrained points are the involution -(i+1) of their position
6740:  in the local vector.

6742:  If section is global and setBC=false, the indices for constrained points are negative (and their value is not
6743:  significant).  It is invalid to call with a global section and setBC=true.

6745:  Developer Note:
6746:  The section is only used for field layout, so islocal is technically a statement about the offset (off).  At some point
6747:  in the future, global sections may have fields set, in which case we could pass the global section and obtain the
6748:  offset could be obtained from the section instead of passing it explicitly as we do now.

6750:  Example:
6751:  Suppose a point contains one field with three components, and for which the unconstrained indices are {10, 11, 12}.
6752:  When the middle component is constrained, we get the array {10, -12, 12} for (islocal=TRUE, setBC=FALSE).
6753:  Note that -12 is the involution of 11, so the user can involute negative indices to recover local indices.
6754:  The global vector does not store constrained dofs, so when this function returns global indices, say {110, -112, 111}, the value of -112 is an arbitrary flag that should not be interpreted beyond its sign.

6756:  Level: developer
6757: */
6758: PetscErrorCode DMPlexGetIndicesPointFields_Internal(PetscSection section, PetscBool islocal, PetscInt point, PetscInt off, PetscInt foffs[], PetscBool setBC, const PetscInt ***perms, PetscInt permsoff, const PetscInt indperm[], PetscInt indices[])
6759: {
6760:   PetscInt numFields, foff, f;

6763:   PetscSectionGetNumFields(section, &numFields);
6764:   for (f = 0, foff = 0; f < numFields; ++f) {
6765:     PetscInt        fdof, cfdof;
6766:     const PetscInt *fcdofs; /* The indices of the constrained dofs for field f on this point */
6767:     PetscInt        cind = 0, b;
6768:     const PetscInt *perm = (perms && perms[f]) ? perms[f][permsoff] : NULL;

6770:     PetscSectionGetFieldDof(section, point, f, &fdof);
6771:     PetscSectionGetFieldConstraintDof(section, point, f, &cfdof);
6772:     if (!cfdof || setBC) {
6773:       for (b = 0; b < fdof; ++b) {
6774:         const PetscInt preind = perm ? foffs[f] + perm[b] : foffs[f] + b;
6775:         const PetscInt ind    = indperm ? indperm[preind] : preind;

6777:         indices[ind] = off + foff + b;
6778:       }
6779:     } else {
6780:       PetscSectionGetFieldConstraintIndices(section, point, f, &fcdofs);
6781:       for (b = 0; b < fdof; ++b) {
6782:         const PetscInt preind = perm ? foffs[f] + perm[b] : foffs[f] + b;
6783:         const PetscInt ind    = indperm ? indperm[preind] : preind;

6785:         if ((cind < cfdof) && (b == fcdofs[cind])) {
6786:           indices[ind] = -(off + foff + b + 1);
6787:           ++cind;
6788:         } else {
6789:           indices[ind] = off + foff + b - (islocal ? 0 : cind);
6790:         }
6791:       }
6792:     }
6793:     foff += (setBC || islocal ? fdof : (fdof - cfdof));
6794:     foffs[f] += fdof;
6795:   }
6796:   return 0;
6797: }

6799: /*
6800:   This version believes the globalSection offsets for each field, rather than just the point offset

6802:  . foffs - The offset into 'indices' for each field, since it is segregated by field

6804:  Notes:
6805:  The semantics of this function relate to that of setBC=FALSE in DMPlexGetIndicesPointFields_Internal.
6806:  Since this function uses global indices, setBC=TRUE would be invalid, so no such argument exists.
6807: */
6808: static PetscErrorCode DMPlexGetIndicesPointFieldsSplit_Internal(PetscSection section, PetscSection globalSection, PetscInt point, PetscInt foffs[], const PetscInt ***perms, PetscInt permsoff, const PetscInt indperm[], PetscInt indices[])
6809: {
6810:   PetscInt numFields, foff, f;

6812:   PetscSectionGetNumFields(section, &numFields);
6813:   for (f = 0; f < numFields; ++f) {
6814:     PetscInt        fdof, cfdof;
6815:     const PetscInt *fcdofs; /* The indices of the constrained dofs for field f on this point */
6816:     PetscInt        cind = 0, b;
6817:     const PetscInt *perm = (perms && perms[f]) ? perms[f][permsoff] : NULL;

6819:     PetscSectionGetFieldDof(section, point, f, &fdof);
6820:     PetscSectionGetFieldConstraintDof(section, point, f, &cfdof);
6821:     PetscSectionGetFieldOffset(globalSection, point, f, &foff);
6822:     if (!cfdof) {
6823:       for (b = 0; b < fdof; ++b) {
6824:         const PetscInt preind = perm ? foffs[f] + perm[b] : foffs[f] + b;
6825:         const PetscInt ind    = indperm ? indperm[preind] : preind;

6827:         indices[ind] = foff + b;
6828:       }
6829:     } else {
6830:       PetscSectionGetFieldConstraintIndices(section, point, f, &fcdofs);
6831:       for (b = 0; b < fdof; ++b) {
6832:         const PetscInt preind = perm ? foffs[f] + perm[b] : foffs[f] + b;
6833:         const PetscInt ind    = indperm ? indperm[preind] : preind;

6835:         if ((cind < cfdof) && (b == fcdofs[cind])) {
6836:           indices[ind] = -(foff + b + 1);
6837:           ++cind;
6838:         } else {
6839:           indices[ind] = foff + b - cind;
6840:         }
6841:       }
6842:     }
6843:     foffs[f] += fdof;
6844:   }
6845:   return 0;
6846: }

6848: PetscErrorCode DMPlexAnchorsModifyMat(DM dm, PetscSection section, PetscInt numPoints, PetscInt numIndices, const PetscInt points[], const PetscInt ***perms, const PetscScalar values[], PetscInt *outNumPoints, PetscInt *outNumIndices, PetscInt *outPoints[], PetscScalar *outValues[], PetscInt offsets[], PetscBool multiplyLeft)
6849: {
6850:   Mat             cMat;
6851:   PetscSection    aSec, cSec;
6852:   IS              aIS;
6853:   PetscInt        aStart = -1, aEnd = -1;
6854:   const PetscInt *anchors;
6855:   PetscInt        numFields, f, p, q, newP = 0;
6856:   PetscInt        newNumPoints = 0, newNumIndices = 0;
6857:   PetscInt       *newPoints, *indices, *newIndices;
6858:   PetscInt        maxAnchor, maxDof;
6859:   PetscInt        newOffsets[32];
6860:   PetscInt       *pointMatOffsets[32];
6861:   PetscInt       *newPointOffsets[32];
6862:   PetscScalar    *pointMat[32];
6863:   PetscScalar    *newValues      = NULL, *tmpValues;
6864:   PetscBool       anyConstrained = PETSC_FALSE;

6868:   PetscSectionGetNumFields(section, &numFields);

6870:   DMPlexGetAnchors(dm, &aSec, &aIS);
6871:   /* if there are point-to-point constraints */
6872:   if (aSec) {
6873:     PetscArrayzero(newOffsets, 32);
6874:     ISGetIndices(aIS, &anchors);
6875:     PetscSectionGetChart(aSec, &aStart, &aEnd);
6876:     /* figure out how many points are going to be in the new element matrix
6877:      * (we allow double counting, because it's all just going to be summed
6878:      * into the global matrix anyway) */
6879:     for (p = 0; p < 2 * numPoints; p += 2) {
6880:       PetscInt b    = points[p];
6881:       PetscInt bDof = 0, bSecDof;

6883:       PetscSectionGetDof(section, b, &bSecDof);
6884:       if (!bSecDof) continue;
6885:       if (b >= aStart && b < aEnd) PetscSectionGetDof(aSec, b, &bDof);
6886:       if (bDof) {
6887:         /* this point is constrained */
6888:         /* it is going to be replaced by its anchors */
6889:         PetscInt bOff, q;

6891:         anyConstrained = PETSC_TRUE;
6892:         newNumPoints += bDof;
6893:         PetscSectionGetOffset(aSec, b, &bOff);
6894:         for (q = 0; q < bDof; q++) {
6895:           PetscInt a = anchors[bOff + q];
6896:           PetscInt aDof;

6898:           PetscSectionGetDof(section, a, &aDof);
6899:           newNumIndices += aDof;
6900:           for (f = 0; f < numFields; ++f) {
6901:             PetscInt fDof;

6903:             PetscSectionGetFieldDof(section, a, f, &fDof);
6904:             newOffsets[f + 1] += fDof;
6905:           }
6906:         }
6907:       } else {
6908:         /* this point is not constrained */
6909:         newNumPoints++;
6910:         newNumIndices += bSecDof;
6911:         for (f = 0; f < numFields; ++f) {
6912:           PetscInt fDof;

6914:           PetscSectionGetFieldDof(section, b, f, &fDof);
6915:           newOffsets[f + 1] += fDof;
6916:         }
6917:       }
6918:     }
6919:   }
6920:   if (!anyConstrained) {
6921:     if (outNumPoints) *outNumPoints = 0;
6922:     if (outNumIndices) *outNumIndices = 0;
6923:     if (outPoints) *outPoints = NULL;
6924:     if (outValues) *outValues = NULL;
6925:     if (aSec) ISRestoreIndices(aIS, &anchors);
6926:     return 0;
6927:   }

6929:   if (outNumPoints) *outNumPoints = newNumPoints;
6930:   if (outNumIndices) *outNumIndices = newNumIndices;

6932:   for (f = 0; f < numFields; ++f) newOffsets[f + 1] += newOffsets[f];

6934:   if (!outPoints && !outValues) {
6935:     if (offsets) {
6936:       for (f = 0; f <= numFields; f++) offsets[f] = newOffsets[f];
6937:     }
6938:     if (aSec) ISRestoreIndices(aIS, &anchors);
6939:     return 0;
6940:   }


6944:   DMGetDefaultConstraints(dm, &cSec, &cMat, NULL);

6946:   /* workspaces */
6947:   if (numFields) {
6948:     for (f = 0; f < numFields; f++) {
6949:       DMGetWorkArray(dm, numPoints + 1, MPIU_INT, &pointMatOffsets[f]);
6950:       DMGetWorkArray(dm, numPoints + 1, MPIU_INT, &newPointOffsets[f]);
6951:     }
6952:   } else {
6953:     DMGetWorkArray(dm, numPoints + 1, MPIU_INT, &pointMatOffsets[0]);
6954:     DMGetWorkArray(dm, numPoints, MPIU_INT, &newPointOffsets[0]);
6955:   }

6957:   /* get workspaces for the point-to-point matrices */
6958:   if (numFields) {
6959:     PetscInt totalOffset, totalMatOffset;

6961:     for (p = 0; p < numPoints; p++) {
6962:       PetscInt b    = points[2 * p];
6963:       PetscInt bDof = 0, bSecDof;

6965:       PetscSectionGetDof(section, b, &bSecDof);
6966:       if (!bSecDof) {
6967:         for (f = 0; f < numFields; f++) {
6968:           newPointOffsets[f][p + 1] = 0;
6969:           pointMatOffsets[f][p + 1] = 0;
6970:         }
6971:         continue;
6972:       }
6973:       if (b >= aStart && b < aEnd) PetscSectionGetDof(aSec, b, &bDof);
6974:       if (bDof) {
6975:         for (f = 0; f < numFields; f++) {
6976:           PetscInt fDof, q, bOff, allFDof = 0;

6978:           PetscSectionGetFieldDof(section, b, f, &fDof);
6979:           PetscSectionGetOffset(aSec, b, &bOff);
6980:           for (q = 0; q < bDof; q++) {
6981:             PetscInt a = anchors[bOff + q];
6982:             PetscInt aFDof;

6984:             PetscSectionGetFieldDof(section, a, f, &aFDof);
6985:             allFDof += aFDof;
6986:           }
6987:           newPointOffsets[f][p + 1] = allFDof;
6988:           pointMatOffsets[f][p + 1] = fDof * allFDof;
6989:         }
6990:       } else {
6991:         for (f = 0; f < numFields; f++) {
6992:           PetscInt fDof;

6994:           PetscSectionGetFieldDof(section, b, f, &fDof);
6995:           newPointOffsets[f][p + 1] = fDof;
6996:           pointMatOffsets[f][p + 1] = 0;
6997:         }
6998:       }
6999:     }
7000:     for (f = 0, totalOffset = 0, totalMatOffset = 0; f < numFields; f++) {
7001:       newPointOffsets[f][0] = totalOffset;
7002:       pointMatOffsets[f][0] = totalMatOffset;
7003:       for (p = 0; p < numPoints; p++) {
7004:         newPointOffsets[f][p + 1] += newPointOffsets[f][p];
7005:         pointMatOffsets[f][p + 1] += pointMatOffsets[f][p];
7006:       }
7007:       totalOffset    = newPointOffsets[f][numPoints];
7008:       totalMatOffset = pointMatOffsets[f][numPoints];
7009:       DMGetWorkArray(dm, pointMatOffsets[f][numPoints], MPIU_SCALAR, &pointMat[f]);
7010:     }
7011:   } else {
7012:     for (p = 0; p < numPoints; p++) {
7013:       PetscInt b    = points[2 * p];
7014:       PetscInt bDof = 0, bSecDof;

7016:       PetscSectionGetDof(section, b, &bSecDof);
7017:       if (!bSecDof) {
7018:         newPointOffsets[0][p + 1] = 0;
7019:         pointMatOffsets[0][p + 1] = 0;
7020:         continue;
7021:       }
7022:       if (b >= aStart && b < aEnd) PetscSectionGetDof(aSec, b, &bDof);
7023:       if (bDof) {
7024:         PetscInt bOff, q, allDof = 0;

7026:         PetscSectionGetOffset(aSec, b, &bOff);
7027:         for (q = 0; q < bDof; q++) {
7028:           PetscInt a = anchors[bOff + q], aDof;

7030:           PetscSectionGetDof(section, a, &aDof);
7031:           allDof += aDof;
7032:         }
7033:         newPointOffsets[0][p + 1] = allDof;
7034:         pointMatOffsets[0][p + 1] = bSecDof * allDof;
7035:       } else {
7036:         newPointOffsets[0][p + 1] = bSecDof;
7037:         pointMatOffsets[0][p + 1] = 0;
7038:       }
7039:     }
7040:     newPointOffsets[0][0] = 0;
7041:     pointMatOffsets[0][0] = 0;
7042:     for (p = 0; p < numPoints; p++) {
7043:       newPointOffsets[0][p + 1] += newPointOffsets[0][p];
7044:       pointMatOffsets[0][p + 1] += pointMatOffsets[0][p];
7045:     }
7046:     DMGetWorkArray(dm, pointMatOffsets[0][numPoints], MPIU_SCALAR, &pointMat[0]);
7047:   }

7049:   /* output arrays */
7050:   DMGetWorkArray(dm, 2 * newNumPoints, MPIU_INT, &newPoints);

7052:   /* get the point-to-point matrices; construct newPoints */
7053:   PetscSectionGetMaxDof(aSec, &maxAnchor);
7054:   PetscSectionGetMaxDof(section, &maxDof);
7055:   DMGetWorkArray(dm, maxDof, MPIU_INT, &indices);
7056:   DMGetWorkArray(dm, maxAnchor * maxDof, MPIU_INT, &newIndices);
7057:   if (numFields) {
7058:     for (p = 0, newP = 0; p < numPoints; p++) {
7059:       PetscInt b    = points[2 * p];
7060:       PetscInt o    = points[2 * p + 1];
7061:       PetscInt bDof = 0, bSecDof;

7063:       PetscSectionGetDof(section, b, &bSecDof);
7064:       if (!bSecDof) continue;
7065:       if (b >= aStart && b < aEnd) PetscSectionGetDof(aSec, b, &bDof);
7066:       if (bDof) {
7067:         PetscInt fStart[32], fEnd[32], fAnchorStart[32], fAnchorEnd[32], bOff, q;

7069:         fStart[0] = 0;
7070:         fEnd[0]   = 0;
7071:         for (f = 0; f < numFields; f++) {
7072:           PetscInt fDof;

7074:           PetscSectionGetFieldDof(cSec, b, f, &fDof);
7075:           fStart[f + 1] = fStart[f] + fDof;
7076:           fEnd[f + 1]   = fStart[f + 1];
7077:         }
7078:         PetscSectionGetOffset(cSec, b, &bOff);
7079:         DMPlexGetIndicesPointFields_Internal(cSec, PETSC_TRUE, b, bOff, fEnd, PETSC_TRUE, perms, p, NULL, indices);

7081:         fAnchorStart[0] = 0;
7082:         fAnchorEnd[0]   = 0;
7083:         for (f = 0; f < numFields; f++) {
7084:           PetscInt fDof = newPointOffsets[f][p + 1] - newPointOffsets[f][p];

7086:           fAnchorStart[f + 1] = fAnchorStart[f] + fDof;
7087:           fAnchorEnd[f + 1]   = fAnchorStart[f + 1];
7088:         }
7089:         PetscSectionGetOffset(aSec, b, &bOff);
7090:         for (q = 0; q < bDof; q++) {
7091:           PetscInt a = anchors[bOff + q], aOff;

7093:           /* we take the orientation of ap into account in the order that we constructed the indices above: the newly added points have no orientation */
7094:           newPoints[2 * (newP + q)]     = a;
7095:           newPoints[2 * (newP + q) + 1] = 0;
7096:           PetscSectionGetOffset(section, a, &aOff);
7097:           DMPlexGetIndicesPointFields_Internal(section, PETSC_TRUE, a, aOff, fAnchorEnd, PETSC_TRUE, NULL, -1, NULL, newIndices);
7098:         }
7099:         newP += bDof;

7101:         if (outValues) {
7102:           /* get the point-to-point submatrix */
7103:           for (f = 0; f < numFields; f++) MatGetValues(cMat, fEnd[f] - fStart[f], indices + fStart[f], fAnchorEnd[f] - fAnchorStart[f], newIndices + fAnchorStart[f], pointMat[f] + pointMatOffsets[f][p]);
7104:         }
7105:       } else {
7106:         newPoints[2 * newP]     = b;
7107:         newPoints[2 * newP + 1] = o;
7108:         newP++;
7109:       }
7110:     }
7111:   } else {
7112:     for (p = 0; p < numPoints; p++) {
7113:       PetscInt b    = points[2 * p];
7114:       PetscInt o    = points[2 * p + 1];
7115:       PetscInt bDof = 0, bSecDof;

7117:       PetscSectionGetDof(section, b, &bSecDof);
7118:       if (!bSecDof) continue;
7119:       if (b >= aStart && b < aEnd) PetscSectionGetDof(aSec, b, &bDof);
7120:       if (bDof) {
7121:         PetscInt bEnd = 0, bAnchorEnd = 0, bOff;

7123:         PetscSectionGetOffset(cSec, b, &bOff);
7124:         DMPlexGetIndicesPoint_Internal(cSec, PETSC_TRUE, b, bOff, &bEnd, PETSC_TRUE, (perms && perms[0]) ? perms[0][p] : NULL, NULL, indices);

7126:         PetscSectionGetOffset(aSec, b, &bOff);
7127:         for (q = 0; q < bDof; q++) {
7128:           PetscInt a = anchors[bOff + q], aOff;

7130:           /* we take the orientation of ap into account in the order that we constructed the indices above: the newly added points have no orientation */

7132:           newPoints[2 * (newP + q)]     = a;
7133:           newPoints[2 * (newP + q) + 1] = 0;
7134:           PetscSectionGetOffset(section, a, &aOff);
7135:           DMPlexGetIndicesPoint_Internal(section, PETSC_TRUE, a, aOff, &bAnchorEnd, PETSC_TRUE, NULL, NULL, newIndices);
7136:         }
7137:         newP += bDof;

7139:         /* get the point-to-point submatrix */
7140:         if (outValues) MatGetValues(cMat, bEnd, indices, bAnchorEnd, newIndices, pointMat[0] + pointMatOffsets[0][p]);
7141:       } else {
7142:         newPoints[2 * newP]     = b;
7143:         newPoints[2 * newP + 1] = o;
7144:         newP++;
7145:       }
7146:     }
7147:   }

7149:   if (outValues) {
7150:     DMGetWorkArray(dm, newNumIndices * numIndices, MPIU_SCALAR, &tmpValues);
7151:     PetscArrayzero(tmpValues, newNumIndices * numIndices);
7152:     /* multiply constraints on the right */
7153:     if (numFields) {
7154:       for (f = 0; f < numFields; f++) {
7155:         PetscInt oldOff = offsets[f];

7157:         for (p = 0; p < numPoints; p++) {
7158:           PetscInt cStart = newPointOffsets[f][p];
7159:           PetscInt b      = points[2 * p];
7160:           PetscInt c, r, k;
7161:           PetscInt dof;

7163:           PetscSectionGetFieldDof(section, b, f, &dof);
7164:           if (!dof) continue;
7165:           if (pointMatOffsets[f][p] < pointMatOffsets[f][p + 1]) {
7166:             PetscInt           nCols = newPointOffsets[f][p + 1] - cStart;
7167:             const PetscScalar *mat   = pointMat[f] + pointMatOffsets[f][p];

7169:             for (r = 0; r < numIndices; r++) {
7170:               for (c = 0; c < nCols; c++) {
7171:                 for (k = 0; k < dof; k++) tmpValues[r * newNumIndices + cStart + c] += values[r * numIndices + oldOff + k] * mat[k * nCols + c];
7172:               }
7173:             }
7174:           } else {
7175:             /* copy this column as is */
7176:             for (r = 0; r < numIndices; r++) {
7177:               for (c = 0; c < dof; c++) tmpValues[r * newNumIndices + cStart + c] = values[r * numIndices + oldOff + c];
7178:             }
7179:           }
7180:           oldOff += dof;
7181:         }
7182:       }
7183:     } else {
7184:       PetscInt oldOff = 0;
7185:       for (p = 0; p < numPoints; p++) {
7186:         PetscInt cStart = newPointOffsets[0][p];
7187:         PetscInt b      = points[2 * p];
7188:         PetscInt c, r, k;
7189:         PetscInt dof;

7191:         PetscSectionGetDof(section, b, &dof);
7192:         if (!dof) continue;
7193:         if (pointMatOffsets[0][p] < pointMatOffsets[0][p + 1]) {
7194:           PetscInt           nCols = newPointOffsets[0][p + 1] - cStart;
7195:           const PetscScalar *mat   = pointMat[0] + pointMatOffsets[0][p];

7197:           for (r = 0; r < numIndices; r++) {
7198:             for (c = 0; c < nCols; c++) {
7199:               for (k = 0; k < dof; k++) tmpValues[r * newNumIndices + cStart + c] += mat[k * nCols + c] * values[r * numIndices + oldOff + k];
7200:             }
7201:           }
7202:         } else {
7203:           /* copy this column as is */
7204:           for (r = 0; r < numIndices; r++) {
7205:             for (c = 0; c < dof; c++) tmpValues[r * newNumIndices + cStart + c] = values[r * numIndices + oldOff + c];
7206:           }
7207:         }
7208:         oldOff += dof;
7209:       }
7210:     }

7212:     if (multiplyLeft) {
7213:       DMGetWorkArray(dm, newNumIndices * newNumIndices, MPIU_SCALAR, &newValues);
7214:       PetscArrayzero(newValues, newNumIndices * newNumIndices);
7215:       /* multiply constraints transpose on the left */
7216:       if (numFields) {
7217:         for (f = 0; f < numFields; f++) {
7218:           PetscInt oldOff = offsets[f];

7220:           for (p = 0; p < numPoints; p++) {
7221:             PetscInt rStart = newPointOffsets[f][p];
7222:             PetscInt b      = points[2 * p];
7223:             PetscInt c, r, k;
7224:             PetscInt dof;

7226:             PetscSectionGetFieldDof(section, b, f, &dof);
7227:             if (pointMatOffsets[f][p] < pointMatOffsets[f][p + 1]) {
7228:               PetscInt                          nRows = newPointOffsets[f][p + 1] - rStart;
7229:               const PetscScalar *PETSC_RESTRICT mat   = pointMat[f] + pointMatOffsets[f][p];

7231:               for (r = 0; r < nRows; r++) {
7232:                 for (c = 0; c < newNumIndices; c++) {
7233:                   for (k = 0; k < dof; k++) newValues[(rStart + r) * newNumIndices + c] += mat[k * nRows + r] * tmpValues[(oldOff + k) * newNumIndices + c];
7234:                 }
7235:               }
7236:             } else {
7237:               /* copy this row as is */
7238:               for (r = 0; r < dof; r++) {
7239:                 for (c = 0; c < newNumIndices; c++) newValues[(rStart + r) * newNumIndices + c] = tmpValues[(oldOff + r) * newNumIndices + c];
7240:               }
7241:             }
7242:             oldOff += dof;
7243:           }
7244:         }
7245:       } else {
7246:         PetscInt oldOff = 0;

7248:         for (p = 0; p < numPoints; p++) {
7249:           PetscInt rStart = newPointOffsets[0][p];
7250:           PetscInt b      = points[2 * p];
7251:           PetscInt c, r, k;
7252:           PetscInt dof;

7254:           PetscSectionGetDof(section, b, &dof);
7255:           if (pointMatOffsets[0][p] < pointMatOffsets[0][p + 1]) {
7256:             PetscInt                          nRows = newPointOffsets[0][p + 1] - rStart;
7257:             const PetscScalar *PETSC_RESTRICT mat   = pointMat[0] + pointMatOffsets[0][p];

7259:             for (r = 0; r < nRows; r++) {
7260:               for (c = 0; c < newNumIndices; c++) {
7261:                 for (k = 0; k < dof; k++) newValues[(rStart + r) * newNumIndices + c] += mat[k * nRows + r] * tmpValues[(oldOff + k) * newNumIndices + c];
7262:               }
7263:             }
7264:           } else {
7265:             /* copy this row as is */
7266:             for (r = 0; r < dof; r++) {
7267:               for (c = 0; c < newNumIndices; c++) newValues[(rStart + r) * newNumIndices + c] = tmpValues[(oldOff + r) * newNumIndices + c];
7268:             }
7269:           }
7270:           oldOff += dof;
7271:         }
7272:       }

7274:       DMRestoreWorkArray(dm, newNumIndices * numIndices, MPIU_SCALAR, &tmpValues);
7275:     } else {
7276:       newValues = tmpValues;
7277:     }
7278:   }

7280:   /* clean up */
7281:   DMRestoreWorkArray(dm, maxDof, MPIU_INT, &indices);
7282:   DMRestoreWorkArray(dm, maxAnchor * maxDof, MPIU_INT, &newIndices);

7284:   if (numFields) {
7285:     for (f = 0; f < numFields; f++) {
7286:       DMRestoreWorkArray(dm, pointMatOffsets[f][numPoints], MPIU_SCALAR, &pointMat[f]);
7287:       DMRestoreWorkArray(dm, numPoints + 1, MPIU_INT, &pointMatOffsets[f]);
7288:       DMRestoreWorkArray(dm, numPoints + 1, MPIU_INT, &newPointOffsets[f]);
7289:     }
7290:   } else {
7291:     DMRestoreWorkArray(dm, pointMatOffsets[0][numPoints], MPIU_SCALAR, &pointMat[0]);
7292:     DMRestoreWorkArray(dm, numPoints + 1, MPIU_INT, &pointMatOffsets[0]);
7293:     DMRestoreWorkArray(dm, numPoints + 1, MPIU_INT, &newPointOffsets[0]);
7294:   }
7295:   ISRestoreIndices(aIS, &anchors);

7297:   /* output */
7298:   if (outPoints) {
7299:     *outPoints = newPoints;
7300:   } else {
7301:     DMRestoreWorkArray(dm, 2 * newNumPoints, MPIU_INT, &newPoints);
7302:   }
7303:   if (outValues) *outValues = newValues;
7304:   for (f = 0; f <= numFields; f++) offsets[f] = newOffsets[f];
7305:   return 0;
7306: }

7308: /*@C
7309:   DMPlexGetClosureIndices - Gets the global dof indices associated with the closure of the given point within the provided sections.

7311:   Not collective

7313:   Input Parameters:
7314: + dm         - The DM
7315: . section    - The PetscSection describing the points (a local section)
7316: . idxSection - The PetscSection from which to obtain indices (may be local or global)
7317: . point      - The point defining the closure
7318: - useClPerm  - Use the closure point permutation if available

7320:   Output Parameters:
7321: + numIndices - The number of dof indices in the closure of point with the input sections
7322: . indices    - The dof indices
7323: . outOffsets - Array to write the field offsets into, or NULL
7324: - values     - The input values, which may be modified if sign flips are induced by the point symmetries, or NULL

7326:   Notes:
7327:   Must call DMPlexRestoreClosureIndices() to free allocated memory

7329:   If idxSection is global, any constrained dofs (see DMAddBoundary(), for example) will get negative indices.  The value
7330:   of those indices is not significant.  If idxSection is local, the constrained dofs will yield the involution -(idx+1)
7331:   of their index in a local vector.  A caller who does not wish to distinguish those points may recover the nonnegative
7332:   indices via involution, -(-(idx+1)+1)==idx.  Local indices are provided when idxSection == section, otherwise global
7333:   indices (with the above semantics) are implied.

7335:   Level: advanced

7337: .seealso `DMPlexRestoreClosureIndices()`, `DMPlexVecGetClosure()`, `DMPlexMatSetClosure()`, `DMGetLocalSection()`, `DMGetGlobalSection()`
7338: @*/
7339: PetscErrorCode DMPlexGetClosureIndices(DM dm, PetscSection section, PetscSection idxSection, PetscInt point, PetscBool useClPerm, PetscInt *numIndices, PetscInt *indices[], PetscInt outOffsets[], PetscScalar *values[])
7340: {
7341:   /* Closure ordering */
7342:   PetscSection    clSection;
7343:   IS              clPoints;
7344:   const PetscInt *clp;
7345:   PetscInt       *points;
7346:   const PetscInt *clperm = NULL;
7347:   /* Dof permutation and sign flips */
7348:   const PetscInt    **perms[32] = {NULL};
7349:   const PetscScalar **flips[32] = {NULL};
7350:   PetscScalar        *valCopy   = NULL;
7351:   /* Hanging node constraints */
7352:   PetscInt    *pointsC = NULL;
7353:   PetscScalar *valuesC = NULL;
7354:   PetscInt     NclC, NiC;

7356:   PetscInt *idx;
7357:   PetscInt  Nf, Ncl, Ni = 0, offsets[32], p, f;
7358:   PetscBool isLocal = (section == idxSection) ? PETSC_TRUE : PETSC_FALSE;

7368:   PetscSectionGetNumFields(section, &Nf);
7370:   PetscArrayzero(offsets, 32);
7371:   /* 1) Get points in closure */
7372:   DMPlexGetCompressedClosure(dm, section, point, &Ncl, &points, &clSection, &clPoints, &clp);
7373:   if (useClPerm) {
7374:     PetscInt depth, clsize;
7375:     DMPlexGetPointDepth(dm, point, &depth);
7376:     for (clsize = 0, p = 0; p < Ncl; p++) {
7377:       PetscInt dof;
7378:       PetscSectionGetDof(section, points[2 * p], &dof);
7379:       clsize += dof;
7380:     }
7381:     PetscSectionGetClosureInversePermutation_Internal(section, (PetscObject)dm, depth, clsize, &clperm);
7382:   }
7383:   /* 2) Get number of indices on these points and field offsets from section */
7384:   for (p = 0; p < Ncl * 2; p += 2) {
7385:     PetscInt dof, fdof;

7387:     PetscSectionGetDof(section, points[p], &dof);
7388:     for (f = 0; f < Nf; ++f) {
7389:       PetscSectionGetFieldDof(section, points[p], f, &fdof);
7390:       offsets[f + 1] += fdof;
7391:     }
7392:     Ni += dof;
7393:   }
7394:   for (f = 1; f < Nf; ++f) offsets[f + 1] += offsets[f];
7396:   /* 3) Get symmetries and sign flips. Apply sign flips to values if passed in (only works for square values matrix) */
7397:   for (f = 0; f < PetscMax(1, Nf); ++f) {
7398:     if (Nf) PetscSectionGetFieldPointSyms(section, f, Ncl, points, &perms[f], &flips[f]);
7399:     else PetscSectionGetPointSyms(section, Ncl, points, &perms[f], &flips[f]);
7400:     /* may need to apply sign changes to the element matrix */
7401:     if (values && flips[f]) {
7402:       PetscInt foffset = offsets[f];

7404:       for (p = 0; p < Ncl; ++p) {
7405:         PetscInt           pnt  = points[2 * p], fdof;
7406:         const PetscScalar *flip = flips[f] ? flips[f][p] : NULL;

7408:         if (!Nf) PetscSectionGetDof(section, pnt, &fdof);
7409:         else PetscSectionGetFieldDof(section, pnt, f, &fdof);
7410:         if (flip) {
7411:           PetscInt i, j, k;

7413:           if (!valCopy) {
7414:             DMGetWorkArray(dm, Ni * Ni, MPIU_SCALAR, &valCopy);
7415:             for (j = 0; j < Ni * Ni; ++j) valCopy[j] = (*values)[j];
7416:             *values = valCopy;
7417:           }
7418:           for (i = 0; i < fdof; ++i) {
7419:             PetscScalar fval = flip[i];

7421:             for (k = 0; k < Ni; ++k) {
7422:               valCopy[Ni * (foffset + i) + k] *= fval;
7423:               valCopy[Ni * k + (foffset + i)] *= fval;
7424:             }
7425:           }
7426:         }
7427:         foffset += fdof;
7428:       }
7429:     }
7430:   }
7431:   /* 4) Apply hanging node constraints. Get new symmetries and replace all storage with constrained storage */
7432:   DMPlexAnchorsModifyMat(dm, section, Ncl, Ni, points, perms, values ? *values : NULL, &NclC, &NiC, &pointsC, values ? &valuesC : NULL, offsets, PETSC_TRUE);
7433:   if (NclC) {
7434:     if (valCopy) DMRestoreWorkArray(dm, Ni * Ni, MPIU_SCALAR, &valCopy);
7435:     for (f = 0; f < PetscMax(1, Nf); ++f) {
7436:       if (Nf) PetscSectionRestoreFieldPointSyms(section, f, Ncl, points, &perms[f], &flips[f]);
7437:       else PetscSectionRestorePointSyms(section, Ncl, points, &perms[f], &flips[f]);
7438:     }
7439:     for (f = 0; f < PetscMax(1, Nf); ++f) {
7440:       if (Nf) PetscSectionGetFieldPointSyms(section, f, NclC, pointsC, &perms[f], &flips[f]);
7441:       else PetscSectionGetPointSyms(section, NclC, pointsC, &perms[f], &flips[f]);
7442:     }
7443:     DMPlexRestoreCompressedClosure(dm, section, point, &Ncl, &points, &clSection, &clPoints, &clp);
7444:     Ncl    = NclC;
7445:     Ni     = NiC;
7446:     points = pointsC;
7447:     if (values) *values = valuesC;
7448:   }
7449:   /* 5) Calculate indices */
7450:   DMGetWorkArray(dm, Ni, MPIU_INT, &idx);
7451:   if (Nf) {
7452:     PetscInt  idxOff;
7453:     PetscBool useFieldOffsets;

7455:     if (outOffsets) {
7456:       for (f = 0; f <= Nf; f++) outOffsets[f] = offsets[f];
7457:     }
7458:     PetscSectionGetUseFieldOffsets(idxSection, &useFieldOffsets);
7459:     if (useFieldOffsets) {
7460:       for (p = 0; p < Ncl; ++p) {
7461:         const PetscInt pnt = points[p * 2];

7463:         DMPlexGetIndicesPointFieldsSplit_Internal(section, idxSection, pnt, offsets, perms, p, clperm, idx);
7464:       }
7465:     } else {
7466:       for (p = 0; p < Ncl; ++p) {
7467:         const PetscInt pnt = points[p * 2];

7469:         PetscSectionGetOffset(idxSection, pnt, &idxOff);
7470:         /* Note that we pass a local section even though we're using global offsets.  This is because global sections do
7471:          * not (at the time of this writing) have fields set. They probably should, in which case we would pass the
7472:          * global section. */
7473:         DMPlexGetIndicesPointFields_Internal(section, isLocal, pnt, idxOff < 0 ? -(idxOff + 1) : idxOff, offsets, PETSC_FALSE, perms, p, clperm, idx);
7474:       }
7475:     }
7476:   } else {
7477:     PetscInt off = 0, idxOff;

7479:     for (p = 0; p < Ncl; ++p) {
7480:       const PetscInt  pnt  = points[p * 2];
7481:       const PetscInt *perm = perms[0] ? perms[0][p] : NULL;

7483:       PetscSectionGetOffset(idxSection, pnt, &idxOff);
7484:       /* Note that we pass a local section even though we're using global offsets.  This is because global sections do
7485:        * not (at the time of this writing) have fields set. They probably should, in which case we would pass the global section. */
7486:       DMPlexGetIndicesPoint_Internal(section, isLocal, pnt, idxOff < 0 ? -(idxOff + 1) : idxOff, &off, PETSC_FALSE, perm, clperm, idx);
7487:     }
7488:   }
7489:   /* 6) Cleanup */
7490:   for (f = 0; f < PetscMax(1, Nf); ++f) {
7491:     if (Nf) PetscSectionRestoreFieldPointSyms(section, f, Ncl, points, &perms[f], &flips[f]);
7492:     else PetscSectionRestorePointSyms(section, Ncl, points, &perms[f], &flips[f]);
7493:   }
7494:   if (NclC) {
7495:     DMRestoreWorkArray(dm, NclC * 2, MPIU_INT, &pointsC);
7496:   } else {
7497:     DMPlexRestoreCompressedClosure(dm, section, point, &Ncl, &points, &clSection, &clPoints, &clp);
7498:   }

7500:   if (numIndices) *numIndices = Ni;
7501:   if (indices) *indices = idx;
7502:   return 0;
7503: }

7505: /*@C
7506:   DMPlexRestoreClosureIndices - Restores the global dof indices associated with the closure of the given point within the provided sections.

7508:   Not collective

7510:   Input Parameters:
7511: + dm         - The DM
7512: . section    - The PetscSection describing the points (a local section)
7513: . idxSection - The PetscSection from which to obtain indices (may be local or global)
7514: . point      - The point defining the closure
7515: - useClPerm  - Use the closure point permutation if available

7517:   Output Parameters:
7518: + numIndices - The number of dof indices in the closure of point with the input sections
7519: . indices    - The dof indices
7520: . outOffsets - Array to write the field offsets into, or NULL
7521: - values     - The input values, which may be modified if sign flips are induced by the point symmetries, or NULL

7523:   Notes:
7524:   If values were modified, the user is responsible for calling DMRestoreWorkArray(dm, 0, MPIU_SCALAR, &values).

7526:   If idxSection is global, any constrained dofs (see DMAddBoundary(), for example) will get negative indices.  The value
7527:   of those indices is not significant.  If idxSection is local, the constrained dofs will yield the involution -(idx+1)
7528:   of their index in a local vector.  A caller who does not wish to distinguish those points may recover the nonnegative
7529:   indices via involution, -(-(idx+1)+1)==idx.  Local indices are provided when idxSection == section, otherwise global
7530:   indices (with the above semantics) are implied.

7532:   Level: advanced

7534: .seealso `DMPlexGetClosureIndices()`, `DMPlexVecGetClosure()`, `DMPlexMatSetClosure()`, `DMGetLocalSection()`, `DMGetGlobalSection()`
7535: @*/
7536: PetscErrorCode DMPlexRestoreClosureIndices(DM dm, PetscSection section, PetscSection idxSection, PetscInt point, PetscBool useClPerm, PetscInt *numIndices, PetscInt *indices[], PetscInt outOffsets[], PetscScalar *values[])
7537: {
7540:   DMRestoreWorkArray(dm, 0, MPIU_INT, indices);
7541:   return 0;
7542: }

7544: /*@C
7545:   DMPlexMatSetClosure - Set an array of the values on the closure of 'point'

7547:   Not collective

7549:   Input Parameters:
7550: + dm - The DM
7551: . section - The section describing the layout in v, or NULL to use the default section
7552: . globalSection - The section describing the layout in v, or NULL to use the default global section
7553: . A - The matrix
7554: . point - The point in the DM
7555: . values - The array of values
7556: - mode - The insert mode, where INSERT_ALL_VALUES and ADD_ALL_VALUES also overwrite boundary conditions

7558:   Fortran Notes:
7559:   This routine is only available in Fortran 90, and you must include petsc.h90 in your code.

7561:   Level: intermediate

7563: .seealso `DMPlexMatSetClosureGeneral()`, `DMPlexVecGetClosure()`, `DMPlexVecSetClosure()`
7564: @*/
7565: PetscErrorCode DMPlexMatSetClosure(DM dm, PetscSection section, PetscSection globalSection, Mat A, PetscInt point, const PetscScalar values[], InsertMode mode)
7566: {
7567:   DM_Plex           *mesh = (DM_Plex *)dm->data;
7568:   PetscInt          *indices;
7569:   PetscInt           numIndices;
7570:   const PetscScalar *valuesOrig = values;
7571:   PetscErrorCode     ierr;

7574:   if (!section) DMGetLocalSection(dm, &section);
7576:   if (!globalSection) DMGetGlobalSection(dm, &globalSection);

7580:   DMPlexGetClosureIndices(dm, section, globalSection, point, PETSC_TRUE, &numIndices, &indices, NULL, (PetscScalar **)&values);

7582:   if (mesh->printSetValues) DMPlexPrintMatSetValues(PETSC_VIEWER_STDOUT_SELF, A, point, numIndices, indices, 0, NULL, values);
7583:   /* TODO: fix this code to not use error codes as handle-able exceptions! */
7584:   MatSetValues(A, numIndices, indices, numIndices, indices, values, mode);
7585:   if (ierr) {
7586:     PetscMPIInt rank;

7588:     MPI_Comm_rank(PetscObjectComm((PetscObject)A), &rank);
7589:     (*PetscErrorPrintf)("[%d]ERROR in DMPlexMatSetClosure\n", rank);
7590:     DMPlexPrintMatSetValues(PETSC_VIEWER_STDERR_SELF, A, point, numIndices, indices, 0, NULL, values);
7591:     DMPlexRestoreClosureIndices(dm, section, globalSection, point, PETSC_TRUE, &numIndices, &indices, NULL, (PetscScalar **)&values);
7592:     if (values != valuesOrig) DMRestoreWorkArray(dm, 0, MPIU_SCALAR, &values);
7593:     SETERRQ(PetscObjectComm((PetscObject)dm), ierr, "Not possible to set matrix values");
7594:   }
7595:   if (mesh->printFEM > 1) {
7596:     PetscInt i;
7597:     PetscPrintf(PETSC_COMM_SELF, "  Indices:");
7598:     for (i = 0; i < numIndices; ++i) PetscPrintf(PETSC_COMM_SELF, " %" PetscInt_FMT, indices[i]);
7599:     PetscPrintf(PETSC_COMM_SELF, "\n");
7600:   }

7602:   DMPlexRestoreClosureIndices(dm, section, globalSection, point, PETSC_TRUE, &numIndices, &indices, NULL, (PetscScalar **)&values);
7603:   if (values != valuesOrig) DMRestoreWorkArray(dm, 0, MPIU_SCALAR, &values);
7604:   return 0;
7605: }

7607: /*@C
7608:   DMPlexMatSetClosure - Set an array of the values on the closure of 'point' using a different row and column section

7610:   Not collective

7612:   Input Parameters:
7613: + dmRow - The DM for the row fields
7614: . sectionRow - The section describing the layout, or NULL to use the default section in dmRow
7615: . globalSectionRow - The section describing the layout, or NULL to use the default global section in dmRow
7616: . dmCol - The DM for the column fields
7617: . sectionCol - The section describing the layout, or NULL to use the default section in dmCol
7618: . globalSectionCol - The section describing the layout, or NULL to use the default global section in dmCol
7619: . A - The matrix
7620: . point - The point in the DMs
7621: . values - The array of values
7622: - mode - The insert mode, where INSERT_ALL_VALUES and ADD_ALL_VALUES also overwrite boundary conditions

7624:   Level: intermediate

7626: .seealso `DMPlexMatSetClosure()`, `DMPlexVecGetClosure()`, `DMPlexVecSetClosure()`
7627: @*/
7628: PetscErrorCode DMPlexMatSetClosureGeneral(DM dmRow, PetscSection sectionRow, PetscSection globalSectionRow, DM dmCol, PetscSection sectionCol, PetscSection globalSectionCol, Mat A, PetscInt point, const PetscScalar values[], InsertMode mode)
7629: {
7630:   DM_Plex           *mesh = (DM_Plex *)dmRow->data;
7631:   PetscInt          *indicesRow, *indicesCol;
7632:   PetscInt           numIndicesRow, numIndicesCol;
7633:   const PetscScalar *valuesOrig = values;
7634:   PetscErrorCode     ierr;

7637:   if (!sectionRow) DMGetLocalSection(dmRow, &sectionRow);
7639:   if (!globalSectionRow) DMGetGlobalSection(dmRow, &globalSectionRow);
7642:   if (!sectionCol) DMGetLocalSection(dmCol, &sectionCol);
7644:   if (!globalSectionCol) DMGetGlobalSection(dmCol, &globalSectionCol);

7648:   DMPlexGetClosureIndices(dmRow, sectionRow, globalSectionRow, point, PETSC_TRUE, &numIndicesRow, &indicesRow, NULL, (PetscScalar **)&values);
7649:   DMPlexGetClosureIndices(dmCol, sectionCol, globalSectionCol, point, PETSC_TRUE, &numIndicesCol, &indicesCol, NULL, (PetscScalar **)&values);

7651:   if (mesh->printSetValues) DMPlexPrintMatSetValues(PETSC_VIEWER_STDOUT_SELF, A, point, numIndicesRow, indicesRow, numIndicesCol, indicesCol, values);
7652:   /* TODO: fix this code to not use error codes as handle-able exceptions! */
7653:   MatSetValues(A, numIndicesRow, indicesRow, numIndicesCol, indicesCol, values, mode);
7654:   if (ierr) {
7655:     PetscMPIInt rank;

7657:     MPI_Comm_rank(PetscObjectComm((PetscObject)A), &rank);
7658:     (*PetscErrorPrintf)("[%d]ERROR in DMPlexMatSetClosure\n", rank);
7659:     DMPlexPrintMatSetValues(PETSC_VIEWER_STDERR_SELF, A, point, numIndicesRow, indicesRow, numIndicesCol, indicesCol, values);
7660:     DMPlexRestoreClosureIndices(dmRow, sectionRow, globalSectionRow, point, PETSC_TRUE, &numIndicesRow, &indicesRow, NULL, (PetscScalar **)&values);
7661:     DMPlexRestoreClosureIndices(dmCol, sectionCol, globalSectionCol, point, PETSC_TRUE, &numIndicesCol, &indicesRow, NULL, (PetscScalar **)&values);
7662:     if (values != valuesOrig) DMRestoreWorkArray(dmRow, 0, MPIU_SCALAR, &values);
7663:   }

7665:   DMPlexRestoreClosureIndices(dmRow, sectionRow, globalSectionRow, point, PETSC_TRUE, &numIndicesRow, &indicesRow, NULL, (PetscScalar **)&values);
7666:   DMPlexRestoreClosureIndices(dmCol, sectionCol, globalSectionCol, point, PETSC_TRUE, &numIndicesCol, &indicesCol, NULL, (PetscScalar **)&values);
7667:   if (values != valuesOrig) DMRestoreWorkArray(dmRow, 0, MPIU_SCALAR, &values);
7668:   return 0;
7669: }

7671: PetscErrorCode DMPlexMatSetClosureRefined(DM dmf, PetscSection fsection, PetscSection globalFSection, DM dmc, PetscSection csection, PetscSection globalCSection, Mat A, PetscInt point, const PetscScalar values[], InsertMode mode)
7672: {
7673:   DM_Plex        *mesh    = (DM_Plex *)dmf->data;
7674:   PetscInt       *fpoints = NULL, *ftotpoints = NULL;
7675:   PetscInt       *cpoints = NULL;
7676:   PetscInt       *findices, *cindices;
7677:   const PetscInt *fclperm = NULL, *cclperm = NULL; /* Closure permutations cannot work here */
7678:   PetscInt        foffsets[32], coffsets[32];
7679:   DMPolytopeType  ct;
7680:   PetscInt        numFields, numSubcells, maxFPoints, numFPoints, numCPoints, numFIndices, numCIndices, dof, off, globalOff, pStart, pEnd, p, q, r, s, f;
7681:   PetscErrorCode  ierr;

7685:   if (!fsection) DMGetLocalSection(dmf, &fsection);
7687:   if (!csection) DMGetLocalSection(dmc, &csection);
7689:   if (!globalFSection) DMGetGlobalSection(dmf, &globalFSection);
7691:   if (!globalCSection) DMGetGlobalSection(dmc, &globalCSection);
7694:   PetscSectionGetNumFields(fsection, &numFields);
7696:   PetscArrayzero(foffsets, 32);
7697:   PetscArrayzero(coffsets, 32);
7698:   /* Column indices */
7699:   DMPlexGetTransitiveClosure(dmc, point, PETSC_TRUE, &numCPoints, &cpoints);
7700:   maxFPoints = numCPoints;
7701:   /* Compress out points not in the section */
7702:   /*   TODO: Squeeze out points with 0 dof as well */
7703:   PetscSectionGetChart(csection, &pStart, &pEnd);
7704:   for (p = 0, q = 0; p < numCPoints * 2; p += 2) {
7705:     if ((cpoints[p] >= pStart) && (cpoints[p] < pEnd)) {
7706:       cpoints[q * 2]     = cpoints[p];
7707:       cpoints[q * 2 + 1] = cpoints[p + 1];
7708:       ++q;
7709:     }
7710:   }
7711:   numCPoints = q;
7712:   for (p = 0, numCIndices = 0; p < numCPoints * 2; p += 2) {
7713:     PetscInt fdof;

7715:     PetscSectionGetDof(csection, cpoints[p], &dof);
7716:     if (!dof) continue;
7717:     for (f = 0; f < numFields; ++f) {
7718:       PetscSectionGetFieldDof(csection, cpoints[p], f, &fdof);
7719:       coffsets[f + 1] += fdof;
7720:     }
7721:     numCIndices += dof;
7722:   }
7723:   for (f = 1; f < numFields; ++f) coffsets[f + 1] += coffsets[f];
7724:   /* Row indices */
7725:   DMPlexGetCellType(dmc, point, &ct);
7726:   {
7727:     DMPlexTransform tr;
7728:     DMPolytopeType *rct;
7729:     PetscInt       *rsize, *rcone, *rornt, Nt;

7731:     DMPlexTransformCreate(PETSC_COMM_SELF, &tr);
7732:     DMPlexTransformSetType(tr, DMPLEXREFINEREGULAR);
7733:     DMPlexTransformCellTransform(tr, ct, point, NULL, &Nt, &rct, &rsize, &rcone, &rornt);
7734:     numSubcells = rsize[Nt - 1];
7735:     DMPlexTransformDestroy(&tr);
7736:   }
7737:   DMGetWorkArray(dmf, maxFPoints * 2 * numSubcells, MPIU_INT, &ftotpoints);
7738:   for (r = 0, q = 0; r < numSubcells; ++r) {
7739:     /* TODO Map from coarse to fine cells */
7740:     DMPlexGetTransitiveClosure(dmf, point * numSubcells + r, PETSC_TRUE, &numFPoints, &fpoints);
7741:     /* Compress out points not in the section */
7742:     PetscSectionGetChart(fsection, &pStart, &pEnd);
7743:     for (p = 0; p < numFPoints * 2; p += 2) {
7744:       if ((fpoints[p] >= pStart) && (fpoints[p] < pEnd)) {
7745:         PetscSectionGetDof(fsection, fpoints[p], &dof);
7746:         if (!dof) continue;
7747:         for (s = 0; s < q; ++s)
7748:           if (fpoints[p] == ftotpoints[s * 2]) break;
7749:         if (s < q) continue;
7750:         ftotpoints[q * 2]     = fpoints[p];
7751:         ftotpoints[q * 2 + 1] = fpoints[p + 1];
7752:         ++q;
7753:       }
7754:     }
7755:     DMPlexRestoreTransitiveClosure(dmf, point, PETSC_TRUE, &numFPoints, &fpoints);
7756:   }
7757:   numFPoints = q;
7758:   for (p = 0, numFIndices = 0; p < numFPoints * 2; p += 2) {
7759:     PetscInt fdof;

7761:     PetscSectionGetDof(fsection, ftotpoints[p], &dof);
7762:     if (!dof) continue;
7763:     for (f = 0; f < numFields; ++f) {
7764:       PetscSectionGetFieldDof(fsection, ftotpoints[p], f, &fdof);
7765:       foffsets[f + 1] += fdof;
7766:     }
7767:     numFIndices += dof;
7768:   }
7769:   for (f = 1; f < numFields; ++f) foffsets[f + 1] += foffsets[f];

7773:   DMGetWorkArray(dmf, numFIndices, MPIU_INT, &findices);
7774:   DMGetWorkArray(dmc, numCIndices, MPIU_INT, &cindices);
7775:   if (numFields) {
7776:     const PetscInt **permsF[32] = {NULL};
7777:     const PetscInt **permsC[32] = {NULL};

7779:     for (f = 0; f < numFields; f++) {
7780:       PetscSectionGetFieldPointSyms(fsection, f, numFPoints, ftotpoints, &permsF[f], NULL);
7781:       PetscSectionGetFieldPointSyms(csection, f, numCPoints, cpoints, &permsC[f], NULL);
7782:     }
7783:     for (p = 0; p < numFPoints; p++) {
7784:       PetscSectionGetOffset(globalFSection, ftotpoints[2 * p], &globalOff);
7785:       DMPlexGetIndicesPointFields_Internal(fsection, PETSC_FALSE, ftotpoints[2 * p], globalOff < 0 ? -(globalOff + 1) : globalOff, foffsets, PETSC_FALSE, permsF, p, fclperm, findices);
7786:     }
7787:     for (p = 0; p < numCPoints; p++) {
7788:       PetscSectionGetOffset(globalCSection, cpoints[2 * p], &globalOff);
7789:       DMPlexGetIndicesPointFields_Internal(csection, PETSC_FALSE, cpoints[2 * p], globalOff < 0 ? -(globalOff + 1) : globalOff, coffsets, PETSC_FALSE, permsC, p, cclperm, cindices);
7790:     }
7791:     for (f = 0; f < numFields; f++) {
7792:       PetscSectionRestoreFieldPointSyms(fsection, f, numFPoints, ftotpoints, &permsF[f], NULL);
7793:       PetscSectionRestoreFieldPointSyms(csection, f, numCPoints, cpoints, &permsC[f], NULL);
7794:     }
7795:   } else {
7796:     const PetscInt **permsF = NULL;
7797:     const PetscInt **permsC = NULL;

7799:     PetscSectionGetPointSyms(fsection, numFPoints, ftotpoints, &permsF, NULL);
7800:     PetscSectionGetPointSyms(csection, numCPoints, cpoints, &permsC, NULL);
7801:     for (p = 0, off = 0; p < numFPoints; p++) {
7802:       const PetscInt *perm = permsF ? permsF[p] : NULL;

7804:       PetscSectionGetOffset(globalFSection, ftotpoints[2 * p], &globalOff);
7805:       DMPlexGetIndicesPoint_Internal(fsection, PETSC_FALSE, ftotpoints[2 * p], globalOff < 0 ? -(globalOff + 1) : globalOff, &off, PETSC_FALSE, perm, fclperm, findices);
7806:     }
7807:     for (p = 0, off = 0; p < numCPoints; p++) {
7808:       const PetscInt *perm = permsC ? permsC[p] : NULL;

7810:       PetscSectionGetOffset(globalCSection, cpoints[2 * p], &globalOff);
7811:       DMPlexGetIndicesPoint_Internal(csection, PETSC_FALSE, cpoints[2 * p], globalOff < 0 ? -(globalOff + 1) : globalOff, &off, PETSC_FALSE, perm, cclperm, cindices);
7812:     }
7813:     PetscSectionRestorePointSyms(fsection, numFPoints, ftotpoints, &permsF, NULL);
7814:     PetscSectionRestorePointSyms(csection, numCPoints, cpoints, &permsC, NULL);
7815:   }
7816:   if (mesh->printSetValues) DMPlexPrintMatSetValues(PETSC_VIEWER_STDOUT_SELF, A, point, numFIndices, findices, numCIndices, cindices, values);
7817:   /* TODO: flips */
7818:   /* TODO: fix this code to not use error codes as handle-able exceptions! */
7819:   MatSetValues(A, numFIndices, findices, numCIndices, cindices, values, mode);
7820:   if (ierr) {
7821:     PetscMPIInt rank;

7823:     MPI_Comm_rank(PetscObjectComm((PetscObject)A), &rank);
7824:     (*PetscErrorPrintf)("[%d]ERROR in DMPlexMatSetClosure\n", rank);
7825:     DMPlexPrintMatSetValues(PETSC_VIEWER_STDERR_SELF, A, point, numFIndices, findices, numCIndices, cindices, values);
7826:     DMRestoreWorkArray(dmf, numFIndices, MPIU_INT, &findices);
7827:     DMRestoreWorkArray(dmc, numCIndices, MPIU_INT, &cindices);
7828:   }
7829:   DMRestoreWorkArray(dmf, numCPoints * 2 * 4, MPIU_INT, &ftotpoints);
7830:   DMPlexRestoreTransitiveClosure(dmc, point, PETSC_TRUE, &numCPoints, &cpoints);
7831:   DMRestoreWorkArray(dmf, numFIndices, MPIU_INT, &findices);
7832:   DMRestoreWorkArray(dmc, numCIndices, MPIU_INT, &cindices);
7833:   return 0;
7834: }

7836: PetscErrorCode DMPlexMatGetClosureIndicesRefined(DM dmf, PetscSection fsection, PetscSection globalFSection, DM dmc, PetscSection csection, PetscSection globalCSection, PetscInt point, PetscInt cindices[], PetscInt findices[])
7837: {
7838:   PetscInt       *fpoints = NULL, *ftotpoints = NULL;
7839:   PetscInt       *cpoints = NULL;
7840:   PetscInt        foffsets[32], coffsets[32];
7841:   const PetscInt *fclperm = NULL, *cclperm = NULL; /* Closure permutations cannot work here */
7842:   DMPolytopeType  ct;
7843:   PetscInt        numFields, numSubcells, maxFPoints, numFPoints, numCPoints, numFIndices, numCIndices, dof, off, globalOff, pStart, pEnd, p, q, r, s, f;

7847:   if (!fsection) DMGetLocalSection(dmf, &fsection);
7849:   if (!csection) DMGetLocalSection(dmc, &csection);
7851:   if (!globalFSection) DMGetGlobalSection(dmf, &globalFSection);
7853:   if (!globalCSection) DMGetGlobalSection(dmc, &globalCSection);
7855:   PetscSectionGetNumFields(fsection, &numFields);
7857:   PetscArrayzero(foffsets, 32);
7858:   PetscArrayzero(coffsets, 32);
7859:   /* Column indices */
7860:   DMPlexGetTransitiveClosure(dmc, point, PETSC_TRUE, &numCPoints, &cpoints);
7861:   maxFPoints = numCPoints;
7862:   /* Compress out points not in the section */
7863:   /*   TODO: Squeeze out points with 0 dof as well */
7864:   PetscSectionGetChart(csection, &pStart, &pEnd);
7865:   for (p = 0, q = 0; p < numCPoints * 2; p += 2) {
7866:     if ((cpoints[p] >= pStart) && (cpoints[p] < pEnd)) {
7867:       cpoints[q * 2]     = cpoints[p];
7868:       cpoints[q * 2 + 1] = cpoints[p + 1];
7869:       ++q;
7870:     }
7871:   }
7872:   numCPoints = q;
7873:   for (p = 0, numCIndices = 0; p < numCPoints * 2; p += 2) {
7874:     PetscInt fdof;

7876:     PetscSectionGetDof(csection, cpoints[p], &dof);
7877:     if (!dof) continue;
7878:     for (f = 0; f < numFields; ++f) {
7879:       PetscSectionGetFieldDof(csection, cpoints[p], f, &fdof);
7880:       coffsets[f + 1] += fdof;
7881:     }
7882:     numCIndices += dof;
7883:   }
7884:   for (f = 1; f < numFields; ++f) coffsets[f + 1] += coffsets[f];
7885:   /* Row indices */
7886:   DMPlexGetCellType(dmc, point, &ct);
7887:   {
7888:     DMPlexTransform tr;
7889:     DMPolytopeType *rct;
7890:     PetscInt       *rsize, *rcone, *rornt, Nt;

7892:     DMPlexTransformCreate(PETSC_COMM_SELF, &tr);
7893:     DMPlexTransformSetType(tr, DMPLEXREFINEREGULAR);
7894:     DMPlexTransformCellTransform(tr, ct, point, NULL, &Nt, &rct, &rsize, &rcone, &rornt);
7895:     numSubcells = rsize[Nt - 1];
7896:     DMPlexTransformDestroy(&tr);
7897:   }
7898:   DMGetWorkArray(dmf, maxFPoints * 2 * numSubcells, MPIU_INT, &ftotpoints);
7899:   for (r = 0, q = 0; r < numSubcells; ++r) {
7900:     /* TODO Map from coarse to fine cells */
7901:     DMPlexGetTransitiveClosure(dmf, point * numSubcells + r, PETSC_TRUE, &numFPoints, &fpoints);
7902:     /* Compress out points not in the section */
7903:     PetscSectionGetChart(fsection, &pStart, &pEnd);
7904:     for (p = 0; p < numFPoints * 2; p += 2) {
7905:       if ((fpoints[p] >= pStart) && (fpoints[p] < pEnd)) {
7906:         PetscSectionGetDof(fsection, fpoints[p], &dof);
7907:         if (!dof) continue;
7908:         for (s = 0; s < q; ++s)
7909:           if (fpoints[p] == ftotpoints[s * 2]) break;
7910:         if (s < q) continue;
7911:         ftotpoints[q * 2]     = fpoints[p];
7912:         ftotpoints[q * 2 + 1] = fpoints[p + 1];
7913:         ++q;
7914:       }
7915:     }
7916:     DMPlexRestoreTransitiveClosure(dmf, point, PETSC_TRUE, &numFPoints, &fpoints);
7917:   }
7918:   numFPoints = q;
7919:   for (p = 0, numFIndices = 0; p < numFPoints * 2; p += 2) {
7920:     PetscInt fdof;

7922:     PetscSectionGetDof(fsection, ftotpoints[p], &dof);
7923:     if (!dof) continue;
7924:     for (f = 0; f < numFields; ++f) {
7925:       PetscSectionGetFieldDof(fsection, ftotpoints[p], f, &fdof);
7926:       foffsets[f + 1] += fdof;
7927:     }
7928:     numFIndices += dof;
7929:   }
7930:   for (f = 1; f < numFields; ++f) foffsets[f + 1] += foffsets[f];

7934:   if (numFields) {
7935:     const PetscInt **permsF[32] = {NULL};
7936:     const PetscInt **permsC[32] = {NULL};

7938:     for (f = 0; f < numFields; f++) {
7939:       PetscSectionGetFieldPointSyms(fsection, f, numFPoints, ftotpoints, &permsF[f], NULL);
7940:       PetscSectionGetFieldPointSyms(csection, f, numCPoints, cpoints, &permsC[f], NULL);
7941:     }
7942:     for (p = 0; p < numFPoints; p++) {
7943:       PetscSectionGetOffset(globalFSection, ftotpoints[2 * p], &globalOff);
7944:       DMPlexGetIndicesPointFields_Internal(fsection, PETSC_FALSE, ftotpoints[2 * p], globalOff < 0 ? -(globalOff + 1) : globalOff, foffsets, PETSC_FALSE, permsF, p, fclperm, findices);
7945:     }
7946:     for (p = 0; p < numCPoints; p++) {
7947:       PetscSectionGetOffset(globalCSection, cpoints[2 * p], &globalOff);
7948:       DMPlexGetIndicesPointFields_Internal(csection, PETSC_FALSE, cpoints[2 * p], globalOff < 0 ? -(globalOff + 1) : globalOff, coffsets, PETSC_FALSE, permsC, p, cclperm, cindices);
7949:     }
7950:     for (f = 0; f < numFields; f++) {
7951:       PetscSectionRestoreFieldPointSyms(fsection, f, numFPoints, ftotpoints, &permsF[f], NULL);
7952:       PetscSectionRestoreFieldPointSyms(csection, f, numCPoints, cpoints, &permsC[f], NULL);
7953:     }
7954:   } else {
7955:     const PetscInt **permsF = NULL;
7956:     const PetscInt **permsC = NULL;

7958:     PetscSectionGetPointSyms(fsection, numFPoints, ftotpoints, &permsF, NULL);
7959:     PetscSectionGetPointSyms(csection, numCPoints, cpoints, &permsC, NULL);
7960:     for (p = 0, off = 0; p < numFPoints; p++) {
7961:       const PetscInt *perm = permsF ? permsF[p] : NULL;

7963:       PetscSectionGetOffset(globalFSection, ftotpoints[2 * p], &globalOff);
7964:       DMPlexGetIndicesPoint_Internal(fsection, PETSC_FALSE, ftotpoints[2 * p], globalOff < 0 ? -(globalOff + 1) : globalOff, &off, PETSC_FALSE, perm, fclperm, findices);
7965:     }
7966:     for (p = 0, off = 0; p < numCPoints; p++) {
7967:       const PetscInt *perm = permsC ? permsC[p] : NULL;

7969:       PetscSectionGetOffset(globalCSection, cpoints[2 * p], &globalOff);
7970:       DMPlexGetIndicesPoint_Internal(csection, PETSC_FALSE, cpoints[2 * p], globalOff < 0 ? -(globalOff + 1) : globalOff, &off, PETSC_FALSE, perm, cclperm, cindices);
7971:     }
7972:     PetscSectionRestorePointSyms(fsection, numFPoints, ftotpoints, &permsF, NULL);
7973:     PetscSectionRestorePointSyms(csection, numCPoints, cpoints, &permsC, NULL);
7974:   }
7975:   DMRestoreWorkArray(dmf, numCPoints * 2 * 4, MPIU_INT, &ftotpoints);
7976:   DMPlexRestoreTransitiveClosure(dmc, point, PETSC_TRUE, &numCPoints, &cpoints);
7977:   return 0;
7978: }

7980: /*@C
7981:   DMPlexGetVTKCellHeight - Returns the height in the DAG used to determine which points are cells (normally 0)

7983:   Input Parameter:
7984: . dm   - The DMPlex object

7986:   Output Parameter:
7987: . cellHeight - The height of a cell

7989:   Level: developer

7991: .seealso `DMPlexSetVTKCellHeight()`
7992: @*/
7993: PetscErrorCode DMPlexGetVTKCellHeight(DM dm, PetscInt *cellHeight)
7994: {
7995:   DM_Plex *mesh = (DM_Plex *)dm->data;

7999:   *cellHeight = mesh->vtkCellHeight;
8000:   return 0;
8001: }

8003: /*@C
8004:   DMPlexSetVTKCellHeight - Sets the height in the DAG used to determine which points are cells (normally 0)

8006:   Input Parameters:
8007: + dm   - The DMPlex object
8008: - cellHeight - The height of a cell

8010:   Level: developer

8012: .seealso `DMPlexGetVTKCellHeight()`
8013: @*/
8014: PetscErrorCode DMPlexSetVTKCellHeight(DM dm, PetscInt cellHeight)
8015: {
8016:   DM_Plex *mesh = (DM_Plex *)dm->data;

8019:   mesh->vtkCellHeight = cellHeight;
8020:   return 0;
8021: }

8023: /*@
8024:   DMPlexGetGhostCellStratum - Get the range of cells which are used to enforce FV boundary conditions

8026:   Input Parameter:
8027: . dm - The DMPlex object

8029:   Output Parameters:
8030: + gcStart - The first ghost cell, or NULL
8031: - gcEnd   - The upper bound on ghost cells, or NULL

8033:   Level: advanced

8035: .seealso `DMPlexConstructGhostCells()`, `DMPlexGetGhostCellStratum()`
8036: @*/
8037: PetscErrorCode DMPlexGetGhostCellStratum(DM dm, PetscInt *gcStart, PetscInt *gcEnd)
8038: {
8039:   DMLabel ctLabel;

8042:   DMPlexGetCellTypeLabel(dm, &ctLabel);
8043:   DMLabelGetStratumBounds(ctLabel, DM_POLYTOPE_FV_GHOST, gcStart, gcEnd);
8044:   // Reset label for fast lookup
8045:   DMLabelMakeAllInvalid_Internal(ctLabel);
8046:   return 0;
8047: }

8049: PetscErrorCode DMPlexCreateNumbering_Plex(DM dm, PetscInt pStart, PetscInt pEnd, PetscInt shift, PetscInt *globalSize, PetscSF sf, IS *numbering)
8050: {
8051:   PetscSection section, globalSection;
8052:   PetscInt    *numbers, p;

8054:   if (PetscDefined(USE_DEBUG)) DMPlexCheckPointSF(dm, sf, PETSC_TRUE);
8055:   PetscSectionCreate(PetscObjectComm((PetscObject)dm), &section);
8056:   PetscSectionSetChart(section, pStart, pEnd);
8057:   for (p = pStart; p < pEnd; ++p) PetscSectionSetDof(section, p, 1);
8058:   PetscSectionSetUp(section);
8059:   PetscSectionCreateGlobalSection(section, sf, PETSC_FALSE, PETSC_FALSE, &globalSection);
8060:   PetscMalloc1(pEnd - pStart, &numbers);
8061:   for (p = pStart; p < pEnd; ++p) {
8062:     PetscSectionGetOffset(globalSection, p, &numbers[p - pStart]);
8063:     if (numbers[p - pStart] < 0) numbers[p - pStart] -= shift;
8064:     else numbers[p - pStart] += shift;
8065:   }
8066:   ISCreateGeneral(PetscObjectComm((PetscObject)dm), pEnd - pStart, numbers, PETSC_OWN_POINTER, numbering);
8067:   if (globalSize) {
8068:     PetscLayout layout;
8069:     PetscSectionGetPointLayout(PetscObjectComm((PetscObject)dm), globalSection, &layout);
8070:     PetscLayoutGetSize(layout, globalSize);
8071:     PetscLayoutDestroy(&layout);
8072:   }
8073:   PetscSectionDestroy(&section);
8074:   PetscSectionDestroy(&globalSection);
8075:   return 0;
8076: }

8078: PetscErrorCode DMPlexCreateCellNumbering_Internal(DM dm, PetscBool includeHybrid, IS *globalCellNumbers)
8079: {
8080:   PetscInt cellHeight, cStart, cEnd;

8082:   DMPlexGetVTKCellHeight(dm, &cellHeight);
8083:   if (includeHybrid) DMPlexGetHeightStratum(dm, cellHeight, &cStart, &cEnd);
8084:   else DMPlexGetSimplexOrBoxCells(dm, cellHeight, &cStart, &cEnd);
8085:   DMPlexCreateNumbering_Plex(dm, cStart, cEnd, 0, NULL, dm->sf, globalCellNumbers);
8086:   return 0;
8087: }

8089: /*@
8090:   DMPlexGetCellNumbering - Get a global cell numbering for all cells on this process

8092:   Input Parameter:
8093: . dm   - The DMPlex object

8095:   Output Parameter:
8096: . globalCellNumbers - Global cell numbers for all cells on this process

8098:   Level: developer

8100: .seealso `DMPlexGetVertexNumbering()`
8101: @*/
8102: PetscErrorCode DMPlexGetCellNumbering(DM dm, IS *globalCellNumbers)
8103: {
8104:   DM_Plex *mesh = (DM_Plex *)dm->data;

8107:   if (!mesh->globalCellNumbers) DMPlexCreateCellNumbering_Internal(dm, PETSC_FALSE, &mesh->globalCellNumbers);
8108:   *globalCellNumbers = mesh->globalCellNumbers;
8109:   return 0;
8110: }

8112: PetscErrorCode DMPlexCreateVertexNumbering_Internal(DM dm, PetscBool includeHybrid, IS *globalVertexNumbers)
8113: {
8114:   PetscInt vStart, vEnd;

8117:   DMPlexGetDepthStratum(dm, 0, &vStart, &vEnd);
8118:   DMPlexCreateNumbering_Plex(dm, vStart, vEnd, 0, NULL, dm->sf, globalVertexNumbers);
8119:   return 0;
8120: }

8122: /*@
8123:   DMPlexGetVertexNumbering - Get a global vertex numbering for all vertices on this process

8125:   Input Parameter:
8126: . dm   - The DMPlex object

8128:   Output Parameter:
8129: . globalVertexNumbers - Global vertex numbers for all vertices on this process

8131:   Level: developer

8133: .seealso `DMPlexGetCellNumbering()`
8134: @*/
8135: PetscErrorCode DMPlexGetVertexNumbering(DM dm, IS *globalVertexNumbers)
8136: {
8137:   DM_Plex *mesh = (DM_Plex *)dm->data;

8140:   if (!mesh->globalVertexNumbers) DMPlexCreateVertexNumbering_Internal(dm, PETSC_FALSE, &mesh->globalVertexNumbers);
8141:   *globalVertexNumbers = mesh->globalVertexNumbers;
8142:   return 0;
8143: }

8145: /*@
8146:   DMPlexCreatePointNumbering - Create a global numbering for all points.

8148:   Collective on dm

8150:   Input Parameter:
8151: . dm   - The DMPlex object

8153:   Output Parameter:
8154: . globalPointNumbers - Global numbers for all points on this process

8156:   Notes:

8158:   The point numbering IS is parallel, with local portion indexed by local points (see `DMGetLocalSection()`). The global
8159:   points are taken as stratified, with each MPI rank owning a contiguous subset of each stratum. In the IS, owned points
8160:   will have their non-negative value while points owned by different ranks will be involuted -(idx+1). As an example,
8161:   consider a parallel mesh in which the first two elements and first two vertices are owned by rank 0.

8163:   The partitioned mesh is
8164: ```
8165:  (2)--0--(3)--1--(4)    (1)--0--(2)
8166: ```
8167:   and its global numbering is
8168: ```
8169:   (3)--0--(4)--1--(5)--2--(6)
8170: ```
8171:   Then the global numbering is provided as
8172: ```
8173: [0] Number of indices in set 5
8174: [0] 0 0
8175: [0] 1 1
8176: [0] 2 3
8177: [0] 3 4
8178: [0] 4 -6
8179: [1] Number of indices in set 3
8180: [1] 0 2
8181: [1] 1 5
8182: [1] 2 6
8183: ```

8185:   Level: developer

8187: .seealso `DMPlexGetCellNumbering()`
8188: @*/
8189: PetscErrorCode DMPlexCreatePointNumbering(DM dm, IS *globalPointNumbers)
8190: {
8191:   IS        nums[4];
8192:   PetscInt  depths[4], gdepths[4], starts[4];
8193:   PetscInt  depth, d, shift = 0;
8194:   PetscBool empty = PETSC_FALSE;

8197:   DMPlexGetDepth(dm, &depth);
8198:   // For unstratified meshes use dim instead of depth
8199:   if (depth < 0) DMGetDimension(dm, &depth);
8200:   // If any stratum is empty, we must mark all empty
8201:   for (d = 0; d <= depth; ++d) {
8202:     PetscInt end;

8204:     depths[d] = depth - d;
8205:     DMPlexGetDepthStratum(dm, depths[d], &starts[d], &end);
8206:     if (!(starts[d] - end)) empty = PETSC_TRUE;
8207:   }
8208:   if (empty)
8209:     for (d = 0; d <= depth; ++d) {
8210:       depths[d] = -1;
8211:       starts[d] = -1;
8212:     }
8213:   else PetscSortIntWithArray(depth + 1, starts, depths);
8214:   MPIU_Allreduce(depths, gdepths, depth + 1, MPIU_INT, MPI_MAX, PetscObjectComm((PetscObject)dm));
8216:   // Note here that 'shift' is collective, so that the numbering is stratified by depth
8217:   for (d = 0; d <= depth; ++d) {
8218:     PetscInt pStart, pEnd, gsize;

8220:     DMPlexGetDepthStratum(dm, gdepths[d], &pStart, &pEnd);
8221:     DMPlexCreateNumbering_Plex(dm, pStart, pEnd, shift, &gsize, dm->sf, &nums[d]);
8222:     shift += gsize;
8223:   }
8224:   ISConcatenate(PetscObjectComm((PetscObject)dm), depth + 1, nums, globalPointNumbers);
8225:   for (d = 0; d <= depth; ++d) ISDestroy(&nums[d]);
8226:   return 0;
8227: }

8229: /*@
8230:   DMPlexCreateRankField - Create a cell field whose value is the rank of the owner

8232:   Input Parameter:
8233: . dm - The DMPlex object

8235:   Output Parameter:
8236: . ranks - The rank field

8238:   Options Database Keys:
8239: . -dm_partition_view - Adds the rank field into the DM output from -dm_view using the same viewer

8241:   Level: intermediate

8243: .seealso: `DMView()`
8244: @*/
8245: PetscErrorCode DMPlexCreateRankField(DM dm, Vec *ranks)
8246: {
8247:   DM             rdm;
8248:   PetscFE        fe;
8249:   PetscScalar   *r;
8250:   PetscMPIInt    rank;
8251:   DMPolytopeType ct;
8252:   PetscInt       dim, cStart, cEnd, c;
8253:   PetscBool      simplex;

8258:   MPI_Comm_rank(PetscObjectComm((PetscObject)dm), &rank);
8259:   DMClone(dm, &rdm);
8260:   DMGetDimension(rdm, &dim);
8261:   DMPlexGetHeightStratum(rdm, 0, &cStart, &cEnd);
8262:   DMPlexGetCellType(dm, cStart, &ct);
8263:   simplex = DMPolytopeTypeGetNumVertices(ct) == DMPolytopeTypeGetDim(ct) + 1 ? PETSC_TRUE : PETSC_FALSE;
8264:   PetscFECreateDefault(PETSC_COMM_SELF, dim, 1, simplex, "PETSc___rank_", -1, &fe);
8265:   PetscObjectSetName((PetscObject)fe, "rank");
8266:   DMSetField(rdm, 0, NULL, (PetscObject)fe);
8267:   PetscFEDestroy(&fe);
8268:   DMCreateDS(rdm);
8269:   DMCreateGlobalVector(rdm, ranks);
8270:   PetscObjectSetName((PetscObject)*ranks, "partition");
8271:   VecGetArray(*ranks, &r);
8272:   for (c = cStart; c < cEnd; ++c) {
8273:     PetscScalar *lr;

8275:     DMPlexPointGlobalRef(rdm, c, r, &lr);
8276:     if (lr) *lr = rank;
8277:   }
8278:   VecRestoreArray(*ranks, &r);
8279:   DMDestroy(&rdm);
8280:   return 0;
8281: }

8283: /*@
8284:   DMPlexCreateLabelField - Create a cell field whose value is the label value for that cell

8286:   Input Parameters:
8287: + dm    - The DMPlex
8288: - label - The DMLabel

8290:   Output Parameter:
8291: . val - The label value field

8293:   Options Database Keys:
8294: . -dm_label_view - Adds the label value field into the DM output from -dm_view using the same viewer

8296:   Level: intermediate

8298: .seealso: `DMView()`
8299: @*/
8300: PetscErrorCode DMPlexCreateLabelField(DM dm, DMLabel label, Vec *val)
8301: {
8302:   DM           rdm;
8303:   PetscFE      fe;
8304:   PetscScalar *v;
8305:   PetscInt     dim, cStart, cEnd, c;

8311:   DMClone(dm, &rdm);
8312:   DMGetDimension(rdm, &dim);
8313:   PetscFECreateDefault(PetscObjectComm((PetscObject)rdm), dim, 1, PETSC_TRUE, "PETSc___label_value_", -1, &fe);
8314:   PetscObjectSetName((PetscObject)fe, "label_value");
8315:   DMSetField(rdm, 0, NULL, (PetscObject)fe);
8316:   PetscFEDestroy(&fe);
8317:   DMCreateDS(rdm);
8318:   DMPlexGetHeightStratum(rdm, 0, &cStart, &cEnd);
8319:   DMCreateGlobalVector(rdm, val);
8320:   PetscObjectSetName((PetscObject)*val, "label_value");
8321:   VecGetArray(*val, &v);
8322:   for (c = cStart; c < cEnd; ++c) {
8323:     PetscScalar *lv;
8324:     PetscInt     cval;

8326:     DMPlexPointGlobalRef(rdm, c, v, &lv);
8327:     DMLabelGetValue(label, c, &cval);
8328:     *lv = cval;
8329:   }
8330:   VecRestoreArray(*val, &v);
8331:   DMDestroy(&rdm);
8332:   return 0;
8333: }

8335: /*@
8336:   DMPlexCheckSymmetry - Check that the adjacency information in the mesh is symmetric.

8338:   Input Parameter:
8339: . dm - The DMPlex object

8341:   Notes:
8342:   This is a useful diagnostic when creating meshes programmatically.

8344:   For the complete list of DMPlexCheck* functions, see DMSetFromOptions().

8346:   Level: developer

8348: .seealso: `DMCreate()`, `DMSetFromOptions()`
8349: @*/
8350: PetscErrorCode DMPlexCheckSymmetry(DM dm)
8351: {
8352:   PetscSection    coneSection, supportSection;
8353:   const PetscInt *cone, *support;
8354:   PetscInt        coneSize, c, supportSize, s;
8355:   PetscInt        pStart, pEnd, p, pp, csize, ssize;
8356:   PetscBool       storagecheck = PETSC_TRUE;

8359:   DMViewFromOptions(dm, NULL, "-sym_dm_view");
8360:   DMPlexGetConeSection(dm, &coneSection);
8361:   DMPlexGetSupportSection(dm, &supportSection);
8362:   /* Check that point p is found in the support of its cone points, and vice versa */
8363:   DMPlexGetChart(dm, &pStart, &pEnd);
8364:   for (p = pStart; p < pEnd; ++p) {
8365:     DMPlexGetConeSize(dm, p, &coneSize);
8366:     DMPlexGetCone(dm, p, &cone);
8367:     for (c = 0; c < coneSize; ++c) {
8368:       PetscBool dup = PETSC_FALSE;
8369:       PetscInt  d;
8370:       for (d = c - 1; d >= 0; --d) {
8371:         if (cone[c] == cone[d]) {
8372:           dup = PETSC_TRUE;
8373:           break;
8374:         }
8375:       }
8376:       DMPlexGetSupportSize(dm, cone[c], &supportSize);
8377:       DMPlexGetSupport(dm, cone[c], &support);
8378:       for (s = 0; s < supportSize; ++s) {
8379:         if (support[s] == p) break;
8380:       }
8381:       if ((s >= supportSize) || (dup && (support[s + 1] != p))) {
8382:         PetscPrintf(PETSC_COMM_SELF, "p: %" PetscInt_FMT " cone: ", p);
8383:         for (s = 0; s < coneSize; ++s) PetscPrintf(PETSC_COMM_SELF, "%" PetscInt_FMT ", ", cone[s]);
8384:         PetscPrintf(PETSC_COMM_SELF, "\n");
8385:         PetscPrintf(PETSC_COMM_SELF, "p: %" PetscInt_FMT " support: ", cone[c]);
8386:         for (s = 0; s < supportSize; ++s) PetscPrintf(PETSC_COMM_SELF, "%" PetscInt_FMT ", ", support[s]);
8387:         PetscPrintf(PETSC_COMM_SELF, "\n");
8389:         SETERRQ(PETSC_COMM_SELF, PETSC_ERR_PLIB, "Point %" PetscInt_FMT " not found in support of cone point %" PetscInt_FMT, p, cone[c]);
8390:       }
8391:     }
8392:     DMPlexGetTreeParent(dm, p, &pp, NULL);
8393:     if (p != pp) {
8394:       storagecheck = PETSC_FALSE;
8395:       continue;
8396:     }
8397:     DMPlexGetSupportSize(dm, p, &supportSize);
8398:     DMPlexGetSupport(dm, p, &support);
8399:     for (s = 0; s < supportSize; ++s) {
8400:       DMPlexGetConeSize(dm, support[s], &coneSize);
8401:       DMPlexGetCone(dm, support[s], &cone);
8402:       for (c = 0; c < coneSize; ++c) {
8403:         DMPlexGetTreeParent(dm, cone[c], &pp, NULL);
8404:         if (cone[c] != pp) {
8405:           c = 0;
8406:           break;
8407:         }
8408:         if (cone[c] == p) break;
8409:       }
8410:       if (c >= coneSize) {
8411:         PetscPrintf(PETSC_COMM_SELF, "p: %" PetscInt_FMT " support: ", p);
8412:         for (c = 0; c < supportSize; ++c) PetscPrintf(PETSC_COMM_SELF, "%" PetscInt_FMT ", ", support[c]);
8413:         PetscPrintf(PETSC_COMM_SELF, "\n");
8414:         PetscPrintf(PETSC_COMM_SELF, "p: %" PetscInt_FMT " cone: ", support[s]);
8415:         for (c = 0; c < coneSize; ++c) PetscPrintf(PETSC_COMM_SELF, "%" PetscInt_FMT ", ", cone[c]);
8416:         PetscPrintf(PETSC_COMM_SELF, "\n");
8417:         SETERRQ(PETSC_COMM_SELF, PETSC_ERR_PLIB, "Point %" PetscInt_FMT " not found in cone of support point %" PetscInt_FMT, p, support[s]);
8418:       }
8419:     }
8420:   }
8421:   if (storagecheck) {
8422:     PetscSectionGetStorageSize(coneSection, &csize);
8423:     PetscSectionGetStorageSize(supportSection, &ssize);
8425:   }
8426:   return 0;
8427: }

8429: /*
8430:   For submeshes with cohesive cells (see DMPlexConstructCohesiveCells()), we allow a special case where some of the boundary of a face (edges and vertices) are not duplicated. We call these special boundary points "unsplit", since the same edge or vertex appears in both copies of the face. These unsplit points throw off our counting, so we have to explicitly account for them here.
8431: */
8432: static PetscErrorCode DMPlexCellUnsplitVertices_Private(DM dm, PetscInt c, DMPolytopeType ct, PetscInt *unsplit)
8433: {
8434:   DMPolytopeType  cct;
8435:   PetscInt        ptpoints[4];
8436:   const PetscInt *cone, *ccone, *ptcone;
8437:   PetscInt        coneSize, cp, cconeSize, ccp, npt = 0, pt;

8439:   *unsplit = 0;
8440:   switch (ct) {
8441:   case DM_POLYTOPE_POINT_PRISM_TENSOR:
8442:     ptpoints[npt++] = c;
8443:     break;
8444:   case DM_POLYTOPE_SEG_PRISM_TENSOR:
8445:     DMPlexGetCone(dm, c, &cone);
8446:     DMPlexGetConeSize(dm, c, &coneSize);
8447:     for (cp = 0; cp < coneSize; ++cp) {
8448:       DMPlexGetCellType(dm, cone[cp], &cct);
8449:       if (cct == DM_POLYTOPE_POINT_PRISM_TENSOR) ptpoints[npt++] = cone[cp];
8450:     }
8451:     break;
8452:   case DM_POLYTOPE_TRI_PRISM_TENSOR:
8453:   case DM_POLYTOPE_QUAD_PRISM_TENSOR:
8454:     DMPlexGetCone(dm, c, &cone);
8455:     DMPlexGetConeSize(dm, c, &coneSize);
8456:     for (cp = 0; cp < coneSize; ++cp) {
8457:       DMPlexGetCone(dm, cone[cp], &ccone);
8458:       DMPlexGetConeSize(dm, cone[cp], &cconeSize);
8459:       for (ccp = 0; ccp < cconeSize; ++ccp) {
8460:         DMPlexGetCellType(dm, ccone[ccp], &cct);
8461:         if (cct == DM_POLYTOPE_POINT_PRISM_TENSOR) {
8462:           PetscInt p;
8463:           for (p = 0; p < npt; ++p)
8464:             if (ptpoints[p] == ccone[ccp]) break;
8465:           if (p == npt) ptpoints[npt++] = ccone[ccp];
8466:         }
8467:       }
8468:     }
8469:     break;
8470:   default:
8471:     break;
8472:   }
8473:   for (pt = 0; pt < npt; ++pt) {
8474:     DMPlexGetCone(dm, ptpoints[pt], &ptcone);
8475:     if (ptcone[0] == ptcone[1]) ++(*unsplit);
8476:   }
8477:   return 0;
8478: }

8480: /*@
8481:   DMPlexCheckSkeleton - Check that each cell has the correct number of vertices

8483:   Input Parameters:
8484: + dm - The DMPlex object
8485: - cellHeight - Normally 0

8487:   Notes:
8488:   This is a useful diagnostic when creating meshes programmatically.
8489:   Currently applicable only to homogeneous simplex or tensor meshes.

8491:   For the complete list of DMPlexCheck* functions, see DMSetFromOptions().

8493:   Level: developer

8495: .seealso: `DMCreate()`, `DMSetFromOptions()`
8496: @*/
8497: PetscErrorCode DMPlexCheckSkeleton(DM dm, PetscInt cellHeight)
8498: {
8499:   DMPlexInterpolatedFlag interp;
8500:   DMPolytopeType         ct;
8501:   PetscInt               vStart, vEnd, cStart, cEnd, c;

8504:   DMPlexIsInterpolated(dm, &interp);
8505:   DMPlexGetHeightStratum(dm, cellHeight, &cStart, &cEnd);
8506:   DMPlexGetDepthStratum(dm, 0, &vStart, &vEnd);
8507:   for (c = cStart; c < cEnd; ++c) {
8508:     PetscInt *closure = NULL;
8509:     PetscInt  coneSize, closureSize, cl, Nv = 0;

8511:     DMPlexGetCellType(dm, c, &ct);
8513:     if (ct == DM_POLYTOPE_UNKNOWN) continue;
8514:     if (interp == DMPLEX_INTERPOLATED_FULL) {
8515:       DMPlexGetConeSize(dm, c, &coneSize);
8517:     }
8518:     DMPlexGetTransitiveClosure(dm, c, PETSC_TRUE, &closureSize, &closure);
8519:     for (cl = 0; cl < closureSize * 2; cl += 2) {
8520:       const PetscInt p = closure[cl];
8521:       if ((p >= vStart) && (p < vEnd)) ++Nv;
8522:     }
8523:     DMPlexRestoreTransitiveClosure(dm, c, PETSC_TRUE, &closureSize, &closure);
8524:     /* Special Case: Tensor faces with identified vertices */
8525:     if (Nv < DMPolytopeTypeGetNumVertices(ct)) {
8526:       PetscInt unsplit;

8528:       DMPlexCellUnsplitVertices_Private(dm, c, ct, &unsplit);
8529:       if (Nv + unsplit == DMPolytopeTypeGetNumVertices(ct)) continue;
8530:     }
8532:   }
8533:   return 0;
8534: }

8536: /*@
8537:   DMPlexCheckFaces - Check that the faces of each cell give a vertex order this is consistent with what we expect from the cell type

8539:   Collective

8541:   Input Parameters:
8542: + dm - The DMPlex object
8543: - cellHeight - Normally 0

8545:   Notes:
8546:   This is a useful diagnostic when creating meshes programmatically.
8547:   This routine is only relevant for meshes that are fully interpolated across all ranks.
8548:   It will error out if a partially interpolated mesh is given on some rank.
8549:   It will do nothing for locally uninterpolated mesh (as there is nothing to check).

8551:   For the complete list of DMPlexCheck* functions, see DMSetFromOptions().

8553:   Level: developer

8555: .seealso: `DMCreate()`, `DMPlexGetVTKCellHeight()`, `DMSetFromOptions()`
8556: @*/
8557: PetscErrorCode DMPlexCheckFaces(DM dm, PetscInt cellHeight)
8558: {
8559:   PetscInt               dim, depth, vStart, vEnd, cStart, cEnd, c, h;
8560:   DMPlexInterpolatedFlag interpEnum;

8563:   DMPlexIsInterpolatedCollective(dm, &interpEnum);
8564:   if (interpEnum == DMPLEX_INTERPOLATED_NONE) return 0;
8565:   if (interpEnum != DMPLEX_INTERPOLATED_FULL) {
8566:     PetscPrintf(PetscObjectComm((PetscObject)dm), "DMPlexCheckFaces() warning: Mesh is only partially interpolated, this is currently not supported");
8567:     return 0;
8568:   }

8570:   DMGetDimension(dm, &dim);
8571:   DMPlexGetDepth(dm, &depth);
8572:   DMPlexGetDepthStratum(dm, 0, &vStart, &vEnd);
8573:   for (h = cellHeight; h < PetscMin(depth, dim); ++h) {
8574:     DMPlexGetHeightStratum(dm, h, &cStart, &cEnd);
8575:     for (c = cStart; c < cEnd; ++c) {
8576:       const PetscInt       *cone, *ornt, *faceSizes, *faces;
8577:       const DMPolytopeType *faceTypes;
8578:       DMPolytopeType        ct;
8579:       PetscInt              numFaces, coneSize, f;
8580:       PetscInt             *closure = NULL, closureSize, cl, numCorners = 0, fOff = 0, unsplit;

8582:       DMPlexGetCellType(dm, c, &ct);
8583:       DMPlexCellUnsplitVertices_Private(dm, c, ct, &unsplit);
8584:       if (unsplit) continue;
8585:       DMPlexGetConeSize(dm, c, &coneSize);
8586:       DMPlexGetCone(dm, c, &cone);
8587:       DMPlexGetConeOrientation(dm, c, &ornt);
8588:       DMPlexGetTransitiveClosure(dm, c, PETSC_TRUE, &closureSize, &closure);
8589:       for (cl = 0; cl < closureSize * 2; cl += 2) {
8590:         const PetscInt p = closure[cl];
8591:         if ((p >= vStart) && (p < vEnd)) closure[numCorners++] = p;
8592:       }
8593:       DMPlexGetRawFaces_Internal(dm, ct, closure, &numFaces, &faceTypes, &faceSizes, &faces);
8595:       for (f = 0; f < numFaces; ++f) {
8596:         DMPolytopeType fct;
8597:         PetscInt      *fclosure = NULL, fclosureSize, cl, fnumCorners = 0, v;

8599:         DMPlexGetCellType(dm, cone[f], &fct);
8600:         DMPlexGetTransitiveClosure_Internal(dm, cone[f], ornt[f], PETSC_TRUE, &fclosureSize, &fclosure);
8601:         for (cl = 0; cl < fclosureSize * 2; cl += 2) {
8602:           const PetscInt p = fclosure[cl];
8603:           if ((p >= vStart) && (p < vEnd)) fclosure[fnumCorners++] = p;
8604:         }
8606:         for (v = 0; v < fnumCorners; ++v) {
8607:           if (fclosure[v] != faces[fOff + v]) {
8608:             PetscInt v1;

8610:             PetscPrintf(PETSC_COMM_SELF, "face closure:");
8611:             for (v1 = 0; v1 < fnumCorners; ++v1) PetscPrintf(PETSC_COMM_SELF, " %" PetscInt_FMT, fclosure[v1]);
8612:             PetscPrintf(PETSC_COMM_SELF, "\ncell face:");
8613:             for (v1 = 0; v1 < fnumCorners; ++v1) PetscPrintf(PETSC_COMM_SELF, " %" PetscInt_FMT, faces[fOff + v1]);
8614:             PetscPrintf(PETSC_COMM_SELF, "\n");
8615:             SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Face %" PetscInt_FMT " of type %s (cone idx %" PetscInt_FMT ", ornt %" PetscInt_FMT ") of cell %" PetscInt_FMT " of type %s vertex %" PetscInt_FMT ", %" PetscInt_FMT " != %" PetscInt_FMT, cone[f], DMPolytopeTypes[fct], f, ornt[f], c, DMPolytopeTypes[ct], v, fclosure[v], faces[fOff + v]);
8616:           }
8617:         }
8618:         DMPlexRestoreTransitiveClosure(dm, cone[f], PETSC_TRUE, &fclosureSize, &fclosure);
8619:         fOff += faceSizes[f];
8620:       }
8621:       DMPlexRestoreRawFaces_Internal(dm, ct, closure, &numFaces, &faceTypes, &faceSizes, &faces);
8622:       DMPlexRestoreTransitiveClosure(dm, c, PETSC_TRUE, &closureSize, &closure);
8623:     }
8624:   }
8625:   return 0;
8626: }

8628: /*@
8629:   DMPlexCheckGeometry - Check the geometry of mesh cells

8631:   Input Parameter:
8632: . dm - The DMPlex object

8634:   Notes:
8635:   This is a useful diagnostic when creating meshes programmatically.

8637:   For the complete list of DMPlexCheck* functions, see DMSetFromOptions().

8639:   Level: developer

8641: .seealso: `DMCreate()`, `DMSetFromOptions()`
8642: @*/
8643: PetscErrorCode DMPlexCheckGeometry(DM dm)
8644: {
8645:   Vec       coordinates;
8646:   PetscReal detJ, J[9], refVol = 1.0;
8647:   PetscReal vol;
8648:   PetscInt  dim, depth, dE, d, cStart, cEnd, c;

8650:   DMGetDimension(dm, &dim);
8651:   DMGetCoordinateDim(dm, &dE);
8652:   if (dim != dE) return 0;
8653:   DMPlexGetDepth(dm, &depth);
8654:   for (d = 0; d < dim; ++d) refVol *= 2.0;
8655:   DMPlexGetHeightStratum(dm, 0, &cStart, &cEnd);
8656:   /* Make sure local coordinates are created, because that step is collective */
8657:   DMGetCoordinatesLocal(dm, &coordinates);
8658:   for (c = cStart; c < cEnd; ++c) {
8659:     DMPolytopeType ct;
8660:     PetscInt       unsplit;
8661:     PetscBool      ignoreZeroVol = PETSC_FALSE;

8663:     DMPlexGetCellType(dm, c, &ct);
8664:     switch (ct) {
8665:     case DM_POLYTOPE_SEG_PRISM_TENSOR:
8666:     case DM_POLYTOPE_TRI_PRISM_TENSOR:
8667:     case DM_POLYTOPE_QUAD_PRISM_TENSOR:
8668:       ignoreZeroVol = PETSC_TRUE;
8669:       break;
8670:     default:
8671:       break;
8672:     }
8673:     switch (ct) {
8674:     case DM_POLYTOPE_TRI_PRISM:
8675:     case DM_POLYTOPE_TRI_PRISM_TENSOR:
8676:     case DM_POLYTOPE_QUAD_PRISM_TENSOR:
8677:     case DM_POLYTOPE_PYRAMID:
8678:       continue;
8679:     default:
8680:       break;
8681:     }
8682:     DMPlexCellUnsplitVertices_Private(dm, c, ct, &unsplit);
8683:     if (unsplit) continue;
8684:     DMPlexComputeCellGeometryFEM(dm, c, NULL, NULL, J, NULL, &detJ);
8686:     PetscInfo(dm, "Cell %" PetscInt_FMT " FEM Volume %g\n", c, (double)(detJ * refVol));
8687:     /* This should work with periodicity since DG coordinates should be used */
8688:     if (depth > 1) {
8689:       DMPlexComputeCellGeometryFVM(dm, c, &vol, NULL, NULL);
8691:       PetscInfo(dm, "Cell %" PetscInt_FMT " FVM Volume %g\n", c, (double)vol);
8692:     }
8693:   }
8694:   return 0;
8695: }

8697: /*@
8698:   DMPlexCheckPointSF - Check that several necessary conditions are met for the Point SF of this plex.

8700:   Collective

8702:   Input Parameters:
8703: + dm - The DMPlex object
8704: . pointSF - The Point SF, or NULL for Point SF attached to DM
8705: - allowExtraRoots - Flag to allow extra points not present in the DM

8707:   Notes:
8708:   This is mainly intended for debugging/testing purposes.

8710:   For the complete list of DMPlexCheck* functions, see DMSetFromOptions().

8712:   Extra roots can come from priodic cuts, where additional points appear on the boundary

8714:   Level: developer

8716: .seealso: `DMGetPointSF()`, `DMSetFromOptions()`
8717: @*/
8718: PetscErrorCode DMPlexCheckPointSF(DM dm, PetscSF pointSF, PetscBool allowExtraRoots)
8719: {
8720:   PetscInt           l, nleaves, nroots, overlap;
8721:   const PetscInt    *locals;
8722:   const PetscSFNode *remotes;
8723:   PetscBool          distributed;
8724:   MPI_Comm           comm;
8725:   PetscMPIInt        rank;

8729:   else pointSF = dm->sf;
8730:   PetscObjectGetComm((PetscObject)dm, &comm);
8732:   MPI_Comm_rank(comm, &rank);
8733:   {
8734:     PetscMPIInt mpiFlag;

8736:     MPI_Comm_compare(comm, PetscObjectComm((PetscObject)pointSF), &mpiFlag);
8738:   }
8739:   PetscSFGetGraph(pointSF, &nroots, &nleaves, &locals, &remotes);
8740:   DMPlexIsDistributed(dm, &distributed);
8741:   if (!distributed) {
8743:     return 0;
8744:   }
8746:   DMPlexGetOverlap(dm, &overlap);

8748:   /* Check SF graph is compatible with DMPlex chart */
8749:   {
8750:     PetscInt pStart, pEnd, maxLeaf;

8752:     DMPlexGetChart(dm, &pStart, &pEnd);
8753:     PetscSFGetLeafRange(pointSF, NULL, &maxLeaf);
8756:   }

8758:   /* Check Point SF has no local points referenced */
8759:   for (l = 0; l < nleaves; l++) {
8760:     PetscAssert(remotes[l].rank != (PetscInt)rank, PETSC_COMM_SELF, PETSC_ERR_PLIB, "Point SF contains local point %" PetscInt_FMT " <- (%" PetscInt_FMT ",%" PetscInt_FMT ")", locals ? locals[l] : l, remotes[l].rank, remotes[l].index);
8761:   }

8763:   /* Check there are no cells in interface */
8764:   if (!overlap) {
8765:     PetscInt cellHeight, cStart, cEnd;

8767:     DMPlexGetVTKCellHeight(dm, &cellHeight);
8768:     DMPlexGetHeightStratum(dm, cellHeight, &cStart, &cEnd);
8769:     for (l = 0; l < nleaves; ++l) {
8770:       const PetscInt point = locals ? locals[l] : l;

8773:     }
8774:   }

8776:   /* If some point is in interface, then all its cone points must be also in interface (either as leaves or roots) */
8777:   {
8778:     const PetscInt *rootdegree;

8780:     PetscSFComputeDegreeBegin(pointSF, &rootdegree);
8781:     PetscSFComputeDegreeEnd(pointSF, &rootdegree);
8782:     for (l = 0; l < nleaves; ++l) {
8783:       const PetscInt  point = locals ? locals[l] : l;
8784:       const PetscInt *cone;
8785:       PetscInt        coneSize, c, idx;

8787:       DMPlexGetConeSize(dm, point, &coneSize);
8788:       DMPlexGetCone(dm, point, &cone);
8789:       for (c = 0; c < coneSize; ++c) {
8790:         if (!rootdegree[cone[c]]) {
8791:           if (locals) {
8792:             PetscFindInt(cone[c], nleaves, locals, &idx);
8793:           } else {
8794:             idx = (cone[c] < nleaves) ? cone[c] : -1;
8795:           }
8797:         }
8798:       }
8799:     }
8800:   }
8801:   return 0;
8802: }

8804: /*@
8805:   DMPlexCheck - Perform various checks of Plex sanity

8807:   Input Parameter:
8808: . dm - The DMPlex object

8810:   Notes:
8811:   This is a useful diagnostic when creating meshes programmatically.

8813:   For the complete list of DMPlexCheck* functions, see DMSetFromOptions().

8815:   Currently does not include DMPlexCheckCellShape().

8817:   Level: developer

8819: .seealso: DMCreate(), DMSetFromOptions()
8820: @*/
8821: PetscErrorCode DMPlexCheck(DM dm)
8822: {
8823:   PetscInt cellHeight;

8825:   DMPlexGetVTKCellHeight(dm, &cellHeight);
8826:   DMPlexCheckSymmetry(dm);
8827:   DMPlexCheckSkeleton(dm, cellHeight);
8828:   DMPlexCheckFaces(dm, cellHeight);
8829:   DMPlexCheckGeometry(dm);
8830:   DMPlexCheckPointSF(dm, NULL, PETSC_FALSE);
8831:   DMPlexCheckInterfaceCones(dm);
8832:   return 0;
8833: }

8835: typedef struct cell_stats {
8836:   PetscReal min, max, sum, squaresum;
8837:   PetscInt  count;
8838: } cell_stats_t;

8840: static void MPIAPI cell_stats_reduce(void *a, void *b, int *len, MPI_Datatype *datatype)
8841: {
8842:   PetscInt i, N = *len;

8844:   for (i = 0; i < N; i++) {
8845:     cell_stats_t *A = (cell_stats_t *)a;
8846:     cell_stats_t *B = (cell_stats_t *)b;

8848:     B->min = PetscMin(A->min, B->min);
8849:     B->max = PetscMax(A->max, B->max);
8850:     B->sum += A->sum;
8851:     B->squaresum += A->squaresum;
8852:     B->count += A->count;
8853:   }
8854: }

8856: /*@
8857:   DMPlexCheckCellShape - Checks the Jacobian of the mapping from reference to real cells and computes some minimal statistics.

8859:   Collective on dm

8861:   Input Parameters:
8862: + dm        - The DMPlex object
8863: . output    - If true, statistics will be displayed on stdout
8864: - condLimit - Display all cells above this condition number, or PETSC_DETERMINE for no cell output

8866:   Notes:
8867:   This is mainly intended for debugging/testing purposes.

8869:   For the complete list of DMPlexCheck* functions, see DMSetFromOptions().

8871:   Level: developer

8873: .seealso: `DMSetFromOptions()`, `DMPlexComputeOrthogonalQuality()`
8874: @*/
8875: PetscErrorCode DMPlexCheckCellShape(DM dm, PetscBool output, PetscReal condLimit)
8876: {
8877:   DM           dmCoarse;
8878:   cell_stats_t stats, globalStats;
8879:   MPI_Comm     comm = PetscObjectComm((PetscObject)dm);
8880:   PetscReal   *J, *invJ, min = 0, max = 0, mean = 0, stdev = 0;
8881:   PetscReal    limit = condLimit > 0 ? condLimit : PETSC_MAX_REAL;
8882:   PetscInt     cdim, cStart, cEnd, c, eStart, eEnd, count = 0;
8883:   PetscMPIInt  rank, size;

8886:   stats.min = PETSC_MAX_REAL;
8887:   stats.max = PETSC_MIN_REAL;
8888:   stats.sum = stats.squaresum = 0.;
8889:   stats.count                 = 0;

8891:   MPI_Comm_size(comm, &size);
8892:   MPI_Comm_rank(comm, &rank);
8893:   DMGetCoordinateDim(dm, &cdim);
8894:   PetscMalloc2(PetscSqr(cdim), &J, PetscSqr(cdim), &invJ);
8895:   DMPlexGetSimplexOrBoxCells(dm, 0, &cStart, &cEnd);
8896:   DMPlexGetDepthStratum(dm, 1, &eStart, &eEnd);
8897:   for (c = cStart; c < cEnd; c++) {
8898:     PetscInt  i;
8899:     PetscReal frobJ = 0., frobInvJ = 0., cond2, cond, detJ;

8901:     DMPlexComputeCellGeometryAffineFEM(dm, c, NULL, J, invJ, &detJ);
8903:     for (i = 0; i < PetscSqr(cdim); ++i) {
8904:       frobJ += J[i] * J[i];
8905:       frobInvJ += invJ[i] * invJ[i];
8906:     }
8907:     cond2 = frobJ * frobInvJ;
8908:     cond  = PetscSqrtReal(cond2);

8910:     stats.min = PetscMin(stats.min, cond);
8911:     stats.max = PetscMax(stats.max, cond);
8912:     stats.sum += cond;
8913:     stats.squaresum += cond2;
8914:     stats.count++;
8915:     if (output && cond > limit) {
8916:       PetscSection coordSection;
8917:       Vec          coordsLocal;
8918:       PetscScalar *coords = NULL;
8919:       PetscInt     Nv, d, clSize, cl, *closure = NULL;

8921:       DMGetCoordinatesLocal(dm, &coordsLocal);
8922:       DMGetCoordinateSection(dm, &coordSection);
8923:       DMPlexVecGetClosure(dm, coordSection, coordsLocal, c, &Nv, &coords);
8924:       PetscSynchronizedPrintf(comm, "[%d] Cell %" PetscInt_FMT " cond %g\n", rank, c, (double)cond);
8925:       for (i = 0; i < Nv / cdim; ++i) {
8926:         PetscSynchronizedPrintf(comm, "  Vertex %" PetscInt_FMT ": (", i);
8927:         for (d = 0; d < cdim; ++d) {
8928:           if (d > 0) PetscSynchronizedPrintf(comm, ", ");
8929:           PetscSynchronizedPrintf(comm, "%g", (double)PetscRealPart(coords[i * cdim + d]));
8930:         }
8931:         PetscSynchronizedPrintf(comm, ")\n");
8932:       }
8933:       DMPlexGetTransitiveClosure(dm, c, PETSC_TRUE, &clSize, &closure);
8934:       for (cl = 0; cl < clSize * 2; cl += 2) {
8935:         const PetscInt edge = closure[cl];

8937:         if ((edge >= eStart) && (edge < eEnd)) {
8938:           PetscReal len;

8940:           DMPlexComputeCellGeometryFVM(dm, edge, &len, NULL, NULL);
8941:           PetscSynchronizedPrintf(comm, "  Edge %" PetscInt_FMT ": length %g\n", edge, (double)len);
8942:         }
8943:       }
8944:       DMPlexRestoreTransitiveClosure(dm, c, PETSC_TRUE, &clSize, &closure);
8945:       DMPlexVecRestoreClosure(dm, coordSection, coordsLocal, c, &Nv, &coords);
8946:     }
8947:   }
8948:   if (output) PetscSynchronizedFlush(comm, NULL);

8950:   if (size > 1) {
8951:     PetscMPIInt  blockLengths[2] = {4, 1};
8952:     MPI_Aint     blockOffsets[2] = {offsetof(cell_stats_t, min), offsetof(cell_stats_t, count)};
8953:     MPI_Datatype blockTypes[2]   = {MPIU_REAL, MPIU_INT}, statType;
8954:     MPI_Op       statReduce;

8956:     MPI_Type_create_struct(2, blockLengths, blockOffsets, blockTypes, &statType);
8957:     MPI_Type_commit(&statType);
8958:     MPI_Op_create(cell_stats_reduce, PETSC_TRUE, &statReduce);
8959:     MPI_Reduce(&stats, &globalStats, 1, statType, statReduce, 0, comm);
8960:     MPI_Op_free(&statReduce);
8961:     MPI_Type_free(&statType);
8962:   } else {
8963:     PetscArraycpy(&globalStats, &stats, 1);
8964:   }
8965:   if (rank == 0) {
8966:     count = globalStats.count;
8967:     min   = globalStats.min;
8968:     max   = globalStats.max;
8969:     mean  = globalStats.sum / globalStats.count;
8970:     stdev = globalStats.count > 1 ? PetscSqrtReal(PetscMax((globalStats.squaresum - globalStats.count * mean * mean) / (globalStats.count - 1), 0)) : 0.0;
8971:   }

8973:   if (output) PetscPrintf(comm, "Mesh with %" PetscInt_FMT " cells, shape condition numbers: min = %g, max = %g, mean = %g, stddev = %g\n", count, (double)min, (double)max, (double)mean, (double)stdev);
8974:   PetscFree2(J, invJ);

8976:   DMGetCoarseDM(dm, &dmCoarse);
8977:   if (dmCoarse) {
8978:     PetscBool isplex;

8980:     PetscObjectTypeCompare((PetscObject)dmCoarse, DMPLEX, &isplex);
8981:     if (isplex) DMPlexCheckCellShape(dmCoarse, output, condLimit);
8982:   }
8983:   return 0;
8984: }

8986: /*@
8987:   DMPlexComputeOrthogonalQuality - Compute cell-wise orthogonal quality mesh statistic. Optionally tags all cells with
8988:   orthogonal quality below given tolerance.

8990:   Collective on dm

8992:   Input Parameters:
8993: + dm   - The DMPlex object
8994: . fv   - Optional PetscFV object for pre-computed cell/face centroid information
8995: - atol - [0, 1] Absolute tolerance for tagging cells.

8997:   Output Parameters:
8998: + OrthQual      - Vec containing orthogonal quality per cell
8999: - OrthQualLabel - DMLabel tagging cells below atol with DM_ADAPT_REFINE

9001:   Options Database Keys:
9002: + -dm_plex_orthogonal_quality_label_view - view OrthQualLabel if label is requested. Currently only PETSCVIEWERASCII is
9003: supported.
9004: - -dm_plex_orthogonal_quality_vec_view - view OrthQual vector.

9006:   Notes:
9007:   Orthogonal quality is given by the following formula:

9009:   \min \left[ \frac{A_i \cdot f_i}{\|A_i\| \|f_i\|} , \frac{A_i \cdot c_i}{\|A_i\| \|c_i\|} \right]

9011:   Where A_i is the i'th face-normal vector, f_i is the vector from the cell centroid to the i'th face centroid, and c_i
9012:   is the vector from the current cells centroid to the centroid of its i'th neighbor (which shares a face with the
9013:   current cell). This computes the vector similarity between each cell face and its corresponding neighbor centroid by
9014:   calculating the cosine of the angle between these vectors.

9016:   Orthogonal quality ranges from 1 (best) to 0 (worst).

9018:   This routine is mainly useful for FVM, however is not restricted to only FVM. The PetscFV object is optionally used to check for
9019:   pre-computed FVM cell data, but if it is not passed in then this data will be computed.

9021:   Cells are tagged if they have an orthogonal quality less than or equal to the absolute tolerance.

9023:   Level: intermediate

9025: .seealso: `DMPlexCheckCellShape()`, `DMCreateLabel()`
9026: @*/
9027: PetscErrorCode DMPlexComputeOrthogonalQuality(DM dm, PetscFV fv, PetscReal atol, Vec *OrthQual, DMLabel *OrthQualLabel)
9028: {
9029:   PetscInt               nc, cellHeight, cStart, cEnd, cell, cellIter = 0;
9030:   PetscInt              *idx;
9031:   PetscScalar           *oqVals;
9032:   const PetscScalar     *cellGeomArr, *faceGeomArr;
9033:   PetscReal             *ci, *fi, *Ai;
9034:   MPI_Comm               comm;
9035:   Vec                    cellgeom, facegeom;
9036:   DM                     dmFace, dmCell;
9037:   IS                     glob;
9038:   ISLocalToGlobalMapping ltog;
9039:   PetscViewer            vwr;

9045:   PetscObjectGetComm((PetscObject)dm, &comm);
9046:   DMGetDimension(dm, &nc);
9048:   {
9049:     DMPlexInterpolatedFlag interpFlag;

9051:     DMPlexIsInterpolated(dm, &interpFlag);
9052:     if (interpFlag != DMPLEX_INTERPOLATED_FULL) {
9053:       PetscMPIInt rank;

9055:       MPI_Comm_rank(comm, &rank);
9056:       SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "DM must be fully interpolated, DM on rank %d is not fully interpolated", rank);
9057:     }
9058:   }
9059:   if (OrthQualLabel) {
9061:     DMCreateLabel(dm, "Orthogonal_Quality");
9062:     DMGetLabel(dm, "Orthogonal_Quality", OrthQualLabel);
9063:   } else {
9064:     *OrthQualLabel = NULL;
9065:   }
9066:   DMPlexGetVTKCellHeight(dm, &cellHeight);
9067:   DMPlexGetHeightStratum(dm, cellHeight, &cStart, &cEnd);
9068:   DMPlexCreateCellNumbering_Internal(dm, PETSC_TRUE, &glob);
9069:   ISLocalToGlobalMappingCreateIS(glob, &ltog);
9070:   ISLocalToGlobalMappingSetType(ltog, ISLOCALTOGLOBALMAPPINGHASH);
9071:   VecCreate(comm, OrthQual);
9072:   VecSetType(*OrthQual, VECSTANDARD);
9073:   VecSetSizes(*OrthQual, cEnd - cStart, PETSC_DETERMINE);
9074:   VecSetLocalToGlobalMapping(*OrthQual, ltog);
9075:   VecSetUp(*OrthQual);
9076:   ISDestroy(&glob);
9077:   ISLocalToGlobalMappingDestroy(&ltog);
9078:   DMPlexGetDataFVM(dm, fv, &cellgeom, &facegeom, NULL);
9079:   VecGetArrayRead(cellgeom, &cellGeomArr);
9080:   VecGetArrayRead(facegeom, &faceGeomArr);
9081:   VecGetDM(cellgeom, &dmCell);
9082:   VecGetDM(facegeom, &dmFace);
9083:   PetscMalloc5(cEnd - cStart, &idx, cEnd - cStart, &oqVals, nc, &ci, nc, &fi, nc, &Ai);
9084:   for (cell = cStart; cell < cEnd; cellIter++, cell++) {
9085:     PetscInt         cellneigh, cellneighiter = 0, adjSize = PETSC_DETERMINE;
9086:     PetscInt         cellarr[2], *adj = NULL;
9087:     PetscScalar     *cArr, *fArr;
9088:     PetscReal        minvalc = 1.0, minvalf = 1.0;
9089:     PetscFVCellGeom *cg;

9091:     idx[cellIter] = cell - cStart;
9092:     cellarr[0]    = cell;
9093:     /* Make indexing into cellGeom easier */
9094:     DMPlexPointLocalRead(dmCell, cell, cellGeomArr, &cg);
9095:     DMPlexGetAdjacency_Internal(dm, cell, PETSC_TRUE, PETSC_FALSE, PETSC_FALSE, &adjSize, &adj);
9096:     /* Technically 1 too big, but easier than fiddling with empty adjacency array */
9097:     PetscCalloc2(adjSize, &cArr, adjSize, &fArr);
9098:     for (cellneigh = 0; cellneigh < adjSize; cellneighiter++, cellneigh++) {
9099:       PetscInt         i;
9100:       const PetscInt   neigh  = adj[cellneigh];
9101:       PetscReal        normci = 0, normfi = 0, normai = 0;
9102:       PetscFVCellGeom *cgneigh;
9103:       PetscFVFaceGeom *fg;

9105:       /* Don't count ourselves in the neighbor list */
9106:       if (neigh == cell) continue;
9107:       DMPlexPointLocalRead(dmCell, neigh, cellGeomArr, &cgneigh);
9108:       cellarr[1] = neigh;
9109:       {
9110:         PetscInt        numcovpts;
9111:         const PetscInt *covpts;

9113:         DMPlexGetMeet(dm, 2, cellarr, &numcovpts, &covpts);
9114:         DMPlexPointLocalRead(dmFace, covpts[0], faceGeomArr, &fg);
9115:         DMPlexRestoreMeet(dm, 2, cellarr, &numcovpts, &covpts);
9116:       }

9118:       /* Compute c_i, f_i and their norms */
9119:       for (i = 0; i < nc; i++) {
9120:         ci[i] = cgneigh->centroid[i] - cg->centroid[i];
9121:         fi[i] = fg->centroid[i] - cg->centroid[i];
9122:         Ai[i] = fg->normal[i];
9123:         normci += PetscPowReal(ci[i], 2);
9124:         normfi += PetscPowReal(fi[i], 2);
9125:         normai += PetscPowReal(Ai[i], 2);
9126:       }
9127:       normci = PetscSqrtReal(normci);
9128:       normfi = PetscSqrtReal(normfi);
9129:       normai = PetscSqrtReal(normai);

9131:       /* Normalize and compute for each face-cell-normal pair */
9132:       for (i = 0; i < nc; i++) {
9133:         ci[i] = ci[i] / normci;
9134:         fi[i] = fi[i] / normfi;
9135:         Ai[i] = Ai[i] / normai;
9136:         /* PetscAbs because I don't know if normals are guaranteed to point out */
9137:         cArr[cellneighiter] += PetscAbs(Ai[i] * ci[i]);
9138:         fArr[cellneighiter] += PetscAbs(Ai[i] * fi[i]);
9139:       }
9140:       if (PetscRealPart(cArr[cellneighiter]) < minvalc) minvalc = PetscRealPart(cArr[cellneighiter]);
9141:       if (PetscRealPart(fArr[cellneighiter]) < minvalf) minvalf = PetscRealPart(fArr[cellneighiter]);
9142:     }
9143:     PetscFree(adj);
9144:     PetscFree2(cArr, fArr);
9145:     /* Defer to cell if they're equal */
9146:     oqVals[cellIter] = PetscMin(minvalf, minvalc);
9147:     if (OrthQualLabel) {
9148:       if (PetscRealPart(oqVals[cellIter]) <= atol) DMLabelSetValue(*OrthQualLabel, cell, DM_ADAPT_REFINE);
9149:     }
9150:   }
9151:   VecSetValuesLocal(*OrthQual, cEnd - cStart, idx, oqVals, INSERT_VALUES);
9152:   VecAssemblyBegin(*OrthQual);
9153:   VecAssemblyEnd(*OrthQual);
9154:   VecRestoreArrayRead(cellgeom, &cellGeomArr);
9155:   VecRestoreArrayRead(facegeom, &faceGeomArr);
9156:   PetscOptionsGetViewer(comm, NULL, NULL, "-dm_plex_orthogonal_quality_label_view", &vwr, NULL, NULL);
9157:   if (OrthQualLabel) {
9158:     if (vwr) DMLabelView(*OrthQualLabel, vwr);
9159:   }
9160:   PetscFree5(idx, oqVals, ci, fi, Ai);
9161:   PetscViewerDestroy(&vwr);
9162:   VecViewFromOptions(*OrthQual, NULL, "-dm_plex_orthogonal_quality_vec_view");
9163:   return 0;
9164: }

9166: /* this is here insead of DMGetOutputDM because output DM still has constraints in the local indices that affect
9167:  * interpolator construction */
9168: static PetscErrorCode DMGetFullDM(DM dm, DM *odm)
9169: {
9170:   PetscSection section, newSection, gsection;
9171:   PetscSF      sf;
9172:   PetscBool    hasConstraints, ghasConstraints;

9176:   DMGetLocalSection(dm, &section);
9177:   PetscSectionHasConstraints(section, &hasConstraints);
9178:   MPI_Allreduce(&hasConstraints, &ghasConstraints, 1, MPIU_BOOL, MPI_LOR, PetscObjectComm((PetscObject)dm));
9179:   if (!ghasConstraints) {
9180:     PetscObjectReference((PetscObject)dm);
9181:     *odm = dm;
9182:     return 0;
9183:   }
9184:   DMClone(dm, odm);
9185:   DMCopyFields(dm, *odm);
9186:   DMGetLocalSection(*odm, &newSection);
9187:   DMGetPointSF(*odm, &sf);
9188:   PetscSectionCreateGlobalSection(newSection, sf, PETSC_TRUE, PETSC_FALSE, &gsection);
9189:   DMSetGlobalSection(*odm, gsection);
9190:   PetscSectionDestroy(&gsection);
9191:   return 0;
9192: }

9194: static PetscErrorCode DMCreateAffineInterpolationCorrection_Plex(DM dmc, DM dmf, Vec *shift)
9195: {
9196:   DM        dmco, dmfo;
9197:   Mat       interpo;
9198:   Vec       rscale;
9199:   Vec       cglobalo, clocal;
9200:   Vec       fglobal, fglobalo, flocal;
9201:   PetscBool regular;

9203:   DMGetFullDM(dmc, &dmco);
9204:   DMGetFullDM(dmf, &dmfo);
9205:   DMSetCoarseDM(dmfo, dmco);
9206:   DMPlexGetRegularRefinement(dmf, &regular);
9207:   DMPlexSetRegularRefinement(dmfo, regular);
9208:   DMCreateInterpolation(dmco, dmfo, &interpo, &rscale);
9209:   DMCreateGlobalVector(dmco, &cglobalo);
9210:   DMCreateLocalVector(dmc, &clocal);
9211:   VecSet(cglobalo, 0.);
9212:   VecSet(clocal, 0.);
9213:   DMCreateGlobalVector(dmf, &fglobal);
9214:   DMCreateGlobalVector(dmfo, &fglobalo);
9215:   DMCreateLocalVector(dmf, &flocal);
9216:   VecSet(fglobal, 0.);
9217:   VecSet(fglobalo, 0.);
9218:   VecSet(flocal, 0.);
9219:   DMPlexInsertBoundaryValues(dmc, PETSC_TRUE, clocal, 0., NULL, NULL, NULL);
9220:   DMLocalToGlobalBegin(dmco, clocal, INSERT_VALUES, cglobalo);
9221:   DMLocalToGlobalEnd(dmco, clocal, INSERT_VALUES, cglobalo);
9222:   MatMult(interpo, cglobalo, fglobalo);
9223:   DMGlobalToLocalBegin(dmfo, fglobalo, INSERT_VALUES, flocal);
9224:   DMGlobalToLocalEnd(dmfo, fglobalo, INSERT_VALUES, flocal);
9225:   DMLocalToGlobalBegin(dmf, flocal, INSERT_VALUES, fglobal);
9226:   DMLocalToGlobalEnd(dmf, flocal, INSERT_VALUES, fglobal);
9227:   *shift = fglobal;
9228:   VecDestroy(&flocal);
9229:   VecDestroy(&fglobalo);
9230:   VecDestroy(&clocal);
9231:   VecDestroy(&cglobalo);
9232:   VecDestroy(&rscale);
9233:   MatDestroy(&interpo);
9234:   DMDestroy(&dmfo);
9235:   DMDestroy(&dmco);
9236:   return 0;
9237: }

9239: PETSC_INTERN PetscErrorCode DMInterpolateSolution_Plex(DM coarse, DM fine, Mat interp, Vec coarseSol, Vec fineSol)
9240: {
9241:   PetscObject shifto;
9242:   Vec         shift;

9244:   if (!interp) {
9245:     Vec rscale;

9247:     DMCreateInterpolation(coarse, fine, &interp, &rscale);
9248:     VecDestroy(&rscale);
9249:   } else {
9250:     PetscObjectReference((PetscObject)interp);
9251:   }
9252:   PetscObjectQuery((PetscObject)interp, "_DMInterpolateSolution_Plex_Vec", &shifto);
9253:   if (!shifto) {
9254:     DMCreateAffineInterpolationCorrection_Plex(coarse, fine, &shift);
9255:     PetscObjectCompose((PetscObject)interp, "_DMInterpolateSolution_Plex_Vec", (PetscObject)shift);
9256:     shifto = (PetscObject)shift;
9257:     VecDestroy(&shift);
9258:   }
9259:   shift = (Vec)shifto;
9260:   MatInterpolate(interp, coarseSol, fineSol);
9261:   VecAXPY(fineSol, 1.0, shift);
9262:   MatDestroy(&interp);
9263:   return 0;
9264: }

9266: /* Pointwise interpolation
9267:      Just code FEM for now
9268:      u^f = I u^c
9269:      sum_k u^f_k phi^f_k = I sum_j u^c_j phi^c_j
9270:      u^f_i = sum_j psi^f_i I phi^c_j u^c_j
9271:      I_{ij} = psi^f_i phi^c_j
9272: */
9273: PetscErrorCode DMCreateInterpolation_Plex(DM dmCoarse, DM dmFine, Mat *interpolation, Vec *scaling)
9274: {
9275:   PetscSection gsc, gsf;
9276:   PetscInt     m, n;
9277:   void        *ctx;
9278:   DM           cdm;
9279:   PetscBool    regular, ismatis, isRefined = dmCoarse->data == dmFine->data ? PETSC_FALSE : PETSC_TRUE;

9281:   DMGetGlobalSection(dmFine, &gsf);
9282:   PetscSectionGetConstrainedStorageSize(gsf, &m);
9283:   DMGetGlobalSection(dmCoarse, &gsc);
9284:   PetscSectionGetConstrainedStorageSize(gsc, &n);

9286:   PetscStrcmp(dmCoarse->mattype, MATIS, &ismatis);
9287:   MatCreate(PetscObjectComm((PetscObject)dmCoarse), interpolation);
9288:   MatSetSizes(*interpolation, m, n, PETSC_DETERMINE, PETSC_DETERMINE);
9289:   MatSetType(*interpolation, ismatis ? MATAIJ : dmCoarse->mattype);
9290:   DMGetApplicationContext(dmFine, &ctx);

9292:   DMGetCoarseDM(dmFine, &cdm);
9293:   DMPlexGetRegularRefinement(dmFine, &regular);
9294:   if (!isRefined || (regular && cdm == dmCoarse)) DMPlexComputeInterpolatorNested(dmCoarse, dmFine, isRefined, *interpolation, ctx);
9295:   else DMPlexComputeInterpolatorGeneral(dmCoarse, dmFine, *interpolation, ctx);
9296:   MatViewFromOptions(*interpolation, NULL, "-interp_mat_view");
9297:   if (scaling) {
9298:     /* Use naive scaling */
9299:     DMCreateInterpolationScale(dmCoarse, dmFine, *interpolation, scaling);
9300:   }
9301:   return 0;
9302: }

9304: PetscErrorCode DMCreateInjection_Plex(DM dmCoarse, DM dmFine, Mat *mat)
9305: {
9306:   VecScatter ctx;

9308:   DMPlexComputeInjectorFEM(dmCoarse, dmFine, &ctx, NULL);
9309:   MatCreateScatter(PetscObjectComm((PetscObject)ctx), ctx, mat);
9310:   VecScatterDestroy(&ctx);
9311:   return 0;
9312: }

9314: static void g0_identity_private(PetscInt dim, PetscInt Nf, PetscInt NfAux, const PetscInt uOff[], const PetscInt uOff_x[], const PetscScalar u[], const PetscScalar u_t[], const PetscScalar u_x[], const PetscInt aOff[], const PetscInt aOff_x[], const PetscScalar a[], const PetscScalar a_t[], const PetscScalar a_x[], PetscReal t, PetscReal u_tShift, const PetscReal x[], PetscInt numConstants, const PetscScalar constants[], PetscScalar g0[])
9315: {
9316:   const PetscInt Nc = uOff[1] - uOff[0];
9317:   PetscInt       c;
9318:   for (c = 0; c < Nc; ++c) g0[c * Nc + c] = 1.0;
9319: }

9321: PetscErrorCode DMCreateMassMatrixLumped_Plex(DM dm, Vec *mass)
9322: {
9323:   DM           dmc;
9324:   PetscDS      ds;
9325:   Vec          ones, locmass;
9326:   IS           cellIS;
9327:   PetscFormKey key;
9328:   PetscInt     depth;

9330:   DMClone(dm, &dmc);
9331:   DMCopyDisc(dm, dmc);
9332:   DMGetDS(dmc, &ds);
9333:   PetscDSSetJacobian(ds, 0, 0, g0_identity_private, NULL, NULL, NULL);
9334:   DMCreateGlobalVector(dmc, mass);
9335:   DMGetLocalVector(dmc, &ones);
9336:   DMGetLocalVector(dmc, &locmass);
9337:   DMPlexGetDepth(dmc, &depth);
9338:   DMGetStratumIS(dmc, "depth", depth, &cellIS);
9339:   VecSet(locmass, 0.0);
9340:   VecSet(ones, 1.0);
9341:   key.label = NULL;
9342:   key.value = 0;
9343:   key.field = 0;
9344:   key.part  = 0;
9345:   DMPlexComputeJacobian_Action_Internal(dmc, key, cellIS, 0.0, 0.0, ones, NULL, ones, locmass, NULL);
9346:   ISDestroy(&cellIS);
9347:   VecSet(*mass, 0.0);
9348:   DMLocalToGlobalBegin(dmc, locmass, ADD_VALUES, *mass);
9349:   DMLocalToGlobalEnd(dmc, locmass, ADD_VALUES, *mass);
9350:   DMRestoreLocalVector(dmc, &ones);
9351:   DMRestoreLocalVector(dmc, &locmass);
9352:   DMDestroy(&dmc);
9353:   return 0;
9354: }

9356: PetscErrorCode DMCreateMassMatrix_Plex(DM dmCoarse, DM dmFine, Mat *mass)
9357: {
9358:   PetscSection gsc, gsf;
9359:   PetscInt     m, n;
9360:   void        *ctx;
9361:   DM           cdm;
9362:   PetscBool    regular;

9364:   if (dmFine == dmCoarse) {
9365:     DM            dmc;
9366:     PetscDS       ds;
9367:     PetscWeakForm wf;
9368:     Vec           u;
9369:     IS            cellIS;
9370:     PetscFormKey  key;
9371:     PetscInt      depth;

9373:     DMClone(dmFine, &dmc);
9374:     DMCopyDisc(dmFine, dmc);
9375:     DMGetDS(dmc, &ds);
9376:     PetscDSGetWeakForm(ds, &wf);
9377:     PetscWeakFormClear(wf);
9378:     PetscDSSetJacobian(ds, 0, 0, g0_identity_private, NULL, NULL, NULL);
9379:     DMCreateMatrix(dmc, mass);
9380:     DMGetLocalVector(dmc, &u);
9381:     DMPlexGetDepth(dmc, &depth);
9382:     DMGetStratumIS(dmc, "depth", depth, &cellIS);
9383:     MatZeroEntries(*mass);
9384:     key.label = NULL;
9385:     key.value = 0;
9386:     key.field = 0;
9387:     key.part  = 0;
9388:     DMPlexComputeJacobian_Internal(dmc, key, cellIS, 0.0, 0.0, u, NULL, *mass, *mass, NULL);
9389:     ISDestroy(&cellIS);
9390:     DMRestoreLocalVector(dmc, &u);
9391:     DMDestroy(&dmc);
9392:   } else {
9393:     DMGetGlobalSection(dmFine, &gsf);
9394:     PetscSectionGetConstrainedStorageSize(gsf, &m);
9395:     DMGetGlobalSection(dmCoarse, &gsc);
9396:     PetscSectionGetConstrainedStorageSize(gsc, &n);

9398:     MatCreate(PetscObjectComm((PetscObject)dmCoarse), mass);
9399:     MatSetSizes(*mass, m, n, PETSC_DETERMINE, PETSC_DETERMINE);
9400:     MatSetType(*mass, dmCoarse->mattype);
9401:     DMGetApplicationContext(dmFine, &ctx);

9403:     DMGetCoarseDM(dmFine, &cdm);
9404:     DMPlexGetRegularRefinement(dmFine, &regular);
9405:     if (regular && cdm == dmCoarse) DMPlexComputeMassMatrixNested(dmCoarse, dmFine, *mass, ctx);
9406:     else DMPlexComputeMassMatrixGeneral(dmCoarse, dmFine, *mass, ctx);
9407:   }
9408:   MatViewFromOptions(*mass, NULL, "-mass_mat_view");
9409:   return 0;
9410: }

9412: /*@
9413:   DMPlexGetRegularRefinement - Get the flag indicating that this mesh was obtained by regular refinement from its coarse mesh

9415:   Input Parameter:
9416: . dm - The DMPlex object

9418:   Output Parameter:
9419: . regular - The flag

9421:   Level: intermediate

9423: .seealso: `DMPlexSetRegularRefinement()`
9424: @*/
9425: PetscErrorCode DMPlexGetRegularRefinement(DM dm, PetscBool *regular)
9426: {
9429:   *regular = ((DM_Plex *)dm->data)->regularRefinement;
9430:   return 0;
9431: }

9433: /*@
9434:   DMPlexSetRegularRefinement - Set the flag indicating that this mesh was obtained by regular refinement from its coarse mesh

9436:   Input Parameters:
9437: + dm - The DMPlex object
9438: - regular - The flag

9440:   Level: intermediate

9442: .seealso: `DMPlexGetRegularRefinement()`
9443: @*/
9444: PetscErrorCode DMPlexSetRegularRefinement(DM dm, PetscBool regular)
9445: {
9447:   ((DM_Plex *)dm->data)->regularRefinement = regular;
9448:   return 0;
9449: }

9451: /* anchors */
9452: /*@
9453:   DMPlexGetAnchors - Get the layout of the anchor (point-to-point) constraints.  Typically, the user will not have to
9454:   call DMPlexGetAnchors() directly: if there are anchors, then DMPlexGetAnchors() is called during DMGetDefaultConstraints().

9456:   not collective

9458:   Input Parameter:
9459: . dm - The DMPlex object

9461:   Output Parameters:
9462: + anchorSection - If not NULL, set to the section describing which points anchor the constrained points.
9463: - anchorIS - If not NULL, set to the list of anchors indexed by anchorSection

9465:   Level: intermediate

9467: .seealso: `DMPlexSetAnchors()`, `DMGetDefaultConstraints()`, `DMSetDefaultConstraints()`
9468: @*/
9469: PetscErrorCode DMPlexGetAnchors(DM dm, PetscSection *anchorSection, IS *anchorIS)
9470: {
9471:   DM_Plex *plex = (DM_Plex *)dm->data;

9474:   if (!plex->anchorSection && !plex->anchorIS && plex->createanchors) (*plex->createanchors)(dm);
9475:   if (anchorSection) *anchorSection = plex->anchorSection;
9476:   if (anchorIS) *anchorIS = plex->anchorIS;
9477:   return 0;
9478: }

9480: /*@
9481:   DMPlexSetAnchors - Set the layout of the local anchor (point-to-point) constraints.  Unlike boundary conditions,
9482:   when a point's degrees of freedom in a section are constrained to an outside value, the anchor constraints set a
9483:   point's degrees of freedom to be a linear combination of other points' degrees of freedom.

9485:   After specifying the layout of constraints with DMPlexSetAnchors(), one specifies the constraints by calling
9486:   DMGetDefaultConstraints() and filling in the entries in the constraint matrix.

9488:   collective on dm

9490:   Input Parameters:
9491: + dm - The DMPlex object
9492: . anchorSection - The section that describes the mapping from constrained points to the anchor points listed in anchorIS.  Must have a local communicator (PETSC_COMM_SELF or derivative).
9493: - anchorIS - The list of all anchor points.  Must have a local communicator (PETSC_COMM_SELF or derivative).

9495:   The reference counts of anchorSection and anchorIS are incremented.

9497:   Level: intermediate

9499: .seealso: `DMPlexGetAnchors()`, `DMGetDefaultConstraints()`, `DMSetDefaultConstraints()`
9500: @*/
9501: PetscErrorCode DMPlexSetAnchors(DM dm, PetscSection anchorSection, IS anchorIS)
9502: {
9503:   DM_Plex    *plex = (DM_Plex *)dm->data;
9504:   PetscMPIInt result;

9507:   if (anchorSection) {
9509:     MPI_Comm_compare(PETSC_COMM_SELF, PetscObjectComm((PetscObject)anchorSection), &result);
9511:   }
9512:   if (anchorIS) {
9514:     MPI_Comm_compare(PETSC_COMM_SELF, PetscObjectComm((PetscObject)anchorIS), &result);
9516:   }

9518:   PetscObjectReference((PetscObject)anchorSection);
9519:   PetscSectionDestroy(&plex->anchorSection);
9520:   plex->anchorSection = anchorSection;

9522:   PetscObjectReference((PetscObject)anchorIS);
9523:   ISDestroy(&plex->anchorIS);
9524:   plex->anchorIS = anchorIS;

9526:   if (PetscUnlikelyDebug(anchorIS && anchorSection)) {
9527:     PetscInt        size, a, pStart, pEnd;
9528:     const PetscInt *anchors;

9530:     PetscSectionGetChart(anchorSection, &pStart, &pEnd);
9531:     ISGetLocalSize(anchorIS, &size);
9532:     ISGetIndices(anchorIS, &anchors);
9533:     for (a = 0; a < size; a++) {
9534:       PetscInt p;

9536:       p = anchors[a];
9537:       if (p >= pStart && p < pEnd) {
9538:         PetscInt dof;

9540:         PetscSectionGetDof(anchorSection, p, &dof);
9541:         if (dof) {
9542:           ISRestoreIndices(anchorIS, &anchors);
9543:           SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_INCOMP, "Point %" PetscInt_FMT " cannot be constrained and an anchor", p);
9544:         }
9545:       }
9546:     }
9547:     ISRestoreIndices(anchorIS, &anchors);
9548:   }
9549:   /* reset the generic constraints */
9550:   DMSetDefaultConstraints(dm, NULL, NULL, NULL);
9551:   return 0;
9552: }

9554: static PetscErrorCode DMPlexCreateConstraintSection_Anchors(DM dm, PetscSection section, PetscSection *cSec)
9555: {
9556:   PetscSection anchorSection;
9557:   PetscInt     pStart, pEnd, sStart, sEnd, p, dof, numFields, f;

9560:   DMPlexGetAnchors(dm, &anchorSection, NULL);
9561:   PetscSectionCreate(PETSC_COMM_SELF, cSec);
9562:   PetscSectionGetNumFields(section, &numFields);
9563:   if (numFields) {
9564:     PetscInt f;
9565:     PetscSectionSetNumFields(*cSec, numFields);

9567:     for (f = 0; f < numFields; f++) {
9568:       PetscInt numComp;

9570:       PetscSectionGetFieldComponents(section, f, &numComp);
9571:       PetscSectionSetFieldComponents(*cSec, f, numComp);
9572:     }
9573:   }
9574:   PetscSectionGetChart(anchorSection, &pStart, &pEnd);
9575:   PetscSectionGetChart(section, &sStart, &sEnd);
9576:   pStart = PetscMax(pStart, sStart);
9577:   pEnd   = PetscMin(pEnd, sEnd);
9578:   pEnd   = PetscMax(pStart, pEnd);
9579:   PetscSectionSetChart(*cSec, pStart, pEnd);
9580:   for (p = pStart; p < pEnd; p++) {
9581:     PetscSectionGetDof(anchorSection, p, &dof);
9582:     if (dof) {
9583:       PetscSectionGetDof(section, p, &dof);
9584:       PetscSectionSetDof(*cSec, p, dof);
9585:       for (f = 0; f < numFields; f++) {
9586:         PetscSectionGetFieldDof(section, p, f, &dof);
9587:         PetscSectionSetFieldDof(*cSec, p, f, dof);
9588:       }
9589:     }
9590:   }
9591:   PetscSectionSetUp(*cSec);
9592:   PetscObjectSetName((PetscObject)*cSec, "Constraint Section");
9593:   return 0;
9594: }

9596: static PetscErrorCode DMPlexCreateConstraintMatrix_Anchors(DM dm, PetscSection section, PetscSection cSec, Mat *cMat)
9597: {
9598:   PetscSection    aSec;
9599:   PetscInt        pStart, pEnd, p, sStart, sEnd, dof, aDof, aOff, off, nnz, annz, m, n, q, a, offset, *i, *j;
9600:   const PetscInt *anchors;
9601:   PetscInt        numFields, f;
9602:   IS              aIS;
9603:   MatType         mtype;
9604:   PetscBool       iscuda, iskokkos;

9607:   PetscSectionGetStorageSize(cSec, &m);
9608:   PetscSectionGetStorageSize(section, &n);
9609:   MatCreate(PETSC_COMM_SELF, cMat);
9610:   MatSetSizes(*cMat, m, n, m, n);
9611:   PetscStrcmp(dm->mattype, MATSEQAIJCUSPARSE, &iscuda);
9612:   if (!iscuda) PetscStrcmp(dm->mattype, MATMPIAIJCUSPARSE, &iscuda);
9613:   PetscStrcmp(dm->mattype, MATSEQAIJKOKKOS, &iskokkos);
9614:   if (!iskokkos) PetscStrcmp(dm->mattype, MATMPIAIJKOKKOS, &iskokkos);
9615:   if (iscuda) mtype = MATSEQAIJCUSPARSE;
9616:   else if (iskokkos) mtype = MATSEQAIJKOKKOS;
9617:   else mtype = MATSEQAIJ;
9618:   MatSetType(*cMat, mtype);
9619:   DMPlexGetAnchors(dm, &aSec, &aIS);
9620:   ISGetIndices(aIS, &anchors);
9621:   /* cSec will be a subset of aSec and section */
9622:   PetscSectionGetChart(cSec, &pStart, &pEnd);
9623:   PetscSectionGetChart(section, &sStart, &sEnd);
9624:   PetscMalloc1(m + 1, &i);
9625:   i[0] = 0;
9626:   PetscSectionGetNumFields(section, &numFields);
9627:   for (p = pStart; p < pEnd; p++) {
9628:     PetscInt rDof, rOff, r;

9630:     PetscSectionGetDof(aSec, p, &rDof);
9631:     if (!rDof) continue;
9632:     PetscSectionGetOffset(aSec, p, &rOff);
9633:     if (numFields) {
9634:       for (f = 0; f < numFields; f++) {
9635:         annz = 0;
9636:         for (r = 0; r < rDof; r++) {
9637:           a = anchors[rOff + r];
9638:           if (a < sStart || a >= sEnd) continue;
9639:           PetscSectionGetFieldDof(section, a, f, &aDof);
9640:           annz += aDof;
9641:         }
9642:         PetscSectionGetFieldDof(cSec, p, f, &dof);
9643:         PetscSectionGetFieldOffset(cSec, p, f, &off);
9644:         for (q = 0; q < dof; q++) i[off + q + 1] = i[off + q] + annz;
9645:       }
9646:     } else {
9647:       annz = 0;
9648:       PetscSectionGetDof(cSec, p, &dof);
9649:       for (q = 0; q < dof; q++) {
9650:         a = anchors[rOff + q];
9651:         if (a < sStart || a >= sEnd) continue;
9652:         PetscSectionGetDof(section, a, &aDof);
9653:         annz += aDof;
9654:       }
9655:       PetscSectionGetDof(cSec, p, &dof);
9656:       PetscSectionGetOffset(cSec, p, &off);
9657:       for (q = 0; q < dof; q++) i[off + q + 1] = i[off + q] + annz;
9658:     }
9659:   }
9660:   nnz = i[m];
9661:   PetscMalloc1(nnz, &j);
9662:   offset = 0;
9663:   for (p = pStart; p < pEnd; p++) {
9664:     if (numFields) {
9665:       for (f = 0; f < numFields; f++) {
9666:         PetscSectionGetFieldDof(cSec, p, f, &dof);
9667:         for (q = 0; q < dof; q++) {
9668:           PetscInt rDof, rOff, r;
9669:           PetscSectionGetDof(aSec, p, &rDof);
9670:           PetscSectionGetOffset(aSec, p, &rOff);
9671:           for (r = 0; r < rDof; r++) {
9672:             PetscInt s;

9674:             a = anchors[rOff + r];
9675:             if (a < sStart || a >= sEnd) continue;
9676:             PetscSectionGetFieldDof(section, a, f, &aDof);
9677:             PetscSectionGetFieldOffset(section, a, f, &aOff);
9678:             for (s = 0; s < aDof; s++) j[offset++] = aOff + s;
9679:           }
9680:         }
9681:       }
9682:     } else {
9683:       PetscSectionGetDof(cSec, p, &dof);
9684:       for (q = 0; q < dof; q++) {
9685:         PetscInt rDof, rOff, r;
9686:         PetscSectionGetDof(aSec, p, &rDof);
9687:         PetscSectionGetOffset(aSec, p, &rOff);
9688:         for (r = 0; r < rDof; r++) {
9689:           PetscInt s;

9691:           a = anchors[rOff + r];
9692:           if (a < sStart || a >= sEnd) continue;
9693:           PetscSectionGetDof(section, a, &aDof);
9694:           PetscSectionGetOffset(section, a, &aOff);
9695:           for (s = 0; s < aDof; s++) j[offset++] = aOff + s;
9696:         }
9697:       }
9698:     }
9699:   }
9700:   MatSeqAIJSetPreallocationCSR(*cMat, i, j, NULL);
9701:   PetscFree(i);
9702:   PetscFree(j);
9703:   ISRestoreIndices(aIS, &anchors);
9704:   return 0;
9705: }

9707: PetscErrorCode DMCreateDefaultConstraints_Plex(DM dm)
9708: {
9709:   DM_Plex     *plex = (DM_Plex *)dm->data;
9710:   PetscSection anchorSection, section, cSec;
9711:   Mat          cMat;

9714:   DMPlexGetAnchors(dm, &anchorSection, NULL);
9715:   if (anchorSection) {
9716:     PetscInt Nf;

9718:     DMGetLocalSection(dm, &section);
9719:     DMPlexCreateConstraintSection_Anchors(dm, section, &cSec);
9720:     DMPlexCreateConstraintMatrix_Anchors(dm, section, cSec, &cMat);
9721:     DMGetNumFields(dm, &Nf);
9722:     if (Nf && plex->computeanchormatrix) (*plex->computeanchormatrix)(dm, section, cSec, cMat);
9723:     DMSetDefaultConstraints(dm, cSec, cMat, NULL);
9724:     PetscSectionDestroy(&cSec);
9725:     MatDestroy(&cMat);
9726:   }
9727:   return 0;
9728: }

9730: PetscErrorCode DMCreateSubDomainDM_Plex(DM dm, DMLabel label, PetscInt value, IS *is, DM *subdm)
9731: {
9732:   IS           subis;
9733:   PetscSection section, subsection;

9735:   DMGetLocalSection(dm, &section);
9738:   /* Create subdomain */
9739:   DMPlexFilter(dm, label, value, subdm);
9740:   /* Create submodel */
9741:   DMPlexGetSubpointIS(*subdm, &subis);
9742:   PetscSectionCreateSubmeshSection(section, subis, &subsection);
9743:   DMSetLocalSection(*subdm, subsection);
9744:   PetscSectionDestroy(&subsection);
9745:   DMCopyDisc(dm, *subdm);
9746:   /* Create map from submodel to global model */
9747:   if (is) {
9748:     PetscSection    sectionGlobal, subsectionGlobal;
9749:     IS              spIS;
9750:     const PetscInt *spmap;
9751:     PetscInt       *subIndices;
9752:     PetscInt        subSize = 0, subOff = 0, pStart, pEnd, p;
9753:     PetscInt        Nf, f, bs = -1, bsLocal[2], bsMinMax[2];

9755:     DMPlexGetSubpointIS(*subdm, &spIS);
9756:     ISGetIndices(spIS, &spmap);
9757:     PetscSectionGetNumFields(section, &Nf);
9758:     DMGetGlobalSection(dm, &sectionGlobal);
9759:     DMGetGlobalSection(*subdm, &subsectionGlobal);
9760:     PetscSectionGetChart(subsection, &pStart, &pEnd);
9761:     for (p = pStart; p < pEnd; ++p) {
9762:       PetscInt gdof, pSubSize = 0;

9764:       PetscSectionGetDof(sectionGlobal, p, &gdof);
9765:       if (gdof > 0) {
9766:         for (f = 0; f < Nf; ++f) {
9767:           PetscInt fdof, fcdof;

9769:           PetscSectionGetFieldDof(subsection, p, f, &fdof);
9770:           PetscSectionGetFieldConstraintDof(subsection, p, f, &fcdof);
9771:           pSubSize += fdof - fcdof;
9772:         }
9773:         subSize += pSubSize;
9774:         if (pSubSize) {
9775:           if (bs < 0) {
9776:             bs = pSubSize;
9777:           } else if (bs != pSubSize) {
9778:             /* Layout does not admit a pointwise block size */
9779:             bs = 1;
9780:           }
9781:         }
9782:       }
9783:     }
9784:     /* Must have same blocksize on all procs (some might have no points) */
9785:     bsLocal[0] = bs < 0 ? PETSC_MAX_INT : bs;
9786:     bsLocal[1] = bs;
9787:     PetscGlobalMinMaxInt(PetscObjectComm((PetscObject)dm), bsLocal, bsMinMax);
9788:     if (bsMinMax[0] != bsMinMax[1]) {
9789:       bs = 1;
9790:     } else {
9791:       bs = bsMinMax[0];
9792:     }
9793:     PetscMalloc1(subSize, &subIndices);
9794:     for (p = pStart; p < pEnd; ++p) {
9795:       PetscInt gdof, goff;

9797:       PetscSectionGetDof(subsectionGlobal, p, &gdof);
9798:       if (gdof > 0) {
9799:         const PetscInt point = spmap[p];

9801:         PetscSectionGetOffset(sectionGlobal, point, &goff);
9802:         for (f = 0; f < Nf; ++f) {
9803:           PetscInt fdof, fcdof, fc, f2, poff = 0;

9805:           /* Can get rid of this loop by storing field information in the global section */
9806:           for (f2 = 0; f2 < f; ++f2) {
9807:             PetscSectionGetFieldDof(section, p, f2, &fdof);
9808:             PetscSectionGetFieldConstraintDof(section, p, f2, &fcdof);
9809:             poff += fdof - fcdof;
9810:           }
9811:           PetscSectionGetFieldDof(section, p, f, &fdof);
9812:           PetscSectionGetFieldConstraintDof(section, p, f, &fcdof);
9813:           for (fc = 0; fc < fdof - fcdof; ++fc, ++subOff) subIndices[subOff] = goff + poff + fc;
9814:         }
9815:       }
9816:     }
9817:     ISRestoreIndices(spIS, &spmap);
9818:     ISCreateGeneral(PetscObjectComm((PetscObject)dm), subSize, subIndices, PETSC_OWN_POINTER, is);
9819:     if (bs > 1) {
9820:       /* We need to check that the block size does not come from non-contiguous fields */
9821:       PetscInt i, j, set = 1;
9822:       for (i = 0; i < subSize; i += bs) {
9823:         for (j = 0; j < bs; ++j) {
9824:           if (subIndices[i + j] != subIndices[i] + j) {
9825:             set = 0;
9826:             break;
9827:           }
9828:         }
9829:       }
9830:       if (set) ISSetBlockSize(*is, bs);
9831:     }
9832:     /* Attach nullspace */
9833:     for (f = 0; f < Nf; ++f) {
9834:       (*subdm)->nullspaceConstructors[f] = dm->nullspaceConstructors[f];
9835:       if ((*subdm)->nullspaceConstructors[f]) break;
9836:     }
9837:     if (f < Nf) {
9838:       MatNullSpace nullSpace;
9839:       (*(*subdm)->nullspaceConstructors[f])(*subdm, f, f, &nullSpace);

9841:       PetscObjectCompose((PetscObject)*is, "nullspace", (PetscObject)nullSpace);
9842:       MatNullSpaceDestroy(&nullSpace);
9843:     }
9844:   }
9845:   return 0;
9846: }

9848: /*@
9849:   DMPlexMonitorThroughput - Report the cell throughput of FE integration

9851:   Input Parameter:
9852: - dm - The DM

9854:   Level: developer

9856:   Options Database Keys:
9857: . -dm_plex_monitor_throughput - Activate the monitor

9859: .seealso: `DMSetFromOptions()`, `DMPlexCreate()`
9860: @*/
9861: PetscErrorCode DMPlexMonitorThroughput(DM dm, void *dummy)
9862: {
9863: #if defined(PETSC_USE_LOG)
9864:   PetscStageLog      stageLog;
9865:   PetscLogEvent      event;
9866:   PetscLogStage      stage;
9867:   PetscEventPerfInfo eventInfo;
9868:   PetscReal          cellRate, flopRate;
9869:   PetscInt           cStart, cEnd, Nf, N;
9870:   const char        *name;
9871: #endif

9874: #if defined(PETSC_USE_LOG)
9875:   PetscObjectGetName((PetscObject)dm, &name);
9876:   DMPlexGetHeightStratum(dm, 0, &cStart, &cEnd);
9877:   DMGetNumFields(dm, &Nf);
9878:   PetscLogGetStageLog(&stageLog);
9879:   PetscStageLogGetCurrent(stageLog, &stage);
9880:   PetscLogEventGetId("DMPlexResidualFE", &event);
9881:   PetscLogEventGetPerfInfo(stage, event, &eventInfo);
9882:   N        = (cEnd - cStart) * Nf * eventInfo.count;
9883:   flopRate = eventInfo.flops / eventInfo.time;
9884:   cellRate = N / eventInfo.time;
9885:   PetscPrintf(PetscObjectComm((PetscObject)dm), "DM (%s) FE Residual Integration: %" PetscInt_FMT " integrals %d reps\n  Cell rate: %.2g/s flop rate: %.2g MF/s\n", name ? name : "unknown", N, eventInfo.count, (double)cellRate, (double)(flopRate / 1.e6));
9886: #else
9887:   SETERRQ(PetscObjectComm((PetscObject)dm), PETSC_ERR_SUP, "Plex Throughput Monitor is not supported if logging is turned off. Reconfigure using --with-log.");
9888: #endif
9889:   return 0;
9890: }