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>
 11: #include <petscblaslapack.h>

 13: /* Logging support */
 14: PetscLogEvent DMPLEX_Interpolate, DMPLEX_Partition, DMPLEX_Distribute, DMPLEX_DistributeMultistage, 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_CreateBoxSFC, 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;
 15: PetscLogEvent DMPLEX_RebalBuildGraph, DMPLEX_RebalRewriteSF, DMPLEX_RebalGatherGraph, DMPLEX_RebalPartition, DMPLEX_RebalScatterPart, DMPLEX_Generate, DMPLEX_GetLocalOffsets, DMPLEX_Uninterpolate;
 16: PetscLogEvent DMPLEX_DistributionView, DMPLEX_DistributionLoad;

 18: PetscBool  Plexcite       = PETSC_FALSE;
 19: const char PlexCitation[] = "@article{LangeMitchellKnepleyGorman2015,\n"
 20:                             "title     = {Efficient mesh management in {Firedrake} using {PETSc-DMPlex}},\n"
 21:                             "author    = {Michael Lange and Lawrence Mitchell and Matthew G. Knepley and Gerard J. Gorman},\n"
 22:                             "journal   = {SIAM Journal on Scientific Computing},\n"
 23:                             "volume    = {38},\n"
 24:                             "number    = {5},\n"
 25:                             "pages     = {S143--S155},\n"
 26:                             "eprint    = {http://arxiv.org/abs/1506.07749},\n"
 27:                             "doi       = {10.1137/15M1026092},\n"
 28:                             "year      = {2016},\n"
 29:                             "petsc_uses={DMPlex},\n}\n";

 31: PETSC_SINGLE_LIBRARY_INTERN PetscErrorCode VecView_MPI(Vec, PetscViewer);

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

 36:   Input Parameter:
 37: . dm - The `DMPLEX` object

 39:   Output Parameter:
 40: . simplex - Flag checking for a simplex

 42:   Level: intermediate

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

 48: .seealso: [](ch_unstructured), `DM`, `DMPLEX`, `DMPlexGetSimplexOrBoxCells()`, `DMPlexGetCellType()`, `DMPlexGetHeightStratum()`, `DMPolytopeTypeGetNumVertices()`
 49: @*/
 50: PetscErrorCode DMPlexIsSimplex(DM dm, PetscBool *simplex)
 51: {
 52:   DMPolytopeType ct;
 53:   PetscInt       cStart, cEnd, cHeight;

 55:   PetscFunctionBegin;
 56:   PetscCall(DMPlexGetVTKCellHeight(dm, &cHeight));
 57:   PetscCall(DMPlexGetHeightStratum(dm, cHeight, &cStart, &cEnd));
 58:   if (cEnd <= cStart) {
 59:     *simplex = PETSC_FALSE;
 60:     PetscFunctionReturn(PETSC_SUCCESS);
 61:   }
 62:   PetscCall(DMPlexGetCellType(dm, cStart, &ct));
 63:   *simplex = DMPolytopeTypeGetNumVertices(ct) == DMPolytopeTypeGetDim(ct) + 1 ? PETSC_TRUE : PETSC_FALSE;
 64:   PetscFunctionReturn(PETSC_SUCCESS);
 65: }

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

 70:   Input Parameters:
 71: + dm     - The `DMPLEX` object
 72: - height - The cell height in the Plex, 0 is the default

 74:   Output Parameters:
 75: + cStart - The first "normal" cell, pass `NULL` if not needed
 76: - cEnd   - The upper bound on "normal" cells, pass `NULL` if not needed

 78:   Level: developer

 80:   Note:
 81:   This function requires that tensor cells are ordered last.

 83: .seealso: [](ch_unstructured), `DM`, `DMPLEX`, `DMPlexConstructGhostCells()`, `DMPlexGetCellTypeStratum()`
 84: @*/
 85: PetscErrorCode DMPlexGetSimplexOrBoxCells(DM dm, PetscInt height, PeOp PetscInt *cStart, PeOp PetscInt *cEnd)
 86: {
 87:   DMLabel         ctLabel;
 88:   IS              valueIS;
 89:   const PetscInt *ctypes;
 90:   PetscBool       found = PETSC_FALSE;
 91:   PetscInt        Nct, cS = PETSC_INT_MAX, cE = 0;

 93:   PetscFunctionBegin;
 94:   PetscCall(DMPlexGetCellTypeLabel(dm, &ctLabel));
 95:   PetscCall(DMLabelGetValueIS(ctLabel, &valueIS));
 96:   PetscCall(ISGetLocalSize(valueIS, &Nct));
 97:   PetscCall(ISGetIndices(valueIS, &ctypes));
 98:   for (PetscInt t = 0; t < Nct; ++t) {
 99:     const DMPolytopeType ct = (DMPolytopeType)ctypes[t];
100:     PetscInt             ctS, ctE, ht;

102:     if (ct == DM_POLYTOPE_UNKNOWN) {
103:       // If any cells are not typed, just use all cells
104:       PetscCall(DMPlexGetHeightStratum(dm, PetscMax(height, 0), cStart, cEnd));
105:       break;
106:     }
107:     if (DMPolytopeTypeIsHybrid(ct) || ct == DM_POLYTOPE_FV_GHOST) continue;
108:     PetscCall(DMLabelGetStratumBounds(ctLabel, ct, &ctS, &ctE));
109:     if (ctS >= ctE) continue;
110:     // Check that a point has the right height
111:     PetscCall(DMPlexGetPointHeight(dm, ctS, &ht));
112:     if (ht != height) continue;
113:     cS    = PetscMin(cS, ctS);
114:     cE    = PetscMax(cE, ctE);
115:     found = PETSC_TRUE;
116:   }
117:   if (!Nct || !found) cS = cE = 0;
118:   PetscCall(ISDestroy(&valueIS));
119:   // Reset label for fast lookup
120:   PetscCall(DMLabelMakeAllInvalid_Internal(ctLabel));
121:   if (cStart) *cStart = cS;
122:   if (cEnd) *cEnd = cE;
123:   PetscFunctionReturn(PETSC_SUCCESS);
124: }

126: PetscErrorCode DMPlexGetFieldTypes_Internal(DM dm, PetscSection section, PetscInt field, PetscInt *types, PetscInt **ssStart, PetscInt **ssEnd, PetscViewerVTKFieldType **sft)
127: {
128:   PetscInt                 cdim, pStart, pEnd, vStart, vEnd, cStart, cEnd, c, depth, cellHeight, t;
129:   PetscInt                *sStart, *sEnd;
130:   PetscViewerVTKFieldType *ft;
131:   PetscInt                 vcdof[DM_NUM_POLYTOPES + 1], globalvcdof[DM_NUM_POLYTOPES + 1];
132:   DMLabel                  depthLabel, ctLabel;

134:   PetscFunctionBegin;
135:   /* the vcdof and globalvcdof are sized to allow every polytope type and simple vertex at DM_NUM_POLYTOPES */
136:   PetscCall(PetscArrayzero(vcdof, DM_NUM_POLYTOPES + 1));
137:   PetscCall(DMGetCoordinateDim(dm, &cdim));
138:   PetscCall(DMPlexGetDepthStratum(dm, 0, &vStart, &vEnd));
139:   PetscCall(PetscSectionGetChart(section, &pStart, &pEnd));
140:   if (field >= 0) {
141:     if ((vStart >= pStart) && (vStart < pEnd)) PetscCall(PetscSectionGetFieldDof(section, vStart, field, &vcdof[DM_NUM_POLYTOPES]));
142:   } else {
143:     if ((vStart >= pStart) && (vStart < pEnd)) PetscCall(PetscSectionGetDof(section, vStart, &vcdof[DM_NUM_POLYTOPES]));
144:   }

146:   PetscCall(DMPlexGetVTKCellHeight(dm, &cellHeight));
147:   PetscCall(DMPlexGetDepth(dm, &depth));
148:   PetscCall(DMPlexGetDepthLabel(dm, &depthLabel));
149:   PetscCall(DMPlexGetCellTypeLabel(dm, &ctLabel));
150:   for (c = 0; c < DM_NUM_POLYTOPES; ++c) {
151:     const DMPolytopeType ict = (DMPolytopeType)c;
152:     PetscInt             dep;

154:     if (ict == DM_POLYTOPE_FV_GHOST) continue;
155:     PetscCall(DMLabelGetStratumBounds(ctLabel, ict, &cStart, &cEnd));
156:     if (pStart >= 0) {
157:       PetscCall(DMLabelGetValue(depthLabel, cStart, &dep));
158:       if (dep != depth - cellHeight) continue;
159:     }
160:     if (field >= 0) {
161:       if ((cStart >= pStart) && (cStart < pEnd)) PetscCall(PetscSectionGetFieldDof(section, cStart, field, &vcdof[c]));
162:     } else {
163:       if ((cStart >= pStart) && (cStart < pEnd)) PetscCall(PetscSectionGetDof(section, cStart, &vcdof[c]));
164:     }
165:   }

167:   PetscCallMPI(MPIU_Allreduce(vcdof, globalvcdof, DM_NUM_POLYTOPES + 1, MPIU_INT, MPI_MAX, PetscObjectComm((PetscObject)dm)));
168:   *types = 0;

170:   for (c = 0; c < DM_NUM_POLYTOPES + 1; ++c) {
171:     if (globalvcdof[c]) ++(*types);
172:   }

174:   PetscCall(PetscMalloc3(*types, &sStart, *types, &sEnd, *types, &ft));
175:   t = 0;
176:   if (globalvcdof[DM_NUM_POLYTOPES]) {
177:     sStart[t] = vStart;
178:     sEnd[t]   = vEnd;
179:     ft[t]     = (globalvcdof[t] == cdim) ? PETSC_VTK_POINT_VECTOR_FIELD : PETSC_VTK_POINT_FIELD;
180:     ++t;
181:   }

183:   for (c = 0; c < DM_NUM_POLYTOPES; ++c) {
184:     if (globalvcdof[c]) {
185:       const DMPolytopeType ict = (DMPolytopeType)c;

187:       PetscCall(DMLabelGetStratumBounds(ctLabel, ict, &cStart, &cEnd));
188:       sStart[t] = cStart;
189:       sEnd[t]   = cEnd;
190:       ft[t]     = (globalvcdof[c] == cdim) ? PETSC_VTK_CELL_VECTOR_FIELD : PETSC_VTK_CELL_FIELD;
191:       ++t;
192:     }
193:   }

195:   if (!*types) {
196:     if (field >= 0) {
197:       const char *fieldname;

199:       PetscCall(PetscSectionGetFieldName(section, field, &fieldname));
200:       PetscCall(PetscInfo((PetscObject)dm, "Could not classify VTK output type of section field %" PetscInt_FMT " \"%s\"\n", field, fieldname));
201:     } else {
202:       PetscCall(PetscInfo((PetscObject)dm, "Could not classify VTK output type of section\n"));
203:     }
204:   }

206:   *ssStart = sStart;
207:   *ssEnd   = sEnd;
208:   *sft     = ft;
209:   PetscFunctionReturn(PETSC_SUCCESS);
210: }

212: PetscErrorCode DMPlexRestoreFieldTypes_Internal(DM dm, PetscSection section, PetscInt field, PetscInt *types, PetscInt **sStart, PetscInt **sEnd, PetscViewerVTKFieldType **ft)
213: {
214:   PetscFunctionBegin;
215:   PetscCall(PetscFree3(*sStart, *sEnd, *ft));
216:   PetscFunctionReturn(PETSC_SUCCESS);
217: }

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

224:   PetscFunctionBegin;
225:   *ft = PETSC_VTK_INVALID;
226:   PetscCall(DMGetCoordinateDim(dm, &cdim));
227:   PetscCall(DMPlexGetDepthStratum(dm, 0, &vStart, &vEnd));
228:   PetscCall(DMPlexGetSimplexOrBoxCells(dm, 0, &cStart, &cEnd));
229:   PetscCall(PetscSectionGetChart(section, &pStart, &pEnd));
230:   if (field >= 0) {
231:     if ((vStart >= pStart) && (vStart < pEnd)) PetscCall(PetscSectionGetFieldDof(section, vStart, field, &vcdof[0]));
232:     if ((cStart >= pStart) && (cStart < pEnd)) PetscCall(PetscSectionGetFieldDof(section, cStart, field, &vcdof[1]));
233:   } else {
234:     if ((vStart >= pStart) && (vStart < pEnd)) PetscCall(PetscSectionGetDof(section, vStart, &vcdof[0]));
235:     if ((cStart >= pStart) && (cStart < pEnd)) PetscCall(PetscSectionGetDof(section, cStart, &vcdof[1]));
236:   }
237:   PetscCallMPI(MPIU_Allreduce(vcdof, globalvcdof, 2, MPIU_INT, MPI_MAX, PetscObjectComm((PetscObject)dm)));
238:   if (globalvcdof[0]) {
239:     *sStart = vStart;
240:     *sEnd   = vEnd;
241:     if (globalvcdof[0] == cdim) *ft = PETSC_VTK_POINT_VECTOR_FIELD;
242:     else *ft = PETSC_VTK_POINT_FIELD;
243:   } else if (globalvcdof[1]) {
244:     *sStart = cStart;
245:     *sEnd   = cEnd;
246:     if (globalvcdof[1] == cdim) *ft = PETSC_VTK_CELL_VECTOR_FIELD;
247:     else *ft = PETSC_VTK_CELL_FIELD;
248:   } else {
249:     if (field >= 0) {
250:       const char *fieldname;

252:       PetscCall(PetscSectionGetFieldName(section, field, &fieldname));
253:       PetscCall(PetscInfo(dm, "Could not classify VTK output type of section field %" PetscInt_FMT " \"%s\"\n", field, fieldname));
254:     } else {
255:       PetscCall(PetscInfo(dm, "Could not classify VTK output type of section\n"));
256:     }
257:   }
258:   PetscFunctionReturn(PETSC_SUCCESS);
259: }

261: static PetscErrorCode DMPlexVecFFT1D_Internal(DM dm, PetscBool removeDC, PetscInt n, Vec u, Vec uhat)
262: {
263:   Mat      FT;
264:   Vec      fftX, fftY;
265:   IS       fftReal;
266:   PetscInt N;

268:   PetscFunctionBegin;
269:   PetscCall(VecDuplicate(u, &uhat));
270:   PetscCall(VecGetSize(u, &N));
271:   PetscCall(MatCreateFFT(PetscObjectComm((PetscObject)dm), 1, &N, MATFFTW, &FT));
272:   PetscCall(MatCreateVecs(FT, &fftX, &fftY));
273:   PetscCall(ISCreateStride(PETSC_COMM_SELF, N, 0, 1, &fftReal));

275:   PetscCall(VecISCopy(fftX, fftReal, SCATTER_FORWARD, u));
276:   PetscCall(MatMult(FT, fftX, fftY));
277:   PetscCall(VecFilter(fftY, PETSC_SMALL));
278:   PetscCall(VecISCopy(fftY, fftReal, SCATTER_REVERSE, uhat));
279:   if (removeDC) PetscCall(VecSetValue(uhat, 0, 0., INSERT_VALUES)); // Remove DC component

281:   PetscCall(MatDestroy(&FT));
282:   PetscCall(VecDestroy(&fftX));
283:   PetscCall(VecDestroy(&fftY));
284:   PetscCall(ISDestroy(&fftReal));
285:   PetscFunctionReturn(PETSC_SUCCESS);
286: }

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

291:   Collective

293:   Input Parameters:
294: + dm     - The `DMPLEX` object
295: . n      - The number of vectors
296: . u      - The array of local vectors
297: - viewer - The `PetscViewer`

299:   Level: advanced

301: .seealso: [](ch_unstructured), `DM`, `DMPLEX`, `VecViewFromOptions()`, `VecView()`
302: @*/
303: PetscErrorCode DMPlexVecView1D(DM dm, PetscInt n, Vec u[], PetscViewer viewer)
304: {
305:   DM                  cdm;
306:   PetscDS             ds;
307:   PetscSection        s;
308:   Vec                *uhat;        // Fourier transform of each vector u[i]
309:   Vec                 coordinates; // Local vector of mesh coordinate
310:   const PetscScalar  *coords;      // Coordinate values
311:   const PetscScalar **sol;         // Arrays from each vector u[i]
312:   char              **names;       // Names for each component of each vector
313:   PetscReal          *vals;        // Values at a point for each component of each vector
314:   PetscInt           *Nc;          // Number of components for each field
315:   PetscInt            Ntc;         // Total number of components across all fields
316:   PetscInt            Nw;          // Number of plots
317:   PetscInt            cdof;        // Total number of cell dofs
318:   PetscInt            vdof;        // Total number of vertex dofs
319:   PetscInt            k;           // The Lagrange degree, and drawing mode
320:   PetscInt            Nf, vStart, vEnd, eStart, eEnd;
321:   PetscBool           separateCmp = PETSC_TRUE;  // Plot components of fields
322:   PetscBool           fft         = PETSC_FALSE; // Fourier Transform the field before plotting
323:   PetscBool           removeDC    = PETSC_FALSE; // Remove DC component before plotting

325:   PetscFunctionBegin;
326:   PetscCall(PetscOptionsGetBool(((PetscObject)dm)->options, ((PetscObject)dm)->prefix, "-dm_plex_view_1d_fft", &fft, NULL));
327:   PetscCall(PetscOptionsGetBool(((PetscObject)dm)->options, ((PetscObject)dm)->prefix, "-dm_plex_view_1d_components", &separateCmp, NULL));
328:   PetscCall(PetscOptionsGetBool(((PetscObject)dm)->options, ((PetscObject)dm)->prefix, "-dm_plex_view_1d_remove_dc", &removeDC, NULL));
329:   if (!n) fft = PETSC_FALSE;
330:   if (fft) {
331:     PetscCall(PetscMalloc1(n, &uhat));
332:     for (PetscInt i = 0; i < n; ++i) {
333:       PetscCall(VecDuplicate(u[i], &uhat[i]));
334:       PetscCall(DMPlexVecFFT1D_Internal(dm, removeDC, 1, u[i], uhat[i]));
335:     }
336:   }
337:   PetscCall(DMPlexGetDepthStratum(dm, 0, &vStart, &vEnd));
338:   PetscCall(DMPlexGetDepthStratum(dm, 1, &eStart, &eEnd));
339:   PetscCall(DMGetCoordinateDM(dm, &cdm));
340:   PetscCall(DMGetDS(dm, &ds));
341:   PetscCall(PetscDSGetNumFields(ds, &Nf));
342:   PetscCall(PetscDSGetTotalComponents(ds, &Ntc));
343:   PetscCall(PetscDSGetComponents(ds, &Nc));

345:   PetscCall(DMGetLocalSection(dm, &s));
346:   PetscCall(PetscSectionGetDof(s, eStart, &cdof));
347:   PetscCall(PetscSectionGetDof(s, vStart, &vdof));
348:   PetscCheck(cdof || vdof, PetscObjectComm((PetscObject)dm), PETSC_ERR_ARG_WRONG, "Unsupported discretization");
349:   if (cdof && vdof) k = 2;
350:   else if (vdof) k = 1;
351:   else if (cdof) k = 0;

353:   PetscCall(PetscMalloc3(n, &sol, n * Ntc, &names, n * Ntc, &vals));
354:   for (PetscInt i = 0, l = 0; i < n; ++i) {
355:     const char *vname;

357:     PetscCall(PetscObjectGetName((PetscObject)u[i], &vname));
358:     for (PetscInt f = 0; f < Nf; ++f) {
359:       PetscObject disc;
360:       const char *fname;
361:       char        tmpname[PETSC_MAX_PATH_LEN];

363:       PetscCall(PetscDSGetDiscretization(ds, f, &disc));
364:       /* TODO Create names for components */
365:       for (PetscInt c = 0; c < Nc[f]; ++c, ++l) {
366:         PetscCall(PetscObjectGetName(disc, &fname));
367:         PetscCall(PetscStrncpy(tmpname, vname, sizeof(tmpname)));
368:         PetscCall(PetscStrlcat(tmpname, ":", sizeof(tmpname)));
369:         PetscCall(PetscStrlcat(tmpname, fname, sizeof(tmpname)));
370:         PetscCall(PetscStrallocpy(tmpname, &names[l]));
371:       }
372:     }
373:   }

375:   PetscCall(DMGetCoordinatesLocal(dm, &coordinates));
376:   PetscCall(VecGetArrayRead(coordinates, &coords));
377:   for (PetscInt i = 0; i < n; ++i) PetscCall(VecGetArrayRead(fft ? uhat[i] : u[i], &sol[i]));

379:   PetscDrawLG *lg;

381:   Nw = separateCmp ? Ntc : 1;
382:   PetscCall(PetscMalloc1(Nw, &lg));
383:   for (PetscInt w = 0; w < Nw; ++w) {
384:     PetscDraw      draw   = NULL;
385:     const PetscInt Nl     = separateCmp ? 1 : Ntc;
386:     PetscInt       vFirst = -1;
387:     PetscInt       field  = 0;
388:     PetscInt       cmp    = 0;
389:     PetscInt       tcmp   = 0;

391:     if (separateCmp) {
392:       for (PetscInt f = 0; f < Nf; ++f) {
393:         PetscInt c;

395:         for (c = 0; c < Nc[f]; ++c, ++tcmp) {
396:           if (tcmp == w) {
397:             cmp = c;
398:             break;
399:           }
400:         }
401:         if (c < Nc[f]) {
402:           field = f;
403:           break;
404:         }
405:       }
406:     }
407:     PetscCall(PetscViewerDrawGetDraw(viewer, w, &draw));
408:     if (!draw) PetscFunctionReturn(PETSC_SUCCESS);
409:     PetscCall(PetscDrawLGCreate(draw, n * Nl, &lg[w]));

411:     PetscCall(PetscDrawLGSetLegend(lg[w], (const char *const *)&names[w]));
412:     switch (k) {
413:     case 0:
414:       for (PetscInt e = eStart; e < eEnd; ++e) {
415:         PetscScalar    *xa, *xb, *svals;
416:         const PetscInt *cone;

418:         PetscCall(DMPlexGetCone(dm, e, &cone));
419:         PetscCall(DMPlexPointLocalRead(cdm, cone[0], coords, &xa));
420:         PetscCall(DMPlexPointLocalRead(cdm, cone[1], coords, &xb));
421:         for (PetscInt i = 0; i < n; ++i) {
422:           if (separateCmp) {
423:             PetscCall(DMPlexPointLocalFieldRead(dm, e, field, sol[i], &svals));
424:             vals[i] = PetscRealPart(svals[cmp]);
425:           } else {
426:             PetscCall(DMPlexPointLocalRead(dm, e, sol[i], &svals));
427:             for (PetscInt l = 0; l < Nl; ++l) vals[i * Nl + l] = PetscRealPart(svals[l]);
428:           }
429:         }
430:         PetscCall(PetscDrawLGAddCommonPoint(lg[w], 0.5 * (PetscRealPart(xa[0]) + PetscRealPart(xb[0])), vals));
431:       }
432:       break;
433:     case 1:
434:       for (PetscInt v = vStart; v < vEnd; ++v) {
435:         PetscScalar *x, *svals;

437:         PetscCall(DMPlexPointLocalRead(cdm, v, coords, &x));
438:         for (PetscInt i = 0; i < n; ++i) {
439:           if (separateCmp) {
440:             PetscCall(DMPlexPointLocalFieldRead(dm, v, field, sol[i], &svals));
441:             vals[i] = PetscRealPart(svals[cmp]);
442:           } else {
443:             PetscCall(DMPlexPointLocalRead(dm, v, sol[i], &svals));
444:             for (PetscInt l = 0; l < Nl; ++l) vals[i * Nl + l] = PetscRealPart(svals[l]);
445:           }
446:         }
447:         PetscCall(PetscDrawLGAddCommonPoint(lg[w], PetscRealPart(x[0]), vals));
448:       }
449:       break;
450:     case 2:
451:       for (PetscInt e = eStart; e < eEnd; ++e) {
452:         PetscScalar    *xa, *xb, *svals;
453:         const PetscInt *cone;

455:         PetscCall(DMPlexGetCone(dm, e, &cone));
456:         PetscCall(DMPlexPointLocalRead(cdm, cone[0], coords, &xa));
457:         PetscCall(DMPlexPointLocalRead(cdm, cone[1], coords, &xb));
458:         if (e == eStart) vFirst = cone[0];
459:         for (PetscInt i = 0; i < n; ++i) {
460:           if (separateCmp) {
461:             PetscCall(DMPlexPointLocalFieldRead(dm, cone[0], field, sol[i], &svals));
462:             vals[i] = PetscRealPart(svals[cmp]);
463:           } else {
464:             PetscCall(DMPlexPointLocalRead(dm, cone[0], sol[i], &svals));
465:             for (PetscInt l = 0; l < Nl; ++l) vals[i * Nl + l] = PetscRealPart(svals[l]);
466:           }
467:         }
468:         PetscCall(PetscDrawLGAddCommonPoint(lg[w], PetscRealPart(xa[0]), vals));
469:         if (e == eEnd - 1 && cone[1] != vFirst) {
470:           for (PetscInt i = 0; i < n; ++i) {
471:             if (separateCmp) {
472:               PetscCall(DMPlexPointLocalFieldRead(dm, e, field, sol[i], &svals));
473:               vals[i] = PetscRealPart(svals[cmp]);
474:             } else {
475:               PetscCall(DMPlexPointLocalRead(dm, e, sol[i], &svals));
476:               for (PetscInt l = 0; l < Nl; ++l) vals[i * Nl + l] = PetscRealPart(svals[l]);
477:             }
478:           }
479:           PetscCall(PetscDrawLGAddCommonPoint(lg[w], 0.5 * (PetscRealPart(xa[0]) + PetscRealPart(xb[0])), vals));
480:           for (PetscInt i = 0; i < n; ++i) {
481:             if (separateCmp) {
482:               PetscCall(DMPlexPointLocalFieldRead(dm, cone[1], field, sol[i], &svals));
483:               vals[i] = PetscRealPart(svals[cmp]);
484:             } else {
485:               PetscCall(DMPlexPointLocalRead(dm, cone[1], sol[i], &svals));
486:               for (PetscInt l = 0; l < Nl; ++l) vals[i * Nl + l] = PetscRealPart(svals[l]);
487:             }
488:           }
489:           PetscCall(PetscDrawLGAddCommonPoint(lg[w], PetscRealPart(xb[0]), vals));
490:         }
491:       }
492:       break;
493:     default:
494:       SETERRQ(PetscObjectComm((PetscObject)dm), PETSC_ERR_PLIB, "Invalid value of k: %" PetscInt_FMT, k);
495:     }
496:   }
497:   PetscCall(VecRestoreArrayRead(coordinates, &coords));
498:   for (PetscInt i = 0; i < n; ++i) PetscCall(VecRestoreArrayRead(fft ? uhat[i] : u[i], &sol[i]));
499:   if (fft) {
500:     for (PetscInt i = 0; i < n; ++i) PetscCall(VecDestroy(&uhat[i]));
501:     PetscCall(PetscFree(uhat));
502:   }
503:   for (PetscInt l = 0; l < n * Ntc; ++l) PetscCall(PetscFree(names[l]));
504:   PetscCall(PetscFree3(sol, names, vals));
505:   for (PetscInt w = 0; w < Nw; ++w) {
506:     PetscCall(PetscDrawLGDraw(lg[w]));
507:     PetscCall(PetscDrawLGDestroy(&lg[w]));
508:   }
509:   PetscCall(PetscFree(lg));
510:   PetscFunctionReturn(PETSC_SUCCESS);
511: }

513: static PetscErrorCode VecView_Plex_Local_Draw_1D(Vec u, PetscViewer viewer)
514: {
515:   DM dm;

517:   PetscFunctionBegin;
518:   PetscCall(VecGetDM(u, &dm));
519:   PetscCall(DMPlexVecView1D(dm, 1, &u, viewer));
520:   PetscFunctionReturn(PETSC_SUCCESS);
521: }

523: static PetscErrorCode VecView_Plex_Local_Draw_2D(Vec v, PetscViewer viewer)
524: {
525:   DM                 dm;
526:   PetscSection       s;
527:   PetscDraw          draw, popup;
528:   DM                 cdm;
529:   PetscSection       coordSection;
530:   Vec                coordinates;
531:   const PetscScalar *array;
532:   PetscReal          lbound[3], ubound[3];
533:   PetscReal          vbound[2], time;
534:   PetscBool          flg;
535:   PetscInt           dim, Nf, f, Nc, comp, vStart, vEnd, cStart, cEnd, c, N, level, step, w = 0;
536:   const char        *name;
537:   char               title[PETSC_MAX_PATH_LEN];

539:   PetscFunctionBegin;
540:   PetscCall(PetscViewerDrawGetDraw(viewer, 0, &draw));
541:   PetscCall(VecGetDM(v, &dm));
542:   PetscCall(DMGetCoordinateDim(dm, &dim));
543:   PetscCall(DMGetLocalSection(dm, &s));
544:   PetscCall(PetscSectionGetNumFields(s, &Nf));
545:   PetscCall(DMGetCoarsenLevel(dm, &level));
546:   PetscCall(DMGetCoordinateDM(dm, &cdm));
547:   PetscCall(DMGetLocalSection(cdm, &coordSection));
548:   PetscCall(DMGetCoordinatesLocal(dm, &coordinates));
549:   PetscCall(DMPlexGetDepthStratum(dm, 0, &vStart, &vEnd));
550:   PetscCall(DMPlexGetHeightStratum(dm, 0, &cStart, &cEnd));

552:   PetscCall(PetscObjectGetName((PetscObject)v, &name));
553:   PetscCall(DMGetOutputSequenceNumber(dm, &step, &time));

555:   PetscCall(VecGetLocalSize(coordinates, &N));
556:   PetscCall(DMGetBoundingBox(dm, lbound, ubound));
557:   PetscCall(PetscDrawClear(draw));

559:   /* Could implement something like DMDASelectFields() */
560:   for (f = 0; f < Nf; ++f) {
561:     DM          fdm = dm;
562:     Vec         fv  = v;
563:     IS          fis;
564:     char        prefix[PETSC_MAX_PATH_LEN];
565:     const char *fname;

567:     PetscCall(PetscSectionGetFieldComponents(s, f, &Nc));
568:     PetscCall(PetscSectionGetFieldName(s, f, &fname));

570:     if (v->hdr.prefix) PetscCall(PetscStrncpy(prefix, v->hdr.prefix, sizeof(prefix)));
571:     else prefix[0] = '\0';
572:     if (Nf > 1) {
573:       PetscCall(DMCreateSubDM(dm, 1, &f, &fis, &fdm));
574:       PetscCall(VecGetSubVector(v, fis, &fv));
575:       PetscCall(PetscStrlcat(prefix, fname, sizeof(prefix)));
576:       PetscCall(PetscStrlcat(prefix, "_", sizeof(prefix)));
577:     }
578:     for (comp = 0; comp < Nc; ++comp, ++w) {
579:       PetscInt nmax = 2;

581:       PetscCall(PetscViewerDrawGetDraw(viewer, w, &draw));
582:       if (Nc > 1) PetscCall(PetscSNPrintf(title, sizeof(title), "%s:%s_%" PetscInt_FMT " Step: %" PetscInt_FMT " Time: %.4g", name, fname, comp, step, (double)time));
583:       else PetscCall(PetscSNPrintf(title, sizeof(title), "%s:%s Step: %" PetscInt_FMT " Time: %.4g", name, fname, step, (double)time));
584:       PetscCall(PetscDrawSetTitle(draw, title));

586:       /* TODO Get max and min only for this component */
587:       PetscCall(PetscOptionsGetRealArray(NULL, prefix, "-vec_view_bounds", vbound, &nmax, &flg));
588:       if (!flg) {
589:         PetscCall(VecMin(fv, NULL, &vbound[0]));
590:         PetscCall(VecMax(fv, NULL, &vbound[1]));
591:         if (vbound[1] <= vbound[0]) vbound[1] = vbound[0] + 1.0;
592:       }

594:       PetscCall(PetscDrawGetPopup(draw, &popup));
595:       PetscCall(PetscDrawScalePopup(popup, vbound[0], vbound[1]));
596:       PetscCall(PetscDrawSetCoordinates(draw, lbound[0], lbound[1], ubound[0], ubound[1]));
597:       PetscCall(VecGetArrayRead(fv, &array));
598:       for (c = cStart; c < cEnd; ++c) {
599:         DMPolytopeType     ct;
600:         PetscScalar       *coords = NULL, *a = NULL;
601:         const PetscScalar *coords_arr;
602:         PetscBool          isDG;
603:         PetscInt           numCoords;
604:         int                color[4] = {-1, -1, -1, -1};

606:         PetscCall(DMPlexGetCellType(dm, c, &ct));
607:         PetscCall(DMPlexPointLocalRead(fdm, c, array, &a));
608:         if (a) {
609:           color[0] = PetscDrawRealToColor(PetscRealPart(a[comp]), vbound[0], vbound[1]);
610:           color[1] = color[2] = color[3] = color[0];
611:         } else {
612:           PetscScalar *vals = NULL;
613:           PetscInt     numVals;

615:           PetscCall(DMPlexVecGetClosure(fdm, NULL, fv, c, &numVals, &vals));
616:           if (!numVals) {
617:             PetscCall(DMPlexVecRestoreClosure(fdm, NULL, fv, c, &numVals, &vals));
618:             continue;
619:           }
620:           PetscCheck(numVals % Nc == 0, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "The number of components %" PetscInt_FMT " does not divide the number of values in the closure %" PetscInt_FMT, Nc, numVals);
621:           switch (numVals / Nc) {
622:           case 1: /* P1 Clamped Segment Prism */
623:           case 2: /* P1 Segment Prism, P2 Clamped Segment Prism */
624:             PetscCheck(ct == DM_POLYTOPE_SEG_PRISM_TENSOR, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Cell should be a tensor segment, but it is a %s", DMPolytopeTypes[ct]);
625:             for (PetscInt va = 0; va < numVals / Nc; ++va) color[va] = PetscDrawRealToColor(PetscRealPart(vals[va * Nc + comp]), vbound[0], vbound[1]);
626:             break;
627:           case 3: /* P1 Triangle */
628:           case 4: /* P1 Quadrangle */
629:             PetscCheck(ct == DM_POLYTOPE_TRIANGLE || ct == DM_POLYTOPE_QUADRILATERAL || ct == DM_POLYTOPE_SEG_PRISM_TENSOR, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Cell should be a triangle or quad, but it is a %s", DMPolytopeTypes[ct]);
630:             for (PetscInt va = 0; va < numVals / Nc; ++va) color[va] = PetscDrawRealToColor(PetscRealPart(vals[va * Nc + comp]), vbound[0], vbound[1]);
631:             break;
632:           case 6: /* P2 Triangle */
633:           case 8: /* P2 Quadrangle */
634:             PetscCheck(ct == DM_POLYTOPE_TRIANGLE || ct == DM_POLYTOPE_QUADRILATERAL || ct == DM_POLYTOPE_SEG_PRISM_TENSOR, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Cell should be a triangle or quad, but it is a %s", DMPolytopeTypes[ct]);
635:             for (PetscInt va = 0; va < numVals / (Nc * 2); ++va) color[va] = PetscDrawRealToColor(PetscRealPart(vals[va * Nc + comp + numVals / (Nc * 2)]), vbound[0], vbound[1]);
636:             break;
637:           default:
638:             SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Number of values for cell closure %" PetscInt_FMT " cannot be handled", numVals / Nc);
639:           }
640:           PetscCall(DMPlexVecRestoreClosure(fdm, NULL, fv, c, &numVals, &vals));
641:         }
642:         PetscCall(DMPlexGetCellCoordinates(dm, c, &isDG, &numCoords, &coords_arr, &coords));
643:         switch (numCoords) {
644:         case 6:
645:         case 12: /* Localized triangle */
646:           PetscCall(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]));
647:           break;
648:         case 8:
649:         case 16: /* Localized quadrilateral */
650:           if (ct == DM_POLYTOPE_SEG_PRISM_TENSOR) {
651:             PetscCall(PetscDrawLine(draw, PetscRealPart(coords[0]), PetscRealPart(coords[1]), PetscRealPart(coords[2]), PetscRealPart(coords[3]), PetscMax(color[0], color[1])));
652:           } else {
653:             PetscCall(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]));
654:             PetscCall(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]));
655:           }
656:           break;
657:         default:
658:           SETERRQ(PETSC_COMM_SELF, PETSC_ERR_SUP, "Cannot draw cells with %" PetscInt_FMT " coordinates", numCoords);
659:         }
660:         PetscCall(DMPlexRestoreCellCoordinates(dm, c, &isDG, &numCoords, &coords_arr, &coords));
661:       }
662:       PetscCall(VecRestoreArrayRead(fv, &array));
663:       PetscCall(PetscDrawFlush(draw));
664:       PetscCall(PetscDrawPause(draw));
665:       PetscCall(PetscDrawSave(draw));
666:     }
667:     if (Nf > 1) {
668:       PetscCall(VecRestoreSubVector(v, fis, &fv));
669:       PetscCall(ISDestroy(&fis));
670:       PetscCall(DMDestroy(&fdm));
671:     }
672:   }
673:   PetscFunctionReturn(PETSC_SUCCESS);
674: }

676: static PetscErrorCode VecView_Plex_Local_Draw(Vec v, PetscViewer viewer)
677: {
678:   DM        dm;
679:   PetscDraw draw;
680:   PetscInt  dim;
681:   PetscBool isnull;

683:   PetscFunctionBegin;
684:   PetscCall(PetscViewerDrawGetDraw(viewer, 0, &draw));
685:   PetscCall(PetscDrawIsNull(draw, &isnull));
686:   if (isnull) PetscFunctionReturn(PETSC_SUCCESS);

688:   PetscCall(VecGetDM(v, &dm));
689:   PetscCall(DMGetCoordinateDim(dm, &dim));
690:   switch (dim) {
691:   case 1:
692:     PetscCall(VecView_Plex_Local_Draw_1D(v, viewer));
693:     break;
694:   case 2:
695:     PetscCall(VecView_Plex_Local_Draw_2D(v, viewer));
696:     break;
697:   default:
698:     SETERRQ(PetscObjectComm((PetscObject)v), PETSC_ERR_SUP, "Cannot draw meshes of dimension %" PetscInt_FMT ". Try PETSCVIEWERGLVIS", dim);
699:   }
700:   PetscFunctionReturn(PETSC_SUCCESS);
701: }

703: static PetscErrorCode VecView_Plex_Local_VTK(Vec v, PetscViewer viewer)
704: {
705:   DM                      dm;
706:   Vec                     locv;
707:   const char             *name;
708:   PetscSection            section;
709:   PetscInt                pStart, pEnd;
710:   PetscInt                numFields;
711:   PetscViewerVTKFieldType ft;

713:   PetscFunctionBegin;
714:   PetscCall(VecGetDM(v, &dm));
715:   PetscCall(DMCreateLocalVector(dm, &locv)); /* VTK viewer requires exclusive ownership of the vector */
716:   PetscCall(PetscObjectGetName((PetscObject)v, &name));
717:   PetscCall(PetscObjectSetName((PetscObject)locv, name));
718:   PetscCall(VecCopy(v, locv));
719:   PetscCall(DMGetLocalSection(dm, &section));
720:   PetscCall(PetscSectionGetNumFields(section, &numFields));
721:   if (!numFields) {
722:     PetscCall(DMPlexGetFieldType_Internal(dm, section, PETSC_DETERMINE, &pStart, &pEnd, &ft));
723:     PetscCall(PetscViewerVTKAddField(viewer, (PetscObject)dm, DMPlexVTKWriteAll, PETSC_DEFAULT, ft, PETSC_TRUE, (PetscObject)locv));
724:   } else {
725:     for (PetscInt f = 0; f < numFields; f++) {
726:       PetscCall(DMPlexGetFieldType_Internal(dm, section, f, &pStart, &pEnd, &ft));
727:       if (ft == PETSC_VTK_INVALID) continue;
728:       PetscCall(PetscObjectReference((PetscObject)locv));
729:       PetscCall(PetscViewerVTKAddField(viewer, (PetscObject)dm, DMPlexVTKWriteAll, f, ft, PETSC_TRUE, (PetscObject)locv));
730:     }
731:     PetscCall(VecDestroy(&locv));
732:   }
733:   PetscFunctionReturn(PETSC_SUCCESS);
734: }

736: PetscErrorCode VecView_Plex_Local(Vec v, PetscViewer viewer)
737: {
738:   DM        dm;
739:   PetscBool isvtk, ishdf5, isdraw, isglvis, iscgns, ispython;

741:   PetscFunctionBegin;
742:   PetscCall(VecGetDM(v, &dm));
743:   PetscCheck(dm, PetscObjectComm((PetscObject)v), PETSC_ERR_ARG_WRONG, "Vector not generated from a DM");
744:   PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERVTK, &isvtk));
745:   PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERHDF5, &ishdf5));
746:   PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERDRAW, &isdraw));
747:   PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERGLVIS, &isglvis));
748:   PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERCGNS, &iscgns));
749:   PetscCall(PetscObjectHasFunction((PetscObject)viewer, "PetscViewerPythonViewObject_C", &ispython));
750:   if (isvtk || ishdf5 || isdraw || isglvis || iscgns || ispython) {
751:     PetscInt    numFields;
752:     PetscObject fe;
753:     PetscBool   fem  = PETSC_FALSE;
754:     Vec         locv = v;
755:     const char *name;
756:     PetscInt    step;
757:     PetscReal   time;

759:     PetscCall(DMGetNumFields(dm, &numFields));
760:     for (PetscInt i = 0; i < numFields; i++) {
761:       PetscCall(DMGetField(dm, i, NULL, &fe));
762:       if (fe->classid == PETSCFE_CLASSID) {
763:         fem = PETSC_TRUE;
764:         break;
765:       }
766:     }
767:     if (fem) {
768:       PetscObject isZero;

770:       PetscCall(DMGetLocalVector(dm, &locv));
771:       PetscCall(PetscObjectGetName((PetscObject)v, &name));
772:       PetscCall(PetscObjectSetName((PetscObject)locv, name));
773:       PetscCall(PetscObjectQuery((PetscObject)v, "__Vec_bc_zero__", &isZero));
774:       PetscCall(PetscObjectCompose((PetscObject)locv, "__Vec_bc_zero__", isZero));
775:       PetscCall(VecCopy(v, locv));
776:       PetscCall(DMGetOutputSequenceNumber(dm, NULL, &time));
777:       PetscCall(DMPlexInsertBoundaryValues(dm, PETSC_TRUE, locv, time, NULL, NULL, NULL));
778:     }
779:     if (isvtk) {
780:       PetscCall(VecView_Plex_Local_VTK(locv, viewer));
781:     } else if (ishdf5) {
782: #if defined(PETSC_HAVE_HDF5)
783:       PetscCall(VecView_Plex_Local_HDF5_Internal(locv, viewer));
784: #else
785:       SETERRQ(PetscObjectComm((PetscObject)dm), PETSC_ERR_SUP, "HDF5 not supported in this build.\nPlease reconfigure using --download-hdf5");
786: #endif
787:     } else if (isdraw) {
788:       PetscCall(VecView_Plex_Local_Draw(locv, viewer));
789:     } else if (ispython) {
790:       PetscCall(PetscViewerPythonViewObject(viewer, (PetscObject)locv));
791:     } else if (isglvis) {
792:       PetscCall(DMGetOutputSequenceNumber(dm, &step, NULL));
793:       PetscCall(PetscViewerGLVisSetSnapId(viewer, step));
794:       PetscCall(VecView_GLVis(locv, viewer));
795:     } else if (iscgns) {
796: #if defined(PETSC_HAVE_CGNS)
797:       PetscCall(VecView_Plex_Local_CGNS(locv, viewer));
798: #else
799:       SETERRQ(PetscObjectComm((PetscObject)dm), PETSC_ERR_SUP, "CGNS not supported in this build.\nPlease reconfigure using --download-cgns");
800: #endif
801:     }
802:     if (fem) {
803:       PetscCall(PetscObjectCompose((PetscObject)locv, "__Vec_bc_zero__", NULL));
804:       PetscCall(DMRestoreLocalVector(dm, &locv));
805:     }
806:   } else {
807:     PetscBool isseq;

809:     PetscCall(PetscObjectTypeCompare((PetscObject)v, VECSEQ, &isseq));
810:     if (isseq) PetscCall(VecView_Seq(v, viewer));
811:     else PetscCall(VecView_MPI(v, viewer));
812:   }
813:   PetscFunctionReturn(PETSC_SUCCESS);
814: }

816: PetscErrorCode VecView_Plex(Vec v, PetscViewer viewer)
817: {
818:   DM        dm;
819:   PetscBool isvtk, ishdf5, isdraw, isglvis, isexodusii, iscgns, ispython;

821:   PetscFunctionBegin;
822:   PetscCall(VecGetDM(v, &dm));
823:   PetscCheck(dm, PetscObjectComm((PetscObject)v), PETSC_ERR_ARG_WRONG, "Vector not generated from a DM");
824:   PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERVTK, &isvtk));
825:   PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERHDF5, &ishdf5));
826:   PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERDRAW, &isdraw));
827:   PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERGLVIS, &isglvis));
828:   PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERCGNS, &iscgns));
829:   PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWEREXODUSII, &isexodusii));
830:   PetscCall(PetscObjectHasFunction((PetscObject)viewer, "PetscViewerPythonViewObject_C", &ispython));
831:   if (isvtk || isdraw || isglvis || iscgns || ispython) {
832:     Vec         locv;
833:     PetscObject isZero;
834:     const char *name;

836:     PetscCall(DMGetLocalVector(dm, &locv));
837:     PetscCall(PetscObjectGetName((PetscObject)v, &name));
838:     PetscCall(PetscObjectSetName((PetscObject)locv, name));
839:     PetscCall(DMGlobalToLocalBegin(dm, v, INSERT_VALUES, locv));
840:     PetscCall(DMGlobalToLocalEnd(dm, v, INSERT_VALUES, locv));
841:     PetscCall(PetscObjectQuery((PetscObject)v, "__Vec_bc_zero__", &isZero));
842:     PetscCall(PetscObjectCompose((PetscObject)locv, "__Vec_bc_zero__", isZero));
843:     PetscCall(VecView_Plex_Local(locv, viewer));
844:     PetscCall(PetscObjectCompose((PetscObject)locv, "__Vec_bc_zero__", NULL));
845:     PetscCall(DMRestoreLocalVector(dm, &locv));
846:   } else if (ishdf5) {
847: #if defined(PETSC_HAVE_HDF5)
848:     PetscCall(VecView_Plex_HDF5_Internal(v, viewer));
849: #else
850:     SETERRQ(PetscObjectComm((PetscObject)dm), PETSC_ERR_SUP, "HDF5 not supported in this build.\nPlease reconfigure using --download-hdf5");
851: #endif
852:   } else if (isexodusii) {
853: #if defined(PETSC_HAVE_EXODUSII)
854:     PetscCall(VecView_PlexExodusII_Internal(v, viewer));
855: #else
856:     SETERRQ(PetscObjectComm((PetscObject)dm), PETSC_ERR_SUP, "ExodusII not supported in this build.\nPlease reconfigure using --download-exodusii");
857: #endif
858:   } else {
859:     PetscBool isseq;

861:     PetscCall(PetscObjectTypeCompare((PetscObject)v, VECSEQ, &isseq));
862:     if (isseq) PetscCall(VecView_Seq(v, viewer));
863:     else PetscCall(VecView_MPI(v, viewer));
864:   }
865:   PetscFunctionReturn(PETSC_SUCCESS);
866: }

868: PetscErrorCode VecView_Plex_Native(Vec originalv, PetscViewer viewer)
869: {
870:   DM                dm;
871:   MPI_Comm          comm;
872:   PetscViewerFormat format;
873:   Vec               v;
874:   PetscBool         isvtk, ishdf5;

876:   PetscFunctionBegin;
877:   PetscCall(VecGetDM(originalv, &dm));
878:   PetscCall(PetscObjectGetComm((PetscObject)originalv, &comm));
879:   PetscCheck(dm, comm, PETSC_ERR_ARG_WRONG, "Vector not generated from a DM");
880:   PetscCall(PetscViewerGetFormat(viewer, &format));
881:   PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERHDF5, &ishdf5));
882:   PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERVTK, &isvtk));
883:   if (format == PETSC_VIEWER_NATIVE) {
884:     /* Natural ordering is the common case for DMDA, NATIVE means plain vector, for PLEX is the opposite */
885:     /* this need a better fix */
886:     if (dm->useNatural) {
887:       const char *vecname;
888:       PetscInt    n, nroots;

890:       PetscCheck(dm->sfNatural, comm, PETSC_ERR_ARG_WRONGSTATE, "DM global to natural SF was not created");
891:       PetscCall(VecGetLocalSize(originalv, &n));
892:       PetscCall(PetscSFGetGraph(dm->sfNatural, &nroots, NULL, NULL, NULL));
893:       PetscCheck(n == nroots, comm, PETSC_ERR_ARG_WRONG, "DM global to natural SF only handles global vectors");
894:       PetscCall(DMPlexCreateNaturalVector(dm, &v));
895:       PetscCall(DMPlexGlobalToNaturalBegin(dm, originalv, v));
896:       PetscCall(DMPlexGlobalToNaturalEnd(dm, originalv, v));
897:       PetscCall(PetscObjectGetName((PetscObject)originalv, &vecname));
898:       PetscCall(PetscObjectSetName((PetscObject)v, vecname));
899:     } else v = originalv;
900:   } else v = originalv;

902:   if (ishdf5) {
903: #if defined(PETSC_HAVE_HDF5)
904:     PetscCall(VecView_Plex_HDF5_Native_Internal(v, viewer));
905: #else
906:     SETERRQ(comm, PETSC_ERR_SUP, "HDF5 not supported in this build.\nPlease reconfigure using --download-hdf5");
907: #endif
908:   } else if (isvtk) {
909:     SETERRQ(comm, PETSC_ERR_SUP, "VTK format does not support viewing in natural order. Please switch to HDF5.");
910:   } else {
911:     PetscBool isseq;

913:     PetscCall(PetscObjectTypeCompare((PetscObject)v, VECSEQ, &isseq));
914:     if (isseq) PetscCall(VecView_Seq(v, viewer));
915:     else PetscCall(VecView_MPI(v, viewer));
916:   }
917:   if (v != originalv) PetscCall(VecDestroy(&v));
918:   PetscFunctionReturn(PETSC_SUCCESS);
919: }

921: PetscErrorCode VecLoad_Plex_Local(Vec v, PetscViewer viewer)
922: {
923:   DM        dm;
924:   PetscBool ishdf5;

926:   PetscFunctionBegin;
927:   PetscCall(VecGetDM(v, &dm));
928:   PetscCheck(dm, PetscObjectComm((PetscObject)v), PETSC_ERR_ARG_WRONG, "Vector not generated from a DM");
929:   PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERHDF5, &ishdf5));
930:   if (ishdf5) {
931:     DM          dmBC;
932:     Vec         gv;
933:     const char *name;

935:     PetscCall(DMGetOutputDM(dm, &dmBC));
936:     PetscCall(DMGetGlobalVector(dmBC, &gv));
937:     PetscCall(PetscObjectGetName((PetscObject)v, &name));
938:     PetscCall(PetscObjectSetName((PetscObject)gv, name));
939:     PetscCall(VecLoad_Default(gv, viewer));
940:     PetscCall(DMGlobalToLocalBegin(dmBC, gv, INSERT_VALUES, v));
941:     PetscCall(DMGlobalToLocalEnd(dmBC, gv, INSERT_VALUES, v));
942:     PetscCall(DMRestoreGlobalVector(dmBC, &gv));
943:   } else PetscCall(VecLoad_Default(v, viewer));
944:   PetscFunctionReturn(PETSC_SUCCESS);
945: }

947: PetscErrorCode VecLoad_Plex(Vec v, PetscViewer viewer)
948: {
949:   DM        dm;
950:   PetscBool ishdf5, isexodusii, iscgns;

952:   PetscFunctionBegin;
953:   PetscCall(VecGetDM(v, &dm));
954:   PetscCheck(dm, PetscObjectComm((PetscObject)v), PETSC_ERR_ARG_WRONG, "Vector not generated from a DM");
955:   PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERHDF5, &ishdf5));
956:   PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWEREXODUSII, &isexodusii));
957:   PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERCGNS, &iscgns));
958:   if (ishdf5) {
959: #if defined(PETSC_HAVE_HDF5)
960:     PetscCall(VecLoad_Plex_HDF5_Internal(v, viewer));
961: #else
962:     SETERRQ(PetscObjectComm((PetscObject)dm), PETSC_ERR_SUP, "HDF5 not supported in this build.\nPlease reconfigure using --download-hdf5");
963: #endif
964:   } else if (isexodusii) {
965: #if defined(PETSC_HAVE_EXODUSII)
966:     PetscCall(VecLoad_PlexExodusII_Internal(v, viewer));
967: #else
968:     SETERRQ(PetscObjectComm((PetscObject)dm), PETSC_ERR_SUP, "ExodusII not supported in this build.\nPlease reconfigure using --download-exodusii");
969: #endif
970:   } else if (iscgns) {
971: #if defined(PETSC_HAVE_CGNS)
972:     PetscCall(VecLoad_Plex_CGNS_Internal(v, viewer));
973: #else
974:     SETERRQ(PetscObjectComm((PetscObject)dm), PETSC_ERR_SUP, "CGNS not supported in this build.\nPlease reconfigure using --download-cgns");
975: #endif
976:   } else PetscCall(VecLoad_Default(v, viewer));
977:   PetscFunctionReturn(PETSC_SUCCESS);
978: }

980: PetscErrorCode VecLoad_Plex_Native(Vec originalv, PetscViewer viewer)
981: {
982:   DM                dm;
983:   PetscViewerFormat format;
984:   PetscBool         ishdf5;

986:   PetscFunctionBegin;
987:   PetscCall(VecGetDM(originalv, &dm));
988:   PetscCheck(dm, PetscObjectComm((PetscObject)originalv), PETSC_ERR_ARG_WRONG, "Vector not generated from a DM");
989:   PetscCall(PetscViewerGetFormat(viewer, &format));
990:   PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERHDF5, &ishdf5));
991:   if (format == PETSC_VIEWER_NATIVE) {
992:     if (dm->useNatural) {
993:       if (dm->sfNatural) {
994:         if (ishdf5) {
995: #if defined(PETSC_HAVE_HDF5)
996:           Vec         v;
997:           const char *vecname;

999:           PetscCall(DMPlexCreateNaturalVector(dm, &v));
1000:           PetscCall(PetscObjectGetName((PetscObject)originalv, &vecname));
1001:           PetscCall(PetscObjectSetName((PetscObject)v, vecname));
1002:           PetscCall(VecLoad_Plex_HDF5_Native_Internal(v, viewer));
1003:           PetscCall(DMPlexNaturalToGlobalBegin(dm, v, originalv));
1004:           PetscCall(DMPlexNaturalToGlobalEnd(dm, v, originalv));
1005:           PetscCall(VecDestroy(&v));
1006: #else
1007:           SETERRQ(PetscObjectComm((PetscObject)dm), PETSC_ERR_SUP, "HDF5 not supported in this build.\nPlease reconfigure using --download-hdf5");
1008: #endif
1009:         } else SETERRQ(PetscObjectComm((PetscObject)dm), PETSC_ERR_SUP, "Reading in natural order is not supported for anything but HDF5.");
1010:       }
1011:     } else PetscCall(VecLoad_Default(originalv, viewer));
1012:   }
1013:   PetscFunctionReturn(PETSC_SUCCESS);
1014: }

1016: PETSC_UNUSED static PetscErrorCode DMPlexView_Ascii_Geometry(DM dm, PetscViewer viewer)
1017: {
1018:   PetscSection       coordSection;
1019:   Vec                coordinates;
1020:   DMLabel            depthLabel, celltypeLabel;
1021:   const char        *name[4];
1022:   const PetscScalar *a;
1023:   PetscInt           dim, pStart, pEnd, cStart, cEnd, c;

1025:   PetscFunctionBegin;
1026:   PetscCall(DMGetDimension(dm, &dim));
1027:   PetscCall(DMGetCoordinatesLocal(dm, &coordinates));
1028:   PetscCall(DMGetCoordinateSection(dm, &coordSection));
1029:   PetscCall(DMPlexGetDepthLabel(dm, &depthLabel));
1030:   PetscCall(DMPlexGetCellTypeLabel(dm, &celltypeLabel));
1031:   PetscCall(DMPlexGetHeightStratum(dm, 0, &cStart, &cEnd));
1032:   PetscCall(PetscSectionGetChart(coordSection, &pStart, &pEnd));
1033:   PetscCall(VecGetArrayRead(coordinates, &a));
1034:   name[0]       = "vertex";
1035:   name[1]       = "edge";
1036:   name[dim - 1] = "face";
1037:   name[dim]     = "cell";
1038:   for (c = cStart; c < cEnd; ++c) {
1039:     PetscInt *closure = NULL;
1040:     PetscInt  closureSize, cl, ct;

1042:     PetscCall(DMLabelGetValue(celltypeLabel, c, &ct));
1043:     PetscCall(PetscViewerASCIIPrintf(viewer, "Geometry for cell %" PetscInt_FMT " polytope type %s:\n", c, DMPolytopeTypes[ct]));
1044:     PetscCall(DMPlexGetTransitiveClosure(dm, c, PETSC_TRUE, &closureSize, &closure));
1045:     PetscCall(PetscViewerASCIIPushTab(viewer));
1046:     for (cl = 0; cl < closureSize * 2; cl += 2) {
1047:       PetscInt point = closure[cl], depth, dof, off, d, p;

1049:       if ((point < pStart) || (point >= pEnd)) continue;
1050:       PetscCall(PetscSectionGetDof(coordSection, point, &dof));
1051:       if (!dof) continue;
1052:       PetscCall(DMLabelGetValue(depthLabel, point, &depth));
1053:       PetscCall(PetscSectionGetOffset(coordSection, point, &off));
1054:       PetscCall(PetscViewerASCIIPrintf(viewer, "%s %" PetscInt_FMT " coords:", name[depth], point));
1055:       for (p = 0; p < dof / dim; ++p) {
1056:         PetscCall(PetscViewerASCIIPrintf(viewer, " ("));
1057:         for (d = 0; d < dim; ++d) {
1058:           if (d > 0) PetscCall(PetscViewerASCIIPrintf(viewer, ", "));
1059:           PetscCall(PetscViewerASCIIPrintf(viewer, "%g", (double)PetscRealPart(a[off + p * dim + d])));
1060:         }
1061:         PetscCall(PetscViewerASCIIPrintf(viewer, ")"));
1062:       }
1063:       PetscCall(PetscViewerASCIIPrintf(viewer, "\n"));
1064:     }
1065:     PetscCall(DMPlexRestoreTransitiveClosure(dm, c, PETSC_TRUE, &closureSize, &closure));
1066:     PetscCall(PetscViewerASCIIPopTab(viewer));
1067:   }
1068:   PetscCall(VecRestoreArrayRead(coordinates, &a));
1069:   PetscFunctionReturn(PETSC_SUCCESS);
1070: }

1072: typedef enum {
1073:   CS_CARTESIAN,
1074:   CS_POLAR,
1075:   CS_CYLINDRICAL,
1076:   CS_SPHERICAL
1077: } CoordSystem;
1078: const char *CoordSystems[] = {"cartesian", "polar", "cylindrical", "spherical", "CoordSystem", "CS_", NULL};

1080: static PetscErrorCode DMPlexView_Ascii_Coordinates(PetscViewer viewer, CoordSystem cs, PetscInt dim, const PetscScalar x[])
1081: {
1082:   PetscFunctionBegin;
1083:   if (dim > 3) {
1084:     for (PetscInt i = 0; i < dim; ++i) PetscCall(PetscViewerASCIISynchronizedPrintf(viewer, " %g", (double)PetscRealPart(x[i])));
1085:   } else {
1086:     PetscReal coords[3], trcoords[3] = {0., 0., 0.};

1088:     for (PetscInt i = 0; i < dim; ++i) coords[i] = PetscRealPart(x[i]);
1089:     switch (cs) {
1090:     case CS_CARTESIAN:
1091:       for (PetscInt i = 0; i < dim; ++i) trcoords[i] = coords[i];
1092:       break;
1093:     case CS_POLAR:
1094:       PetscCheck(dim == 2, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Polar coordinates are for 2 dimension, not %" PetscInt_FMT, dim);
1095:       trcoords[0] = PetscSqrtReal(PetscSqr(coords[0]) + PetscSqr(coords[1]));
1096:       trcoords[1] = PetscAtan2Real(coords[1], coords[0]);
1097:       break;
1098:     case CS_CYLINDRICAL:
1099:       PetscCheck(dim == 3, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Cylindrical coordinates are for 3 dimension, not %" PetscInt_FMT, dim);
1100:       trcoords[0] = PetscSqrtReal(PetscSqr(coords[0]) + PetscSqr(coords[1]));
1101:       trcoords[1] = PetscAtan2Real(coords[1], coords[0]);
1102:       trcoords[2] = coords[2];
1103:       break;
1104:     case CS_SPHERICAL:
1105:       PetscCheck(dim == 3, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Spherical coordinates are for 3 dimension, not %" PetscInt_FMT, dim);
1106:       trcoords[0] = PetscSqrtReal(PetscSqr(coords[0]) + PetscSqr(coords[1]) + PetscSqr(coords[2]));
1107:       trcoords[1] = PetscAtan2Real(PetscSqrtReal(PetscSqr(coords[0]) + PetscSqr(coords[1])), coords[2]);
1108:       trcoords[2] = PetscAtan2Real(coords[1], coords[0]);
1109:       break;
1110:     }
1111:     for (PetscInt i = 0; i < dim; ++i) PetscCall(PetscViewerASCIISynchronizedPrintf(viewer, " %g", (double)trcoords[i]));
1112:   }
1113:   PetscFunctionReturn(PETSC_SUCCESS);
1114: }

1116: static PetscErrorCode DMPlexView_Ascii(DM dm, PetscViewer viewer)
1117: {
1118:   DM_Plex          *mesh = (DM_Plex *)dm->data;
1119:   DM                cdm, cdmCell;
1120:   PetscSection      coordSection, coordSectionCell;
1121:   Vec               coordinates, coordinatesCell;
1122:   PetscViewerFormat format;

1124:   PetscFunctionBegin;
1125:   PetscCall(PetscViewerGetFormat(viewer, &format));
1126:   if (format == PETSC_VIEWER_ASCII_INFO_DETAIL) {
1127:     const char *name;
1128:     PetscInt    dim, cellHeight, maxConeSize, maxSupportSize;
1129:     PetscInt    pStart, pEnd, p, numLabels, l;
1130:     PetscMPIInt rank, size;

1132:     PetscCall(DMGetCoordinateDM(dm, &cdm));
1133:     PetscCall(DMGetCoordinateSection(dm, &coordSection));
1134:     PetscCall(DMGetCoordinatesLocal(dm, &coordinates));
1135:     PetscCall(DMGetCellCoordinateDM(dm, &cdmCell));
1136:     PetscCall(DMGetCellCoordinateSection(dm, &coordSectionCell));
1137:     PetscCall(DMGetCellCoordinatesLocal(dm, &coordinatesCell));
1138:     PetscCallMPI(MPI_Comm_rank(PetscObjectComm((PetscObject)dm), &rank));
1139:     PetscCallMPI(MPI_Comm_size(PetscObjectComm((PetscObject)dm), &size));
1140:     PetscCall(PetscObjectGetName((PetscObject)dm, &name));
1141:     PetscCall(DMPlexGetChart(dm, &pStart, &pEnd));
1142:     PetscCall(DMPlexGetMaxSizes(dm, &maxConeSize, &maxSupportSize));
1143:     PetscCall(DMGetDimension(dm, &dim));
1144:     PetscCall(DMPlexGetVTKCellHeight(dm, &cellHeight));
1145:     if (name) PetscCall(PetscViewerASCIIPrintf(viewer, "%s in %" PetscInt_FMT " dimension%s:\n", name, dim, dim == 1 ? "" : "s"));
1146:     else PetscCall(PetscViewerASCIIPrintf(viewer, "Mesh in %" PetscInt_FMT " dimension%s:\n", dim, dim == 1 ? "" : "s"));
1147:     if (cellHeight) PetscCall(PetscViewerASCIIPrintf(viewer, "  Cells are at height %" PetscInt_FMT "\n", cellHeight));
1148:     PetscCall(PetscViewerASCIIPrintf(viewer, "Supports:\n"));
1149:     PetscCall(PetscViewerASCIIPushSynchronized(viewer));
1150:     PetscCall(PetscViewerASCIISynchronizedPrintf(viewer, "[%d] Max support size: %" PetscInt_FMT "\n", rank, maxSupportSize));
1151:     for (p = pStart; p < pEnd; ++p) {
1152:       PetscInt dof, off, s;

1154:       PetscCall(PetscSectionGetDof(mesh->supportSection, p, &dof));
1155:       PetscCall(PetscSectionGetOffset(mesh->supportSection, p, &off));
1156:       for (s = off; s < off + dof; ++s) PetscCall(PetscViewerASCIISynchronizedPrintf(viewer, "[%d]: %" PetscInt_FMT " ----> %" PetscInt_FMT "\n", rank, p, mesh->supports[s]));
1157:     }
1158:     PetscCall(PetscViewerFlush(viewer));
1159:     PetscCall(PetscViewerASCIIPrintf(viewer, "Cones:\n"));
1160:     PetscCall(PetscViewerASCIISynchronizedPrintf(viewer, "[%d] Max cone size: %" PetscInt_FMT "\n", rank, maxConeSize));
1161:     for (p = pStart; p < pEnd; ++p) {
1162:       PetscInt dof, off, c;

1164:       PetscCall(PetscSectionGetDof(mesh->coneSection, p, &dof));
1165:       PetscCall(PetscSectionGetOffset(mesh->coneSection, p, &off));
1166:       for (c = off; c < off + dof; ++c) PetscCall(PetscViewerASCIISynchronizedPrintf(viewer, "[%d]: %" PetscInt_FMT " <---- %" PetscInt_FMT " (%" PetscInt_FMT ")\n", rank, p, mesh->cones[c], mesh->coneOrientations[c]));
1167:     }
1168:     PetscCall(PetscViewerFlush(viewer));
1169:     PetscCall(PetscViewerASCIIPopSynchronized(viewer));
1170:     if (coordSection && coordinates) {
1171:       CoordSystem        cs = CS_CARTESIAN;
1172:       const PetscScalar *array, *arrayCell = NULL;
1173:       PetscInt           Nf, Nc, pvStart, pvEnd, pcStart = PETSC_INT_MAX, pcEnd = PETSC_INT_MIN, pStart, pEnd, p;
1174:       PetscMPIInt        rank;
1175:       const char        *name;

1177:       PetscCall(PetscOptionsGetEnum(((PetscObject)viewer)->options, ((PetscObject)viewer)->prefix, "-dm_plex_view_coord_system", CoordSystems, (PetscEnum *)&cs, NULL));
1178:       PetscCallMPI(MPI_Comm_rank(PetscObjectComm((PetscObject)viewer), &rank));
1179:       PetscCall(PetscSectionGetNumFields(coordSection, &Nf));
1180:       PetscCheck(Nf == 1, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Coordinate section should have 1 field, not %" PetscInt_FMT, Nf);
1181:       PetscCall(PetscSectionGetFieldComponents(coordSection, 0, &Nc));
1182:       PetscCall(PetscSectionGetChart(coordSection, &pvStart, &pvEnd));
1183:       if (coordSectionCell) PetscCall(PetscSectionGetChart(coordSectionCell, &pcStart, &pcEnd));
1184:       pStart = PetscMin(pvStart, pcStart);
1185:       pEnd   = PetscMax(pvEnd, pcEnd);
1186:       PetscCall(PetscObjectGetName((PetscObject)coordinates, &name));
1187:       PetscCall(PetscViewerASCIIPrintf(viewer, "%s with %" PetscInt_FMT " fields\n", name, Nf));
1188:       PetscCall(PetscViewerASCIIPrintf(viewer, "  field 0 with %" PetscInt_FMT " components\n", Nc));
1189:       if (cs != CS_CARTESIAN) PetscCall(PetscViewerASCIIPrintf(viewer, "  output coordinate system: %s\n", CoordSystems[cs]));

1191:       PetscCall(VecGetArrayRead(coordinates, &array));
1192:       if (coordinatesCell) PetscCall(VecGetArrayRead(coordinatesCell, &arrayCell));
1193:       PetscCall(PetscViewerASCIIPushSynchronized(viewer));
1194:       PetscCall(PetscViewerASCIISynchronizedPrintf(viewer, "Process %d:\n", rank));
1195:       for (p = pStart; p < pEnd; ++p) {
1196:         PetscInt dof, off;

1198:         if (p >= pvStart && p < pvEnd) {
1199:           PetscCall(PetscSectionGetDof(coordSection, p, &dof));
1200:           PetscCall(PetscSectionGetOffset(coordSection, p, &off));
1201:           if (dof) {
1202:             PetscCall(PetscViewerASCIISynchronizedPrintf(viewer, "  (%4" PetscInt_FMT ") dof %2" PetscInt_FMT " offset %3" PetscInt_FMT, p, dof, off));
1203:             PetscCall(DMPlexView_Ascii_Coordinates(viewer, cs, dof, &array[off]));
1204:             PetscCall(PetscViewerASCIISynchronizedPrintf(viewer, "\n"));
1205:           }
1206:         }
1207:         if (cdmCell && p >= pcStart && p < pcEnd) {
1208:           PetscCall(PetscSectionGetDof(coordSectionCell, p, &dof));
1209:           PetscCall(PetscSectionGetOffset(coordSectionCell, p, &off));
1210:           if (dof) {
1211:             PetscCall(PetscViewerASCIISynchronizedPrintf(viewer, "  (%4" PetscInt_FMT ") dof %2" PetscInt_FMT " offset %3" PetscInt_FMT, p, dof, off));
1212:             PetscCall(DMPlexView_Ascii_Coordinates(viewer, cs, dof, &arrayCell[off]));
1213:             PetscCall(PetscViewerASCIISynchronizedPrintf(viewer, "\n"));
1214:           }
1215:         }
1216:       }
1217:       PetscCall(PetscViewerFlush(viewer));
1218:       PetscCall(PetscViewerASCIIPopSynchronized(viewer));
1219:       PetscCall(VecRestoreArrayRead(coordinates, &array));
1220:       if (coordinatesCell) PetscCall(VecRestoreArrayRead(coordinatesCell, &arrayCell));
1221:     }
1222:     PetscCall(DMGetNumLabels(dm, &numLabels));
1223:     if (numLabels) PetscCall(PetscViewerASCIIPrintf(viewer, "Labels:\n"));
1224:     for (l = 0; l < numLabels; ++l) {
1225:       DMLabel     label;
1226:       PetscBool   isdepth;
1227:       const char *name;

1229:       PetscCall(DMGetLabelName(dm, l, &name));
1230:       PetscCall(PetscStrcmp(name, "depth", &isdepth));
1231:       if (isdepth) continue;
1232:       PetscCall(DMGetLabel(dm, name, &label));
1233:       PetscCall(DMLabelView(label, viewer));
1234:     }
1235:     if (size > 1) {
1236:       PetscSF sf;

1238:       PetscCall(DMGetPointSF(dm, &sf));
1239:       PetscCall(PetscSFView(sf, viewer));
1240:     }
1241:     if (mesh->periodic.face_sfs)
1242:       for (PetscInt i = 0; i < mesh->periodic.num_face_sfs; i++) PetscCall(PetscSFView(mesh->periodic.face_sfs[i], viewer));
1243:     PetscCall(PetscViewerFlush(viewer));
1244:   } else if (format == PETSC_VIEWER_ASCII_LATEX) {
1245:     const char  *name, *color;
1246:     const char  *defcolors[3]  = {"gray", "orange", "green"};
1247:     const char  *deflcolors[4] = {"blue", "cyan", "red", "magenta"};
1248:     char         lname[PETSC_MAX_PATH_LEN];
1249:     PetscReal    scale      = 2.0;
1250:     PetscReal    tikzscale  = 1.0;
1251:     PetscBool    useNumbers = PETSC_TRUE, drawNumbers[4], drawColors[4], useLabels, useColors, plotEdges, drawHasse = PETSC_FALSE;
1252:     double       tcoords[3];
1253:     PetscScalar *coords;
1254:     PetscInt     numLabels, l, numColors, numLColors, dim, d, depth, cStart, cEnd, c, vStart, vEnd, v, eStart = 0, eEnd = 0, fStart = 0, fEnd = 0, e, p, n;
1255:     PetscMPIInt  rank, size;
1256:     char       **names, **colors, **lcolors;
1257:     PetscBool    flg, lflg;
1258:     PetscBT      wp = NULL;
1259:     PetscInt     pEnd, pStart;

1261:     PetscCall(DMGetCoordinateDM(dm, &cdm));
1262:     PetscCall(DMGetCoordinateSection(dm, &coordSection));
1263:     PetscCall(DMGetCoordinatesLocal(dm, &coordinates));
1264:     PetscCall(DMGetCellCoordinateDM(dm, &cdmCell));
1265:     PetscCall(DMGetCellCoordinateSection(dm, &coordSectionCell));
1266:     PetscCall(DMGetCellCoordinatesLocal(dm, &coordinatesCell));
1267:     PetscCall(DMGetDimension(dm, &dim));
1268:     PetscCall(DMPlexGetDepth(dm, &depth));
1269:     PetscCall(DMGetNumLabels(dm, &numLabels));
1270:     numLabels  = PetscMax(numLabels, 10);
1271:     numColors  = 10;
1272:     numLColors = 10;
1273:     PetscCall(PetscCalloc3(numLabels, &names, numColors, &colors, numLColors, &lcolors));
1274:     PetscCall(PetscOptionsGetReal(((PetscObject)viewer)->options, ((PetscObject)viewer)->prefix, "-dm_plex_view_scale", &scale, NULL));
1275:     PetscCall(PetscOptionsGetReal(((PetscObject)viewer)->options, ((PetscObject)viewer)->prefix, "-dm_plex_view_tikzscale", &tikzscale, NULL));
1276:     PetscCall(PetscOptionsGetBool(((PetscObject)viewer)->options, ((PetscObject)viewer)->prefix, "-dm_plex_view_numbers", &useNumbers, NULL));
1277:     for (d = 0; d < 4; ++d) drawNumbers[d] = useNumbers;
1278:     for (d = 0; d < 4; ++d) drawColors[d] = PETSC_TRUE;
1279:     n = 4;
1280:     PetscCall(PetscOptionsGetBoolArray(((PetscObject)viewer)->options, ((PetscObject)viewer)->prefix, "-dm_plex_view_numbers_depth", drawNumbers, &n, &flg));
1281:     PetscCheck(!flg || n == dim + 1, PetscObjectComm((PetscObject)dm), PETSC_ERR_ARG_SIZ, "Number of flags %" PetscInt_FMT " != %" PetscInt_FMT " dim+1", n, dim + 1);
1282:     n = 4;
1283:     PetscCall(PetscOptionsGetBoolArray(((PetscObject)viewer)->options, ((PetscObject)viewer)->prefix, "-dm_plex_view_colors_depth", drawColors, &n, &flg));
1284:     PetscCheck(!flg || n == dim + 1, PetscObjectComm((PetscObject)dm), PETSC_ERR_ARG_SIZ, "Number of flags %" PetscInt_FMT " != %" PetscInt_FMT " dim+1", n, dim + 1);
1285:     PetscCall(PetscOptionsGetStringArray(((PetscObject)viewer)->options, ((PetscObject)viewer)->prefix, "-dm_plex_view_labels", names, &numLabels, &useLabels));
1286:     if (!useLabels) numLabels = 0;
1287:     PetscCall(PetscOptionsGetStringArray(((PetscObject)viewer)->options, ((PetscObject)viewer)->prefix, "-dm_plex_view_colors", colors, &numColors, &useColors));
1288:     if (!useColors) {
1289:       numColors = 3;
1290:       for (c = 0; c < numColors; ++c) PetscCall(PetscStrallocpy(defcolors[c], &colors[c]));
1291:     }
1292:     PetscCall(PetscOptionsGetStringArray(((PetscObject)viewer)->options, ((PetscObject)viewer)->prefix, "-dm_plex_view_lcolors", lcolors, &numLColors, &useColors));
1293:     if (!useColors) {
1294:       numLColors = 4;
1295:       for (c = 0; c < numLColors; ++c) PetscCall(PetscStrallocpy(deflcolors[c], &lcolors[c]));
1296:     }
1297:     PetscCall(PetscOptionsGetString(((PetscObject)viewer)->options, ((PetscObject)viewer)->prefix, "-dm_plex_view_label_filter", lname, sizeof(lname), &lflg));
1298:     plotEdges = (PetscBool)(depth > 1 && drawNumbers[1] && dim < 3);
1299:     PetscCall(PetscOptionsGetBool(((PetscObject)viewer)->options, ((PetscObject)viewer)->prefix, "-dm_plex_view_edges", &plotEdges, &flg));
1300:     PetscCheck(!flg || !plotEdges || depth >= dim, PetscObjectComm((PetscObject)dm), PETSC_ERR_SUP, "Mesh must be interpolated");
1301:     if (depth < dim) plotEdges = PETSC_FALSE;
1302:     PetscCall(PetscOptionsGetBool(((PetscObject)viewer)->options, ((PetscObject)viewer)->prefix, "-dm_plex_view_hasse", &drawHasse, NULL));

1304:     /* filter points with labelvalue != labeldefaultvalue */
1305:     PetscCall(DMPlexGetChart(dm, &pStart, &pEnd));
1306:     PetscCall(DMPlexGetDepthStratum(dm, 0, &vStart, &vEnd));
1307:     PetscCall(DMPlexGetDepthStratum(dm, 1, &eStart, &eEnd));
1308:     PetscCall(DMPlexGetHeightStratum(dm, 0, &cStart, &cEnd));
1309:     PetscCall(DMPlexGetHeightStratum(dm, 1, &fStart, &fEnd));
1310:     if (lflg) {
1311:       DMLabel lbl;

1313:       PetscCall(DMGetLabel(dm, lname, &lbl));
1314:       if (lbl) {
1315:         PetscInt val, defval;

1317:         PetscCall(DMLabelGetDefaultValue(lbl, &defval));
1318:         PetscCall(PetscBTCreate(pEnd - pStart, &wp));
1319:         for (c = pStart; c < pEnd; c++) {
1320:           PetscInt *closure = NULL;
1321:           PetscInt  closureSize;

1323:           PetscCall(DMLabelGetValue(lbl, c, &val));
1324:           if (val == defval) continue;

1326:           PetscCall(DMPlexGetTransitiveClosure(dm, c, PETSC_TRUE, &closureSize, &closure));
1327:           for (p = 0; p < closureSize * 2; p += 2) PetscCall(PetscBTSet(wp, closure[p] - pStart));
1328:           PetscCall(DMPlexRestoreTransitiveClosure(dm, c, PETSC_TRUE, &closureSize, &closure));
1329:         }
1330:       }
1331:     }

1333:     PetscCallMPI(MPI_Comm_rank(PetscObjectComm((PetscObject)dm), &rank));
1334:     PetscCallMPI(MPI_Comm_size(PetscObjectComm((PetscObject)dm), &size));
1335:     PetscCall(PetscObjectGetName((PetscObject)dm, &name));
1336:     PetscCall(PetscViewerASCIIPrintf(viewer, "\
1337: \\documentclass[tikz]{standalone}\n\n\
1338: \\usepackage{pgflibraryshapes}\n\
1339: \\usetikzlibrary{backgrounds}\n\
1340: \\usetikzlibrary{arrows}\n\
1341: \\begin{document}\n"));
1342:     if (size > 1) {
1343:       PetscCall(PetscViewerASCIIPrintf(viewer, "%s for process ", name));
1344:       for (p = 0; p < size; ++p) {
1345:         if (p) PetscCall(PetscViewerASCIIPrintf(viewer, (p == size - 1) ? ", and " : ", "));
1346:         PetscCall(PetscViewerASCIIPrintf(viewer, "{\\textcolor{%s}%" PetscInt_FMT "}", colors[p % numColors], p));
1347:       }
1348:       PetscCall(PetscViewerASCIIPrintf(viewer, ".\n\n\n"));
1349:     }
1350:     if (drawHasse) {
1351:       PetscInt maxStratum = PetscMax(vEnd - vStart, PetscMax(eEnd - eStart, PetscMax(fEnd - fStart, cEnd - cStart)));

1353:       PetscCall(PetscViewerASCIIPrintf(viewer, "\\newcommand{\\vStart}{%" PetscInt_FMT "}\n", vStart));
1354:       PetscCall(PetscViewerASCIIPrintf(viewer, "\\newcommand{\\vEnd}{%" PetscInt_FMT "}\n", vEnd - 1));
1355:       PetscCall(PetscViewerASCIIPrintf(viewer, "\\newcommand{\\numVertices}{%" PetscInt_FMT "}\n", vEnd - vStart));
1356:       PetscCall(PetscViewerASCIIPrintf(viewer, "\\newcommand{\\vShift}{%.2f}\n", 3 + (maxStratum - (vEnd - vStart)) / 2.));
1357:       PetscCall(PetscViewerASCIIPrintf(viewer, "\\newcommand{\\eStart}{%" PetscInt_FMT "}\n", eStart));
1358:       PetscCall(PetscViewerASCIIPrintf(viewer, "\\newcommand{\\eEnd}{%" PetscInt_FMT "}\n", eEnd - 1));
1359:       PetscCall(PetscViewerASCIIPrintf(viewer, "\\newcommand{\\eShift}{%.2f}\n", 3 + (maxStratum - (eEnd - eStart)) / 2.));
1360:       PetscCall(PetscViewerASCIIPrintf(viewer, "\\newcommand{\\numEdges}{%" PetscInt_FMT "}\n", eEnd - eStart));
1361:       PetscCall(PetscViewerASCIIPrintf(viewer, "\\newcommand{\\fStart}{%" PetscInt_FMT "}\n", fStart));
1362:       PetscCall(PetscViewerASCIIPrintf(viewer, "\\newcommand{\\fEnd}{%" PetscInt_FMT "}\n", fEnd - 1));
1363:       PetscCall(PetscViewerASCIIPrintf(viewer, "\\newcommand{\\fShift}{%.2f}\n", 3 + (maxStratum - (fEnd - fStart)) / 2.));
1364:       PetscCall(PetscViewerASCIIPrintf(viewer, "\\newcommand{\\numFaces}{%" PetscInt_FMT "}\n", fEnd - fStart));
1365:       PetscCall(PetscViewerASCIIPrintf(viewer, "\\newcommand{\\cStart}{%" PetscInt_FMT "}\n", cStart));
1366:       PetscCall(PetscViewerASCIIPrintf(viewer, "\\newcommand{\\cEnd}{%" PetscInt_FMT "}\n", cEnd - 1));
1367:       PetscCall(PetscViewerASCIIPrintf(viewer, "\\newcommand{\\numCells}{%" PetscInt_FMT "}\n", cEnd - cStart));
1368:       PetscCall(PetscViewerASCIIPrintf(viewer, "\\newcommand{\\cShift}{%.2f}\n", 3 + (maxStratum - (cEnd - cStart)) / 2.));
1369:     }
1370:     PetscCall(PetscViewerASCIIPrintf(viewer, "\\begin{tikzpicture}[scale = %g,font=\\fontsize{8}{8}\\selectfont]\n", (double)tikzscale));

1372:     /* Plot vertices */
1373:     PetscCall(VecGetArray(coordinates, &coords));
1374:     PetscCall(PetscViewerASCIIPushSynchronized(viewer));
1375:     for (v = vStart; v < vEnd; ++v) {
1376:       PetscInt  off, dof, d;
1377:       PetscBool isLabeled = PETSC_FALSE;

1379:       if (wp && !PetscBTLookup(wp, v - pStart)) continue;
1380:       PetscCall(PetscSectionGetDof(coordSection, v, &dof));
1381:       PetscCall(PetscSectionGetOffset(coordSection, v, &off));
1382:       PetscCall(PetscViewerASCIISynchronizedPrintf(viewer, "\\path ("));
1383:       PetscCheck(dof <= 3, PETSC_COMM_SELF, PETSC_ERR_PLIB, "coordSection vertex %" PetscInt_FMT " has dof %" PetscInt_FMT " > 3", v, dof);
1384:       for (d = 0; d < dof; ++d) {
1385:         tcoords[d] = (double)(scale * PetscRealPart(coords[off + d]));
1386:         tcoords[d] = PetscAbs(tcoords[d]) < 1e-10 ? 0.0 : tcoords[d];
1387:       }
1388:       /* Rotate coordinates since PGF makes z point out of the page instead of up */
1389:       if (dim == 3) {
1390:         PetscReal tmp = tcoords[1];
1391:         tcoords[1]    = tcoords[2];
1392:         tcoords[2]    = -tmp;
1393:       }
1394:       for (d = 0; d < dof; ++d) {
1395:         if (d > 0) PetscCall(PetscViewerASCIISynchronizedPrintf(viewer, ","));
1396:         PetscCall(PetscViewerASCIISynchronizedPrintf(viewer, "%g", tcoords[d]));
1397:       }
1398:       if (drawHasse) color = colors[0 % numColors];
1399:       else color = colors[rank % numColors];
1400:       for (l = 0; l < numLabels; ++l) {
1401:         PetscInt val;
1402:         PetscCall(DMGetLabelValue(dm, names[l], v, &val));
1403:         if (val >= 0) {
1404:           color     = lcolors[l % numLColors];
1405:           isLabeled = PETSC_TRUE;
1406:           break;
1407:         }
1408:       }
1409:       if (drawNumbers[0]) {
1410:         PetscCall(PetscViewerASCIISynchronizedPrintf(viewer, ") node(%" PetscInt_FMT "_%d) [draw,shape=circle,color=%s] {%" PetscInt_FMT "};\n", v, rank, color, v));
1411:       } else if (drawColors[0]) {
1412:         PetscCall(PetscViewerASCIISynchronizedPrintf(viewer, ") node(%" PetscInt_FMT "_%d) [fill,inner sep=%dpt,shape=circle,color=%s] {};\n", v, rank, !isLabeled ? 1 : 2, color));
1413:       } else PetscCall(PetscViewerASCIISynchronizedPrintf(viewer, ") node(%" PetscInt_FMT "_%d) [] {};\n", v, rank));
1414:     }
1415:     PetscCall(VecRestoreArray(coordinates, &coords));
1416:     PetscCall(PetscViewerFlush(viewer));
1417:     /* Plot edges */
1418:     if (plotEdges) {
1419:       PetscCall(VecGetArray(coordinates, &coords));
1420:       PetscCall(PetscViewerASCIIPrintf(viewer, "\\path\n"));
1421:       for (e = eStart; e < eEnd; ++e) {
1422:         const PetscInt *cone;
1423:         PetscInt        coneSize, offA, offB, dof, d;

1425:         if (wp && !PetscBTLookup(wp, e - pStart)) continue;
1426:         PetscCall(DMPlexGetConeSize(dm, e, &coneSize));
1427:         PetscCheck(coneSize == 2, PetscObjectComm((PetscObject)dm), PETSC_ERR_ARG_WRONG, "Edge %" PetscInt_FMT " cone should have two vertices, not %" PetscInt_FMT, e, coneSize);
1428:         PetscCall(DMPlexGetCone(dm, e, &cone));
1429:         PetscCall(PetscSectionGetDof(coordSection, cone[0], &dof));
1430:         PetscCall(PetscSectionGetOffset(coordSection, cone[0], &offA));
1431:         PetscCall(PetscSectionGetOffset(coordSection, cone[1], &offB));
1432:         PetscCall(PetscViewerASCIISynchronizedPrintf(viewer, "("));
1433:         for (d = 0; d < dof; ++d) {
1434:           tcoords[d] = (double)(scale * PetscRealPart(coords[offA + d] + coords[offB + d]) / 2);
1435:           tcoords[d] = PetscAbs(tcoords[d]) < 1e-10 ? 0.0 : tcoords[d];
1436:         }
1437:         /* Rotate coordinates since PGF makes z point out of the page instead of up */
1438:         if (dim == 3) {
1439:           PetscReal tmp = tcoords[1];
1440:           tcoords[1]    = tcoords[2];
1441:           tcoords[2]    = -tmp;
1442:         }
1443:         for (d = 0; d < dof; ++d) {
1444:           if (d > 0) PetscCall(PetscViewerASCIISynchronizedPrintf(viewer, ","));
1445:           PetscCall(PetscViewerASCIISynchronizedPrintf(viewer, "%g", tcoords[d]));
1446:         }
1447:         if (drawHasse) color = colors[1 % numColors];
1448:         else color = colors[rank % numColors];
1449:         for (l = 0; l < numLabels; ++l) {
1450:           PetscInt val;
1451:           PetscCall(DMGetLabelValue(dm, names[l], e, &val));
1452:           if (val >= 0) {
1453:             color = lcolors[l % numLColors];
1454:             break;
1455:           }
1456:         }
1457:         PetscCall(PetscViewerASCIISynchronizedPrintf(viewer, ") node(%" PetscInt_FMT "_%d) [draw,shape=circle,color=%s] {%" PetscInt_FMT "} --\n", e, rank, color, e));
1458:       }
1459:       PetscCall(VecRestoreArray(coordinates, &coords));
1460:       PetscCall(PetscViewerFlush(viewer));
1461:       PetscCall(PetscViewerASCIIPrintf(viewer, "(0,0);\n"));
1462:     }
1463:     /* Plot cells */
1464:     if (dim == 3 || !drawNumbers[1]) {
1465:       for (e = eStart; e < eEnd; ++e) {
1466:         const PetscInt *cone;

1468:         if (wp && !PetscBTLookup(wp, e - pStart)) continue;
1469:         color = colors[rank % numColors];
1470:         for (l = 0; l < numLabels; ++l) {
1471:           PetscInt val;
1472:           PetscCall(DMGetLabelValue(dm, names[l], e, &val));
1473:           if (val >= 0) {
1474:             color = lcolors[l % numLColors];
1475:             break;
1476:           }
1477:         }
1478:         PetscCall(DMPlexGetCone(dm, e, &cone));
1479:         PetscCall(PetscViewerASCIISynchronizedPrintf(viewer, "\\draw[color=%s] (%" PetscInt_FMT "_%d) -- (%" PetscInt_FMT "_%d);\n", color, cone[0], rank, cone[1], rank));
1480:       }
1481:     } else {
1482:       DMPolytopeType ct;

1484:       /* Drawing a 2D polygon */
1485:       for (c = cStart; c < cEnd; ++c) {
1486:         if (wp && !PetscBTLookup(wp, c - pStart)) continue;
1487:         PetscCall(DMPlexGetCellType(dm, c, &ct));
1488:         if (DMPolytopeTypeIsHybrid(ct)) {
1489:           const PetscInt *cone;
1490:           PetscInt        coneSize;

1492:           PetscCall(DMPlexGetCone(dm, c, &cone));
1493:           PetscCall(DMPlexGetConeSize(dm, c, &coneSize));
1494:           for (PetscInt e = 0; e < coneSize; ++e) {
1495:             const PetscInt *econe;

1497:             PetscCall(DMPlexGetCone(dm, cone[e], &econe));
1498:             PetscCall(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));
1499:           }
1500:         } else {
1501:           PetscInt *closure = NULL;
1502:           PetscInt  closureSize, Nv = 0, v;

1504:           PetscCall(DMPlexGetTransitiveClosure(dm, c, PETSC_TRUE, &closureSize, &closure));
1505:           for (p = 0; p < closureSize * 2; p += 2) {
1506:             const PetscInt point = closure[p];

1508:             if ((point >= vStart) && (point < vEnd)) closure[Nv++] = point;
1509:           }
1510:           PetscCall(PetscViewerASCIISynchronizedPrintf(viewer, "\\draw[color=%s] ", colors[rank % numColors]));
1511:           for (v = 0; v <= Nv; ++v) {
1512:             const PetscInt vertex = closure[v % Nv];

1514:             if (v > 0) {
1515:               if (plotEdges) {
1516:                 const PetscInt *edge;
1517:                 PetscInt        endpoints[2], ne;

1519:                 endpoints[0] = closure[v - 1];
1520:                 endpoints[1] = vertex;
1521:                 PetscCall(DMPlexGetJoin(dm, 2, endpoints, &ne, &edge));
1522:                 PetscCheck(ne == 1, PETSC_COMM_SELF, PETSC_ERR_PLIB, "Could not find edge for vertices %" PetscInt_FMT ", %" PetscInt_FMT, endpoints[0], endpoints[1]);
1523:                 PetscCall(PetscViewerASCIISynchronizedPrintf(viewer, " -- (%" PetscInt_FMT "_%d) -- ", edge[0], rank));
1524:                 PetscCall(DMPlexRestoreJoin(dm, 2, endpoints, &ne, &edge));
1525:               } else PetscCall(PetscViewerASCIISynchronizedPrintf(viewer, " -- "));
1526:             }
1527:             PetscCall(PetscViewerASCIISynchronizedPrintf(viewer, "(%" PetscInt_FMT "_%d)", vertex, rank));
1528:           }
1529:           PetscCall(PetscViewerASCIISynchronizedPrintf(viewer, ";\n"));
1530:           PetscCall(DMPlexRestoreTransitiveClosure(dm, c, PETSC_TRUE, &closureSize, &closure));
1531:         }
1532:       }
1533:     }
1534:     for (c = cStart; c < cEnd; ++c) {
1535:       double             ccoords[3] = {0.0, 0.0, 0.0};
1536:       PetscBool          isLabeled  = PETSC_FALSE;
1537:       PetscScalar       *cellCoords = NULL;
1538:       const PetscScalar *array;
1539:       PetscInt           numCoords, cdim, d;
1540:       PetscBool          isDG;

1542:       if (wp && !PetscBTLookup(wp, c - pStart)) continue;
1543:       PetscCall(DMGetCoordinateDim(dm, &cdim));
1544:       PetscCall(DMPlexGetCellCoordinates(dm, c, &isDG, &numCoords, &array, &cellCoords));
1545:       PetscCheck(!(numCoords % cdim), PETSC_COMM_SELF, PETSC_ERR_ARG_INCOMP, "coordinate dim %" PetscInt_FMT " does not divide numCoords %" PetscInt_FMT, cdim, numCoords);
1546:       PetscCall(PetscViewerASCIISynchronizedPrintf(viewer, "\\path ("));
1547:       for (p = 0; p < numCoords / cdim; ++p) {
1548:         for (d = 0; d < cdim; ++d) {
1549:           tcoords[d] = (double)(scale * PetscRealPart(cellCoords[p * cdim + d]));
1550:           tcoords[d] = PetscAbs(tcoords[d]) < 1e-10 ? 0.0 : tcoords[d];
1551:         }
1552:         /* Rotate coordinates since PGF makes z point out of the page instead of up */
1553:         if (cdim == 3) {
1554:           PetscReal tmp = tcoords[1];
1555:           tcoords[1]    = tcoords[2];
1556:           tcoords[2]    = -tmp;
1557:         }
1558:         for (d = 0; d < dim; ++d) ccoords[d] += tcoords[d];
1559:       }
1560:       for (d = 0; d < cdim; ++d) ccoords[d] /= (numCoords / cdim);
1561:       PetscCall(DMPlexRestoreCellCoordinates(dm, c, &isDG, &numCoords, &array, &cellCoords));
1562:       for (d = 0; d < cdim; ++d) {
1563:         if (d > 0) PetscCall(PetscViewerASCIISynchronizedPrintf(viewer, ","));
1564:         PetscCall(PetscViewerASCIISynchronizedPrintf(viewer, "%g", ccoords[d]));
1565:       }
1566:       if (drawHasse) color = colors[depth % numColors];
1567:       else color = colors[rank % numColors];
1568:       for (l = 0; l < numLabels; ++l) {
1569:         PetscInt val;
1570:         PetscCall(DMGetLabelValue(dm, names[l], c, &val));
1571:         if (val >= 0) {
1572:           color     = lcolors[l % numLColors];
1573:           isLabeled = PETSC_TRUE;
1574:           break;
1575:         }
1576:       }
1577:       if (drawNumbers[dim]) {
1578:         PetscCall(PetscViewerASCIISynchronizedPrintf(viewer, ") node(%" PetscInt_FMT "_%d) [draw,shape=circle,color=%s] {%" PetscInt_FMT "};\n", c, rank, color, c));
1579:       } else if (drawColors[dim]) {
1580:         PetscCall(PetscViewerASCIISynchronizedPrintf(viewer, ") node(%" PetscInt_FMT "_%d) [fill,inner sep=%dpt,shape=circle,color=%s] {};\n", c, rank, !isLabeled ? 1 : 2, color));
1581:       } else PetscCall(PetscViewerASCIISynchronizedPrintf(viewer, ") node(%" PetscInt_FMT "_%d) [] {};\n", c, rank));
1582:     }
1583:     if (drawHasse) {
1584:       int height = 0;

1586:       color = colors[depth % numColors];
1587:       PetscCall(PetscViewerASCIIPrintf(viewer, "%% Cells\n"));
1588:       PetscCall(PetscViewerASCIIPrintf(viewer, "\\foreach \\c in {\\cStart,...,\\cEnd}\n"));
1589:       PetscCall(PetscViewerASCIIPrintf(viewer, "{\n"));
1590:       PetscCall(PetscViewerASCIIPrintf(viewer, "  \\node(\\c_%d) [draw,shape=circle,color=%s,minimum size = 6mm] at (\\cShift+\\c-\\cStart,%d) {\\c};\n", rank, color, height++));
1591:       PetscCall(PetscViewerASCIIPrintf(viewer, "}\n"));

1593:       if (depth > 2) {
1594:         color = colors[1 % numColors];
1595:         PetscCall(PetscViewerASCIIPrintf(viewer, "%% Faces\n"));
1596:         PetscCall(PetscViewerASCIIPrintf(viewer, "\\foreach \\f in {\\fStart,...,\\fEnd}\n"));
1597:         PetscCall(PetscViewerASCIIPrintf(viewer, "{\n"));
1598:         PetscCall(PetscViewerASCIIPrintf(viewer, "  \\node(\\f_%d) [draw,shape=circle,color=%s,minimum size = 6mm] at (\\fShift+\\f-\\fStart,%d) {\\f};\n", rank, color, height++));
1599:         PetscCall(PetscViewerASCIIPrintf(viewer, "}\n"));
1600:       }

1602:       color = colors[1 % numColors];
1603:       PetscCall(PetscViewerASCIIPrintf(viewer, "%% Edges\n"));
1604:       PetscCall(PetscViewerASCIIPrintf(viewer, "\\foreach \\e in {\\eStart,...,\\eEnd}\n"));
1605:       PetscCall(PetscViewerASCIIPrintf(viewer, "{\n"));
1606:       PetscCall(PetscViewerASCIIPrintf(viewer, "  \\node(\\e_%d) [draw,shape=circle,color=%s,minimum size = 6mm] at (\\eShift+\\e-\\eStart,%d) {\\e};\n", rank, color, height++));
1607:       PetscCall(PetscViewerASCIIPrintf(viewer, "}\n"));

1609:       color = colors[0 % numColors];
1610:       PetscCall(PetscViewerASCIIPrintf(viewer, "%% Vertices\n"));
1611:       PetscCall(PetscViewerASCIIPrintf(viewer, "\\foreach \\v in {\\vStart,...,\\vEnd}\n"));
1612:       PetscCall(PetscViewerASCIIPrintf(viewer, "{\n"));
1613:       PetscCall(PetscViewerASCIIPrintf(viewer, "  \\node(\\v_%d) [draw,shape=circle,color=%s,minimum size = 6mm] at (\\vShift+\\v-\\vStart,%d) {\\v};\n", rank, color, height++));
1614:       PetscCall(PetscViewerASCIIPrintf(viewer, "}\n"));

1616:       for (p = pStart; p < pEnd; ++p) {
1617:         const PetscInt *cone;
1618:         PetscInt        coneSize;

1620:         PetscCall(DMPlexGetCone(dm, p, &cone));
1621:         PetscCall(DMPlexGetConeSize(dm, p, &coneSize));
1622:         for (PetscInt cp = 0; cp < coneSize; ++cp) PetscCall(PetscViewerASCIIPrintf(viewer, "\\draw[->, shorten >=1pt] (%" PetscInt_FMT "_%d) -- (%" PetscInt_FMT "_%d);\n", cone[cp], rank, p, rank));
1623:       }
1624:     }
1625:     PetscCall(PetscViewerFlush(viewer));
1626:     PetscCall(PetscViewerASCIIPopSynchronized(viewer));
1627:     PetscCall(PetscViewerASCIIPrintf(viewer, "\\end{tikzpicture}\n"));
1628:     PetscCall(PetscViewerASCIIPrintf(viewer, "\\end{document}\n"));
1629:     for (l = 0; l < numLabels; ++l) PetscCall(PetscFree(names[l]));
1630:     for (c = 0; c < numColors; ++c) PetscCall(PetscFree(colors[c]));
1631:     for (c = 0; c < numLColors; ++c) PetscCall(PetscFree(lcolors[c]));
1632:     PetscCall(PetscFree3(names, colors, lcolors));
1633:     PetscCall(PetscBTDestroy(&wp));
1634:   } else if (format == PETSC_VIEWER_LOAD_BALANCE) {
1635:     Vec                    cown, acown;
1636:     VecScatter             sct;
1637:     ISLocalToGlobalMapping g2l;
1638:     IS                     gid, acis;
1639:     MPI_Comm               comm, ncomm = MPI_COMM_NULL;
1640:     MPI_Group              ggroup, ngroup;
1641:     PetscScalar           *array, nid;
1642:     const PetscInt        *idxs;
1643:     PetscInt              *idxs2, *start, *adjacency, *work;
1644:     PetscInt64             lm[3], gm[3];
1645:     PetscInt               i, c, cStart, cEnd, cum, numVertices, ect, ectn, cellHeight;
1646:     PetscMPIInt            d1, d2, rank;

1648:     PetscCall(PetscObjectGetComm((PetscObject)dm, &comm));
1649:     PetscCallMPI(MPI_Comm_rank(comm, &rank));
1650: #if defined(PETSC_HAVE_MPI_PROCESS_SHARED_MEMORY)
1651:     PetscCallMPI(MPI_Comm_split_type(comm, MPI_COMM_TYPE_SHARED, rank, MPI_INFO_NULL, &ncomm));
1652: #endif
1653:     if (ncomm != MPI_COMM_NULL) {
1654:       PetscCallMPI(MPI_Comm_group(comm, &ggroup));
1655:       PetscCallMPI(MPI_Comm_group(ncomm, &ngroup));
1656:       d1 = 0;
1657:       PetscCallMPI(MPI_Group_translate_ranks(ngroup, 1, &d1, ggroup, &d2));
1658:       nid = d2;
1659:       PetscCallMPI(MPI_Group_free(&ggroup));
1660:       PetscCallMPI(MPI_Group_free(&ngroup));
1661:       PetscCallMPI(MPI_Comm_free(&ncomm));
1662:     } else nid = 0.0;

1664:     /* Get connectivity */
1665:     PetscCall(DMPlexGetVTKCellHeight(dm, &cellHeight));
1666:     PetscCall(DMPlexCreatePartitionerGraph(dm, cellHeight, &numVertices, &start, &adjacency, &gid));

1668:     /* filter overlapped local cells */
1669:     PetscCall(DMPlexGetHeightStratum(dm, cellHeight, &cStart, &cEnd));
1670:     PetscCall(ISGetIndices(gid, &idxs));
1671:     PetscCall(ISGetLocalSize(gid, &cum));
1672:     PetscCall(PetscMalloc1(cum, &idxs2));
1673:     for (c = cStart, cum = 0; c < cEnd; c++) {
1674:       if (idxs[c - cStart] < 0) continue;
1675:       idxs2[cum++] = idxs[c - cStart];
1676:     }
1677:     PetscCall(ISRestoreIndices(gid, &idxs));
1678:     PetscCheck(numVertices == cum, PETSC_COMM_SELF, PETSC_ERR_PLIB, "Unexpected %" PetscInt_FMT " != %" PetscInt_FMT, numVertices, cum);
1679:     PetscCall(ISDestroy(&gid));
1680:     PetscCall(ISCreateGeneral(comm, numVertices, idxs2, PETSC_OWN_POINTER, &gid));

1682:     /* support for node-aware cell locality */
1683:     PetscCall(ISCreateGeneral(comm, start[numVertices], adjacency, PETSC_USE_POINTER, &acis));
1684:     PetscCall(VecCreateSeq(PETSC_COMM_SELF, start[numVertices], &acown));
1685:     PetscCall(VecCreateMPI(comm, numVertices, PETSC_DECIDE, &cown));
1686:     PetscCall(VecGetArray(cown, &array));
1687:     for (c = 0; c < numVertices; c++) array[c] = nid;
1688:     PetscCall(VecRestoreArray(cown, &array));
1689:     PetscCall(VecScatterCreate(cown, acis, acown, NULL, &sct));
1690:     PetscCall(VecScatterBegin(sct, cown, acown, INSERT_VALUES, SCATTER_FORWARD));
1691:     PetscCall(VecScatterEnd(sct, cown, acown, INSERT_VALUES, SCATTER_FORWARD));
1692:     PetscCall(ISDestroy(&acis));
1693:     PetscCall(VecScatterDestroy(&sct));
1694:     PetscCall(VecDestroy(&cown));

1696:     /* compute edgeCut */
1697:     for (c = 0, cum = 0; c < numVertices; c++) cum = PetscMax(cum, start[c + 1] - start[c]);
1698:     PetscCall(PetscMalloc1(cum, &work));
1699:     PetscCall(ISLocalToGlobalMappingCreateIS(gid, &g2l));
1700:     PetscCall(ISLocalToGlobalMappingSetType(g2l, ISLOCALTOGLOBALMAPPINGHASH));
1701:     PetscCall(ISDestroy(&gid));
1702:     PetscCall(VecGetArray(acown, &array));
1703:     for (c = 0, ect = 0, ectn = 0; c < numVertices; c++) {
1704:       PetscInt totl;

1706:       totl = start[c + 1] - start[c];
1707:       PetscCall(ISGlobalToLocalMappingApply(g2l, IS_GTOLM_MASK, totl, adjacency + start[c], NULL, work));
1708:       for (i = 0; i < totl; i++) {
1709:         if (work[i] < 0) {
1710:           ect += 1;
1711:           ectn += (array[i + start[c]] != nid) ? 0 : 1;
1712:         }
1713:       }
1714:     }
1715:     PetscCall(PetscFree(work));
1716:     PetscCall(VecRestoreArray(acown, &array));
1717:     lm[0] = numVertices > 0 ? numVertices : PETSC_INT_MAX;
1718:     lm[1] = -numVertices;
1719:     PetscCallMPI(MPIU_Allreduce(lm, gm, 2, MPIU_INT64, MPI_MIN, comm));
1720:     PetscCall(PetscViewerASCIIPrintf(viewer, "  Cell balance: %.2f (max %" PetscInt64_FMT ", min %" PetscInt64_FMT, -((double)gm[1]) / ((double)gm[0]), -gm[1], gm[0]));
1721:     lm[0] = ect;                     /* edgeCut */
1722:     lm[1] = ectn;                    /* node-aware edgeCut */
1723:     lm[2] = numVertices > 0 ? 0 : 1; /* empty processes */
1724:     PetscCallMPI(MPIU_Allreduce(lm, gm, 3, MPIU_INT64, MPI_SUM, comm));
1725:     PetscCall(PetscViewerASCIIPrintf(viewer, ", empty %" PetscInt64_FMT ")\n", gm[2]));
1726: #if defined(PETSC_HAVE_MPI_PROCESS_SHARED_MEMORY)
1727:     PetscCall(PetscViewerASCIIPrintf(viewer, "  Edge Cut: %" PetscInt64_FMT " (on node %.3f)\n", gm[0] / 2, gm[0] ? ((double)gm[1]) / ((double)gm[0]) : 1.));
1728: #else
1729:     PetscCall(PetscViewerASCIIPrintf(viewer, "  Edge Cut: %" PetscInt64_FMT " (on node %.3f)\n", gm[0] / 2, 0.0));
1730: #endif
1731:     PetscCall(ISLocalToGlobalMappingDestroy(&g2l));
1732:     PetscCall(PetscFree(start));
1733:     PetscCall(PetscFree(adjacency));
1734:     PetscCall(VecDestroy(&acown));
1735:   } else {
1736:     const char    *name;
1737:     PetscInt      *sizes, *hybsizes, *ghostsizes;
1738:     PetscInt       locDepth, depth, cellHeight, dim, d;
1739:     PetscInt       pStart, pEnd, p, gcStart, gcEnd, gcNum;
1740:     PetscInt       numLabels, l, maxSize = 17;
1741:     DMPolytopeType ct0 = DM_POLYTOPE_UNKNOWN;
1742:     MPI_Comm       comm;
1743:     PetscMPIInt    size, rank;

1745:     PetscCall(PetscObjectGetComm((PetscObject)dm, &comm));
1746:     PetscCallMPI(MPI_Comm_size(comm, &size));
1747:     PetscCallMPI(MPI_Comm_rank(comm, &rank));
1748:     PetscCall(DMGetDimension(dm, &dim));
1749:     PetscCall(DMPlexGetVTKCellHeight(dm, &cellHeight));
1750:     PetscCall(PetscObjectGetName((PetscObject)dm, &name));
1751:     if (name) PetscCall(PetscViewerASCIIPrintf(viewer, "%s in %" PetscInt_FMT " dimension%s:\n", name, dim, dim == 1 ? "" : "s"));
1752:     else PetscCall(PetscViewerASCIIPrintf(viewer, "Mesh in %" PetscInt_FMT " dimension%s:\n", dim, dim == 1 ? "" : "s"));
1753:     if (cellHeight) PetscCall(PetscViewerASCIIPrintf(viewer, "  Cells are at height %" PetscInt_FMT "\n", cellHeight));
1754:     PetscCall(DMPlexGetDepth(dm, &locDepth));
1755:     PetscCallMPI(MPIU_Allreduce(&locDepth, &depth, 1, MPIU_INT, MPI_MAX, comm));
1756:     PetscCall(DMPlexGetCellTypeStratum(dm, DM_POLYTOPE_FV_GHOST, &gcStart, &gcEnd));
1757:     gcNum = gcEnd - gcStart;
1758:     if (size < maxSize) PetscCall(PetscCalloc3(size, &sizes, size, &hybsizes, size, &ghostsizes));
1759:     else PetscCall(PetscCalloc3(3, &sizes, 3, &hybsizes, 3, &ghostsizes));
1760:     for (d = 0; d <= depth; d++) {
1761:       PetscInt Nc[2] = {0, 0}, ict;

1763:       PetscCall(DMPlexGetDepthStratum(dm, d, &pStart, &pEnd));
1764:       if (pStart < pEnd) PetscCall(DMPlexGetCellType(dm, pStart, &ct0));
1765:       ict = ct0;
1766:       PetscCallMPI(MPI_Bcast(&ict, 1, MPIU_INT, 0, comm));
1767:       ct0 = (DMPolytopeType)ict;
1768:       for (p = pStart; p < pEnd; ++p) {
1769:         DMPolytopeType ct;

1771:         PetscCall(DMPlexGetCellType(dm, p, &ct));
1772:         if (ct == ct0) ++Nc[0];
1773:         else ++Nc[1];
1774:       }
1775:       if (size < maxSize) {
1776:         PetscCallMPI(MPI_Gather(&Nc[0], 1, MPIU_INT, sizes, 1, MPIU_INT, 0, comm));
1777:         PetscCallMPI(MPI_Gather(&Nc[1], 1, MPIU_INT, hybsizes, 1, MPIU_INT, 0, comm));
1778:         if (d == depth) PetscCallMPI(MPI_Gather(&gcNum, 1, MPIU_INT, ghostsizes, 1, MPIU_INT, 0, comm));
1779:         PetscCall(PetscViewerASCIIPrintf(viewer, "  Number of %" PetscInt_FMT "-cells per rank:", (depth == 1) && d ? dim : d));
1780:         for (p = 0; p < size; ++p) {
1781:           if (rank == 0) {
1782:             PetscCall(PetscViewerASCIIPrintf(viewer, " %" PetscInt_FMT, sizes[p] + hybsizes[p]));
1783:             if (hybsizes[p] > 0) PetscCall(PetscViewerASCIIPrintf(viewer, " (%" PetscInt_FMT ")", hybsizes[p]));
1784:             if (ghostsizes[p] > 0) PetscCall(PetscViewerASCIIPrintf(viewer, " [%" PetscInt_FMT "]", ghostsizes[p]));
1785:           }
1786:         }
1787:       } else {
1788:         sizes[0] = Nc[0] + Nc[1];
1789:         sizes[1] = Nc[0] + Nc[1];
1790:         PetscCall(PetscGlobalMinMaxInt(comm, sizes, sizes));
1791:         hybsizes[0] = Nc[1];
1792:         hybsizes[1] = Nc[1];
1793:         PetscCall(PetscGlobalMinMaxInt(comm, hybsizes, hybsizes));
1794:         if (d == depth) {
1795:           ghostsizes[0] = gcNum;
1796:           ghostsizes[1] = gcNum;
1797:           PetscCall(PetscGlobalMinMaxInt(comm, ghostsizes, ghostsizes));
1798:         }
1799:         PetscCall(PetscViewerASCIIPrintf(viewer, "  Min/Max of %" PetscInt_FMT "-cells per rank:", (depth == 1) && d ? dim : d));
1800:         PetscCall(PetscViewerASCIIPrintf(viewer, " %" PetscInt_FMT "/%" PetscInt_FMT, sizes[0], sizes[1]));
1801:         if (hybsizes[0] > 0) PetscCall(PetscViewerASCIIPrintf(viewer, " (%" PetscInt_FMT "/%" PetscInt_FMT ")", hybsizes[0], hybsizes[1]));
1802:         if (ghostsizes[0] > 0) PetscCall(PetscViewerASCIIPrintf(viewer, " [%" PetscInt_FMT "/%" PetscInt_FMT "]", ghostsizes[0], ghostsizes[1]));
1803:       }
1804:       PetscCall(PetscViewerASCIIPrintf(viewer, "\n"));
1805:     }
1806:     PetscCall(PetscFree3(sizes, hybsizes, ghostsizes));
1807:     {
1808:       DM               cdm;
1809:       const PetscReal *maxCell;
1810:       const PetscReal *L;
1811:       PetscBool        localized;

1813:       PetscCall(DMGetCoordinateDM(dm, &cdm));
1814:       PetscCall(DMViewDSFromOptions_Internal(cdm, "-plex_view_ds"));
1815:       PetscCall(DMViewSectionFromOptions_Internal(cdm, "-plex_view_section"));
1816:       PetscCall(DMGetPeriodicity(dm, &maxCell, NULL, &L));
1817:       PetscCall(DMGetCoordinatesLocalized(dm, &localized));
1818:       if (L || localized) {
1819:         PetscCall(PetscViewerASCIIPrintf(viewer, "Periodic mesh"));
1820:         PetscCall(PetscViewerASCIIUseTabs(viewer, PETSC_FALSE));
1821:         if (L) {
1822:           PetscCall(PetscViewerASCIIPrintf(viewer, " ("));
1823:           for (d = 0; d < dim; ++d) {
1824:             if (d > 0) PetscCall(PetscViewerASCIIPrintf(viewer, ", "));
1825:             PetscCall(PetscViewerASCIIPrintf(viewer, "%s", L[d] > 0.0 ? "PERIODIC" : "NONE"));
1826:           }
1827:           PetscCall(PetscViewerASCIIPrintf(viewer, ")"));
1828:         }
1829:         PetscCall(PetscViewerASCIIPrintf(viewer, " coordinates %s\n", localized ? "localized" : "not localized"));
1830:         PetscCall(PetscViewerASCIIUseTabs(viewer, PETSC_TRUE));
1831:       }
1832:     }
1833:     PetscCall(DMGetNumLabels(dm, &numLabels));
1834:     if (numLabels) PetscCall(PetscViewerASCIIPrintf(viewer, "Labels:\n"));
1835:     for (l = 0; l < numLabels; ++l) {
1836:       DMLabel     label;
1837:       const char *name;
1838:       PetscInt   *values;
1839:       PetscInt    numValues;

1841:       PetscCall(DMGetLabelName(dm, l, &name));
1842:       PetscCall(DMGetLabel(dm, name, &label));
1843:       PetscCall(DMLabelGetNumValues(label, &numValues));
1844:       PetscCall(PetscViewerASCIIPrintf(viewer, "  %s: %" PetscInt_FMT " strata with value/size (", name, numValues));

1846:       { // Extract array of DMLabel values so it can be sorted
1847:         IS              is_values;
1848:         const PetscInt *is_values_local = NULL;

1850:         PetscCall(DMLabelGetValueIS(label, &is_values));
1851:         PetscCall(ISGetIndices(is_values, &is_values_local));
1852:         PetscCall(PetscMalloc1(numValues, &values));
1853:         PetscCall(PetscArraycpy(values, is_values_local, numValues));
1854:         PetscCall(PetscSortInt(numValues, values));
1855:         PetscCall(ISRestoreIndices(is_values, &is_values_local));
1856:         PetscCall(ISDestroy(&is_values));
1857:       }
1858:       PetscCall(PetscViewerASCIIUseTabs(viewer, PETSC_FALSE));
1859:       for (PetscInt v = 0; v < numValues; ++v) {
1860:         PetscInt size;

1862:         PetscCall(DMLabelGetStratumSize(label, values[v], &size));
1863:         if (v > 0) PetscCall(PetscViewerASCIIPrintf(viewer, ", "));
1864:         PetscCall(PetscViewerASCIIPrintf(viewer, "%" PetscInt_FMT " (%" PetscInt_FMT ")", values[v], size));
1865:       }
1866:       PetscCall(PetscViewerASCIIPrintf(viewer, ")\n"));
1867:       PetscCall(PetscViewerASCIIUseTabs(viewer, PETSC_TRUE));
1868:       PetscCall(PetscFree(values));
1869:     }
1870:     {
1871:       char    **labelNames;
1872:       PetscInt  Nl = numLabels;
1873:       PetscBool flg;

1875:       PetscCall(PetscMalloc1(Nl, &labelNames));
1876:       PetscCall(PetscOptionsGetStringArray(((PetscObject)dm)->options, ((PetscObject)dm)->prefix, "-dm_plex_view_labels", labelNames, &Nl, &flg));
1877:       for (l = 0; l < Nl; ++l) {
1878:         DMLabel label;

1880:         PetscCall(DMHasLabel(dm, labelNames[l], &flg));
1881:         if (flg) {
1882:           PetscCall(DMGetLabel(dm, labelNames[l], &label));
1883:           PetscCall(DMLabelView(label, viewer));
1884:         }
1885:         PetscCall(PetscFree(labelNames[l]));
1886:       }
1887:       PetscCall(PetscFree(labelNames));
1888:     }
1889:     /* If no fields are specified, people do not want to see adjacency */
1890:     if (dm->Nf) {
1891:       for (PetscInt f = 0; f < dm->Nf; ++f) {
1892:         const char *name;

1894:         PetscCall(PetscObjectGetName(dm->fields[f].disc, &name));
1895:         if (numLabels) PetscCall(PetscViewerASCIIPrintf(viewer, "Field %s:\n", name));
1896:         PetscCall(PetscViewerASCIIPushTab(viewer));
1897:         if (dm->fields[f].label) PetscCall(DMLabelView(dm->fields[f].label, viewer));
1898:         if (dm->fields[f].adjacency[0]) {
1899:           if (dm->fields[f].adjacency[1]) PetscCall(PetscViewerASCIIPrintf(viewer, "adjacency FVM++\n"));
1900:           else PetscCall(PetscViewerASCIIPrintf(viewer, "adjacency FVM\n"));
1901:         } else {
1902:           if (dm->fields[f].adjacency[1]) PetscCall(PetscViewerASCIIPrintf(viewer, "adjacency FEM\n"));
1903:           else PetscCall(PetscViewerASCIIPrintf(viewer, "adjacency FUNKY\n"));
1904:         }
1905:         PetscCall(PetscViewerASCIIPopTab(viewer));
1906:       }
1907:     }
1908:     DMPlexTransform tr;

1910:     PetscCall(DMPlexGetTransform(dm, &tr));
1911:     if (tr) {
1912:       PetscCall(PetscViewerASCIIPushTab(viewer));
1913:       PetscCall(PetscViewerASCIIPrintf(viewer, "Created using transform:\n"));
1914:       PetscCall(DMPlexTransformView(tr, viewer));
1915:       PetscCall(PetscViewerASCIIPopTab(viewer));
1916:     }
1917:     PetscCall(DMGetCoarseDM(dm, &cdm));
1918:     if (cdm) {
1919:       PetscCall(PetscViewerASCIIPushTab(viewer));
1920:       PetscCall(PetscViewerASCIIPrintf(viewer, "Defined by transform from:\n"));
1921:       PetscCall(DMPlexView_Ascii(cdm, viewer));
1922:       PetscCall(PetscViewerASCIIPopTab(viewer));
1923:     }
1924:   }
1925:   PetscFunctionReturn(PETSC_SUCCESS);
1926: }

1928: /*@
1929:   DMPlexDrawCell - Draw the given cell on the `PetscDraw` object.

1931:   Not collective

1933:   Input Parameters:
1934: + dm     - The `DMPLEX` object
1935: . draw   - The `PetscDraw` object
1936: . lC     - The line color, or `PETSC_DETERMINE` to use the default
1937: . cC     - The cell color, or `PETSC_DETERMINE` to use the default
1938: . cell   - The cell to draw
1939: - coords - The vertex coordinates for the cell

1941:   Level: developer

1943: .seealso: [](ch_unstructured), `DM`, `DMPLEX`, `DMView()`
1944: @*/
1945: PetscErrorCode DMPlexDrawCell(DM dm, PetscDraw draw, PetscInt lC, PetscInt cC, PetscInt cell, const PetscScalar coords[])
1946: {
1947:   DMPolytopeType ct;
1948:   PetscMPIInt    rank;
1949:   PetscInt       cdim;
1950:   int            lineColor, cellColor;

1952:   PetscFunctionBegin;
1955:   PetscCallMPI(MPI_Comm_rank(PetscObjectComm((PetscObject)dm), &rank));
1956:   PetscCall(DMPlexGetCellType(dm, cell, &ct));
1957:   PetscCall(DMGetCoordinateDim(dm, &cdim));
1958:   lineColor = (int)(lC == PETSC_DETERMINE ? PETSC_DRAW_BLACK : lC);
1959:   cellColor = (int)(cC == PETSC_DETERMINE ? PETSC_DRAW_WHITE + rank % (PETSC_DRAW_BASIC_COLORS - 2) + 2 : cC);
1960:   switch (ct) {
1961:   case DM_POLYTOPE_SEGMENT:
1962:   case DM_POLYTOPE_POINT_PRISM_TENSOR:
1963:     switch (cdim) {
1964:     case 1: {
1965:       const PetscReal y  = 0.5;  /* TODO Put it in the middle of the viewport */
1966:       const PetscReal dy = 0.05; /* TODO Make it a fraction of the total length */

1968:       PetscCall(PetscDrawLine(draw, PetscRealPart(coords[0]), y, PetscRealPart(coords[1]), y, lineColor));
1969:       PetscCall(PetscDrawLine(draw, PetscRealPart(coords[0]), y + dy, PetscRealPart(coords[0]), y - dy, lineColor));
1970:       PetscCall(PetscDrawLine(draw, PetscRealPart(coords[1]), y + dy, PetscRealPart(coords[1]), y - dy, lineColor));
1971:     } break;
1972:     case 2: {
1973:       const PetscReal dx = (PetscRealPart(coords[3]) - PetscRealPart(coords[1]));
1974:       const PetscReal dy = (PetscRealPart(coords[2]) - PetscRealPart(coords[0]));
1975:       const PetscReal l  = 0.1 / PetscSqrtReal(dx * dx + dy * dy);

1977:       PetscCall(PetscDrawLine(draw, PetscRealPart(coords[0]), PetscRealPart(coords[1]), PetscRealPart(coords[2]), PetscRealPart(coords[3]), lineColor));
1978:       PetscCall(PetscDrawLine(draw, PetscRealPart(coords[0]) + l * dx, PetscRealPart(coords[1]) + l * dy, PetscRealPart(coords[0]) - l * dx, PetscRealPart(coords[1]) - l * dy, lineColor));
1979:       PetscCall(PetscDrawLine(draw, PetscRealPart(coords[2]) + l * dx, PetscRealPart(coords[3]) + l * dy, PetscRealPart(coords[2]) - l * dx, PetscRealPart(coords[3]) - l * dy, lineColor));
1980:     } break;
1981:     default:
1982:       SETERRQ(PETSC_COMM_SELF, PETSC_ERR_SUP, "Cannot draw cells of dimension %" PetscInt_FMT, cdim);
1983:     }
1984:     break;
1985:   case DM_POLYTOPE_TRIANGLE:
1986:     if (cellColor >= 0) PetscCall(PetscDrawTriangle(draw, PetscRealPart(coords[0]), PetscRealPart(coords[1]), PetscRealPart(coords[2]), PetscRealPart(coords[3]), PetscRealPart(coords[4]), PetscRealPart(coords[5]), cellColor, cellColor, cellColor));
1987:     PetscCall(PetscDrawLine(draw, PetscRealPart(coords[0]), PetscRealPart(coords[1]), PetscRealPart(coords[2]), PetscRealPart(coords[3]), lineColor));
1988:     PetscCall(PetscDrawLine(draw, PetscRealPart(coords[2]), PetscRealPart(coords[3]), PetscRealPart(coords[4]), PetscRealPart(coords[5]), lineColor));
1989:     PetscCall(PetscDrawLine(draw, PetscRealPart(coords[4]), PetscRealPart(coords[5]), PetscRealPart(coords[0]), PetscRealPart(coords[1]), lineColor));
1990:     break;
1991:   case DM_POLYTOPE_QUADRILATERAL:
1992:     if (cellColor >= 0) {
1993:       PetscCall(PetscDrawTriangle(draw, PetscRealPart(coords[0]), PetscRealPart(coords[1]), PetscRealPart(coords[2]), PetscRealPart(coords[3]), PetscRealPart(coords[4]), PetscRealPart(coords[5]), cellColor, cellColor, cellColor));
1994:       PetscCall(PetscDrawTriangle(draw, PetscRealPart(coords[0]), PetscRealPart(coords[1]), PetscRealPart(coords[4]), PetscRealPart(coords[5]), PetscRealPart(coords[6]), PetscRealPart(coords[7]), cellColor, cellColor, cellColor));
1995:     }
1996:     PetscCall(PetscDrawLine(draw, PetscRealPart(coords[0]), PetscRealPart(coords[1]), PetscRealPart(coords[2]), PetscRealPart(coords[3]), lineColor));
1997:     PetscCall(PetscDrawLine(draw, PetscRealPart(coords[2]), PetscRealPart(coords[3]), PetscRealPart(coords[4]), PetscRealPart(coords[5]), lineColor));
1998:     PetscCall(PetscDrawLine(draw, PetscRealPart(coords[4]), PetscRealPart(coords[5]), PetscRealPart(coords[6]), PetscRealPart(coords[7]), lineColor));
1999:     PetscCall(PetscDrawLine(draw, PetscRealPart(coords[6]), PetscRealPart(coords[7]), PetscRealPart(coords[0]), PetscRealPart(coords[1]), lineColor));
2000:     break;
2001:   case DM_POLYTOPE_SEG_PRISM_TENSOR:
2002:     if (cellColor >= 0) {
2003:       PetscCall(PetscDrawTriangle(draw, PetscRealPart(coords[0]), PetscRealPart(coords[1]), PetscRealPart(coords[2]), PetscRealPart(coords[3]), PetscRealPart(coords[4]), PetscRealPart(coords[5]), cellColor, cellColor, cellColor));
2004:       PetscCall(PetscDrawTriangle(draw, PetscRealPart(coords[2]), PetscRealPart(coords[3]), PetscRealPart(coords[6]), PetscRealPart(coords[7]), PetscRealPart(coords[4]), PetscRealPart(coords[5]), cellColor, cellColor, cellColor));
2005:     }
2006:     PetscCall(PetscDrawLine(draw, PetscRealPart(coords[0]), PetscRealPart(coords[1]), PetscRealPart(coords[2]), PetscRealPart(coords[3]), lineColor));
2007:     PetscCall(PetscDrawLine(draw, PetscRealPart(coords[2]), PetscRealPart(coords[3]), PetscRealPart(coords[6]), PetscRealPart(coords[7]), lineColor));
2008:     PetscCall(PetscDrawLine(draw, PetscRealPart(coords[6]), PetscRealPart(coords[7]), PetscRealPart(coords[4]), PetscRealPart(coords[5]), lineColor));
2009:     PetscCall(PetscDrawLine(draw, PetscRealPart(coords[4]), PetscRealPart(coords[5]), PetscRealPart(coords[0]), PetscRealPart(coords[1]), lineColor));
2010:     break;
2011:   case DM_POLYTOPE_FV_GHOST:
2012:     break;
2013:   default:
2014:     SETERRQ(PETSC_COMM_SELF, PETSC_ERR_SUP, "Cannot draw cells of type %s", DMPolytopeTypes[ct]);
2015:   }
2016:   PetscFunctionReturn(PETSC_SUCCESS);
2017: }

2019: static PetscErrorCode DrawPolygon_Private(DM dm, PetscDraw draw, PetscInt cell, PetscInt Nv, const PetscReal refVertices[], const PetscScalar coords[], PetscInt edgeDiv, PetscReal refCoords[], PetscReal edgeCoords[])
2020: {
2021:   PetscReal   centroid[2] = {0., 0.};
2022:   PetscMPIInt rank;
2023:   PetscMPIInt fillColor;

2025:   PetscFunctionBegin;
2026:   PetscCallMPI(MPI_Comm_rank(PetscObjectComm((PetscObject)dm), &rank));
2027:   fillColor = PETSC_DRAW_WHITE + rank % (PETSC_DRAW_BASIC_COLORS - 2) + 2;
2028:   for (PetscInt v = 0; v < Nv; ++v) {
2029:     centroid[0] += PetscRealPart(coords[v * 2 + 0]) / Nv;
2030:     centroid[1] += PetscRealPart(coords[v * 2 + 1]) / Nv;
2031:   }
2032:   for (PetscInt e = 0; e < Nv; ++e) {
2033:     refCoords[0] = refVertices[e * 2 + 0];
2034:     refCoords[1] = refVertices[e * 2 + 1];
2035:     for (PetscInt d = 1; d <= edgeDiv; ++d) {
2036:       refCoords[d * 2 + 0] = refCoords[0] + (refVertices[(e + 1) % Nv * 2 + 0] - refCoords[0]) * d / edgeDiv;
2037:       refCoords[d * 2 + 1] = refCoords[1] + (refVertices[(e + 1) % Nv * 2 + 1] - refCoords[1]) * d / edgeDiv;
2038:     }
2039:     PetscCall(DMPlexReferenceToCoordinates(dm, cell, edgeDiv + 1, refCoords, edgeCoords));
2040:     for (PetscInt d = 0; d < edgeDiv; ++d) {
2041:       PetscCall(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));
2042:       PetscCall(PetscDrawLine(draw, edgeCoords[d * 2 + 0], edgeCoords[d * 2 + 1], edgeCoords[(d + 1) * 2 + 0], edgeCoords[(d + 1) * 2 + 1], PETSC_DRAW_BLACK));
2043:     }
2044:   }
2045:   PetscFunctionReturn(PETSC_SUCCESS);
2046: }

2048: static PetscErrorCode DMPlexDrawCellHighOrder(DM dm, PetscDraw draw, PetscInt cell, const PetscScalar coords[], PetscInt edgeDiv, PetscReal refCoords[], PetscReal edgeCoords[])
2049: {
2050:   DMPolytopeType ct;

2052:   PetscFunctionBegin;
2053:   PetscCall(DMPlexGetCellType(dm, cell, &ct));
2054:   switch (ct) {
2055:   case DM_POLYTOPE_TRIANGLE: {
2056:     PetscReal refVertices[6] = {-1., -1., 1., -1., -1., 1.};

2058:     PetscCall(DrawPolygon_Private(dm, draw, cell, 3, refVertices, coords, edgeDiv, refCoords, edgeCoords));
2059:   } break;
2060:   case DM_POLYTOPE_QUADRILATERAL: {
2061:     PetscReal refVertices[8] = {-1., -1., 1., -1., 1., 1., -1., 1.};

2063:     PetscCall(DrawPolygon_Private(dm, draw, cell, 4, refVertices, coords, edgeDiv, refCoords, edgeCoords));
2064:   } break;
2065:   default:
2066:     SETERRQ(PETSC_COMM_SELF, PETSC_ERR_SUP, "Cannot draw cells of type %s", DMPolytopeTypes[ct]);
2067:   }
2068:   PetscFunctionReturn(PETSC_SUCCESS);
2069: }

2071: static PetscErrorCode DMPlexView_Draw(DM dm, PetscViewer viewer)
2072: {
2073:   PetscDraw    draw;
2074:   DM           cdm;
2075:   PetscSection coordSection;
2076:   Vec          coordinates;
2077:   PetscReal    xyl[3], xyr[3];
2078:   PetscReal   *refCoords, *edgeCoords;
2079:   PetscBool    isnull, drawAffine;
2080:   PetscInt     dim, vStart, vEnd, cStart, cEnd, c, cDegree, edgeDiv, lineColor = PETSC_DETERMINE, cellColor = PETSC_DETERMINE;

2082:   PetscFunctionBegin;
2083:   PetscCall(DMGetCoordinateDim(dm, &dim));
2084:   PetscCheck(dim <= 2, PetscObjectComm((PetscObject)dm), PETSC_ERR_SUP, "Cannot draw meshes of dimension %" PetscInt_FMT, dim);
2085:   PetscCall(DMGetCoordinateDegree_Internal(dm, &cDegree));
2086:   drawAffine = cDegree > 1 ? PETSC_FALSE : PETSC_TRUE;
2087:   edgeDiv    = cDegree + 1;
2088:   PetscCall(PetscOptionsGetInt(((PetscObject)dm)->options, ((PetscObject)dm)->prefix, "-dm_view_draw_line_color", &lineColor, NULL));
2089:   PetscCall(PetscOptionsGetInt(((PetscObject)dm)->options, ((PetscObject)dm)->prefix, "-dm_view_draw_cell_color", &cellColor, NULL));
2090:   PetscCall(PetscOptionsGetBool(((PetscObject)dm)->options, ((PetscObject)dm)->prefix, "-dm_view_draw_affine", &drawAffine, NULL));
2091:   if (!drawAffine) PetscCall(PetscMalloc2((edgeDiv + 1) * dim, &refCoords, (edgeDiv + 1) * dim, &edgeCoords));
2092:   PetscCall(DMGetCoordinateDM(dm, &cdm));
2093:   PetscCall(DMGetLocalSection(cdm, &coordSection));
2094:   PetscCall(DMGetCoordinatesLocal(dm, &coordinates));
2095:   PetscCall(DMPlexGetDepthStratum(dm, 0, &vStart, &vEnd));
2096:   PetscCall(DMPlexGetHeightStratum(dm, 0, &cStart, &cEnd));

2098:   PetscCall(PetscViewerDrawGetDraw(viewer, 0, &draw));
2099:   PetscCall(PetscDrawIsNull(draw, &isnull));
2100:   if (isnull) PetscFunctionReturn(PETSC_SUCCESS);
2101:   PetscCall(PetscDrawSetTitle(draw, "Mesh"));

2103:   PetscCall(DMGetBoundingBox(dm, xyl, xyr));
2104:   PetscCall(PetscDrawSetCoordinates(draw, xyl[0], xyl[1], xyr[0], xyr[1]));
2105:   PetscCall(PetscDrawClear(draw));

2107:   for (c = cStart; c < cEnd; ++c) {
2108:     PetscScalar       *coords = NULL;
2109:     const PetscScalar *coords_arr;
2110:     PetscInt           numCoords;
2111:     PetscBool          isDG;

2113:     PetscCall(DMPlexGetCellCoordinates(dm, c, &isDG, &numCoords, &coords_arr, &coords));
2114:     if (drawAffine) PetscCall(DMPlexDrawCell(dm, draw, lineColor, cellColor, c, coords));
2115:     else PetscCall(DMPlexDrawCellHighOrder(dm, draw, c, coords, edgeDiv, refCoords, edgeCoords));
2116:     PetscCall(DMPlexRestoreCellCoordinates(dm, c, &isDG, &numCoords, &coords_arr, &coords));
2117:   }
2118:   if (!drawAffine) PetscCall(PetscFree2(refCoords, edgeCoords));
2119:   PetscCall(PetscDrawFlush(draw));
2120:   PetscCall(PetscDrawPause(draw));
2121:   PetscCall(PetscDrawSave(draw));
2122:   PetscFunctionReturn(PETSC_SUCCESS);
2123: }

2125: static PetscErrorCode DMPlexCreateHighOrderSurrogate_Internal(DM dm, DM *hdm)
2126: {
2127:   DM           odm = dm, rdm = dm, cdm;
2128:   PetscFE      fe;
2129:   PetscSpace   sp;
2130:   PetscClassId id;
2131:   PetscInt     degree;
2132:   PetscBool    hoView = PETSC_TRUE;

2134:   PetscFunctionBegin;
2135:   PetscObjectOptionsBegin((PetscObject)dm);
2136:   PetscCall(PetscOptionsBool("-dm_plex_high_order_view", "Subsample to view meshes with high order coordinates", "DMPlexCreateHighOrderSurrogate_Internal", hoView, &hoView, NULL));
2137:   PetscOptionsEnd();
2138:   PetscCall(PetscObjectReference((PetscObject)dm));
2139:   *hdm = dm;
2140:   if (!hoView) PetscFunctionReturn(PETSC_SUCCESS);
2141:   PetscCall(DMGetCoordinateDM(dm, &cdm));
2142:   PetscCall(DMGetField(cdm, 0, NULL, (PetscObject *)&fe));
2143:   PetscCall(PetscObjectGetClassId((PetscObject)fe, &id));
2144:   if (id != PETSCFE_CLASSID) PetscFunctionReturn(PETSC_SUCCESS);
2145:   PetscCall(PetscFEGetBasisSpace(fe, &sp));
2146:   PetscCall(PetscSpaceGetDegree(sp, &degree, NULL));
2147:   for (PetscInt r = 0, rd = PetscCeilReal(((PetscReal)degree) / 2.); r < (PetscInt)PetscCeilReal(PetscLog2Real(degree)); ++r, rd = PetscCeilReal(((PetscReal)rd) / 2.)) {
2148:     DM  cdm, rcdm;
2149:     Mat In;
2150:     Vec cl, rcl;

2152:     PetscCall(DMRefine(odm, PetscObjectComm((PetscObject)odm), &rdm));
2153:     PetscCall(DMPlexCreateCoordinateSpace(rdm, rd, PETSC_FALSE, PETSC_FALSE));
2154:     PetscCall(PetscObjectSetName((PetscObject)rdm, "Refined Mesh with Linear Coordinates"));
2155:     PetscCall(DMGetCoordinateDM(odm, &cdm));
2156:     PetscCall(DMGetCoordinateDM(rdm, &rcdm));
2157:     PetscCall(DMGetCoordinatesLocal(odm, &cl));
2158:     PetscCall(DMGetCoordinatesLocal(rdm, &rcl));
2159:     PetscCall(DMSetCoarseDM(rcdm, cdm));
2160:     PetscCall(DMCreateInterpolation(cdm, rcdm, &In, NULL));
2161:     PetscCall(MatMult(In, cl, rcl));
2162:     PetscCall(MatDestroy(&In));
2163:     PetscCall(DMSetCoordinatesLocal(rdm, rcl));
2164:     PetscCall(DMDestroy(&odm));
2165:     odm = rdm;
2166:   }
2167:   *hdm = rdm;
2168:   PetscFunctionReturn(PETSC_SUCCESS);
2169: }

2171: #if defined(PETSC_HAVE_EXODUSII)
2172:   #include <exodusII.h>
2173: #endif

2175: PetscErrorCode DMView_Plex(DM dm, PetscViewer viewer)
2176: {
2177:   PetscBool isascii, ishdf5, isvtk, isdraw, flg, isglvis, isexodus, iscgns, ispython;
2178:   char      name[PETSC_MAX_PATH_LEN];

2180:   PetscFunctionBegin;
2183:   PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERASCII, &isascii));
2184:   PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERVTK, &isvtk));
2185:   PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERHDF5, &ishdf5));
2186:   PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERDRAW, &isdraw));
2187:   PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERGLVIS, &isglvis));
2188:   PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWEREXODUSII, &isexodus));
2189:   PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERCGNS, &iscgns));
2190:   PetscCall(PetscObjectHasFunction((PetscObject)viewer, "PetscViewerPythonViewObject_C", &ispython));
2191:   if (isascii) {
2192:     PetscViewerFormat format;
2193:     PetscCall(PetscViewerGetFormat(viewer, &format));
2194:     if (format == PETSC_VIEWER_ASCII_GLVIS) PetscCall(DMPlexView_GLVis(dm, viewer));
2195:     else PetscCall(DMPlexView_Ascii(dm, viewer));
2196:   } else if (ishdf5) {
2197: #if defined(PETSC_HAVE_HDF5)
2198:     PetscCall(DMPlexView_HDF5_Internal(dm, viewer));
2199: #else
2200:     SETERRQ(PetscObjectComm((PetscObject)dm), PETSC_ERR_SUP, "HDF5 not supported in this build.\nPlease reconfigure using --download-hdf5");
2201: #endif
2202:   } else if (isvtk) {
2203:     PetscCall(DMPlexVTKWriteAll((PetscObject)dm, viewer));
2204:   } else if (isdraw) {
2205:     DM hdm;

2207:     PetscCall(DMPlexCreateHighOrderSurrogate_Internal(dm, &hdm));
2208:     PetscCall(DMPlexView_Draw(hdm, viewer));
2209:     PetscCall(DMDestroy(&hdm));
2210:   } else if (isglvis) {
2211:     PetscCall(DMPlexView_GLVis(dm, viewer));
2212: #if defined(PETSC_HAVE_EXODUSII)
2213:   } else if (isexodus) {
2214:     /*
2215:       ExodusII requires that all sets be part of exactly one cell set.
2216:       If the dm does not have a "Cell Sets" label defined, we create one
2217:       with ID 1, containing all cells.
2218:       Note that if the Cell Sets label is defined but does not cover all cells,
2219:       we may still have a problem. This should probably be checked here or in the viewer;
2220:     */
2221:     PetscInt numCS;
2222:     PetscCall(DMGetLabelSize(dm, "Cell Sets", &numCS));
2223:     if (!numCS) {
2224:       PetscInt cStart, cEnd, c;
2225:       PetscCall(DMCreateLabel(dm, "Cell Sets"));
2226:       PetscCall(DMPlexGetHeightStratum(dm, 0, &cStart, &cEnd));
2227:       for (c = cStart; c < cEnd; ++c) PetscCall(DMSetLabelValue(dm, "Cell Sets", c, 1));
2228:     }
2229:     PetscCall(DMView_PlexExodusII(dm, viewer));
2230: #endif
2231: #if defined(PETSC_HAVE_CGNS)
2232:   } else if (iscgns) {
2233:     PetscCall(DMView_PlexCGNS(dm, viewer));
2234: #endif
2235:   } else if (ispython) {
2236:     PetscCall(PetscViewerPythonViewObject(viewer, (PetscObject)dm));
2237:   } else SETERRQ(PetscObjectComm((PetscObject)dm), PETSC_ERR_SUP, "Viewer type %s not yet supported for DMPlex writing", ((PetscObject)viewer)->type_name);
2238:   /* Optionally view the partition */
2239:   PetscCall(PetscOptionsHasName(((PetscObject)dm)->options, ((PetscObject)dm)->prefix, "-dm_partition_view", &flg));
2240:   if (flg) {
2241:     Vec ranks;
2242:     PetscCall(DMPlexCreateRankField(dm, &ranks));
2243:     PetscCall(VecView(ranks, viewer));
2244:     PetscCall(VecDestroy(&ranks));
2245:   }
2246:   /* Optionally view a label */
2247:   PetscCall(PetscOptionsGetString(((PetscObject)dm)->options, ((PetscObject)dm)->prefix, "-dm_label_view", name, sizeof(name), &flg));
2248:   if (flg) {
2249:     DMLabel label;
2250:     Vec     val;

2252:     PetscCall(DMGetLabel(dm, name, &label));
2253:     PetscCheck(label, PetscObjectComm((PetscObject)dm), PETSC_ERR_ARG_WRONG, "Label %s provided to -dm_label_view does not exist in this DM", name);
2254:     PetscCall(DMPlexCreateLabelField(dm, label, &val));
2255:     PetscCall(VecView(val, viewer));
2256:     PetscCall(VecDestroy(&val));
2257:   }
2258:   PetscFunctionReturn(PETSC_SUCCESS);
2259: }

2261: /*@
2262:   DMPlexTopologyView - Saves a `DMPLEX` topology into a file

2264:   Collective

2266:   Input Parameters:
2267: + dm     - The `DM` whose topology is to be saved
2268: - viewer - The `PetscViewer` to save it in

2270:   Level: advanced

2272: .seealso: [](ch_unstructured), `DM`, `DMPLEX`, `DMView()`, `DMPlexCoordinatesView()`, `DMPlexLabelsView()`, `DMPlexTopologyLoad()`, `PetscViewer`
2273: @*/
2274: PetscErrorCode DMPlexTopologyView(DM dm, PetscViewer viewer)
2275: {
2276:   PetscBool ishdf5;

2278:   PetscFunctionBegin;
2281:   PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERHDF5, &ishdf5));
2282:   PetscCall(PetscLogEventBegin(DMPLEX_TopologyView, viewer, 0, 0, 0));
2283:   if (ishdf5) {
2284: #if defined(PETSC_HAVE_HDF5)
2285:     IS                globalPointNumbering;
2286:     PetscViewerFormat format;

2288:     PetscCall(PetscViewerGetFormat(viewer, &format));
2289:     PetscCheck(format == PETSC_VIEWER_HDF5_PETSC || format == PETSC_VIEWER_DEFAULT || format == PETSC_VIEWER_NATIVE, PetscObjectComm((PetscObject)dm), PETSC_ERR_SUP, "PetscViewerFormat %s not supported for HDF5 output.", PetscViewerFormats[format]);
2290:     PetscCall(DMPlexCreatePointNumbering(dm, &globalPointNumbering));
2291:     PetscCall(DMPlexTopologyView_HDF5_Internal(dm, globalPointNumbering, viewer));
2292:     PetscCall(ISDestroy(&globalPointNumbering));
2293: #else
2294:     SETERRQ(PetscObjectComm((PetscObject)dm), PETSC_ERR_SUP, "HDF5 not supported in this build.\nPlease reconfigure using --download-hdf5");
2295: #endif
2296:   }
2297:   PetscCall(PetscLogEventEnd(DMPLEX_TopologyView, viewer, 0, 0, 0));
2298:   PetscFunctionReturn(PETSC_SUCCESS);
2299: }

2301: /*@
2302:   DMPlexCoordinatesView - Saves `DMPLEX` coordinates into a file

2304:   Collective

2306:   Input Parameters:
2307: + dm     - The `DM` whose coordinates are to be saved
2308: - viewer - The `PetscViewer` for saving

2310:   Level: advanced

2312: .seealso: [](ch_unstructured), `DM`, `DMPLEX`, `DMView()`, `DMPlexTopologyView()`, `DMPlexLabelsView()`, `DMPlexCoordinatesLoad()`, `PetscViewer`
2313: @*/
2314: PetscErrorCode DMPlexCoordinatesView(DM dm, PetscViewer viewer)
2315: {
2316:   PetscBool ishdf5;

2318:   PetscFunctionBegin;
2321:   PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERHDF5, &ishdf5));
2322:   PetscCall(PetscLogEventBegin(DMPLEX_CoordinatesView, viewer, 0, 0, 0));
2323:   if (ishdf5) {
2324: #if defined(PETSC_HAVE_HDF5)
2325:     PetscViewerFormat format;

2327:     PetscCall(PetscViewerGetFormat(viewer, &format));
2328:     PetscCheck(format == PETSC_VIEWER_HDF5_PETSC || format == PETSC_VIEWER_DEFAULT || format == PETSC_VIEWER_NATIVE, PetscObjectComm((PetscObject)dm), PETSC_ERR_SUP, "PetscViewerFormat %s not supported for HDF5 output.", PetscViewerFormats[format]);
2329:     PetscCall(DMPlexCoordinatesView_HDF5_Internal(dm, viewer));
2330: #else
2331:     SETERRQ(PetscObjectComm((PetscObject)dm), PETSC_ERR_SUP, "HDF5 not supported in this build.\nPlease reconfigure using --download-hdf5");
2332: #endif
2333:   }
2334:   PetscCall(PetscLogEventEnd(DMPLEX_CoordinatesView, viewer, 0, 0, 0));
2335:   PetscFunctionReturn(PETSC_SUCCESS);
2336: }

2338: /*@
2339:   DMPlexLabelsView - Saves `DMPLEX` labels into a file

2341:   Collective

2343:   Input Parameters:
2344: + dm     - The `DM` whose labels are to be saved
2345: - viewer - The `PetscViewer` for saving

2347:   Level: advanced

2349: .seealso: [](ch_unstructured), `DM`, `DMPLEX`, `DMView()`, `DMPlexTopologyView()`, `DMPlexCoordinatesView()`, `DMPlexLabelsLoad()`, `PetscViewer`
2350: @*/
2351: PetscErrorCode DMPlexLabelsView(DM dm, PetscViewer viewer)
2352: {
2353:   PetscBool ishdf5;

2355:   PetscFunctionBegin;
2358:   PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERHDF5, &ishdf5));
2359:   PetscCall(PetscLogEventBegin(DMPLEX_LabelsView, viewer, 0, 0, 0));
2360:   if (ishdf5) {
2361: #if defined(PETSC_HAVE_HDF5)
2362:     IS                globalPointNumbering;
2363:     PetscViewerFormat format;

2365:     PetscCall(PetscViewerGetFormat(viewer, &format));
2366:     PetscCheck(format == PETSC_VIEWER_HDF5_PETSC || format == PETSC_VIEWER_DEFAULT || format == PETSC_VIEWER_NATIVE, PetscObjectComm((PetscObject)dm), PETSC_ERR_SUP, "PetscViewerFormat %s not supported for HDF5 input.", PetscViewerFormats[format]);
2367:     PetscCall(DMPlexCreatePointNumbering(dm, &globalPointNumbering));
2368:     PetscCall(DMPlexLabelsView_HDF5_Internal(dm, globalPointNumbering, viewer));
2369:     PetscCall(ISDestroy(&globalPointNumbering));
2370: #else
2371:     SETERRQ(PetscObjectComm((PetscObject)dm), PETSC_ERR_SUP, "HDF5 not supported in this build.\nPlease reconfigure using --download-hdf5");
2372: #endif
2373:   }
2374:   PetscCall(PetscLogEventEnd(DMPLEX_LabelsView, viewer, 0, 0, 0));
2375:   PetscFunctionReturn(PETSC_SUCCESS);
2376: }

2378: /*@
2379:   DMPlexSectionView - Saves a section associated with a `DMPLEX`

2381:   Collective

2383:   Input Parameters:
2384: + dm        - The `DM` that contains the topology on which the section to be saved is defined
2385: . viewer    - The `PetscViewer` for saving
2386: - sectiondm - The `DM` that contains the section to be saved, can be `NULL`

2388:   Level: advanced

2390:   Notes:
2391:   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.

2393:   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 (or in case `sectiondm` is `NULL`) 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.

2395: .seealso: [](ch_unstructured), `DM`, `DMPLEX`, `DMView()`, `DMPlexTopologyView()`, `DMPlexCoordinatesView()`, `DMPlexLabelsView()`, `DMPlexGlobalVectorView()`, `DMPlexLocalVectorView()`, `PetscSectionView()`, `DMPlexSectionLoad()`, `PetscViewer`
2396: @*/
2397: PetscErrorCode DMPlexSectionView(DM dm, PetscViewer viewer, DM sectiondm)
2398: {
2399:   PetscBool ishdf5;

2401:   PetscFunctionBegin;
2404:   if (!sectiondm) sectiondm = dm;
2406:   PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERHDF5, &ishdf5));
2407:   PetscCall(PetscLogEventBegin(DMPLEX_SectionView, viewer, 0, 0, 0));
2408:   if (ishdf5) {
2409: #if defined(PETSC_HAVE_HDF5)
2410:     PetscCall(DMPlexSectionView_HDF5_Internal(dm, viewer, sectiondm));
2411: #else
2412:     SETERRQ(PetscObjectComm((PetscObject)dm), PETSC_ERR_SUP, "HDF5 not supported in this build.\nPlease reconfigure using --download-hdf5");
2413: #endif
2414:   }
2415:   PetscCall(PetscLogEventEnd(DMPLEX_SectionView, viewer, 0, 0, 0));
2416:   PetscFunctionReturn(PETSC_SUCCESS);
2417: }

2419: /*@
2420:   DMPlexGlobalVectorView - Saves a global vector

2422:   Collective

2424:   Input Parameters:
2425: + dm        - The `DM` that represents the topology
2426: . viewer    - The `PetscViewer` to save data with
2427: . sectiondm - The `DM` that contains the global section on which vec is defined, can be `NULL`
2428: - vec       - The global vector to be saved

2430:   Level: advanced

2432:   Notes:
2433:   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 (or in case `sectiondm` is `NULL`) 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.

2435:   Calling sequence:
2436: .vb
2437:        DMCreate(PETSC_COMM_WORLD, &dm);
2438:        DMSetType(dm, DMPLEX);
2439:        PetscObjectSetName((PetscObject)dm, "topologydm_name");
2440:        DMClone(dm, &sectiondm);
2441:        PetscObjectSetName((PetscObject)sectiondm, "sectiondm_name");
2442:        PetscSectionCreate(PETSC_COMM_WORLD, &section);
2443:        DMPlexGetChart(sectiondm, &pStart, &pEnd);
2444:        PetscSectionSetChart(section, pStart, pEnd);
2445:        PetscSectionSetUp(section);
2446:        DMSetLocalSection(sectiondm, section);
2447:        PetscSectionDestroy(&section);
2448:        DMGetGlobalVector(sectiondm, &vec);
2449:        PetscObjectSetName((PetscObject)vec, "vec_name");
2450:        DMPlexTopologyView(dm, viewer);
2451:        DMPlexSectionView(dm, viewer, sectiondm);
2452:        DMPlexGlobalVectorView(dm, viewer, sectiondm, vec);
2453:        DMRestoreGlobalVector(sectiondm, &vec);
2454:        DMDestroy(&sectiondm);
2455:        DMDestroy(&dm);
2456: .ve

2458: .seealso: [](ch_unstructured), `DM`, `DMPLEX`, `DMPlexTopologyView()`, `DMPlexSectionView()`, `DMPlexLocalVectorView()`, `DMPlexGlobalVectorLoad()`, `DMPlexLocalVectorLoad()`
2459: @*/
2460: PetscErrorCode DMPlexGlobalVectorView(DM dm, PetscViewer viewer, DM sectiondm, Vec vec)
2461: {
2462:   PetscBool ishdf5;

2464:   PetscFunctionBegin;
2467:   if (!sectiondm) sectiondm = dm;
2470:   /* Check consistency */
2471:   {
2472:     PetscSection section;
2473:     PetscBool    includesConstraints;
2474:     PetscInt     m, m1;

2476:     PetscCall(VecGetLocalSize(vec, &m1));
2477:     PetscCall(DMGetGlobalSection(sectiondm, &section));
2478:     PetscCall(PetscSectionGetIncludesConstraints(section, &includesConstraints));
2479:     if (includesConstraints) PetscCall(PetscSectionGetStorageSize(section, &m));
2480:     else PetscCall(PetscSectionGetConstrainedStorageSize(section, &m));
2481:     PetscCheck(m1 == m, PETSC_COMM_SELF, PETSC_ERR_PLIB, "Global vector size (%" PetscInt_FMT ") != global section storage size (%" PetscInt_FMT ")", m1, m);
2482:   }
2483:   PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERHDF5, &ishdf5));
2484:   PetscCall(PetscLogEventBegin(DMPLEX_GlobalVectorView, viewer, 0, 0, 0));
2485:   if (ishdf5) {
2486: #if defined(PETSC_HAVE_HDF5)
2487:     PetscCall(DMPlexGlobalVectorView_HDF5_Internal(dm, viewer, sectiondm, vec));
2488: #else
2489:     SETERRQ(PetscObjectComm((PetscObject)dm), PETSC_ERR_SUP, "HDF5 not supported in this build.\nPlease reconfigure using --download-hdf5");
2490: #endif
2491:   }
2492:   PetscCall(PetscLogEventEnd(DMPLEX_GlobalVectorView, viewer, 0, 0, 0));
2493:   PetscFunctionReturn(PETSC_SUCCESS);
2494: }

2496: /*@
2497:   DMPlexLocalVectorView - Saves a local vector

2499:   Collective

2501:   Input Parameters:
2502: + dm        - The `DM` that represents the topology
2503: . viewer    - The `PetscViewer` to save data with
2504: . sectiondm - The `DM` that contains the local section on which `vec` is defined, can be `NULL`
2505: - vec       - The local vector to be saved

2507:   Level: advanced

2509:   Note:
2510:   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 (or in case `sectiondm` is `NULL`) 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.

2512:   Calling sequence:
2513: .vb
2514:        DMCreate(PETSC_COMM_WORLD, &dm);
2515:        DMSetType(dm, DMPLEX);
2516:        PetscObjectSetName((PetscObject)dm, "topologydm_name");
2517:        DMClone(dm, &sectiondm);
2518:        PetscObjectSetName((PetscObject)sectiondm, "sectiondm_name");
2519:        PetscSectionCreate(PETSC_COMM_WORLD, &section);
2520:        DMPlexGetChart(sectiondm, &pStart, &pEnd);
2521:        PetscSectionSetChart(section, pStart, pEnd);
2522:        PetscSectionSetUp(section);
2523:        DMSetLocalSection(sectiondm, section);
2524:        DMGetLocalVector(sectiondm, &vec);
2525:        PetscObjectSetName((PetscObject)vec, "vec_name");
2526:        DMPlexTopologyView(dm, viewer);
2527:        DMPlexSectionView(dm, viewer, sectiondm);
2528:        DMPlexLocalVectorView(dm, viewer, sectiondm, vec);
2529:        DMRestoreLocalVector(sectiondm, &vec);
2530:        DMDestroy(&sectiondm);
2531:        DMDestroy(&dm);
2532: .ve

2534: .seealso: [](ch_unstructured), `DM`, `DMPLEX`, `DMPlexTopologyView()`, `DMPlexSectionView()`, `DMPlexGlobalVectorView()`, `DMPlexGlobalVectorLoad()`, `DMPlexLocalVectorLoad()`
2535: @*/
2536: PetscErrorCode DMPlexLocalVectorView(DM dm, PetscViewer viewer, DM sectiondm, Vec vec)
2537: {
2538:   PetscBool ishdf5;

2540:   PetscFunctionBegin;
2543:   if (!sectiondm) sectiondm = dm;
2546:   /* Check consistency */
2547:   {
2548:     PetscSection section;
2549:     PetscBool    includesConstraints;
2550:     PetscInt     m, m1;

2552:     PetscCall(VecGetLocalSize(vec, &m1));
2553:     PetscCall(DMGetLocalSection(sectiondm, &section));
2554:     PetscCall(PetscSectionGetIncludesConstraints(section, &includesConstraints));
2555:     if (includesConstraints) PetscCall(PetscSectionGetStorageSize(section, &m));
2556:     else PetscCall(PetscSectionGetConstrainedStorageSize(section, &m));
2557:     PetscCheck(m1 == m, PETSC_COMM_SELF, PETSC_ERR_PLIB, "Local vector size (%" PetscInt_FMT ") != local section storage size (%" PetscInt_FMT ")", m1, m);
2558:   }
2559:   PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERHDF5, &ishdf5));
2560:   PetscCall(PetscLogEventBegin(DMPLEX_LocalVectorView, viewer, 0, 0, 0));
2561:   if (ishdf5) {
2562: #if defined(PETSC_HAVE_HDF5)
2563:     PetscCall(DMPlexLocalVectorView_HDF5_Internal(dm, viewer, sectiondm, vec));
2564: #else
2565:     SETERRQ(PetscObjectComm((PetscObject)dm), PETSC_ERR_SUP, "HDF5 not supported in this build.\nPlease reconfigure using --download-hdf5");
2566: #endif
2567:   }
2568:   PetscCall(PetscLogEventEnd(DMPLEX_LocalVectorView, viewer, 0, 0, 0));
2569:   PetscFunctionReturn(PETSC_SUCCESS);
2570: }

2572: PetscErrorCode DMLoad_Plex(DM dm, PetscViewer viewer)
2573: {
2574:   PetscBool ishdf5;

2576:   PetscFunctionBegin;
2579:   PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERHDF5, &ishdf5));
2580:   if (ishdf5) {
2581: #if defined(PETSC_HAVE_HDF5)
2582:     PetscViewerFormat format;
2583:     PetscCall(PetscViewerGetFormat(viewer, &format));
2584:     if (format == PETSC_VIEWER_HDF5_XDMF || format == PETSC_VIEWER_HDF5_VIZ) {
2585:       PetscCall(DMPlexLoad_HDF5_Xdmf_Internal(dm, viewer));
2586:     } else if (format == PETSC_VIEWER_HDF5_PETSC || format == PETSC_VIEWER_DEFAULT || format == PETSC_VIEWER_NATIVE) {
2587:       PetscCall(DMPlexLoad_HDF5_Internal(dm, viewer));
2588:     } else SETERRQ(PetscObjectComm((PetscObject)dm), PETSC_ERR_SUP, "PetscViewerFormat %s not supported for HDF5 input.", PetscViewerFormats[format]);
2589:     PetscFunctionReturn(PETSC_SUCCESS);
2590: #else
2591:     SETERRQ(PetscObjectComm((PetscObject)dm), PETSC_ERR_SUP, "HDF5 not supported in this build.\nPlease reconfigure using --download-hdf5");
2592: #endif
2593:   } else SETERRQ(PetscObjectComm((PetscObject)dm), PETSC_ERR_SUP, "Viewer type %s not yet supported for DMPlex loading", ((PetscObject)viewer)->type_name);
2594: }

2596: /*@
2597:   DMPlexTopologyLoad - Loads a topology into a `DMPLEX`

2599:   Collective

2601:   Input Parameters:
2602: + dm     - The `DM` into which the topology is loaded
2603: - viewer - The `PetscViewer` for the saved topology

2605:   Output Parameter:
2606: . globalToLocalPointSF - The `PetscSF` that pushes points in [0, N) to the associated points in the loaded `DMPLEX`, where N is the global number of points;
2607:   `NULL` if unneeded

2609:   Level: advanced

2611: .seealso: [](ch_unstructured), `DM`, `DMPLEX`, `DMLoad()`, `DMPlexCoordinatesLoad()`, `DMPlexLabelsLoad()`, `DMView()`, `PetscViewerHDF5Open()`, `PetscViewerPushFormat()`,
2612:           `PetscViewer`, `PetscSF`
2613: @*/
2614: PetscErrorCode DMPlexTopologyLoad(DM dm, PetscViewer viewer, PetscSF *globalToLocalPointSF)
2615: {
2616:   PetscBool ishdf5;

2618:   PetscFunctionBegin;
2621:   if (globalToLocalPointSF) PetscAssertPointer(globalToLocalPointSF, 3);
2622:   PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERHDF5, &ishdf5));
2623:   PetscCall(PetscLogEventBegin(DMPLEX_TopologyLoad, viewer, 0, 0, 0));
2624:   if (ishdf5) {
2625: #if defined(PETSC_HAVE_HDF5)
2626:     PetscViewerFormat format;

2628:     PetscCall(PetscViewerGetFormat(viewer, &format));
2629:     PetscCheck(format == PETSC_VIEWER_HDF5_PETSC || format == PETSC_VIEWER_DEFAULT || format == PETSC_VIEWER_NATIVE, PetscObjectComm((PetscObject)dm), PETSC_ERR_SUP, "PetscViewerFormat %s not supported for HDF5 input.", PetscViewerFormats[format]);
2630:     PetscCall(DMPlexTopologyLoad_HDF5_Internal(dm, viewer, globalToLocalPointSF));
2631: #else
2632:     SETERRQ(PetscObjectComm((PetscObject)dm), PETSC_ERR_SUP, "HDF5 not supported in this build.\nPlease reconfigure using --download-hdf5");
2633: #endif
2634:   }
2635:   PetscCall(PetscLogEventEnd(DMPLEX_TopologyLoad, viewer, 0, 0, 0));
2636:   PetscFunctionReturn(PETSC_SUCCESS);
2637: }

2639: /*@
2640:   DMPlexCoordinatesLoad - Loads coordinates into a `DMPLEX`

2642:   Collective

2644:   Input Parameters:
2645: + dm                   - The `DM` into which the coordinates are loaded
2646: . viewer               - The `PetscViewer` for the saved coordinates
2647: - globalToLocalPointSF - The `PetscSF` returned by `DMPlexTopologyLoad()` when loading dm from viewer

2649:   Level: advanced

2651: .seealso: [](ch_unstructured), `DM`, `DMPLEX`, `DMLoad()`, `DMPlexTopologyLoad()`, `DMPlexLabelsLoad()`, `DMView()`, `PetscViewerHDF5Open()`, `PetscViewerPushFormat()`,
2652:           `PetscSF`, `PetscViewer`
2653: @*/
2654: PetscErrorCode DMPlexCoordinatesLoad(DM dm, PetscViewer viewer, PetscSF globalToLocalPointSF)
2655: {
2656:   PetscBool ishdf5;

2658:   PetscFunctionBegin;
2662:   PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERHDF5, &ishdf5));
2663:   PetscCall(PetscLogEventBegin(DMPLEX_CoordinatesLoad, viewer, 0, 0, 0));
2664:   if (ishdf5) {
2665: #if defined(PETSC_HAVE_HDF5)
2666:     PetscViewerFormat format;

2668:     PetscCall(PetscViewerGetFormat(viewer, &format));
2669:     PetscCheck(format == PETSC_VIEWER_HDF5_PETSC || format == PETSC_VIEWER_DEFAULT || format == PETSC_VIEWER_NATIVE, PetscObjectComm((PetscObject)dm), PETSC_ERR_SUP, "PetscViewerFormat %s not supported for HDF5 input.", PetscViewerFormats[format]);
2670:     PetscCall(DMPlexCoordinatesLoad_HDF5_Internal(dm, viewer, globalToLocalPointSF));
2671: #else
2672:     SETERRQ(PetscObjectComm((PetscObject)dm), PETSC_ERR_SUP, "HDF5 not supported in this build.\nPlease reconfigure using --download-hdf5");
2673: #endif
2674:   }
2675:   PetscCall(PetscLogEventEnd(DMPLEX_CoordinatesLoad, viewer, 0, 0, 0));
2676:   PetscFunctionReturn(PETSC_SUCCESS);
2677: }

2679: /*@
2680:   DMPlexLabelsLoad - Loads labels into a `DMPLEX`

2682:   Collective

2684:   Input Parameters:
2685: + dm                   - The `DM` into which the labels are loaded
2686: . viewer               - The `PetscViewer` for the saved labels
2687: - globalToLocalPointSF - The `PetscSF` returned by `DMPlexTopologyLoad()` when loading `dm` from viewer

2689:   Level: advanced

2691:   Note:
2692:   The `PetscSF` argument must not be `NULL` if the `DM` is distributed, otherwise an error occurs.

2694: .seealso: [](ch_unstructured), `DM`, `DMPLEX`, `DMLoad()`, `DMPlexTopologyLoad()`, `DMPlexCoordinatesLoad()`, `DMView()`, `PetscViewerHDF5Open()`, `PetscViewerPushFormat()`,
2695:           `PetscSF`, `PetscViewer`
2696: @*/
2697: PetscErrorCode DMPlexLabelsLoad(DM dm, PetscViewer viewer, PetscSF globalToLocalPointSF)
2698: {
2699:   PetscBool ishdf5;

2701:   PetscFunctionBegin;
2705:   PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERHDF5, &ishdf5));
2706:   PetscCall(PetscLogEventBegin(DMPLEX_LabelsLoad, viewer, 0, 0, 0));
2707:   if (ishdf5) {
2708: #if defined(PETSC_HAVE_HDF5)
2709:     PetscViewerFormat format;

2711:     PetscCall(PetscViewerGetFormat(viewer, &format));
2712:     PetscCheck(format == PETSC_VIEWER_HDF5_PETSC || format == PETSC_VIEWER_DEFAULT || format == PETSC_VIEWER_NATIVE, PetscObjectComm((PetscObject)dm), PETSC_ERR_SUP, "PetscViewerFormat %s not supported for HDF5 input.", PetscViewerFormats[format]);
2713:     PetscCall(DMPlexLabelsLoad_HDF5_Internal(dm, viewer, globalToLocalPointSF));
2714: #else
2715:     SETERRQ(PetscObjectComm((PetscObject)dm), PETSC_ERR_SUP, "HDF5 not supported in this build.\nPlease reconfigure using --download-hdf5");
2716: #endif
2717:   }
2718:   PetscCall(PetscLogEventEnd(DMPLEX_LabelsLoad, viewer, 0, 0, 0));
2719:   PetscFunctionReturn(PETSC_SUCCESS);
2720: }

2722: /*@
2723:   DMPlexSectionLoad - Loads section into a `DMPLEX`

2725:   Collective

2727:   Input Parameters:
2728: + dm                   - The `DM` that represents the topology
2729: . viewer               - The `PetscViewer` that represents the on-disk section (sectionA)
2730: . sectiondm            - The `DM` into which the on-disk section (sectionA) is migrated, can be `NULL`
2731: - globalToLocalPointSF - The `PetscSF` returned by `DMPlexTopologyLoad(`) when loading dm from viewer

2733:   Output Parameters:
2734: + globalDofSF - The `PetscSF` 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)
2735: - localDofSF  - The `PetscSF` 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)

2737:   Level: advanced

2739:   Notes:
2740:   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.

2742:   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 (or in case `sectiondm` is `NULL`) 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.

2744:   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.

2746:   Example using 2 processes:
2747: .vb
2748:   NX (number of points on dm): 4
2749:   sectionA                   : the on-disk section
2750:   vecA                       : a vector associated with sectionA
2751:   sectionB                   : sectiondm's local section constructed in this function
2752:   vecB (local)               : a vector associated with sectiondm's local section
2753:   vecB (global)              : a vector associated with sectiondm's global section

2755:                                      rank 0    rank 1
2756:   vecA (global)                  : [.0 .4 .1 | .2 .3]        <- to be loaded in DMPlexGlobalVectorLoad() or DMPlexLocalVectorLoad()
2757:   sectionA->atlasOff             :       0 2 | 1             <- loaded in PetscSectionLoad()
2758:   sectionA->atlasDof             :       1 3 | 1             <- loaded in PetscSectionLoad()
2759:   sectionA's global point numbers:       0 2 | 3             <- loaded in DMPlexSectionLoad()
2760:   [0, NX)                        :       0 1 | 2 3           <- conceptual partition used in globalToLocalPointSF
2761:   sectionB's global point numbers:     0 1 3 | 3 2           <- associated with [0, NX) by globalToLocalPointSF
2762:   sectionB->atlasDof             :     1 0 1 | 1 3
2763:   sectionB->atlasOff (no perm)   :     0 1 1 | 0 1
2764:   vecB (local)                   :   [.0 .4] | [.4 .1 .2 .3] <- to be constructed by calling DMPlexLocalVectorLoad() with localDofSF
2765:   vecB (global)                  :    [.0 .4 | .1 .2 .3]     <- to be constructed by calling DMPlexGlobalVectorLoad() with globalDofSF
2766: .ve
2767:   where "|" represents a partition of loaded data, and global point 3 is assumed to be owned by rank 0.

2769: .seealso: [](ch_unstructured), `DM`, `DMPLEX`, `DMLoad()`, `DMPlexTopologyLoad()`, `DMPlexCoordinatesLoad()`, `DMPlexLabelsLoad()`, `DMPlexGlobalVectorLoad()`, `DMPlexLocalVectorLoad()`, `PetscSectionLoad()`, `DMPlexSectionView()`, `PetscSF`, `PetscViewer`
2770: @*/
2771: PetscErrorCode DMPlexSectionLoad(DM dm, PetscViewer viewer, PeOp DM sectiondm, PetscSF globalToLocalPointSF, PeOp PetscSF *globalDofSF, PeOp PetscSF *localDofSF)
2772: {
2773:   PetscBool ishdf5;

2775:   PetscFunctionBegin;
2778:   if (!sectiondm) sectiondm = dm;
2781:   if (globalDofSF) PetscAssertPointer(globalDofSF, 5);
2782:   if (localDofSF) PetscAssertPointer(localDofSF, 6);
2783:   PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERHDF5, &ishdf5));
2784:   PetscCall(PetscLogEventBegin(DMPLEX_SectionLoad, viewer, 0, 0, 0));
2785:   if (ishdf5) {
2786: #if defined(PETSC_HAVE_HDF5)
2787:     PetscCall(DMPlexSectionLoad_HDF5_Internal(dm, viewer, sectiondm, globalToLocalPointSF, globalDofSF, localDofSF));
2788: #else
2789:     SETERRQ(PetscObjectComm((PetscObject)dm), PETSC_ERR_SUP, "HDF5 not supported in this build.\nPlease reconfigure using --download-hdf5");
2790: #endif
2791:   }
2792:   PetscCall(PetscLogEventEnd(DMPLEX_SectionLoad, viewer, 0, 0, 0));
2793:   PetscFunctionReturn(PETSC_SUCCESS);
2794: }

2796: /*@
2797:   DMPlexGlobalVectorLoad - Loads on-disk vector data into a global vector

2799:   Collective

2801:   Input Parameters:
2802: + dm        - The `DM` that represents the topology
2803: . viewer    - The `PetscViewer` that represents the on-disk vector data
2804: . sectiondm - The `DM` that contains the global section on which vec is defined, can be `NULL`
2805: . sf        - The `PetscSF` that migrates the on-disk vector data into vec
2806: - vec       - The global vector to set values of

2808:   Level: advanced

2810:   Notes:
2811:   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 (or in case `sectiondm` is `NULL`) 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.

2813:   Calling sequence:
2814: .vb
2815:        DMCreate(PETSC_COMM_WORLD, &dm);
2816:        DMSetType(dm, DMPLEX);
2817:        PetscObjectSetName((PetscObject)dm, "topologydm_name");
2818:        DMPlexTopologyLoad(dm, viewer, &sfX);
2819:        DMClone(dm, &sectiondm);
2820:        PetscObjectSetName((PetscObject)sectiondm, "sectiondm_name");
2821:        DMPlexSectionLoad(dm, viewer, sectiondm, sfX, &gsf, NULL);
2822:        DMGetGlobalVector(sectiondm, &vec);
2823:        PetscObjectSetName((PetscObject)vec, "vec_name");
2824:        DMPlexGlobalVectorLoad(dm, viewer, sectiondm, gsf, vec);
2825:        DMRestoreGlobalVector(sectiondm, &vec);
2826:        PetscSFDestroy(&gsf);
2827:        PetscSFDestroy(&sfX);
2828:        DMDestroy(&sectiondm);
2829:        DMDestroy(&dm);
2830: .ve

2832: .seealso: [](ch_unstructured), `DM`, `DMPLEX`, `DMPlexTopologyLoad()`, `DMPlexSectionLoad()`, `DMPlexLocalVectorLoad()`, `DMPlexGlobalVectorView()`, `DMPlexLocalVectorView()`,
2833:           `PetscSF`, `PetscViewer`
2834: @*/
2835: PetscErrorCode DMPlexGlobalVectorLoad(DM dm, PetscViewer viewer, DM sectiondm, PetscSF sf, Vec vec)
2836: {
2837:   PetscBool ishdf5;

2839:   PetscFunctionBegin;
2842:   if (!sectiondm) sectiondm = dm;
2846:   /* Check consistency */
2847:   {
2848:     PetscSection section;
2849:     PetscBool    includesConstraints;
2850:     PetscInt     m, m1;

2852:     PetscCall(VecGetLocalSize(vec, &m1));
2853:     PetscCall(DMGetGlobalSection(sectiondm, &section));
2854:     PetscCall(PetscSectionGetIncludesConstraints(section, &includesConstraints));
2855:     if (includesConstraints) PetscCall(PetscSectionGetStorageSize(section, &m));
2856:     else PetscCall(PetscSectionGetConstrainedStorageSize(section, &m));
2857:     PetscCheck(m1 == m, PETSC_COMM_SELF, PETSC_ERR_PLIB, "Global vector size (%" PetscInt_FMT ") != global section storage size (%" PetscInt_FMT ")", m1, m);
2858:   }
2859:   PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERHDF5, &ishdf5));
2860:   PetscCall(PetscLogEventBegin(DMPLEX_GlobalVectorLoad, viewer, 0, 0, 0));
2861:   if (ishdf5) {
2862: #if defined(PETSC_HAVE_HDF5)
2863:     PetscCall(DMPlexVecLoad_HDF5_Internal(dm, viewer, sectiondm, sf, vec));
2864: #else
2865:     SETERRQ(PetscObjectComm((PetscObject)dm), PETSC_ERR_SUP, "HDF5 not supported in this build.\nPlease reconfigure using --download-hdf5");
2866: #endif
2867:   }
2868:   PetscCall(PetscLogEventEnd(DMPLEX_GlobalVectorLoad, viewer, 0, 0, 0));
2869:   PetscFunctionReturn(PETSC_SUCCESS);
2870: }

2872: /*@
2873:   DMPlexLocalVectorLoad - Loads on-disk vector data into a local vector

2875:   Collective

2877:   Input Parameters:
2878: + dm        - The `DM` that represents the topology
2879: . viewer    - The `PetscViewer` that represents the on-disk vector data
2880: . sectiondm - The `DM` that contains the local section on which vec is defined, can be `NULL`
2881: . sf        - The `PetscSF` that migrates the on-disk vector data into vec
2882: - vec       - The local vector to set values of

2884:   Level: advanced

2886:   Notes:
2887:   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 (or in case `sectiondm` is `NULL`) 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.

2889:   Calling sequence:
2890: .vb
2891:        DMCreate(PETSC_COMM_WORLD, &dm);
2892:        DMSetType(dm, DMPLEX);
2893:        PetscObjectSetName((PetscObject)dm, "topologydm_name");
2894:        DMPlexTopologyLoad(dm, viewer, &sfX);
2895:        DMClone(dm, &sectiondm);
2896:        PetscObjectSetName((PetscObject)sectiondm, "sectiondm_name");
2897:        DMPlexSectionLoad(dm, viewer, sectiondm, sfX, NULL, &lsf);
2898:        DMGetLocalVector(sectiondm, &vec);
2899:        PetscObjectSetName((PetscObject)vec, "vec_name");
2900:        DMPlexLocalVectorLoad(dm, viewer, sectiondm, lsf, vec);
2901:        DMRestoreLocalVector(sectiondm, &vec);
2902:        PetscSFDestroy(&lsf);
2903:        PetscSFDestroy(&sfX);
2904:        DMDestroy(&sectiondm);
2905:        DMDestroy(&dm);
2906: .ve

2908: .seealso: [](ch_unstructured), `DM`, `DMPLEX`, `DMPlexTopologyLoad()`, `DMPlexSectionLoad()`, `DMPlexGlobalVectorLoad()`, `DMPlexGlobalVectorView()`, `DMPlexLocalVectorView()`,
2909:           `PetscSF`, `PetscViewer`
2910: @*/
2911: PetscErrorCode DMPlexLocalVectorLoad(DM dm, PetscViewer viewer, DM sectiondm, PetscSF sf, Vec vec)
2912: {
2913:   PetscBool ishdf5;

2915:   PetscFunctionBegin;
2918:   if (!sectiondm) sectiondm = dm;
2922:   /* Check consistency */
2923:   {
2924:     PetscSection section;
2925:     PetscBool    includesConstraints;
2926:     PetscInt     m, m1;

2928:     PetscCall(VecGetLocalSize(vec, &m1));
2929:     PetscCall(DMGetLocalSection(sectiondm, &section));
2930:     PetscCall(PetscSectionGetIncludesConstraints(section, &includesConstraints));
2931:     if (includesConstraints) PetscCall(PetscSectionGetStorageSize(section, &m));
2932:     else PetscCall(PetscSectionGetConstrainedStorageSize(section, &m));
2933:     PetscCheck(m1 == m, PETSC_COMM_SELF, PETSC_ERR_PLIB, "Local vector size (%" PetscInt_FMT ") != local section storage size (%" PetscInt_FMT ")", m1, m);
2934:   }
2935:   PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERHDF5, &ishdf5));
2936:   PetscCall(PetscLogEventBegin(DMPLEX_LocalVectorLoad, viewer, 0, 0, 0));
2937:   if (ishdf5) {
2938: #if defined(PETSC_HAVE_HDF5)
2939:     PetscCall(DMPlexVecLoad_HDF5_Internal(dm, viewer, sectiondm, sf, vec));
2940: #else
2941:     SETERRQ(PetscObjectComm((PetscObject)dm), PETSC_ERR_SUP, "HDF5 not supported in this build.\nPlease reconfigure using --download-hdf5");
2942: #endif
2943:   }
2944:   PetscCall(PetscLogEventEnd(DMPLEX_LocalVectorLoad, viewer, 0, 0, 0));
2945:   PetscFunctionReturn(PETSC_SUCCESS);
2946: }

2948: PetscErrorCode DMDestroy_Plex(DM dm)
2949: {
2950:   DM_Plex *mesh = (DM_Plex *)dm->data;

2952:   PetscFunctionBegin;
2953:   PetscCall(PetscObjectComposeFunction((PetscObject)dm, "DMSetUpGLVisViewer_C", NULL));
2954:   PetscCall(PetscObjectComposeFunction((PetscObject)dm, "DMPlexInsertBoundaryValues_C", NULL));
2955:   PetscCall(PetscObjectComposeFunction((PetscObject)dm, "DMPlexInsertTimeDerivativeBoundaryValues_C", NULL));
2956:   PetscCall(PetscObjectComposeFunction((PetscObject)dm, "DMPlexInsertBounds_C", NULL));
2957:   PetscCall(PetscObjectComposeFunction((PetscObject)dm, "DMCreateNeumannOverlap_C", NULL));
2958:   PetscCall(PetscObjectComposeFunction((PetscObject)dm, "DMInterpolateSolution_C", NULL));
2959:   PetscCall(PetscObjectComposeFunction((PetscObject)dm, "DMPlexGetOverlap_C", NULL));
2960:   PetscCall(PetscObjectComposeFunction((PetscObject)dm, "DMPlexDistributeGetDefault_C", NULL));
2961:   PetscCall(PetscObjectComposeFunction((PetscObject)dm, "DMPlexDistributeSetDefault_C", NULL));
2962:   PetscCall(PetscObjectComposeFunction((PetscObject)dm, "MatComputeNeumannOverlap_C", NULL));
2963:   PetscCall(PetscObjectComposeFunction((PetscObject)dm, "DMPlexReorderGetDefault_C", NULL));
2964:   PetscCall(PetscObjectComposeFunction((PetscObject)dm, "DMPlexReorderSetDefault_C", NULL));
2965:   PetscCall(PetscObjectComposeFunction((PetscObject)dm, "DMReorderSectionGetDefault_C", NULL));
2966:   PetscCall(PetscObjectComposeFunction((PetscObject)dm, "DMReorderSectionSetDefault_C", NULL));
2967:   PetscCall(PetscObjectComposeFunction((PetscObject)dm, "DMReorderSectionGetType_C", NULL));
2968:   PetscCall(PetscObjectComposeFunction((PetscObject)dm, "DMReorderSectionSetType_C", NULL));
2969:   PetscCall(PetscObjectComposeFunction((PetscObject)dm, "DMPlexGetOverlap_C", NULL));
2970:   PetscCall(PetscObjectComposeFunction((PetscObject)dm, "DMPlexSetOverlap_C", NULL));
2971:   PetscCall(PetscObjectComposeFunction((PetscObject)dm, "DMPlexGetUseCeed_C", NULL));
2972:   PetscCall(PetscObjectComposeFunction((PetscObject)dm, "DMPlexSetUseCeed_C", NULL));
2973:   PetscCall(PetscObjectComposeFunction((PetscObject)dm, "DMGetIsoperiodicPointSF_C", NULL));
2974:   if (--mesh->refct > 0) PetscFunctionReturn(PETSC_SUCCESS);
2975:   PetscCall(PetscSectionDestroy(&mesh->coneSection));
2976:   PetscCall(PetscFree(mesh->cones));
2977:   PetscCall(PetscFree(mesh->coneOrientations));
2978:   PetscCall(PetscSectionDestroy(&mesh->supportSection));
2979:   PetscCall(PetscSectionDestroy(&mesh->subdomainSection));
2980:   PetscCall(PetscFree(mesh->supports));
2981:   PetscCall(PetscFree(mesh->cellTypes));
2982:   PetscCall(DMPlexTransformDestroy(&mesh->tr));
2983:   PetscCall(PetscFree(mesh->tetgenOpts));
2984:   PetscCall(PetscFree(mesh->triangleOpts));
2985:   PetscCall(PetscFree(mesh->transformType));
2986:   PetscCall(PetscFree(mesh->distributionName));
2987:   PetscCall(PetscPartitionerDestroy(&mesh->partitioner));
2988:   PetscCall(DMLabelDestroy(&mesh->subpointMap));
2989:   PetscCall(ISDestroy(&mesh->subpointIS));
2990:   PetscCall(ISDestroy(&mesh->globalVertexNumbers));
2991:   PetscCall(ISDestroy(&mesh->globalCellNumbers));
2992:   if (mesh->periodic.face_sfs) {
2993:     for (PetscInt i = 0; i < mesh->periodic.num_face_sfs; i++) PetscCall(PetscSFDestroy(&mesh->periodic.face_sfs[i]));
2994:     PetscCall(PetscFree(mesh->periodic.face_sfs));
2995:   }
2996:   PetscCall(PetscSFDestroy(&mesh->periodic.composed_sf));
2997:   if (mesh->periodic.periodic_points) {
2998:     for (PetscInt i = 0; i < mesh->periodic.num_face_sfs; i++) PetscCall(ISDestroy(&mesh->periodic.periodic_points[i]));
2999:     PetscCall(PetscFree(mesh->periodic.periodic_points));
3000:   }
3001:   PetscCall(PetscFree(mesh->periodic.transform));
3002:   PetscCall(PetscSectionDestroy(&mesh->anchorSection));
3003:   PetscCall(ISDestroy(&mesh->anchorIS));
3004:   PetscCall(PetscSectionDestroy(&mesh->parentSection));
3005:   PetscCall(PetscFree(mesh->parents));
3006:   PetscCall(PetscFree(mesh->childIDs));
3007:   PetscCall(PetscSectionDestroy(&mesh->childSection));
3008:   PetscCall(PetscFree(mesh->children));
3009:   PetscCall(DMDestroy(&mesh->referenceTree));
3010:   PetscCall(PetscGridHashDestroy(&mesh->lbox));
3011:   PetscCall(PetscFree(mesh->neighbors));
3012:   PetscCall(PetscFree(mesh->metricCtx));
3013:   if (mesh->nonempty_comm != MPI_COMM_NULL && mesh->nonempty_comm != MPI_COMM_SELF) PetscCallMPI(MPI_Comm_free(&mesh->nonempty_comm));
3014:   PetscCall(DMPlexTransformDestroy(&mesh->transform));
3015:   /* This was originally freed in DMDestroy(), but that prevents reference counting of backend objects */
3016:   PetscCall(PetscFree(mesh));
3017:   PetscFunctionReturn(PETSC_SUCCESS);
3018: }

3020: PetscErrorCode DMCreateMatrix_Plex(DM dm, Mat *J)
3021: {
3022:   PetscSection           sectionGlobal, sectionLocal;
3023:   PetscInt               bs = -1, mbs;
3024:   PetscInt               localSize, localStart = 0;
3025:   PetscBool              isShell, isBlock, isSeqBlock, isMPIBlock, isSymBlock, isSymSeqBlock, isSymMPIBlock, isMatIS;
3026:   MatType                mtype;
3027:   ISLocalToGlobalMapping ltog;

3029:   PetscFunctionBegin;
3030:   PetscCall(MatInitializePackage());
3031:   mtype = dm->mattype;
3032:   PetscCall(DMGetLocalSection(dm, &sectionLocal));
3033:   PetscCall(DMGetGlobalSection(dm, &sectionGlobal));
3034:   /* PetscCall(PetscSectionGetStorageSize(sectionGlobal, &localSize)); */
3035:   PetscCall(PetscSectionGetConstrainedStorageSize(sectionGlobal, &localSize));
3036:   PetscCallMPI(MPI_Exscan(&localSize, &localStart, 1, MPIU_INT, MPI_SUM, PetscObjectComm((PetscObject)dm)));
3037:   PetscCall(MatCreate(PetscObjectComm((PetscObject)dm), J));
3038:   PetscCall(MatSetSizes(*J, localSize, localSize, PETSC_DETERMINE, PETSC_DETERMINE));
3039:   PetscCall(MatSetType(*J, mtype));
3040:   PetscCall(MatSetFromOptions(*J));
3041:   PetscCall(MatGetBlockSize(*J, &mbs));
3042:   if (mbs > 1) bs = mbs;
3043:   PetscCall(PetscStrcmp(mtype, MATSHELL, &isShell));
3044:   PetscCall(PetscStrcmp(mtype, MATBAIJ, &isBlock));
3045:   PetscCall(PetscStrcmp(mtype, MATSEQBAIJ, &isSeqBlock));
3046:   PetscCall(PetscStrcmp(mtype, MATMPIBAIJ, &isMPIBlock));
3047:   PetscCall(PetscStrcmp(mtype, MATSBAIJ, &isSymBlock));
3048:   PetscCall(PetscStrcmp(mtype, MATSEQSBAIJ, &isSymSeqBlock));
3049:   PetscCall(PetscStrcmp(mtype, MATMPISBAIJ, &isSymMPIBlock));
3050:   PetscCall(PetscStrcmp(mtype, MATIS, &isMatIS));
3051:   if (!isShell) {
3052:     // There are three states with pblocks, since block starts can have no dofs:
3053:     // UNKNOWN) New Block:   An open block has been signalled by pblocks[p] == 1
3054:     // TRUE)    Block Start: The first entry in a block has been added
3055:     // FALSE)   Block Add:   An additional block entry has been added, since pblocks[p] == 0
3056:     PetscBT         blst;
3057:     PetscBool3      bstate     = PETSC_BOOL3_UNKNOWN;
3058:     PetscBool       fillMatrix = (PetscBool)(!dm->prealloc_only && !isMatIS);
3059:     const PetscInt *perm       = NULL;
3060:     PetscInt       *dnz, *onz, *dnzu, *onzu, bsLocal[2], bsMinMax[2], *pblocks;
3061:     PetscInt        pStart, pEnd, dof, cdof, num_fields;

3063:     PetscCall(DMGetLocalToGlobalMapping(dm, &ltog));
3064:     PetscCall(PetscSectionGetBlockStarts(sectionLocal, &blst));
3065:     if (sectionLocal->perm) PetscCall(ISGetIndices(sectionLocal->perm, &perm));

3067:     PetscCall(PetscCalloc1(localSize, &pblocks));
3068:     PetscCall(PetscSectionGetChart(sectionGlobal, &pStart, &pEnd));
3069:     PetscCall(PetscSectionGetNumFields(sectionGlobal, &num_fields));
3070:     // We need to process in the permuted order to get block sizes right
3071:     for (PetscInt point = pStart; point < pEnd; ++point) {
3072:       const PetscInt p = perm ? perm[point] : point;

3074:       switch (dm->blocking_type) {
3075:       case DM_BLOCKING_TOPOLOGICAL_POINT: { // One block per topological point
3076:         PetscInt bdof, offset;

3078:         PetscCall(PetscSectionGetDof(sectionGlobal, p, &dof));
3079:         PetscCall(PetscSectionGetOffset(sectionGlobal, p, &offset));
3080:         PetscCall(PetscSectionGetConstraintDof(sectionGlobal, p, &cdof));
3081:         if (blst && PetscBTLookup(blst, p)) bstate = PETSC_BOOL3_UNKNOWN;
3082:         if (dof > 0) {
3083:           // State change
3084:           if (bstate == PETSC_BOOL3_UNKNOWN) bstate = PETSC_BOOL3_TRUE;
3085:           else if (bstate == PETSC_BOOL3_TRUE && blst && !PetscBTLookup(blst, p)) bstate = PETSC_BOOL3_FALSE;

3087:           for (PetscInt i = 0; i < dof - cdof; ++i) pblocks[offset - localStart + i] = dof - cdof;
3088:           // Signal block concatenation
3089:           if (bstate == PETSC_BOOL3_FALSE && dof - cdof) pblocks[offset - localStart] = -(dof - cdof);
3090:         }
3091:         dof  = dof < 0 ? -(dof + 1) : dof;
3092:         bdof = cdof && (dof - cdof) ? 1 : dof;
3093:         if (dof) {
3094:           if (bs < 0) {
3095:             bs = bdof;
3096:           } else if (bs != bdof) {
3097:             bs = 1;
3098:           }
3099:         }
3100:       } break;
3101:       case DM_BLOCKING_FIELD_NODE: {
3102:         for (PetscInt field = 0; field < num_fields; field++) {
3103:           PetscInt num_comp, bdof, offset;
3104:           PetscCall(PetscSectionGetFieldComponents(sectionGlobal, field, &num_comp));
3105:           PetscCall(PetscSectionGetFieldDof(sectionGlobal, p, field, &dof));
3106:           if (dof < 0) continue;
3107:           PetscCall(PetscSectionGetFieldOffset(sectionGlobal, p, field, &offset));
3108:           PetscCall(PetscSectionGetFieldConstraintDof(sectionGlobal, p, field, &cdof));
3109:           PetscAssert(dof % num_comp == 0, PETSC_COMM_SELF, PETSC_ERR_ARG_INCOMP, "Point %" PetscInt_FMT " field %" PetscInt_FMT " has %" PetscInt_FMT " dof, not divisible by %" PetscInt_FMT " component ", p, field, dof, num_comp);
3110:           PetscInt num_nodes = dof / num_comp;
3111:           for (PetscInt i = 0; i < dof - cdof; i++) pblocks[offset - localStart + i] = (dof - cdof) / num_nodes;
3112:           // Handle possibly constant block size (unlikely)
3113:           bdof = cdof && (dof - cdof) ? 1 : dof;
3114:           if (dof) {
3115:             if (bs < 0) {
3116:               bs = bdof;
3117:             } else if (bs != bdof) {
3118:               bs = 1;
3119:             }
3120:           }
3121:         }
3122:       } break;
3123:       }
3124:     }
3125:     if (sectionLocal->perm) PetscCall(ISRestoreIndices(sectionLocal->perm, &perm));
3126:     /* Must have same blocksize on all procs (some might have no points) */
3127:     bsLocal[0] = bs < 0 ? PETSC_INT_MAX : bs;
3128:     bsLocal[1] = bs;
3129:     PetscCall(PetscGlobalMinMaxInt(PetscObjectComm((PetscObject)dm), bsLocal, bsMinMax));
3130:     if (bsMinMax[0] != bsMinMax[1]) bs = 1;
3131:     else bs = bsMinMax[0];
3132:     bs = PetscMax(1, bs);
3133:     PetscCall(MatSetLocalToGlobalMapping(*J, ltog, ltog));
3134:     if (dm->prealloc_skip) { // User will likely use MatSetPreallocationCOO(), but still set structural parameters
3135:       PetscCall(MatSetBlockSize(*J, bs));
3136:       PetscCall(MatSetUp(*J));
3137:     } else {
3138:       PetscCall(PetscCalloc4(localSize / bs, &dnz, localSize / bs, &onz, localSize / bs, &dnzu, localSize / bs, &onzu));
3139:       PetscCall(DMPlexPreallocateOperator(dm, bs, dnz, onz, dnzu, onzu, *J, fillMatrix));
3140:       PetscCall(PetscFree4(dnz, onz, dnzu, onzu));
3141:     }
3142:     if (pblocks) { // Consolidate blocks
3143:       PetscInt nblocks = 0;
3144:       pblocks[0]       = PetscAbs(pblocks[0]);
3145:       for (PetscInt i = 0; i < localSize; i += PetscMax(1, pblocks[i])) {
3146:         if (pblocks[i] == 0) continue;
3147:         // Negative block size indicates the blocks should be concatenated
3148:         if (pblocks[i] < 0) {
3149:           pblocks[i] = -pblocks[i];
3150:           pblocks[nblocks - 1] += pblocks[i];
3151:         } else {
3152:           pblocks[nblocks++] = pblocks[i]; // nblocks always <= i
3153:         }
3154:         for (PetscInt j = 1; j < pblocks[i]; j++)
3155:           PetscCheck(pblocks[i + j] == pblocks[i], PETSC_COMM_SELF, PETSC_ERR_PLIB, "Block of size %" PetscInt_FMT " at %" PetscInt_FMT " mismatches entry %" PetscInt_FMT " at %" PetscInt_FMT, pblocks[i], i, pblocks[i + j], i + j);
3156:       }
3157:       PetscCall(MatSetVariableBlockSizes(*J, nblocks, pblocks));
3158:     }
3159:     PetscCall(PetscFree(pblocks));
3160:   }
3161:   PetscCall(MatSetDM(*J, dm));
3162:   PetscFunctionReturn(PETSC_SUCCESS);
3163: }

3165: /*@
3166:   DMPlexGetSubdomainSection - Returns the section associated with the subdomain

3168:   Not Collective

3170:   Input Parameter:
3171: . dm - The `DMPLEX`

3173:   Output Parameter:
3174: . subsection - The subdomain section

3176:   Level: developer

3178: .seealso: [](ch_unstructured), `DM`, `DMPLEX`, `PetscSection`
3179: @*/
3180: PetscErrorCode DMPlexGetSubdomainSection(DM dm, PetscSection *subsection)
3181: {
3182:   DM_Plex *mesh = (DM_Plex *)dm->data;

3184:   PetscFunctionBegin;
3186:   if (!mesh->subdomainSection) {
3187:     PetscSection section;
3188:     PetscSF      sf;

3190:     PetscCall(PetscSFCreate(PETSC_COMM_SELF, &sf));
3191:     PetscCall(DMGetLocalSection(dm, &section));
3192:     PetscCall(PetscSectionCreateGlobalSection(section, sf, PETSC_TRUE, PETSC_FALSE, PETSC_TRUE, &mesh->subdomainSection));
3193:     PetscCall(PetscSFDestroy(&sf));
3194:   }
3195:   *subsection = mesh->subdomainSection;
3196:   PetscFunctionReturn(PETSC_SUCCESS);
3197: }

3199: /*@
3200:   DMPlexGetChart - Return the interval for all mesh points [`pStart`, `pEnd`)

3202:   Not Collective

3204:   Input Parameter:
3205: . dm - The `DMPLEX`

3207:   Output Parameters:
3208: + pStart - The first mesh point
3209: - pEnd   - The upper bound for mesh points

3211:   Level: beginner

3213: .seealso: [](ch_unstructured), `DM`, `DMPLEX`, `DMPlexCreate()`, `DMPlexSetChart()`
3214: @*/
3215: PetscErrorCode DMPlexGetChart(DM dm, PetscInt *pStart, PetscInt *pEnd)
3216: {
3217:   DM_Plex *mesh = (DM_Plex *)dm->data;

3219:   PetscFunctionBegin;
3221:   if (mesh->tr) PetscCall(DMPlexTransformGetChart(mesh->tr, pStart, pEnd));
3222:   else PetscCall(PetscSectionGetChart(mesh->coneSection, pStart, pEnd));
3223:   PetscFunctionReturn(PETSC_SUCCESS);
3224: }

3226: /*@
3227:   DMPlexSetChart - Set the interval for all mesh points [`pStart`, `pEnd`)

3229:   Not Collective

3231:   Input Parameters:
3232: + dm     - The `DMPLEX`
3233: . pStart - The first mesh point
3234: - pEnd   - The upper bound for mesh points

3236:   Level: beginner

3238: .seealso: [](ch_unstructured), `DM`, `DMPLEX`, `DMPlexCreate()`, `DMPlexGetChart()`
3239: @*/
3240: PetscErrorCode DMPlexSetChart(DM dm, PetscInt pStart, PetscInt pEnd)
3241: {
3242:   DM_Plex *mesh = (DM_Plex *)dm->data;

3244:   PetscFunctionBegin;
3246:   PetscCall(PetscSectionSetChart(mesh->coneSection, pStart, pEnd));
3247:   PetscCall(PetscSectionSetChart(mesh->supportSection, pStart, pEnd));
3248:   PetscCall(PetscFree(mesh->cellTypes));
3249:   PetscFunctionReturn(PETSC_SUCCESS);
3250: }

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

3255:   Not Collective

3257:   Input Parameters:
3258: + dm - The `DMPLEX`
3259: - p  - The point, which must lie in the chart set with `DMPlexSetChart()`

3261:   Output Parameter:
3262: . size - The cone size for point `p`

3264:   Level: beginner

3266: .seealso: [](ch_unstructured), `DM`, `DMPLEX`, `DMPlexCreate()`, `DMPlexSetConeSize()`, `DMPlexSetChart()`
3267: @*/
3268: PetscErrorCode DMPlexGetConeSize(DM dm, PetscInt p, PetscInt *size)
3269: {
3270:   DM_Plex *mesh = (DM_Plex *)dm->data;

3272:   PetscFunctionBegin;
3274:   PetscAssertPointer(size, 3);
3275:   if (mesh->tr) PetscCall(DMPlexTransformGetConeSize(mesh->tr, p, size));
3276:   else PetscCall(PetscSectionGetDof(mesh->coneSection, p, size));
3277:   PetscFunctionReturn(PETSC_SUCCESS);
3278: }

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

3283:   Not Collective

3285:   Input Parameters:
3286: + dm   - The `DMPLEX`
3287: . p    - The point, which must lie in the chart set with `DMPlexSetChart()`
3288: - size - The cone size for point `p`

3290:   Level: beginner

3292:   Note:
3293:   This should be called after `DMPlexSetChart()`.

3295: .seealso: [](ch_unstructured), `DM`, `DMPLEX`, `DMPlexSetCone()`, `DMPlexCreate()`, `DMPlexGetConeSize()`, `DMPlexSetChart()`
3296: @*/
3297: PetscErrorCode DMPlexSetConeSize(DM dm, PetscInt p, PetscInt size)
3298: {
3299:   DM_Plex *mesh = (DM_Plex *)dm->data;

3301:   PetscFunctionBegin;
3303:   PetscCheck(!mesh->tr, PetscObjectComm((PetscObject)dm), PETSC_ERR_ARG_WRONG, "Cannot call DMPlexSetConeSize() on a mesh with a transform defined.");
3304:   PetscCall(PetscSectionSetDof(mesh->coneSection, p, size));
3305:   PetscFunctionReturn(PETSC_SUCCESS);
3306: }

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

3311:   Not Collective

3313:   Input Parameters:
3314: + dm - The `DMPLEX`
3315: - p  - The point, which must lie in the chart set with `DMPlexSetChart()`

3317:   Output Parameter:
3318: . cone - An array of points which are on the in-edges for point `p`, the length of `cone` is the result of `DMPlexGetConeSize()`

3320:   Level: beginner

3322:   Fortran Notes:
3323:   `cone` must be declared with
3324: .vb
3325:   PetscInt, pointer :: cone(:)
3326: .ve

3328:   You must call `DMPlexRestoreCone()` after you finish using the array.
3329:   `DMPlexRestoreCone()` is not needed/available in C.

3331: .seealso: [](ch_unstructured), `DM`, `DMPLEX`, `DMPlexGetConeSize()`, `DMPlexSetCone()`, `DMPlexGetConeTuple()`, `DMPlexSetChart()`, `DMPlexRestoreCone()`
3332: @*/
3333: PetscErrorCode DMPlexGetCone(DM dm, PetscInt p, const PetscInt *cone[])
3334: {
3335:   DM_Plex *mesh = (DM_Plex *)dm->data;
3336:   PetscInt off;

3338:   PetscFunctionBegin;
3340:   PetscAssertPointer(cone, 3);
3341:   PetscCall(PetscSectionGetOffset(mesh->coneSection, p, &off));
3342:   *cone = PetscSafePointerPlusOffset(mesh->cones, off);
3343:   PetscFunctionReturn(PETSC_SUCCESS);
3344: }

3346: /*@
3347:   DMPlexGetConeTuple - Return the points on the in-edges of several points in the DAG

3349:   Not Collective

3351:   Input Parameters:
3352: + dm - The `DMPLEX`
3353: - p  - The `IS` of points, which must lie in the chart set with `DMPlexSetChart()`

3355:   Output Parameters:
3356: + pConesSection - `PetscSection` describing the layout of `pCones`
3357: - pCones        - An `IS` containing the points which are on the in-edges for the point set `p`

3359:   Level: intermediate

3361: .seealso: [](ch_unstructured), `DM`, `DMPLEX`, `DMPlexCreate()`, `DMPlexGetCone()`, `DMPlexGetConeRecursive()`, `DMPlexSetChart()`, `PetscSection`, `IS`
3362: @*/
3363: PetscErrorCode DMPlexGetConeTuple(DM dm, IS p, PeOp PetscSection *pConesSection, PeOp IS *pCones)
3364: {
3365:   PetscSection cs, newcs;
3366:   PetscInt    *cones;
3367:   PetscInt    *newarr = NULL;
3368:   PetscInt     n;

3370:   PetscFunctionBegin;
3371:   PetscCall(DMPlexGetCones(dm, &cones));
3372:   PetscCall(DMPlexGetConeSection(dm, &cs));
3373:   PetscCall(PetscSectionExtractDofsFromArray(cs, MPIU_INT, cones, p, &newcs, pCones ? ((void **)&newarr) : NULL));
3374:   if (pConesSection) *pConesSection = newcs;
3375:   if (pCones) {
3376:     PetscCall(PetscSectionGetStorageSize(newcs, &n));
3377:     PetscCall(ISCreateGeneral(PetscObjectComm((PetscObject)p), n, newarr, PETSC_OWN_POINTER, pCones));
3378:   }
3379:   PetscFunctionReturn(PETSC_SUCCESS);
3380: }

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

3385:   Not Collective

3387:   Input Parameters:
3388: + dm     - The `DMPLEX`
3389: - points - The `IS` of points, which must lie in the chart set with `DMPlexSetChart()`

3391:   Output Parameter:
3392: . expandedPoints - An `IS` containing the of vertices recursively expanded from input points

3394:   Level: advanced

3396:   Notes:
3397:   Like `DMPlexGetConeRecursive()` but returns only the 0-depth `IS` (i.e. vertices only) and no sections.

3399:   There is no corresponding Restore function, just call `ISDestroy()` on the returned `IS` to deallocate.

3401: .seealso: [](ch_unstructured), `DM`, `DMPLEX`, `DMPlexCreate()`, `DMPlexGetCone()`, `DMPlexGetConeTuple()`, `DMPlexGetConeRecursive()`, `DMPlexRestoreConeRecursive()`,
3402:           `DMPlexGetDepth()`, `IS`
3403: @*/
3404: PetscErrorCode DMPlexGetConeRecursiveVertices(DM dm, IS points, IS *expandedPoints)
3405: {
3406:   IS      *expandedPointsAll;
3407:   PetscInt depth;

3409:   PetscFunctionBegin;
3412:   PetscAssertPointer(expandedPoints, 3);
3413:   PetscCall(DMPlexGetConeRecursive(dm, points, &depth, &expandedPointsAll, NULL));
3414:   *expandedPoints = expandedPointsAll[0];
3415:   PetscCall(PetscObjectReference((PetscObject)expandedPointsAll[0]));
3416:   PetscCall(DMPlexRestoreConeRecursive(dm, points, &depth, &expandedPointsAll, NULL));
3417:   PetscFunctionReturn(PETSC_SUCCESS);
3418: }

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

3424:   Not Collective

3426:   Input Parameters:
3427: + dm     - The `DMPLEX`
3428: - points - The `IS` of points, which must lie in the chart set with `DMPlexSetChart()`

3430:   Output Parameters:
3431: + depth          - (optional) Size of the output arrays, equal to `DMPLEX` depth, returned by `DMPlexGetDepth()`
3432: . expandedPoints - (optional) An array of index sets with recursively expanded cones
3433: - sections       - (optional) An array of sections which describe mappings from points to their cone points

3435:   Level: advanced

3437:   Notes:
3438:   Like `DMPlexGetConeTuple()` but recursive.

3440:   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.
3441:   For example, for d=0 it contains only vertices, for d=1 it can contain vertices and edges, etc.

3443:   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\:
3444:   (1) DAG points in `expandedPoints`[d+1] with `depth` d+1 to their cone points in `expandedPoints`[d];
3445:   (2) DAG points in `expandedPoints`[d+1] with `depth` in [0,d] to the same points in `expandedPoints`[d].

3447: .seealso: [](ch_unstructured), `DM`, `DMPLEX`, `DMPlexCreate()`, `DMPlexGetCone()`, `DMPlexGetConeTuple()`, `DMPlexRestoreConeRecursive()`, `DMPlexGetConeRecursiveVertices()`,
3448:           `DMPlexGetDepth()`, `PetscSection`, `IS`
3449: @*/
3450: PetscErrorCode DMPlexGetConeRecursive(DM dm, IS points, PeOp PetscInt *depth, PeOp IS *expandedPoints[], PeOp PetscSection *sections[])
3451: {
3452:   const PetscInt *arr0 = NULL, *cone = NULL;
3453:   PetscInt       *arr = NULL, *newarr = NULL;
3454:   PetscInt        d, depth_, i, n, newn, cn, co, start, end;
3455:   IS             *expandedPoints_;
3456:   PetscSection   *sections_;

3458:   PetscFunctionBegin;
3461:   if (depth) PetscAssertPointer(depth, 3);
3462:   if (expandedPoints) PetscAssertPointer(expandedPoints, 4);
3463:   if (sections) PetscAssertPointer(sections, 5);
3464:   PetscCall(ISGetLocalSize(points, &n));
3465:   PetscCall(ISGetIndices(points, &arr0));
3466:   PetscCall(DMPlexGetDepth(dm, &depth_));
3467:   PetscCall(PetscCalloc1(depth_, &expandedPoints_));
3468:   PetscCall(PetscCalloc1(depth_, &sections_));
3469:   arr = (PetscInt *)arr0; /* this is ok because first generation of arr is not modified */
3470:   for (d = depth_ - 1; d >= 0; d--) {
3471:     PetscCall(PetscSectionCreate(PETSC_COMM_SELF, &sections_[d]));
3472:     PetscCall(PetscSectionSetChart(sections_[d], 0, n));
3473:     for (i = 0; i < n; i++) {
3474:       PetscCall(DMPlexGetDepthStratum(dm, d + 1, &start, &end));
3475:       if (arr[i] >= start && arr[i] < end) {
3476:         PetscCall(DMPlexGetConeSize(dm, arr[i], &cn));
3477:         PetscCall(PetscSectionSetDof(sections_[d], i, cn));
3478:       } else {
3479:         PetscCall(PetscSectionSetDof(sections_[d], i, 1));
3480:       }
3481:     }
3482:     PetscCall(PetscSectionSetUp(sections_[d]));
3483:     PetscCall(PetscSectionGetStorageSize(sections_[d], &newn));
3484:     PetscCall(PetscMalloc1(newn, &newarr));
3485:     for (i = 0; i < n; i++) {
3486:       PetscCall(PetscSectionGetDof(sections_[d], i, &cn));
3487:       PetscCall(PetscSectionGetOffset(sections_[d], i, &co));
3488:       if (cn > 1) {
3489:         PetscCall(DMPlexGetCone(dm, arr[i], &cone));
3490:         PetscCall(PetscArraycpy(&newarr[co], cone, cn));
3491:       } else {
3492:         newarr[co] = arr[i];
3493:       }
3494:     }
3495:     PetscCall(ISCreateGeneral(PETSC_COMM_SELF, newn, newarr, PETSC_OWN_POINTER, &expandedPoints_[d]));
3496:     arr = newarr;
3497:     n   = newn;
3498:   }
3499:   PetscCall(ISRestoreIndices(points, &arr0));
3500:   *depth = depth_;
3501:   if (expandedPoints) *expandedPoints = expandedPoints_;
3502:   else {
3503:     for (d = 0; d < depth_; d++) PetscCall(ISDestroy(&expandedPoints_[d]));
3504:     PetscCall(PetscFree(expandedPoints_));
3505:   }
3506:   if (sections) *sections = sections_;
3507:   else {
3508:     for (d = 0; d < depth_; d++) PetscCall(PetscSectionDestroy(&sections_[d]));
3509:     PetscCall(PetscFree(sections_));
3510:   }
3511:   PetscFunctionReturn(PETSC_SUCCESS);
3512: }

3514: /*@
3515:   DMPlexRestoreConeRecursive - Deallocates arrays created by `DMPlexGetConeRecursive()`

3517:   Not Collective

3519:   Input Parameters:
3520: + dm     - The `DMPLEX`
3521: - points - The `IS` of points, which must lie in the chart set with `DMPlexSetChart()`

3523:   Output Parameters:
3524: + depth          - (optional) Size of the output arrays, equal to `DMPLEX` depth, returned by `DMPlexGetDepth()`
3525: . expandedPoints - (optional) An array of recursively expanded cones
3526: - sections       - (optional) An array of sections which describe mappings from points to their cone points

3528:   Level: advanced

3530:   Note:
3531:   See `DMPlexGetConeRecursive()`

3533: .seealso: [](ch_unstructured), `DM`, `DMPLEX`, `DMPlexCreate()`, `DMPlexGetCone()`, `DMPlexGetConeTuple()`, `DMPlexGetConeRecursive()`, `DMPlexGetConeRecursiveVertices()`,
3534:           `DMPlexGetDepth()`, `IS`, `PetscSection`
3535: @*/
3536: PetscErrorCode DMPlexRestoreConeRecursive(DM dm, IS points, PeOp PetscInt *depth, PeOp IS *expandedPoints[], PeOp PetscSection *sections[])
3537: {
3538:   PetscInt depth_;

3540:   PetscFunctionBegin;
3541:   PetscCall(DMPlexGetDepth(dm, &depth_));
3542:   PetscCheck(!depth || *depth == depth_, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "depth changed since last call to DMPlexGetConeRecursive");
3543:   if (depth) *depth = 0;
3544:   if (expandedPoints) {
3545:     for (PetscInt d = 0; d < depth_; d++) PetscCall(ISDestroy(&(*expandedPoints)[d]));
3546:     PetscCall(PetscFree(*expandedPoints));
3547:   }
3548:   if (sections) {
3549:     for (PetscInt d = 0; d < depth_; d++) PetscCall(PetscSectionDestroy(&(*sections)[d]));
3550:     PetscCall(PetscFree(*sections));
3551:   }
3552:   PetscFunctionReturn(PETSC_SUCCESS);
3553: }

3555: /*@
3556:   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

3558:   Not Collective

3560:   Input Parameters:
3561: + dm   - The `DMPLEX`
3562: . p    - The point, which must lie in the chart set with `DMPlexSetChart()`
3563: - cone - An array of points which are on the in-edges for point `p`, its length must have been previously provided with `DMPlexSetConeSize()`

3565:   Level: beginner

3567:   Note:
3568:   This should be called after all calls to `DMPlexSetConeSize()` and `DMSetUp()`.

3570: .seealso: [](ch_unstructured), `DM`, `DMPLEX`, `DMPlexCreate()`, `DMPlexGetCone()`, `DMPlexSetChart()`, `DMPlexSetConeSize()`, `DMSetUp()`, `DMPlexSetSupport()`, `DMPlexSetSupportSize()`
3571: @*/
3572: PetscErrorCode DMPlexSetCone(DM dm, PetscInt p, const PetscInt cone[])
3573: {
3574:   DM_Plex *mesh = (DM_Plex *)dm->data;
3575:   PetscInt dof, off, c;

3577:   PetscFunctionBegin;
3579:   PetscCall(PetscSectionGetDof(mesh->coneSection, p, &dof));
3580:   if (dof) PetscAssertPointer(cone, 3);
3581:   PetscCall(PetscSectionGetOffset(mesh->coneSection, p, &off));
3582:   if (PetscDefined(USE_DEBUG)) {
3583:     PetscInt pStart, pEnd;
3584:     PetscCall(PetscSectionGetChart(mesh->coneSection, &pStart, &pEnd));
3585:     PetscCheck(!(p < pStart) && !(p >= pEnd), PetscObjectComm((PetscObject)dm), PETSC_ERR_ARG_OUTOFRANGE, "Mesh point %" PetscInt_FMT " is not in the valid range [%" PetscInt_FMT ", %" PetscInt_FMT ")", p, pStart, pEnd);
3586:     for (c = 0; c < dof; ++c) {
3587:       PetscCheck(!(cone[c] < pStart) && !(cone[c] >= pEnd), PetscObjectComm((PetscObject)dm), PETSC_ERR_ARG_OUTOFRANGE, "Cone point %" PetscInt_FMT " is not in the valid range [%" PetscInt_FMT ", %" PetscInt_FMT ")", cone[c], pStart, pEnd);
3588:       mesh->cones[off + c] = cone[c];
3589:     }
3590:   } else {
3591:     for (c = 0; c < dof; ++c) mesh->cones[off + c] = cone[c];
3592:   }
3593:   PetscFunctionReturn(PETSC_SUCCESS);
3594: }

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

3599:   Not Collective

3601:   Input Parameters:
3602: + dm - The `DMPLEX`
3603: - p  - The point, which must lie in the chart set with `DMPlexSetChart()`

3605:   Output Parameter:
3606: . coneOrientation - An array of orientations which are on the in-edges for point `p`. An orientation is an
3607:                     integer giving the prescription for cone traversal. Its length is given by the result of `DMPlexSetConeSize()`

3609:   Level: beginner

3611:   Note:
3612:   The number indexes the symmetry transformations for the cell type (see manual). Orientation 0 is always
3613:   the identity transformation. Negative orientation indicates reflection so that -(o+1) is the reflection
3614:   of o, however it is not necessarily the inverse. To get the inverse, use `DMPolytopeTypeComposeOrientationInv()`
3615:   with the identity.

3617:   Fortran Notes:
3618:   You must call `DMPlexRestoreConeOrientation()` after you finish using the returned array.
3619:   `DMPlexRestoreConeOrientation()` is not needed/available in C.

3621: .seealso: [](ch_unstructured), `DM`, `DMPLEX`, `DMPlexSetConeSize()`, `DMPolytopeTypeComposeOrientation()`, `DMPolytopeTypeComposeOrientationInv()`,
3622:           `DMPlexCreate()`, `DMPlexGetCone()`, `DMPlexSetCone()`, `DMPlexSetChart()`
3623: @*/
3624: PetscErrorCode DMPlexGetConeOrientation(DM dm, PetscInt p, const PetscInt *coneOrientation[])
3625: {
3626:   DM_Plex *mesh = (DM_Plex *)dm->data;
3627:   PetscInt off;

3629:   PetscFunctionBegin;
3631:   if (PetscDefined(USE_DEBUG)) {
3632:     PetscInt dof;
3633:     PetscCall(PetscSectionGetDof(mesh->coneSection, p, &dof));
3634:     if (dof) PetscAssertPointer(coneOrientation, 3);
3635:   }
3636:   PetscCall(PetscSectionGetOffset(mesh->coneSection, p, &off));

3638:   *coneOrientation = &mesh->coneOrientations[off];
3639:   PetscFunctionReturn(PETSC_SUCCESS);
3640: }

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

3645:   Not Collective

3647:   Input Parameters:
3648: + dm              - The `DMPLEX`
3649: . p               - The point, which must lie in the chart set with `DMPlexSetChart()`
3650: - coneOrientation - An array of orientations. Its length is given by the result of `DMPlexSetConeSize()`

3652:   Level: beginner

3654:   Notes:
3655:   This should be called after all calls to `DMPlexSetConeSize()` and `DMSetUp()`.

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

3659: .seealso: [](ch_unstructured), `DM`, `DMPLEX`, `DMPlexCreate()`, `DMPlexGetConeOrientation()`, `DMPlexSetCone()`, `DMPlexSetChart()`, `DMPlexSetConeSize()`, `DMSetUp()`
3660: @*/
3661: PetscErrorCode DMPlexSetConeOrientation(DM dm, PetscInt p, const PetscInt coneOrientation[])
3662: {
3663:   DM_Plex *mesh = (DM_Plex *)dm->data;
3664:   PetscInt pStart, pEnd;
3665:   PetscInt dof, off, c;

3667:   PetscFunctionBegin;
3669:   PetscCall(PetscSectionGetDof(mesh->coneSection, p, &dof));
3670:   if (dof) PetscAssertPointer(coneOrientation, 3);
3671:   PetscCall(PetscSectionGetOffset(mesh->coneSection, p, &off));
3672:   if (PetscDefined(USE_DEBUG)) {
3673:     PetscCall(PetscSectionGetChart(mesh->coneSection, &pStart, &pEnd));
3674:     PetscCheck(!(p < pStart) && !(p >= pEnd), PetscObjectComm((PetscObject)dm), PETSC_ERR_ARG_OUTOFRANGE, "Mesh point %" PetscInt_FMT " is not in the valid range [%" PetscInt_FMT ", %" PetscInt_FMT ")", p, pStart, pEnd);
3675:     for (c = 0; c < dof; ++c) {
3676:       PetscInt cdof, o = coneOrientation[c];

3678:       PetscCall(PetscSectionGetDof(mesh->coneSection, mesh->cones[off + c], &cdof));
3679:       PetscCheck(!o || (o >= -(cdof + 1) && o < cdof), PetscObjectComm((PetscObject)dm), PETSC_ERR_ARG_OUTOFRANGE, "Cone orientation %" PetscInt_FMT " is not in the valid range [%" PetscInt_FMT ". %" PetscInt_FMT ")", o, -(cdof + 1), cdof);
3680:       mesh->coneOrientations[off + c] = o;
3681:     }
3682:   } else {
3683:     for (c = 0; c < dof; ++c) mesh->coneOrientations[off + c] = coneOrientation[c];
3684:   }
3685:   PetscFunctionReturn(PETSC_SUCCESS);
3686: }

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

3691:   Not Collective

3693:   Input Parameters:
3694: + dm        - The `DMPLEX`
3695: . p         - The point, which must lie in the chart set with `DMPlexSetChart()`
3696: . conePos   - The local index in the cone where the point should be put
3697: - conePoint - The mesh point to insert

3699:   Level: beginner

3701: .seealso: [](ch_unstructured), `DM`, `DMPLEX`, `DMPlexCreate()`, `DMPlexGetCone()`, `DMPlexSetChart()`, `DMPlexSetConeSize()`, `DMSetUp()`
3702: @*/
3703: PetscErrorCode DMPlexInsertCone(DM dm, PetscInt p, PetscInt conePos, PetscInt conePoint)
3704: {
3705:   DM_Plex *mesh = (DM_Plex *)dm->data;
3706:   PetscInt pStart, pEnd;
3707:   PetscInt dof, off;

3709:   PetscFunctionBegin;
3711:   if (PetscDefined(USE_DEBUG)) {
3712:     PetscCall(PetscSectionGetChart(mesh->coneSection, &pStart, &pEnd));
3713:     PetscCheck(!(p < pStart) && !(p >= pEnd), PetscObjectComm((PetscObject)dm), PETSC_ERR_ARG_OUTOFRANGE, "Mesh point %" PetscInt_FMT " is not in the valid range [%" PetscInt_FMT ", %" PetscInt_FMT ")", p, pStart, pEnd);
3714:     PetscCheck(!(conePoint < pStart) && !(conePoint >= pEnd), PetscObjectComm((PetscObject)dm), PETSC_ERR_ARG_OUTOFRANGE, "Cone point %" PetscInt_FMT " is not in the valid range [%" PetscInt_FMT ", %" PetscInt_FMT ")", conePoint, pStart, pEnd);
3715:     PetscCall(PetscSectionGetDof(mesh->coneSection, p, &dof));
3716:     PetscCheck(!(conePos < 0) && !(conePos >= dof), PetscObjectComm((PetscObject)dm), PETSC_ERR_ARG_OUTOFRANGE, "Cone position %" PetscInt_FMT " of point %" PetscInt_FMT " is not in the valid range [0, %" PetscInt_FMT ")", conePos, p, dof);
3717:   }
3718:   PetscCall(PetscSectionGetOffset(mesh->coneSection, p, &off));
3719:   mesh->cones[off + conePos] = conePoint;
3720:   PetscFunctionReturn(PETSC_SUCCESS);
3721: }

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

3726:   Not Collective

3728:   Input Parameters:
3729: + dm              - The `DMPLEX`
3730: . p               - The point, which must lie in the chart set with `DMPlexSetChart()`
3731: . conePos         - The local index in the cone where the point should be put
3732: - coneOrientation - The point orientation to insert

3734:   Level: beginner

3736:   Note:
3737:   The meaning of coneOrientation values is detailed in `DMPlexGetConeOrientation()`.

3739: .seealso: [](ch_unstructured), `DM`, `DMPLEX`, `DMPlexCreate()`, `DMPlexGetCone()`, `DMPlexSetChart()`, `DMPlexSetConeSize()`, `DMSetUp()`
3740: @*/
3741: PetscErrorCode DMPlexInsertConeOrientation(DM dm, PetscInt p, PetscInt conePos, PetscInt coneOrientation)
3742: {
3743:   DM_Plex *mesh = (DM_Plex *)dm->data;
3744:   PetscInt pStart, pEnd;
3745:   PetscInt dof, off;

3747:   PetscFunctionBegin;
3749:   if (PetscDefined(USE_DEBUG)) {
3750:     PetscCall(PetscSectionGetChart(mesh->coneSection, &pStart, &pEnd));
3751:     PetscCheck(!(p < pStart) && !(p >= pEnd), PetscObjectComm((PetscObject)dm), PETSC_ERR_ARG_OUTOFRANGE, "Mesh point %" PetscInt_FMT " is not in the valid range [%" PetscInt_FMT ", %" PetscInt_FMT ")", p, pStart, pEnd);
3752:     PetscCall(PetscSectionGetDof(mesh->coneSection, p, &dof));
3753:     PetscCheck(!(conePos < 0) && !(conePos >= dof), PetscObjectComm((PetscObject)dm), PETSC_ERR_ARG_OUTOFRANGE, "Cone position %" PetscInt_FMT " of point %" PetscInt_FMT " is not in the valid range [0, %" PetscInt_FMT ")", conePos, p, dof);
3754:   }
3755:   PetscCall(PetscSectionGetOffset(mesh->coneSection, p, &off));
3756:   mesh->coneOrientations[off + conePos] = coneOrientation;
3757:   PetscFunctionReturn(PETSC_SUCCESS);
3758: }

3760: /*@C
3761:   DMPlexGetOrientedCone - Return the points and orientations on the in-edges for this point in the DAG

3763:   Not collective

3765:   Input Parameters:
3766: + dm - The DMPlex
3767: - p  - The point, which must lie in the chart set with DMPlexSetChart()

3769:   Output Parameters:
3770: + cone - An array of points which are on the in-edges for point `p`
3771: - ornt - An array of orientations which are on the in-edges for point `p`. An orientation is an
3772:          integer giving the prescription for cone traversal.

3774:   Level: beginner

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

3782:   You must also call `DMPlexRestoreOrientedCone()` after you finish using the returned array.

3784:   Fortran Notes:
3785:   `cone` and `ornt` must be declared with
3786: .vb
3787:   PetscInt, pointer :: cone(:)
3788:   PetscInt, pointer :: ornt(:)
3789: .ve

3791: .seealso: [](ch_unstructured), `DM`, `DMPLEX`, `DMPlexRestoreOrientedCone()`, `DMPlexGetConeSize()`, `DMPlexGetCone()`, `DMPlexGetChart()`
3792: @*/
3793: PetscErrorCode DMPlexGetOrientedCone(DM dm, PetscInt p, PeOp const PetscInt *cone[], PeOp const PetscInt *ornt[])
3794: {
3795:   DM_Plex *mesh = (DM_Plex *)dm->data;

3797:   PetscFunctionBegin;
3799:   if (mesh->tr) {
3800:     PetscCall(DMPlexTransformGetCone(mesh->tr, p, cone, ornt));
3801:   } else {
3802:     PetscInt off;
3803:     if (PetscDefined(USE_DEBUG)) {
3804:       PetscInt dof;
3805:       PetscCall(PetscSectionGetDof(mesh->coneSection, p, &dof));
3806:       if (dof) {
3807:         if (cone) PetscAssertPointer(cone, 3);
3808:         if (ornt) PetscAssertPointer(ornt, 4);
3809:       }
3810:     }
3811:     PetscCall(PetscSectionGetOffset(mesh->coneSection, p, &off));
3812:     if (cone) *cone = PetscSafePointerPlusOffset(mesh->cones, off);
3813:     if (ornt) *ornt = PetscSafePointerPlusOffset(mesh->coneOrientations, off);
3814:   }
3815:   PetscFunctionReturn(PETSC_SUCCESS);
3816: }

3818: /*@C
3819:   DMPlexRestoreOrientedCone - Restore the points and orientations on the in-edges for this point in the DAG obtained with `DMPlexGetOrientedCone()`

3821:   Not Collective

3823:   Input Parameters:
3824: + dm   - The DMPlex
3825: . p    - The point, which must lie in the chart set with `DMPlexSetChart()`
3826: . cone - An array of points which are on the in-edges for point p
3827: - ornt - An array of orientations which are on the in-edges for point `p`. An orientation is an
3828:          integer giving the prescription for cone traversal.

3830:   Level: beginner

3832: .seealso: [](ch_unstructured), `DM`, `DMPLEX`, `DMPlexGetOrientedCone()`, `DMPlexGetConeSize()`, `DMPlexGetCone()`, `DMPlexGetChart()`
3833: @*/
3834: PetscErrorCode DMPlexRestoreOrientedCone(DM dm, PetscInt p, const PetscInt *cone[], const PetscInt *ornt[])
3835: {
3836:   DM_Plex *mesh = (DM_Plex *)dm->data;

3838:   PetscFunctionBegin;
3840:   if (mesh->tr) PetscCall(DMPlexTransformRestoreCone(mesh->tr, p, cone, ornt));
3841:   PetscFunctionReturn(PETSC_SUCCESS);
3842: }

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

3847:   Not Collective

3849:   Input Parameters:
3850: + dm - The `DMPLEX`
3851: - p  - The point, which must lie in the chart set with `DMPlexSetChart()`

3853:   Output Parameter:
3854: . size - The support size for point `p`

3856:   Level: beginner

3858: .seealso: [](ch_unstructured), `DM`, `DMPLEX`, `DMPlexCreate()`, `DMPlexSetConeSize()`, `DMPlexSetChart()`, `DMPlexGetConeSize()`
3859: @*/
3860: PetscErrorCode DMPlexGetSupportSize(DM dm, PetscInt p, PetscInt *size)
3861: {
3862:   DM_Plex *mesh = (DM_Plex *)dm->data;

3864:   PetscFunctionBegin;
3866:   PetscAssertPointer(size, 3);
3867:   PetscCall(PetscSectionGetDof(mesh->supportSection, p, size));
3868:   PetscFunctionReturn(PETSC_SUCCESS);
3869: }

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

3874:   Not Collective

3876:   Input Parameters:
3877: + dm   - The `DMPLEX`
3878: . p    - The point, which must lie in the chart set with `DMPlexSetChart()`
3879: - size - The support size for point `p`

3881:   Level: beginner

3883:   Note:
3884:   This should be called after `DMPlexSetChart()`.

3886: .seealso: [](ch_unstructured), `DM`, `DMPLEX`, `DMPlexCreate()`, `DMPlexGetSupportSize()`, `DMPlexSetChart()`
3887: @*/
3888: PetscErrorCode DMPlexSetSupportSize(DM dm, PetscInt p, PetscInt size)
3889: {
3890:   DM_Plex *mesh = (DM_Plex *)dm->data;

3892:   PetscFunctionBegin;
3894:   PetscCall(PetscSectionSetDof(mesh->supportSection, p, size));
3895:   PetscFunctionReturn(PETSC_SUCCESS);
3896: }

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

3901:   Not Collective

3903:   Input Parameters:
3904: + dm - The `DMPLEX`
3905: - p  - The point, which must lie in the chart set with `DMPlexSetChart()`

3907:   Output Parameter:
3908: . support - An array of points which are on the out-edges for point `p`, its length is that obtained from `DMPlexGetSupportSize()`

3910:   Level: beginner

3912:   Fortran Notes:
3913:   `support` must be declared with
3914: .vb
3915:   PetscInt, pointer :: support(:)
3916: .ve

3918:   You must also call `DMPlexRestoreSupport()` after you finish using the returned array.
3919:   `DMPlexRestoreSupport()` is not needed/available in C.

3921: .seealso: [](ch_unstructured), `DM`, `DMPLEX`, `DMPlexGetSupportSize()`, `DMPlexSetSupport()`, `DMPlexGetCone()`, `DMPlexSetChart()`
3922: @*/
3923: PetscErrorCode DMPlexGetSupport(DM dm, PetscInt p, const PetscInt *support[])
3924: {
3925:   DM_Plex *mesh = (DM_Plex *)dm->data;
3926:   PetscInt off;

3928:   PetscFunctionBegin;
3930:   PetscAssertPointer(support, 3);
3931:   PetscCall(PetscSectionGetOffset(mesh->supportSection, p, &off));
3932:   *support = PetscSafePointerPlusOffset(mesh->supports, off);
3933:   PetscFunctionReturn(PETSC_SUCCESS);
3934: }

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

3939:   Not Collective

3941:   Input Parameters:
3942: + dm      - The `DMPLEX`
3943: . p       - The point, which must lie in the chart set with `DMPlexSetChart()`
3944: - support - An array of points which are on the out-edges for point `p`, its length is that obtained from `DMPlexGetSupportSize()`

3946:   Level: beginner

3948:   Note:
3949:   This should be called after all calls to `DMPlexSetSupportSize()` and `DMSetUp()`.

3951: .seealso: [](ch_unstructured), `DM`, `DMPLEX`, `DMPlexSetCone()`, `DMPlexSetConeSize()`, `DMPlexCreate()`, `DMPlexGetSupport()`, `DMPlexSetChart()`, `DMPlexSetSupportSize()`, `DMSetUp()`
3952: @*/
3953: PetscErrorCode DMPlexSetSupport(DM dm, PetscInt p, const PetscInt support[])
3954: {
3955:   DM_Plex *mesh = (DM_Plex *)dm->data;
3956:   PetscInt pStart, pEnd;
3957:   PetscInt dof, off, c;

3959:   PetscFunctionBegin;
3961:   PetscCall(PetscSectionGetChart(mesh->supportSection, &pStart, &pEnd));
3962:   PetscCall(PetscSectionGetDof(mesh->supportSection, p, &dof));
3963:   if (dof) PetscAssertPointer(support, 3);
3964:   PetscCall(PetscSectionGetOffset(mesh->supportSection, p, &off));
3965:   PetscCheck(!(p < pStart) && !(p >= pEnd), PetscObjectComm((PetscObject)dm), PETSC_ERR_ARG_OUTOFRANGE, "Mesh point %" PetscInt_FMT " is not in the valid range [%" PetscInt_FMT ", %" PetscInt_FMT ")", p, pStart, pEnd);
3966:   for (c = 0; c < dof; ++c) {
3967:     PetscCheck(!(support[c] < pStart) && !(support[c] >= pEnd), PetscObjectComm((PetscObject)dm), PETSC_ERR_ARG_OUTOFRANGE, "Support point %" PetscInt_FMT " is not in the valid range [%" PetscInt_FMT ", %" PetscInt_FMT ")", support[c], pStart, pEnd);
3968:     mesh->supports[off + c] = support[c];
3969:   }
3970:   PetscFunctionReturn(PETSC_SUCCESS);
3971: }

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

3976:   Not Collective

3978:   Input Parameters:
3979: + dm           - The `DMPLEX`
3980: . p            - The point, which must lie in the chart set with `DMPlexSetChart()`
3981: . supportPos   - The local index in the cone where the point should be put
3982: - supportPoint - The mesh point to insert

3984:   Level: beginner

3986: .seealso: [](ch_unstructured), `DM`, `DMPLEX`, `DMPlexCreate()`, `DMPlexGetCone()`, `DMPlexSetChart()`, `DMPlexSetConeSize()`, `DMSetUp()`
3987: @*/
3988: PetscErrorCode DMPlexInsertSupport(DM dm, PetscInt p, PetscInt supportPos, PetscInt supportPoint)
3989: {
3990:   DM_Plex *mesh = (DM_Plex *)dm->data;
3991:   PetscInt pStart, pEnd;
3992:   PetscInt dof, off;

3994:   PetscFunctionBegin;
3996:   PetscCall(PetscSectionGetChart(mesh->supportSection, &pStart, &pEnd));
3997:   PetscCall(PetscSectionGetDof(mesh->supportSection, p, &dof));
3998:   PetscCall(PetscSectionGetOffset(mesh->supportSection, p, &off));
3999:   PetscCheck(!(p < pStart) && !(p >= pEnd), PetscObjectComm((PetscObject)dm), PETSC_ERR_ARG_OUTOFRANGE, "Mesh point %" PetscInt_FMT " is not in the valid range [%" PetscInt_FMT ", %" PetscInt_FMT ")", p, pStart, pEnd);
4000:   PetscCheck(!(supportPoint < pStart) && !(supportPoint >= pEnd), PetscObjectComm((PetscObject)dm), PETSC_ERR_ARG_OUTOFRANGE, "Support point %" PetscInt_FMT " is not in the valid range [%" PetscInt_FMT ", %" PetscInt_FMT ")", supportPoint, pStart, pEnd);
4001:   PetscCheck(supportPos < dof, PetscObjectComm((PetscObject)dm), PETSC_ERR_ARG_OUTOFRANGE, "Support position %" PetscInt_FMT " of point %" PetscInt_FMT " is not in the valid range [0, %" PetscInt_FMT ")", supportPos, p, dof);
4002:   mesh->supports[off + supportPos] = supportPoint;
4003:   PetscFunctionReturn(PETSC_SUCCESS);
4004: }

4006: /* Converts an orientation o in the current numbering to the previous scheme used in Plex */
4007: PetscInt DMPolytopeConvertNewOrientation_Internal(DMPolytopeType ct, PetscInt o)
4008: {
4009:   switch (ct) {
4010:   case DM_POLYTOPE_SEGMENT:
4011:     if (o == -1) return -2;
4012:     break;
4013:   case DM_POLYTOPE_TRIANGLE:
4014:     if (o == -3) return -1;
4015:     if (o == -2) return -3;
4016:     if (o == -1) return -2;
4017:     break;
4018:   case DM_POLYTOPE_QUADRILATERAL:
4019:     if (o == -4) return -2;
4020:     if (o == -3) return -1;
4021:     if (o == -2) return -4;
4022:     if (o == -1) return -3;
4023:     break;
4024:   default:
4025:     return o;
4026:   }
4027:   return o;
4028: }

4030: /* Converts an orientation o in the previous scheme used in Plex to the current numbering */
4031: PetscInt DMPolytopeConvertOldOrientation_Internal(DMPolytopeType ct, PetscInt o)
4032: {
4033:   switch (ct) {
4034:   case DM_POLYTOPE_SEGMENT:
4035:     if ((o == -2) || (o == 1)) return -1;
4036:     if (o == -1) return 0;
4037:     break;
4038:   case DM_POLYTOPE_TRIANGLE:
4039:     if (o == -3) return -2;
4040:     if (o == -2) return -1;
4041:     if (o == -1) return -3;
4042:     break;
4043:   case DM_POLYTOPE_QUADRILATERAL:
4044:     if (o == -4) return -2;
4045:     if (o == -3) return -1;
4046:     if (o == -2) return -4;
4047:     if (o == -1) return -3;
4048:     break;
4049:   default:
4050:     return o;
4051:   }
4052:   return o;
4053: }

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

4060:   PetscFunctionBegin;
4061:   PetscCall(DMPlexGetChart(dm, &pStart, &pEnd));
4062:   for (p = pStart; p < pEnd; ++p) {
4063:     const PetscInt *cone, *ornt;
4064:     PetscInt        coneSize, c;

4066:     PetscCall(DMPlexGetConeSize(dm, p, &coneSize));
4067:     PetscCall(DMPlexGetCone(dm, p, &cone));
4068:     PetscCall(DMPlexGetConeOrientation(dm, p, &ornt));
4069:     for (c = 0; c < coneSize; ++c) {
4070:       DMPolytopeType ct;
4071:       const PetscInt o = ornt[c];

4073:       PetscCall(DMPlexGetCellType(dm, cone[c], &ct));
4074:       switch (ct) {
4075:       case DM_POLYTOPE_SEGMENT:
4076:         if ((o == -2) || (o == 1)) PetscCall(DMPlexInsertConeOrientation(dm, p, c, -1));
4077:         if (o == -1) PetscCall(DMPlexInsertConeOrientation(dm, p, c, 0));
4078:         break;
4079:       case DM_POLYTOPE_TRIANGLE:
4080:         if (o == -3) PetscCall(DMPlexInsertConeOrientation(dm, p, c, -2));
4081:         if (o == -2) PetscCall(DMPlexInsertConeOrientation(dm, p, c, -1));
4082:         if (o == -1) PetscCall(DMPlexInsertConeOrientation(dm, p, c, -3));
4083:         break;
4084:       case DM_POLYTOPE_QUADRILATERAL:
4085:         if (o == -4) PetscCall(DMPlexInsertConeOrientation(dm, p, c, -2));
4086:         if (o == -3) PetscCall(DMPlexInsertConeOrientation(dm, p, c, -1));
4087:         if (o == -2) PetscCall(DMPlexInsertConeOrientation(dm, p, c, -4));
4088:         if (o == -1) PetscCall(DMPlexInsertConeOrientation(dm, p, c, -3));
4089:         break;
4090:       default:
4091:         break;
4092:       }
4093:     }
4094:   }
4095:   PetscFunctionReturn(PETSC_SUCCESS);
4096: }

4098: static inline PetscErrorCode DMPlexGetTransitiveClosure_Hot_Private(DM dm, PetscInt p, PetscBool useCone, PetscInt *size, const PetscInt *arr[], const PetscInt *ornt[])
4099: {
4100:   DM_Plex *mesh = (DM_Plex *)dm->data;

4102:   PetscFunctionBeginHot;
4103:   if (PetscDefined(USE_DEBUG) || mesh->tr) {
4104:     if (useCone) {
4105:       PetscCall(DMPlexGetConeSize(dm, p, size));
4106:       PetscCall(DMPlexGetOrientedCone(dm, p, arr, ornt));
4107:     } else {
4108:       PetscCall(DMPlexGetSupportSize(dm, p, size));
4109:       PetscCall(DMPlexGetSupport(dm, p, arr));
4110:     }
4111:   } else {
4112:     if (useCone) {
4113:       const PetscSection s   = mesh->coneSection;
4114:       const PetscInt     ps  = p - s->pStart;
4115:       const PetscInt     off = s->atlasOff[ps];

4117:       *size = s->atlasDof[ps];
4118:       *arr  = mesh->cones + off;
4119:       *ornt = mesh->coneOrientations + off;
4120:     } else {
4121:       const PetscSection s   = mesh->supportSection;
4122:       const PetscInt     ps  = p - s->pStart;
4123:       const PetscInt     off = s->atlasOff[ps];

4125:       *size = s->atlasDof[ps];
4126:       *arr  = mesh->supports + off;
4127:     }
4128:   }
4129:   PetscFunctionReturn(PETSC_SUCCESS);
4130: }

4132: static inline PetscErrorCode DMPlexRestoreTransitiveClosure_Hot_Private(DM dm, PetscInt p, PetscBool useCone, PetscInt *size, const PetscInt *arr[], const PetscInt *ornt[])
4133: {
4134:   DM_Plex *mesh = (DM_Plex *)dm->data;

4136:   PetscFunctionBeginHot;
4137:   if (PetscDefined(USE_DEBUG) || mesh->tr) {
4138:     if (useCone) PetscCall(DMPlexRestoreOrientedCone(dm, p, arr, ornt));
4139:   }
4140:   PetscFunctionReturn(PETSC_SUCCESS);
4141: }

4143: static PetscErrorCode DMPlexGetTransitiveClosure_Depth1_Private(DM dm, PetscInt p, PetscInt ornt, PetscBool useCone, PetscInt *numPoints, PetscInt *points[])
4144: {
4145:   DMPolytopeType  ct = DM_POLYTOPE_UNKNOWN;
4146:   PetscInt       *closure;
4147:   const PetscInt *tmp = NULL, *tmpO = NULL;
4148:   PetscInt        off = 0, tmpSize, t;

4150:   PetscFunctionBeginHot;
4151:   if (ornt) {
4152:     PetscCall(DMPlexGetCellType(dm, p, &ct));
4153:     if (ct == DM_POLYTOPE_FV_GHOST || ct == DM_POLYTOPE_INTERIOR_GHOST || ct == DM_POLYTOPE_UNKNOWN || ct == DM_POLYTOPE_UNKNOWN_CELL || ct == DM_POLYTOPE_UNKNOWN_FACE) ct = DM_POLYTOPE_UNKNOWN;
4154:   }
4155:   if (*points) {
4156:     closure = *points;
4157:   } else {
4158:     PetscInt maxConeSize, maxSupportSize;
4159:     PetscCall(DMPlexGetMaxSizes(dm, &maxConeSize, &maxSupportSize));
4160:     PetscCall(DMGetWorkArray(dm, 2 * (PetscMax(maxConeSize, maxSupportSize) + 1), MPIU_INT, &closure));
4161:   }
4162:   PetscCall(DMPlexGetTransitiveClosure_Hot_Private(dm, p, useCone, &tmpSize, &tmp, &tmpO));
4163:   if (ct == DM_POLYTOPE_UNKNOWN) {
4164:     closure[off++] = p;
4165:     closure[off++] = 0;
4166:     for (t = 0; t < tmpSize; ++t) {
4167:       closure[off++] = tmp[t];
4168:       closure[off++] = tmpO ? tmpO[t] : 0;
4169:     }
4170:   } else {
4171:     const PetscInt *arr = DMPolytopeTypeGetArrangement(ct, ornt);

4173:     /* We assume that cells with a valid type have faces with a valid type */
4174:     closure[off++] = p;
4175:     closure[off++] = ornt;
4176:     for (t = 0; t < tmpSize; ++t) {
4177:       DMPolytopeType ft;

4179:       PetscCall(DMPlexGetCellType(dm, tmp[t], &ft));
4180:       closure[off++] = tmp[arr[t]];
4181:       closure[off++] = tmpO ? DMPolytopeTypeComposeOrientation(ft, ornt, tmpO[t]) : 0;
4182:     }
4183:   }
4184:   PetscCall(DMPlexRestoreTransitiveClosure_Hot_Private(dm, p, useCone, &tmpSize, &tmp, &tmpO));
4185:   if (numPoints) *numPoints = tmpSize + 1;
4186:   if (points) *points = closure;
4187:   PetscFunctionReturn(PETSC_SUCCESS);
4188: }

4190: /* We need a special tensor version because we want to allow duplicate points in the endcaps for hybrid cells */
4191: static PetscErrorCode DMPlexTransitiveClosure_Tensor_Internal(DM dm, PetscInt point, DMPolytopeType ct, PetscInt o, PetscBool useCone, PetscInt *numPoints, PetscInt **points)
4192: {
4193:   const PetscInt *arr = DMPolytopeTypeGetArrangement(ct, o);
4194:   const PetscInt *cone, *ornt;
4195:   PetscInt       *pts, *closure = NULL;
4196:   DMPolytopeType  ft;
4197:   PetscInt        maxConeSize, maxSupportSize, coneSeries, supportSeries, maxSize;
4198:   PetscInt        dim, coneSize, c, d, clSize, cl;

4200:   PetscFunctionBeginHot;
4201:   PetscCall(DMGetDimension(dm, &dim));
4202:   PetscCall(DMPlexGetTransitiveClosure_Hot_Private(dm, point, PETSC_TRUE, &coneSize, &cone, &ornt));
4203:   PetscCall(DMPlexGetMaxSizes(dm, &maxConeSize, &maxSupportSize));
4204:   coneSeries    = (maxConeSize > 1) ? ((PetscPowInt(maxConeSize, dim + 1) - 1) / (maxConeSize - 1)) : dim + 1;
4205:   supportSeries = (maxSupportSize > 1) ? ((PetscPowInt(maxSupportSize, dim + 1) - 1) / (maxSupportSize - 1)) : dim + 1;
4206:   maxSize       = PetscMax(coneSeries, supportSeries);
4207:   if (*points) {
4208:     pts = *points;
4209:   } else PetscCall(DMGetWorkArray(dm, 2 * maxSize, MPIU_INT, &pts));
4210:   c        = 0;
4211:   pts[c++] = point;
4212:   pts[c++] = o;
4213:   PetscCall(DMPlexGetCellType(dm, cone[arr[0 * 2 + 0]], &ft));
4214:   PetscCall(DMPlexGetTransitiveClosure_Internal(dm, cone[arr[0 * 2 + 0]], DMPolytopeTypeComposeOrientation(ft, arr[0 * 2 + 1], ornt[0]), useCone, &clSize, &closure));
4215:   for (cl = 0; cl < clSize * 2; cl += 2) {
4216:     pts[c++] = closure[cl];
4217:     pts[c++] = closure[cl + 1];
4218:   }
4219:   PetscCall(DMPlexGetTransitiveClosure_Internal(dm, cone[arr[1 * 2 + 0]], DMPolytopeTypeComposeOrientation(ft, arr[1 * 2 + 1], ornt[1]), useCone, &clSize, &closure));
4220:   for (cl = 0; cl < clSize * 2; cl += 2) {
4221:     pts[c++] = closure[cl];
4222:     pts[c++] = closure[cl + 1];
4223:   }
4224:   PetscCall(DMPlexRestoreTransitiveClosure(dm, cone[0], useCone, &clSize, &closure));
4225:   for (d = 2; d < coneSize; ++d) {
4226:     PetscCall(DMPlexGetCellType(dm, cone[arr[d * 2 + 0]], &ft));
4227:     pts[c++] = cone[arr[d * 2 + 0]];
4228:     pts[c++] = DMPolytopeTypeComposeOrientation(ft, arr[d * 2 + 1], ornt[d]);
4229:   }
4230:   PetscCall(DMPlexRestoreTransitiveClosure_Hot_Private(dm, point, PETSC_TRUE, &coneSize, &cone, &ornt));
4231:   if (dim >= 3) {
4232:     for (d = 2; d < coneSize; ++d) {
4233:       const PetscInt  fpoint = cone[arr[d * 2 + 0]];
4234:       const PetscInt *fcone, *fornt;
4235:       PetscInt        fconeSize, fc, i;

4237:       PetscCall(DMPlexGetCellType(dm, fpoint, &ft));
4238:       const PetscInt *farr = DMPolytopeTypeGetArrangement(ft, DMPolytopeTypeComposeOrientation(ft, arr[d * 2 + 1], ornt[d]));
4239:       PetscCall(DMPlexGetTransitiveClosure_Hot_Private(dm, fpoint, PETSC_TRUE, &fconeSize, &fcone, &fornt));
4240:       for (fc = 0; fc < fconeSize; ++fc) {
4241:         const PetscInt cp = fcone[farr[fc * 2 + 0]];
4242:         const PetscInt co = farr[fc * 2 + 1];

4244:         for (i = 0; i < c; i += 2)
4245:           if (pts[i] == cp) break;
4246:         if (i == c) {
4247:           PetscCall(DMPlexGetCellType(dm, cp, &ft));
4248:           pts[c++] = cp;
4249:           pts[c++] = DMPolytopeTypeComposeOrientation(ft, co, fornt[farr[fc * 2 + 0]]);
4250:         }
4251:       }
4252:       PetscCall(DMPlexRestoreTransitiveClosure_Hot_Private(dm, fpoint, PETSC_TRUE, &fconeSize, &fcone, &fornt));
4253:     }
4254:   }
4255:   *numPoints = c / 2;
4256:   *points    = pts;
4257:   PetscFunctionReturn(PETSC_SUCCESS);
4258: }

4260: PetscErrorCode DMPlexGetTransitiveClosure_Internal(DM dm, PetscInt p, PetscInt ornt, PetscBool useCone, PetscInt *numPoints, PetscInt *points[])
4261: {
4262:   DMPolytopeType ct;
4263:   PetscInt      *closure, *fifo;
4264:   PetscInt       closureSize = 0, fifoStart = 0, fifoSize = 0;
4265:   PetscInt       maxConeSize, maxSupportSize, coneSeries, supportSeries;
4266:   PetscInt       depth, maxSize;

4268:   PetscFunctionBeginHot;
4269:   PetscCall(DMPlexGetDepth(dm, &depth));
4270:   if (depth == 1) {
4271:     PetscCall(DMPlexGetTransitiveClosure_Depth1_Private(dm, p, ornt, useCone, numPoints, points));
4272:     PetscFunctionReturn(PETSC_SUCCESS);
4273:   }
4274:   PetscCall(DMPlexGetCellType(dm, p, &ct));
4275:   if (ct == DM_POLYTOPE_FV_GHOST || ct == DM_POLYTOPE_INTERIOR_GHOST || ct == DM_POLYTOPE_UNKNOWN || ct == DM_POLYTOPE_UNKNOWN_CELL || ct == DM_POLYTOPE_UNKNOWN_FACE) ct = DM_POLYTOPE_UNKNOWN;
4276:   if (DMPolytopeTypeIsHybrid(ct) && ct != DM_POLYTOPE_POINT_PRISM_TENSOR) {
4277:     PetscCall(DMPlexTransitiveClosure_Tensor_Internal(dm, p, ct, ornt, useCone, numPoints, points));
4278:     PetscFunctionReturn(PETSC_SUCCESS);
4279:   }
4280:   PetscCall(DMPlexGetMaxSizes(dm, &maxConeSize, &maxSupportSize));
4281:   coneSeries    = (maxConeSize > 1) ? ((PetscPowInt(maxConeSize, depth + 1) - 1) / (maxConeSize - 1)) : depth + 1;
4282:   supportSeries = (maxSupportSize > 1) ? ((PetscPowInt(maxSupportSize, depth + 1) - 1) / (maxSupportSize - 1)) : depth + 1;
4283:   maxSize       = PetscMax(coneSeries, supportSeries);
4284:   PetscCall(DMGetWorkArray(dm, 3 * maxSize, MPIU_INT, &fifo));
4285:   if (*points) {
4286:     closure = *points;
4287:   } else PetscCall(DMGetWorkArray(dm, 2 * maxSize, MPIU_INT, &closure));
4288:   closure[closureSize++] = p;
4289:   closure[closureSize++] = ornt;
4290:   fifo[fifoSize++]       = p;
4291:   fifo[fifoSize++]       = ornt;
4292:   fifo[fifoSize++]       = ct;
4293:   /* Should kick out early when depth is reached, rather than checking all vertices for empty cones */
4294:   while (fifoSize - fifoStart) {
4295:     const PetscInt       q    = fifo[fifoStart++];
4296:     const PetscInt       o    = fifo[fifoStart++];
4297:     const DMPolytopeType qt   = (DMPolytopeType)fifo[fifoStart++];
4298:     const PetscInt      *qarr = DMPolytopeTypeGetArrangement(qt, o);
4299:     const PetscInt      *tmp, *tmpO = NULL;
4300:     PetscInt             tmpSize;

4302:     if (PetscDefined(USE_DEBUG)) {
4303:       PetscInt nO = DMPolytopeTypeGetNumArrangements(qt) / 2;
4304:       PetscCheck(!o || !(o >= nO || o < -nO), PETSC_COMM_SELF, PETSC_ERR_PLIB, "Invalid orientation %" PetscInt_FMT " not in [%" PetscInt_FMT ",%" PetscInt_FMT ") for %s %" PetscInt_FMT, o, -nO, nO, DMPolytopeTypes[qt], q);
4305:     }
4306:     PetscCall(DMPlexGetTransitiveClosure_Hot_Private(dm, q, useCone, &tmpSize, &tmp, &tmpO));
4307:     for (PetscInt t = 0; t < tmpSize; ++t) {
4308:       const PetscInt ip = useCone && qarr ? qarr[t * 2] : t;
4309:       const PetscInt io = useCone && qarr ? qarr[t * 2 + 1] : 0;
4310:       const PetscInt cp = tmp[ip];
4311:       PetscCall(DMPlexGetCellType(dm, cp, &ct));
4312:       const PetscInt co = tmpO ? DMPolytopeTypeComposeOrientation(ct, io, tmpO[ip]) : 0;
4313:       PetscInt       c;

4315:       /* Check for duplicate */
4316:       for (c = 0; c < closureSize; c += 2) {
4317:         if (closure[c] == cp) break;
4318:       }
4319:       if (c == closureSize) {
4320:         closure[closureSize++] = cp;
4321:         closure[closureSize++] = co;
4322:         fifo[fifoSize++]       = cp;
4323:         fifo[fifoSize++]       = co;
4324:         fifo[fifoSize++]       = ct;
4325:       }
4326:     }
4327:     PetscCall(DMPlexRestoreTransitiveClosure_Hot_Private(dm, q, useCone, &tmpSize, &tmp, &tmpO));
4328:   }
4329:   PetscCall(DMRestoreWorkArray(dm, 3 * maxSize, MPIU_INT, &fifo));
4330:   if (numPoints) *numPoints = closureSize / 2;
4331:   if (points) *points = closure;
4332:   PetscFunctionReturn(PETSC_SUCCESS);
4333: }

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

4338:   Not Collective

4340:   Input Parameters:
4341: + dm      - The `DMPLEX`
4342: . p       - The mesh point
4343: - useCone - `PETSC_TRUE` for the closure, otherwise return the support

4345:   Input/Output Parameter:
4346: . points - The points and point orientations, interleaved as pairs [p0, o0, p1, o1, ...];
4347:            if *points is `NULL` on input, internal storage will be returned, use `DMPlexRestoreTransitiveClosure()`,
4348:            otherwise the provided array is used to hold the values

4350:   Output Parameter:
4351: . numPoints - The number of points in the closure, so `points` is of size 2*`numPoints`

4353:   Level: beginner

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

4358:   Fortran Notes:
4359:   `points` must be declared with
4360: .vb
4361:   PetscInt, pointer :: points(:)
4362: .ve
4363:   and is always allocated by the function.

4365:   Pass `PETSC_NULL_INTEGER` for `numPoints` if it is not needed

4367: .seealso: [](ch_unstructured), `DM`, `DMPLEX`, `DMPlexRestoreTransitiveClosure()`, `DMPlexCreate()`, `DMPlexSetCone()`, `DMPlexSetChart()`, `DMPlexGetCone()`
4368: @*/
4369: PetscErrorCode DMPlexGetTransitiveClosure(DM dm, PetscInt p, PetscBool useCone, PetscInt *numPoints, PetscInt *points[])
4370: {
4371:   PetscFunctionBeginHot;
4373:   if (numPoints) PetscAssertPointer(numPoints, 4);
4374:   if (points) PetscAssertPointer(points, 5);
4375:   if (PetscDefined(USE_DEBUG)) {
4376:     PetscInt pStart, pEnd;
4377:     PetscCall(DMPlexGetChart(dm, &pStart, &pEnd));
4378:     PetscCheck(p >= pStart && p < pEnd, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Point %" PetscInt_FMT " is not in [%" PetscInt_FMT ", %" PetscInt_FMT ")", p, pStart, pEnd);
4379:   }
4380:   PetscCall(DMPlexGetTransitiveClosure_Internal(dm, p, 0, useCone, numPoints, points));
4381:   PetscFunctionReturn(PETSC_SUCCESS);
4382: }

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

4387:   Not Collective

4389:   Input Parameters:
4390: + dm        - The `DMPLEX`
4391: . p         - The mesh point
4392: . useCone   - `PETSC_TRUE` for the closure, otherwise return the star
4393: . numPoints - The number of points in the closure, so points[] is of size 2*`numPoints`
4394: - points    - The points and point orientations, interleaved as pairs [p0, o0, p1, o1, ...]

4396:   Level: beginner

4398:   Note:
4399:   If not using internal storage (points is not `NULL` on input), this call is unnecessary

4401: .seealso: [](ch_unstructured), `DM`, `DMPLEX`, `DMPlexGetTransitiveClosure()`, `DMPlexCreate()`, `DMPlexSetCone()`, `DMPlexSetChart()`, `DMPlexGetCone()`
4402: @*/
4403: PetscErrorCode DMPlexRestoreTransitiveClosure(DM dm, PetscInt p, PetscBool useCone, PetscInt *numPoints, PetscInt *points[])
4404: {
4405:   PetscFunctionBeginHot;
4407:   if (numPoints) *numPoints = 0;
4408:   PetscCall(DMRestoreWorkArray(dm, 0, MPIU_INT, points));
4409:   PetscFunctionReturn(PETSC_SUCCESS);
4410: }

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

4415:   Not Collective

4417:   Input Parameter:
4418: . dm - The `DMPLEX`

4420:   Output Parameters:
4421: + maxConeSize    - The maximum number of in-edges
4422: - maxSupportSize - The maximum number of out-edges

4424:   Level: beginner

4426: .seealso: [](ch_unstructured), `DM`, `DMPLEX`, `DMPlexCreate()`, `DMPlexSetConeSize()`, `DMPlexSetChart()`
4427: @*/
4428: PetscErrorCode DMPlexGetMaxSizes(DM dm, PeOp PetscInt *maxConeSize, PeOp PetscInt *maxSupportSize)
4429: {
4430:   DM_Plex *mesh = (DM_Plex *)dm->data;

4432:   PetscFunctionBegin;
4434:   if (maxConeSize) PetscCall(PetscSectionGetMaxDof(mesh->coneSection, maxConeSize));
4435:   if (maxSupportSize) PetscCall(PetscSectionGetMaxDof(mesh->supportSection, maxSupportSize));
4436:   PetscFunctionReturn(PETSC_SUCCESS);
4437: }

4439: PetscErrorCode DMSetUp_Plex(DM dm)
4440: {
4441:   DM_Plex *mesh = (DM_Plex *)dm->data;
4442:   PetscInt size, maxSupportSize;

4444:   PetscFunctionBegin;
4446:   PetscCall(PetscSectionSetUp(mesh->coneSection));
4447:   PetscCall(PetscSectionGetStorageSize(mesh->coneSection, &size));
4448:   PetscCall(PetscMalloc1(size, &mesh->cones));
4449:   PetscCall(PetscCalloc1(size, &mesh->coneOrientations));
4450:   PetscCall(PetscSectionGetMaxDof(mesh->supportSection, &maxSupportSize));
4451:   if (maxSupportSize) {
4452:     PetscCall(PetscSectionSetUp(mesh->supportSection));
4453:     PetscCall(PetscSectionGetStorageSize(mesh->supportSection, &size));
4454:     PetscCall(PetscMalloc1(size, &mesh->supports));
4455:   }
4456:   PetscFunctionReturn(PETSC_SUCCESS);
4457: }

4459: PetscErrorCode DMCreateSubDM_Plex(DM dm, PetscInt numFields, const PetscInt fields[], IS *is, DM *subdm)
4460: {
4461:   PetscFunctionBegin;
4462:   if (subdm) PetscCall(DMClone(dm, subdm));
4463:   PetscCall(DMCreateSectionSubDM(dm, numFields, fields, NULL, NULL, is, subdm));
4464:   if (subdm) (*subdm)->useNatural = dm->useNatural;
4465:   if (dm->useNatural && dm->sfMigration) {
4466:     PetscSF sfNatural;

4468:     (*subdm)->sfMigration = dm->sfMigration;
4469:     PetscCall(PetscObjectReference((PetscObject)dm->sfMigration));
4470:     PetscCall(DMPlexCreateGlobalToNaturalSF(*subdm, NULL, (*subdm)->sfMigration, &sfNatural));
4471:     (*subdm)->sfNatural = sfNatural;
4472:   }
4473:   PetscFunctionReturn(PETSC_SUCCESS);
4474: }

4476: PetscErrorCode DMCreateSuperDM_Plex(DM dms[], PetscInt len, IS **is, DM *superdm)
4477: {
4478:   PetscInt i = 0;

4480:   PetscFunctionBegin;
4481:   PetscCall(DMClone(dms[0], superdm));
4482:   PetscCall(DMCreateSectionSuperDM(dms, len, is, superdm));
4483:   (*superdm)->useNatural = PETSC_FALSE;
4484:   for (i = 0; i < len; i++) {
4485:     if (dms[i]->useNatural && dms[i]->sfMigration) {
4486:       PetscSF sfNatural;

4488:       (*superdm)->sfMigration = dms[i]->sfMigration;
4489:       PetscCall(PetscObjectReference((PetscObject)dms[i]->sfMigration));
4490:       (*superdm)->useNatural = PETSC_TRUE;
4491:       PetscCall(DMPlexCreateGlobalToNaturalSF(*superdm, NULL, (*superdm)->sfMigration, &sfNatural));
4492:       (*superdm)->sfNatural = sfNatural;
4493:       break;
4494:     }
4495:   }
4496:   PetscFunctionReturn(PETSC_SUCCESS);
4497: }

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

4502:   Not Collective

4504:   Input Parameter:
4505: . dm - The `DMPLEX`

4507:   Level: beginner

4509:   Note:
4510:   This should be called after all calls to `DMPlexSetCone()`

4512: .seealso: [](ch_unstructured), `DM`, `DMPLEX`, `DMPlexCreate()`, `DMPlexSetChart()`, `DMPlexSetConeSize()`, `DMPlexSetCone()`
4513: @*/
4514: PetscErrorCode DMPlexSymmetrize(DM dm)
4515: {
4516:   DM_Plex  *mesh = (DM_Plex *)dm->data;
4517:   PetscInt *offsets;
4518:   PetscInt  supportSize;
4519:   PetscInt  pStart, pEnd, p;

4521:   PetscFunctionBegin;
4523:   PetscCheck(!mesh->supports, PetscObjectComm((PetscObject)dm), PETSC_ERR_ARG_WRONGSTATE, "Supports were already setup in this DMPlex");
4524:   PetscCall(PetscLogEventBegin(DMPLEX_Symmetrize, dm, 0, 0, 0));
4525:   /* Calculate support sizes */
4526:   PetscCall(DMPlexGetChart(dm, &pStart, &pEnd));
4527:   for (p = pStart; p < pEnd; ++p) {
4528:     PetscInt dof, off, c;

4530:     PetscCall(PetscSectionGetDof(mesh->coneSection, p, &dof));
4531:     PetscCall(PetscSectionGetOffset(mesh->coneSection, p, &off));
4532:     for (c = off; c < off + dof; ++c) PetscCall(PetscSectionAddDof(mesh->supportSection, mesh->cones[c], 1));
4533:   }
4534:   PetscCall(PetscSectionSetUp(mesh->supportSection));
4535:   /* Calculate supports */
4536:   PetscCall(PetscSectionGetStorageSize(mesh->supportSection, &supportSize));
4537:   PetscCall(PetscMalloc1(supportSize, &mesh->supports));
4538:   PetscCall(PetscCalloc1(pEnd - pStart, &offsets));
4539:   for (p = pStart; p < pEnd; ++p) {
4540:     PetscInt dof, off, c;

4542:     PetscCall(PetscSectionGetDof(mesh->coneSection, p, &dof));
4543:     PetscCall(PetscSectionGetOffset(mesh->coneSection, p, &off));
4544:     for (c = off; c < off + dof; ++c) {
4545:       const PetscInt q = mesh->cones[c];
4546:       PetscInt       offS;

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

4550:       mesh->supports[offS + offsets[q]] = p;
4551:       ++offsets[q];
4552:     }
4553:   }
4554:   PetscCall(PetscFree(offsets));
4555:   PetscCall(PetscLogEventEnd(DMPLEX_Symmetrize, dm, 0, 0, 0));
4556:   PetscFunctionReturn(PETSC_SUCCESS);
4557: }

4559: static PetscErrorCode DMPlexCreateDepthStratum(DM dm, DMLabel label, PetscInt depth, PetscInt pStart, PetscInt pEnd)
4560: {
4561:   IS stratumIS;

4563:   PetscFunctionBegin;
4564:   if (pStart >= pEnd) PetscFunctionReturn(PETSC_SUCCESS);
4565:   if (PetscDefined(USE_DEBUG)) {
4566:     PetscInt  qStart, qEnd, numLevels, level;
4567:     PetscBool overlap = PETSC_FALSE;
4568:     PetscCall(DMLabelGetNumValues(label, &numLevels));
4569:     for (level = 0; level < numLevels; level++) {
4570:       PetscCall(DMLabelGetStratumBounds(label, level, &qStart, &qEnd));
4571:       if ((pStart >= qStart && pStart < qEnd) || (pEnd > qStart && pEnd <= qEnd)) {
4572:         overlap = PETSC_TRUE;
4573:         break;
4574:       }
4575:     }
4576:     PetscCheck(!overlap, PETSC_COMM_SELF, PETSC_ERR_PLIB, "New depth %" PetscInt_FMT " range [%" PetscInt_FMT ",%" PetscInt_FMT ") overlaps with depth %" PetscInt_FMT " range [%" PetscInt_FMT ",%" PetscInt_FMT ")", depth, pStart, pEnd, level, qStart, qEnd);
4577:   }
4578:   PetscCall(ISCreateStride(PETSC_COMM_SELF, pEnd - pStart, pStart, 1, &stratumIS));
4579:   PetscCall(DMLabelSetStratumIS(label, depth, stratumIS));
4580:   PetscCall(ISDestroy(&stratumIS));
4581:   PetscFunctionReturn(PETSC_SUCCESS);
4582: }

4584: static PetscErrorCode DMPlexStratify_CellType_Private(DM dm, DMLabel label)
4585: {
4586:   PetscInt *pMin, *pMax;
4587:   PetscInt  pStart, pEnd;
4588:   PetscInt  dmin = PETSC_INT_MAX, dmax = PETSC_INT_MIN;

4590:   PetscFunctionBegin;
4591:   {
4592:     DMLabel label2;

4594:     PetscCall(DMPlexGetCellTypeLabel(dm, &label2));
4595:     PetscCall(PetscObjectViewFromOptions((PetscObject)label2, NULL, "-ct_view"));
4596:   }
4597:   PetscCall(DMPlexGetChart(dm, &pStart, &pEnd));
4598:   for (PetscInt p = pStart; p < pEnd; ++p) {
4599:     DMPolytopeType ct;

4601:     PetscCall(DMPlexGetCellType(dm, p, &ct));
4602:     dmin = PetscMin(DMPolytopeTypeGetDim(ct), dmin);
4603:     dmax = PetscMax(DMPolytopeTypeGetDim(ct), dmax);
4604:   }
4605:   PetscCall(PetscMalloc2(dmax + 1, &pMin, dmax + 1, &pMax));
4606:   for (PetscInt d = dmin; d <= dmax; ++d) {
4607:     pMin[d] = PETSC_INT_MAX;
4608:     pMax[d] = PETSC_INT_MIN;
4609:   }
4610:   for (PetscInt p = pStart; p < pEnd; ++p) {
4611:     DMPolytopeType ct;
4612:     PetscInt       d;

4614:     PetscCall(DMPlexGetCellType(dm, p, &ct));
4615:     d       = DMPolytopeTypeGetDim(ct);
4616:     pMin[d] = PetscMin(p, pMin[d]);
4617:     pMax[d] = PetscMax(p, pMax[d]);
4618:   }
4619:   for (PetscInt d = dmin; d <= dmax; ++d) {
4620:     if (pMin[d] > pMax[d]) continue;
4621:     PetscCall(DMPlexCreateDepthStratum(dm, label, d, pMin[d], pMax[d] + 1));
4622:   }
4623:   PetscCall(PetscFree2(pMin, pMax));
4624:   PetscFunctionReturn(PETSC_SUCCESS);
4625: }

4627: static PetscErrorCode DMPlexStratify_Topological_Private(DM dm, DMLabel label)
4628: {
4629:   PetscInt pStart, pEnd;
4630:   PetscInt numRoots = 0, numLeaves = 0;

4632:   PetscFunctionBegin;
4633:   PetscCall(DMPlexGetChart(dm, &pStart, &pEnd));
4634:   {
4635:     /* Initialize roots and count leaves */
4636:     PetscInt sMin = PETSC_INT_MAX;
4637:     PetscInt sMax = PETSC_INT_MIN;
4638:     PetscInt coneSize, supportSize;

4640:     for (PetscInt p = pStart; p < pEnd; ++p) {
4641:       PetscCall(DMPlexGetConeSize(dm, p, &coneSize));
4642:       PetscCall(DMPlexGetSupportSize(dm, p, &supportSize));
4643:       if (!coneSize && supportSize) {
4644:         sMin = PetscMin(p, sMin);
4645:         sMax = PetscMax(p, sMax);
4646:         ++numRoots;
4647:       } else if (!supportSize && coneSize) {
4648:         ++numLeaves;
4649:       } else if (!supportSize && !coneSize) {
4650:         /* Isolated points */
4651:         sMin = PetscMin(p, sMin);
4652:         sMax = PetscMax(p, sMax);
4653:       }
4654:     }
4655:     PetscCall(DMPlexCreateDepthStratum(dm, label, 0, sMin, sMax + 1));
4656:   }

4658:   if (numRoots + numLeaves == (pEnd - pStart)) {
4659:     PetscInt sMin = PETSC_INT_MAX;
4660:     PetscInt sMax = PETSC_INT_MIN;
4661:     PetscInt coneSize, supportSize;

4663:     for (PetscInt p = pStart; p < pEnd; ++p) {
4664:       PetscCall(DMPlexGetConeSize(dm, p, &coneSize));
4665:       PetscCall(DMPlexGetSupportSize(dm, p, &supportSize));
4666:       if (!supportSize && coneSize) {
4667:         sMin = PetscMin(p, sMin);
4668:         sMax = PetscMax(p, sMax);
4669:       }
4670:     }
4671:     PetscCall(DMPlexCreateDepthStratum(dm, label, 1, sMin, sMax + 1));
4672:   } else {
4673:     PetscInt level = 0;
4674:     PetscInt qStart, qEnd;

4676:     PetscCall(DMLabelGetStratumBounds(label, level, &qStart, &qEnd));
4677:     while (qEnd > qStart) {
4678:       PetscInt sMin = PETSC_INT_MAX;
4679:       PetscInt sMax = PETSC_INT_MIN;

4681:       for (PetscInt q = qStart; q < qEnd; ++q) {
4682:         const PetscInt *support;
4683:         PetscInt        supportSize;

4685:         PetscCall(DMPlexGetSupportSize(dm, q, &supportSize));
4686:         PetscCall(DMPlexGetSupport(dm, q, &support));
4687:         for (PetscInt s = 0; s < supportSize; ++s) {
4688:           sMin = PetscMin(support[s], sMin);
4689:           sMax = PetscMax(support[s], sMax);
4690:         }
4691:       }
4692:       PetscCall(DMLabelGetNumValues(label, &level));
4693:       PetscCall(DMPlexCreateDepthStratum(dm, label, level, sMin, sMax + 1));
4694:       PetscCall(DMLabelGetStratumBounds(label, level, &qStart, &qEnd));
4695:     }
4696:   }
4697:   PetscFunctionReturn(PETSC_SUCCESS);
4698: }

4700: /*@
4701:   DMPlexStratify - Computes the strata for all points in the `DMPLEX`

4703:   Collective

4705:   Input Parameter:
4706: . dm - The `DMPLEX`

4708:   Level: beginner

4710:   Notes:
4711:   The strata group all points of the same grade, and this function calculates the strata. This
4712:   grade can be seen as the height (or depth) of the point in the DAG.

4714:   The DAG for most topologies is a graded poset (https://en.wikipedia.org/wiki/Graded_poset), and
4715:   can be illustrated by a Hasse Diagram (https://en.wikipedia.org/wiki/Hasse_diagram).
4716:   Concretely, `DMPlexStratify()` creates a new label named "depth" containing the depth in the DAG of each point. For cell-vertex
4717:   meshes, vertices are depth 0 and cells are depth 1. For fully interpolated meshes, depth 0 for vertices, 1 for edges, and so on
4718:   until cells have depth equal to the dimension of the mesh. The depth label can be accessed through `DMPlexGetDepthLabel()` or `DMPlexGetDepthStratum()`, or
4719:   manually via `DMGetLabel()`.  The height is defined implicitly by height = maxDimension - depth, and can be accessed
4720:   via `DMPlexGetHeightStratum()`.  For example, cells have height 0 and faces have height 1.

4722:   The depth of a point is calculated by executing a breadth-first search (BFS) on the DAG. This could produce surprising results
4723:   if run on a partially interpolated mesh, meaning one that had some edges and faces, but not others. For example, suppose that
4724:   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
4725:   to interpolate only that one (e0), so that
4726: .vb
4727:   cone(c0) = {e0, v2}
4728:   cone(e0) = {v0, v1}
4729: .ve
4730:   If `DMPlexStratify()` is run on this mesh, it will give depths
4731: .vb
4732:    depth 0 = {v0, v1, v2}
4733:    depth 1 = {e0, c0}
4734: .ve
4735:   where the triangle has been given depth 1, instead of 2, because it is reachable from vertex v2.

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

4739: .seealso: [](ch_unstructured), `DM`, `DMPLEX`, `DMPlexCreate()`, `DMPlexSymmetrize()`, `DMPlexComputeCellTypes()`
4740: @*/
4741: PetscErrorCode DMPlexStratify(DM dm)
4742: {
4743:   DM_Plex  *mesh = (DM_Plex *)dm->data;
4744:   DMLabel   label;
4745:   PetscBool flg = PETSC_FALSE;

4747:   PetscFunctionBegin;
4749:   PetscCall(PetscLogEventBegin(DMPLEX_Stratify, dm, 0, 0, 0));

4751:   // Create depth label
4752:   PetscCall(DMRemoveLabel(dm, "depth", NULL));
4753:   PetscCall(DMCreateLabel(dm, "depth"));
4754:   PetscCall(DMPlexGetDepthLabel(dm, &label));

4756:   PetscCall(PetscOptionsGetBool(NULL, dm->hdr.prefix, "-dm_plex_stratify_celltype", &flg, NULL));
4757:   if (flg) PetscCall(DMPlexStratify_CellType_Private(dm, label));
4758:   else PetscCall(DMPlexStratify_Topological_Private(dm, label));

4760:   { /* just in case there is an empty process */
4761:     PetscInt numValues, maxValues = 0, v;

4763:     PetscCall(DMLabelGetNumValues(label, &numValues));
4764:     PetscCallMPI(MPIU_Allreduce(&numValues, &maxValues, 1, MPIU_INT, MPI_MAX, PetscObjectComm((PetscObject)dm)));
4765:     for (v = numValues; v < maxValues; v++) PetscCall(DMLabelAddStratum(label, v));
4766:   }
4767:   PetscCall(PetscObjectStateGet((PetscObject)label, &mesh->depthState));
4768:   PetscCall(PetscLogEventEnd(DMPLEX_Stratify, dm, 0, 0, 0));
4769:   PetscFunctionReturn(PETSC_SUCCESS);
4770: }

4772: PetscErrorCode DMPlexComputeCellType_Internal(DM dm, PetscInt p, PetscInt pdepth, DMPolytopeType *pt)
4773: {
4774:   DMPolytopeType ct = DM_POLYTOPE_UNKNOWN;
4775:   PetscInt       dim, depth, pheight, coneSize;
4776:   PetscBool      preferTensor;

4778:   PetscFunctionBeginHot;
4779:   PetscCall(DMGetDimension(dm, &dim));
4780:   PetscCall(DMPlexGetDepth(dm, &depth));
4781:   PetscCall(DMPlexGetConeSize(dm, p, &coneSize));
4782:   PetscCall(DMPlexGetInterpolatePreferTensor(dm, &preferTensor));
4783:   pheight = depth - pdepth;
4784:   if (depth <= 1) {
4785:     switch (pdepth) {
4786:     case 0:
4787:       ct = DM_POLYTOPE_POINT;
4788:       break;
4789:     case 1:
4790:       switch (coneSize) {
4791:       case 2:
4792:         ct = DM_POLYTOPE_SEGMENT;
4793:         break;
4794:       case 3:
4795:         ct = DM_POLYTOPE_TRIANGLE;
4796:         break;
4797:       case 4:
4798:         switch (dim) {
4799:         case 2:
4800:           ct = DM_POLYTOPE_QUADRILATERAL;
4801:           break;
4802:         case 3:
4803:           ct = DM_POLYTOPE_TETRAHEDRON;
4804:           break;
4805:         default:
4806:           break;
4807:         }
4808:         break;
4809:       case 5:
4810:         ct = DM_POLYTOPE_PYRAMID;
4811:         break;
4812:       case 6:
4813:         ct = preferTensor ? DM_POLYTOPE_TRI_PRISM_TENSOR : DM_POLYTOPE_TRI_PRISM;
4814:         break;
4815:       case 8:
4816:         ct = DM_POLYTOPE_HEXAHEDRON;
4817:         break;
4818:       default:
4819:         break;
4820:       }
4821:     }
4822:   } else {
4823:     if (pdepth == 0) {
4824:       ct = DM_POLYTOPE_POINT;
4825:     } else if (pheight == 0) {
4826:       switch (dim) {
4827:       case 1:
4828:         switch (coneSize) {
4829:         case 2:
4830:           ct = DM_POLYTOPE_SEGMENT;
4831:           break;
4832:         default:
4833:           break;
4834:         }
4835:         break;
4836:       case 2:
4837:         switch (coneSize) {
4838:         case 3:
4839:           ct = DM_POLYTOPE_TRIANGLE;
4840:           break;
4841:         case 4:
4842:           ct = DM_POLYTOPE_QUADRILATERAL;
4843:           break;
4844:         default:
4845:           break;
4846:         }
4847:         break;
4848:       case 3:
4849:         switch (coneSize) {
4850:         case 4:
4851:           ct = DM_POLYTOPE_TETRAHEDRON;
4852:           break;
4853:         case 5: {
4854:           const PetscInt *cone;
4855:           PetscInt        faceConeSize;

4857:           PetscCall(DMPlexGetCone(dm, p, &cone));
4858:           PetscCall(DMPlexGetConeSize(dm, cone[0], &faceConeSize));
4859:           switch (faceConeSize) {
4860:           case 3:
4861:             ct = preferTensor ? DM_POLYTOPE_TRI_PRISM_TENSOR : DM_POLYTOPE_TRI_PRISM;
4862:             break;
4863:           case 4:
4864:             ct = DM_POLYTOPE_PYRAMID;
4865:             break;
4866:           }
4867:         } break;
4868:         case 6:
4869:           ct = DM_POLYTOPE_HEXAHEDRON;
4870:           break;
4871:         default:
4872:           break;
4873:         }
4874:         break;
4875:       default:
4876:         break;
4877:       }
4878:     } else if (pheight > 0) {
4879:       switch (coneSize) {
4880:       case 2:
4881:         ct = DM_POLYTOPE_SEGMENT;
4882:         break;
4883:       case 3:
4884:         ct = DM_POLYTOPE_TRIANGLE;
4885:         break;
4886:       case 4:
4887:         ct = DM_POLYTOPE_QUADRILATERAL;
4888:         break;
4889:       default:
4890:         break;
4891:       }
4892:     }
4893:   }
4894:   *pt = ct;
4895:   PetscFunctionReturn(PETSC_SUCCESS);
4896: }

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

4901:   Collective

4903:   Input Parameter:
4904: . dm - The `DMPLEX`

4906:   Level: developer

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

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

4915: .seealso: [](ch_unstructured), `DM`, `DMPLEX`, `DMPlexCreate()`, `DMPlexSymmetrize()`, `DMPlexStratify()`, `DMGetLabel()`, `DMCreateLabel()`
4916: @*/
4917: PetscErrorCode DMPlexComputeCellTypes(DM dm)
4918: {
4919:   DM_Plex *mesh;
4920:   DMLabel  ctLabel;
4921:   PetscInt pStart, pEnd, p;

4923:   PetscFunctionBegin;
4925:   mesh = (DM_Plex *)dm->data;
4926:   PetscCall(DMCreateLabel(dm, "celltype"));
4927:   PetscCall(DMPlexGetCellTypeLabel(dm, &ctLabel));
4928:   PetscCall(DMPlexGetChart(dm, &pStart, &pEnd));
4929:   PetscCall(PetscFree(mesh->cellTypes));
4930:   PetscCall(PetscMalloc1(pEnd - pStart, &mesh->cellTypes));
4931:   for (p = pStart; p < pEnd; ++p) {
4932:     DMPolytopeType ct = DM_POLYTOPE_UNKNOWN;
4933:     PetscInt       pdepth;

4935:     PetscCall(DMPlexGetPointDepth(dm, p, &pdepth));
4936:     PetscCall(DMPlexComputeCellType_Internal(dm, p, pdepth, &ct));
4937:     PetscCheck(ct != DM_POLYTOPE_UNKNOWN && ct != DM_POLYTOPE_UNKNOWN_CELL && ct != DM_POLYTOPE_UNKNOWN_FACE, PETSC_COMM_SELF, PETSC_ERR_SUP, "Point %" PetscInt_FMT " has invalid celltype (%s)", p, DMPolytopeTypes[ct]);
4938:     PetscCall(DMLabelSetValue(ctLabel, p, ct));
4939:     mesh->cellTypes[p - pStart].value_as_uint8 = (uint8_t)ct;
4940:   }
4941:   PetscCall(PetscObjectStateGet((PetscObject)ctLabel, &mesh->celltypeState));
4942:   PetscCall(PetscObjectViewFromOptions((PetscObject)ctLabel, NULL, "-dm_plex_celltypes_view"));
4943:   PetscFunctionReturn(PETSC_SUCCESS);
4944: }

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

4949:   Not Collective

4951:   Input Parameters:
4952: + dm        - The `DMPLEX` object
4953: . numPoints - The number of input points for the join
4954: - points    - The input points

4956:   Output Parameters:
4957: + numCoveredPoints - The number of points in the join
4958: - coveredPoints    - The points in the join

4960:   Level: intermediate

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

4965:   Fortran Notes:
4966:   `converedPoints` must be declared with
4967: .vb
4968:   PetscInt, pointer :: coveredPints(:)
4969: .ve

4971: .seealso: [](ch_unstructured), `DM`, `DMPLEX`, `DMPlexRestoreJoin()`, `DMPlexGetMeet()`
4972: @*/
4973: PetscErrorCode DMPlexGetJoin(DM dm, PetscInt numPoints, const PetscInt points[], PetscInt *numCoveredPoints, const PetscInt *coveredPoints[])
4974: {
4975:   DM_Plex  *mesh = (DM_Plex *)dm->data;
4976:   PetscInt *join[2];
4977:   PetscInt  joinSize, i = 0;
4978:   PetscInt  dof, off, p, c, m;
4979:   PetscInt  maxSupportSize;

4981:   PetscFunctionBegin;
4983:   PetscAssertPointer(points, 3);
4984:   PetscAssertPointer(numCoveredPoints, 4);
4985:   PetscAssertPointer(coveredPoints, 5);
4986:   PetscCall(PetscSectionGetMaxDof(mesh->supportSection, &maxSupportSize));
4987:   PetscCall(DMGetWorkArray(dm, maxSupportSize, MPIU_INT, &join[0]));
4988:   PetscCall(DMGetWorkArray(dm, maxSupportSize, MPIU_INT, &join[1]));
4989:   /* Copy in support of first point */
4990:   PetscCall(PetscSectionGetDof(mesh->supportSection, points[0], &dof));
4991:   PetscCall(PetscSectionGetOffset(mesh->supportSection, points[0], &off));
4992:   for (joinSize = 0; joinSize < dof; ++joinSize) join[i][joinSize] = mesh->supports[off + joinSize];
4993:   /* Check each successive support */
4994:   for (p = 1; p < numPoints; ++p) {
4995:     PetscInt newJoinSize = 0;

4997:     PetscCall(PetscSectionGetDof(mesh->supportSection, points[p], &dof));
4998:     PetscCall(PetscSectionGetOffset(mesh->supportSection, points[p], &off));
4999:     for (c = 0; c < dof; ++c) {
5000:       const PetscInt point = mesh->supports[off + c];

5002:       for (m = 0; m < joinSize; ++m) {
5003:         if (point == join[i][m]) {
5004:           join[1 - i][newJoinSize++] = point;
5005:           break;
5006:         }
5007:       }
5008:     }
5009:     joinSize = newJoinSize;
5010:     i        = 1 - i;
5011:   }
5012:   *numCoveredPoints = joinSize;
5013:   *coveredPoints    = join[i];
5014:   PetscCall(DMRestoreWorkArray(dm, maxSupportSize, MPIU_INT, &join[1 - i]));
5015:   PetscFunctionReturn(PETSC_SUCCESS);
5016: }

5018: /*@C
5019:   DMPlexRestoreJoin - Restore an array for the join of the set of points obtained with `DMPlexGetJoin()`

5021:   Not Collective

5023:   Input Parameters:
5024: + dm        - The `DMPLEX` object
5025: . numPoints - The number of input points for the join
5026: - points    - The input points

5028:   Output Parameters:
5029: + numCoveredPoints - The number of points in the join
5030: - coveredPoints    - The points in the join

5032:   Level: intermediate

5034:   Fortran Notes:
5035:   `converedPoints` must be declared with
5036: .vb
5037:   PetscInt, pointer :: coveredPoints(:)
5038: .ve

5040:   Pass `PETSC_NULL_INTEGER` for `numCoveredPoints` if it is not needed

5042: .seealso: [](ch_unstructured), `DM`, `DMPLEX`, `DMPlexGetJoin()`, `DMPlexGetFullJoin()`, `DMPlexGetMeet()`
5043: @*/
5044: PetscErrorCode DMPlexRestoreJoin(DM dm, PetscInt numPoints, const PetscInt points[], PetscInt *numCoveredPoints, const PetscInt *coveredPoints[])
5045: {
5046:   PetscFunctionBegin;
5048:   if (points) PetscAssertPointer(points, 3);
5049:   if (numCoveredPoints) PetscAssertPointer(numCoveredPoints, 4);
5050:   PetscAssertPointer(coveredPoints, 5);
5051:   PetscCall(DMRestoreWorkArray(dm, 0, MPIU_INT, (void *)coveredPoints));
5052:   if (numCoveredPoints) *numCoveredPoints = 0;
5053:   PetscFunctionReturn(PETSC_SUCCESS);
5054: }

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

5059:   Not Collective

5061:   Input Parameters:
5062: + dm        - The `DMPLEX` object
5063: . numPoints - The number of input points for the join
5064: - points    - The input points, its length is `numPoints`

5066:   Output Parameters:
5067: + numCoveredPoints - The number of points in the join
5068: - coveredPoints    - The points in the join, its length is `numCoveredPoints`

5070:   Level: intermediate

5072:   Fortran Notes:
5073: .vb
5074:   PetscInt, pointer :: coveredPints(:)
5075: .ve

5077: .seealso: [](ch_unstructured), `DM`, `DMPLEX`, `DMPlexGetJoin()`, `DMPlexRestoreJoin()`, `DMPlexGetMeet()`
5078: @*/
5079: PetscErrorCode DMPlexGetFullJoin(DM dm, PetscInt numPoints, const PetscInt points[], PetscInt *numCoveredPoints, const PetscInt *coveredPoints[])
5080: {
5081:   PetscInt *offsets, **closures;
5082:   PetscInt *join[2];
5083:   PetscInt  depth = 0, maxSize, joinSize = 0, i = 0;
5084:   PetscInt  p, d, c, m, ms;

5086:   PetscFunctionBegin;
5088:   PetscAssertPointer(points, 3);
5089:   PetscAssertPointer(numCoveredPoints, 4);
5090:   PetscAssertPointer(coveredPoints, 5);

5092:   PetscCall(DMPlexGetDepth(dm, &depth));
5093:   PetscCall(PetscCalloc1(numPoints, &closures));
5094:   PetscCall(DMGetWorkArray(dm, numPoints * (depth + 2), MPIU_INT, &offsets));
5095:   PetscCall(DMPlexGetMaxSizes(dm, NULL, &ms));
5096:   maxSize = (ms > 1) ? ((PetscPowInt(ms, depth + 1) - 1) / (ms - 1)) : depth + 1;
5097:   PetscCall(DMGetWorkArray(dm, maxSize, MPIU_INT, &join[0]));
5098:   PetscCall(DMGetWorkArray(dm, maxSize, MPIU_INT, &join[1]));

5100:   for (p = 0; p < numPoints; ++p) {
5101:     PetscInt closureSize;

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

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

5109:       PetscCall(DMPlexGetDepthStratum(dm, d, &pStart, &pEnd));
5110:       for (i = offsets[p * (depth + 2) + d]; i < closureSize; ++i) {
5111:         if ((pStart > closures[p][i * 2]) || (pEnd <= closures[p][i * 2])) {
5112:           offsets[p * (depth + 2) + d + 1] = i;
5113:           break;
5114:         }
5115:       }
5116:       if (i == closureSize) offsets[p * (depth + 2) + d + 1] = i;
5117:     }
5118:     PetscCheck(offsets[p * (depth + 2) + depth + 1] == closureSize, PetscObjectComm((PetscObject)dm), PETSC_ERR_PLIB, "Total size of closure %" PetscInt_FMT " should be %" PetscInt_FMT, offsets[p * (depth + 2) + depth + 1], closureSize);
5119:   }
5120:   for (d = 0; d < depth + 1; ++d) {
5121:     PetscInt dof;

5123:     /* Copy in support of first point */
5124:     dof = offsets[d + 1] - offsets[d];
5125:     for (joinSize = 0; joinSize < dof; ++joinSize) join[i][joinSize] = closures[0][(offsets[d] + joinSize) * 2];
5126:     /* Check each successive cone */
5127:     for (p = 1; p < numPoints && joinSize; ++p) {
5128:       PetscInt newJoinSize = 0;

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

5134:         for (m = 0; m < joinSize; ++m) {
5135:           if (point == join[i][m]) {
5136:             join[1 - i][newJoinSize++] = point;
5137:             break;
5138:           }
5139:         }
5140:       }
5141:       joinSize = newJoinSize;
5142:       i        = 1 - i;
5143:     }
5144:     if (joinSize) break;
5145:   }
5146:   *numCoveredPoints = joinSize;
5147:   *coveredPoints    = join[i];
5148:   for (p = 0; p < numPoints; ++p) PetscCall(DMPlexRestoreTransitiveClosure(dm, points[p], PETSC_FALSE, NULL, &closures[p]));
5149:   PetscCall(PetscFree(closures));
5150:   PetscCall(DMRestoreWorkArray(dm, numPoints * (depth + 2), MPIU_INT, &offsets));
5151:   PetscCall(DMRestoreWorkArray(dm, ms, MPIU_INT, &join[1 - i]));
5152:   PetscFunctionReturn(PETSC_SUCCESS);
5153: }

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

5158:   Not Collective

5160:   Input Parameters:
5161: + dm        - The `DMPLEX` object
5162: . numPoints - The number of input points for the meet
5163: - points    - The input points, of length `numPoints`

5165:   Output Parameters:
5166: + numCoveringPoints - The number of points in the meet
5167: - coveringPoints    - The points in the meet, of length `numCoveringPoints`

5169:   Level: intermediate

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

5174:   Fortran Note:
5175:   `coveringPoints` must be declared with
5176: .vb
5177:   PetscInt, pointer :: coveringPoints(:)
5178: .ve

5180: .seealso: [](ch_unstructured), `DM`, `DMPLEX`, `DMPlexRestoreMeet()`, `DMPlexGetJoin()`
5181: @*/
5182: PetscErrorCode DMPlexGetMeet(DM dm, PetscInt numPoints, const PetscInt points[], PetscInt *numCoveringPoints, const PetscInt *coveringPoints[])
5183: {
5184:   DM_Plex  *mesh = (DM_Plex *)dm->data;
5185:   PetscInt *meet[2];
5186:   PetscInt  meetSize, i = 0;
5187:   PetscInt  dof, off, p, c, m;
5188:   PetscInt  maxConeSize;

5190:   PetscFunctionBegin;
5192:   PetscAssertPointer(points, 3);
5193:   PetscAssertPointer(numCoveringPoints, 4);
5194:   PetscAssertPointer(coveringPoints, 5);
5195:   PetscCall(PetscSectionGetMaxDof(mesh->coneSection, &maxConeSize));
5196:   PetscCall(DMGetWorkArray(dm, maxConeSize, MPIU_INT, &meet[0]));
5197:   PetscCall(DMGetWorkArray(dm, maxConeSize, MPIU_INT, &meet[1]));
5198:   /* Copy in cone of first point */
5199:   PetscCall(PetscSectionGetDof(mesh->coneSection, points[0], &dof));
5200:   PetscCall(PetscSectionGetOffset(mesh->coneSection, points[0], &off));
5201:   for (meetSize = 0; meetSize < dof; ++meetSize) meet[i][meetSize] = mesh->cones[off + meetSize];
5202:   /* Check each successive cone */
5203:   for (p = 1; p < numPoints; ++p) {
5204:     PetscInt newMeetSize = 0;

5206:     PetscCall(PetscSectionGetDof(mesh->coneSection, points[p], &dof));
5207:     PetscCall(PetscSectionGetOffset(mesh->coneSection, points[p], &off));
5208:     for (c = 0; c < dof; ++c) {
5209:       const PetscInt point = mesh->cones[off + c];

5211:       for (m = 0; m < meetSize; ++m) {
5212:         if (point == meet[i][m]) {
5213:           meet[1 - i][newMeetSize++] = point;
5214:           break;
5215:         }
5216:       }
5217:     }
5218:     meetSize = newMeetSize;
5219:     i        = 1 - i;
5220:   }
5221:   *numCoveringPoints = meetSize;
5222:   *coveringPoints    = meet[i];
5223:   PetscCall(DMRestoreWorkArray(dm, maxConeSize, MPIU_INT, &meet[1 - i]));
5224:   PetscFunctionReturn(PETSC_SUCCESS);
5225: }

5227: /*@C
5228:   DMPlexRestoreMeet - Restore an array for the meet of the set of points obtained with `DMPlexGetMeet()`

5230:   Not Collective

5232:   Input Parameters:
5233: + dm        - The `DMPLEX` object
5234: . numPoints - The number of input points for the meet
5235: - points    - The input points

5237:   Output Parameters:
5238: + numCoveredPoints - The number of points in the meet
5239: - coveredPoints    - The points in the meet

5241:   Level: intermediate

5243: .seealso: [](ch_unstructured), `DM`, `DMPLEX`, `DMPlexGetMeet()`, `DMPlexGetFullMeet()`, `DMPlexGetJoin()`
5244: @*/
5245: PetscErrorCode DMPlexRestoreMeet(DM dm, PetscInt numPoints, const PetscInt points[], PetscInt *numCoveredPoints, const PetscInt *coveredPoints[])
5246: {
5247:   PetscFunctionBegin;
5249:   if (points) PetscAssertPointer(points, 3);
5250:   if (numCoveredPoints) PetscAssertPointer(numCoveredPoints, 4);
5251:   PetscAssertPointer(coveredPoints, 5);
5252:   PetscCall(DMRestoreWorkArray(dm, 0, MPIU_INT, (void *)coveredPoints));
5253:   if (numCoveredPoints) *numCoveredPoints = 0;
5254:   PetscFunctionReturn(PETSC_SUCCESS);
5255: }

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

5260:   Not Collective

5262:   Input Parameters:
5263: + dm        - The `DMPLEX` object
5264: . numPoints - The number of input points for the meet
5265: - points    - The input points, of length  `numPoints`

5267:   Output Parameters:
5268: + numCoveredPoints - The number of points in the meet
5269: - coveredPoints    - The points in the meet, of length  `numCoveredPoints`

5271:   Level: intermediate

5273:   Fortran Notes:
5274:   `coveredPoints` must be declared with
5275: .vb
5276:   PetscInt, pointer :: coveredPoints(:)
5277: .ve

5279: .seealso: [](ch_unstructured), `DM`, `DMPLEX`, `DMPlexGetMeet()`, `DMPlexRestoreMeet()`, `DMPlexGetJoin()`
5280: @*/
5281: PetscErrorCode DMPlexGetFullMeet(DM dm, PetscInt numPoints, const PetscInt points[], PetscInt *numCoveredPoints, const PetscInt *coveredPoints[])
5282: {
5283:   PetscInt *offsets, **closures;
5284:   PetscInt *meet[2];
5285:   PetscInt  height = 0, maxSize, meetSize = 0, i = 0;
5286:   PetscInt  p, h, c, m, mc;

5288:   PetscFunctionBegin;
5290:   PetscAssertPointer(points, 3);
5291:   PetscAssertPointer(numCoveredPoints, 4);
5292:   PetscAssertPointer(coveredPoints, 5);

5294:   PetscCall(DMPlexGetDepth(dm, &height));
5295:   PetscCall(PetscMalloc1(numPoints, &closures));
5296:   PetscCall(DMGetWorkArray(dm, numPoints * (height + 2), MPIU_INT, &offsets));
5297:   PetscCall(DMPlexGetMaxSizes(dm, &mc, NULL));
5298:   maxSize = (mc > 1) ? ((PetscPowInt(mc, height + 1) - 1) / (mc - 1)) : height + 1;
5299:   PetscCall(DMGetWorkArray(dm, maxSize, MPIU_INT, &meet[0]));
5300:   PetscCall(DMGetWorkArray(dm, maxSize, MPIU_INT, &meet[1]));

5302:   for (p = 0; p < numPoints; ++p) {
5303:     PetscInt closureSize;

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

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

5311:       PetscCall(DMPlexGetHeightStratum(dm, h, &pStart, &pEnd));
5312:       for (i = offsets[p * (height + 2) + h]; i < closureSize; ++i) {
5313:         if ((pStart > closures[p][i * 2]) || (pEnd <= closures[p][i * 2])) {
5314:           offsets[p * (height + 2) + h + 1] = i;
5315:           break;
5316:         }
5317:       }
5318:       if (i == closureSize) offsets[p * (height + 2) + h + 1] = i;
5319:     }
5320:     PetscCheck(offsets[p * (height + 2) + height + 1] == closureSize, PetscObjectComm((PetscObject)dm), PETSC_ERR_PLIB, "Total size of closure %" PetscInt_FMT " should be %" PetscInt_FMT, offsets[p * (height + 2) + height + 1], closureSize);
5321:   }
5322:   for (h = 0; h < height + 1; ++h) {
5323:     PetscInt dof;

5325:     /* Copy in cone of first point */
5326:     dof = offsets[h + 1] - offsets[h];
5327:     for (meetSize = 0; meetSize < dof; ++meetSize) meet[i][meetSize] = closures[0][(offsets[h] + meetSize) * 2];
5328:     /* Check each successive cone */
5329:     for (p = 1; p < numPoints && meetSize; ++p) {
5330:       PetscInt newMeetSize = 0;

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

5336:         for (m = 0; m < meetSize; ++m) {
5337:           if (point == meet[i][m]) {
5338:             meet[1 - i][newMeetSize++] = point;
5339:             break;
5340:           }
5341:         }
5342:       }
5343:       meetSize = newMeetSize;
5344:       i        = 1 - i;
5345:     }
5346:     if (meetSize) break;
5347:   }
5348:   *numCoveredPoints = meetSize;
5349:   *coveredPoints    = meet[i];
5350:   for (p = 0; p < numPoints; ++p) PetscCall(DMPlexRestoreTransitiveClosure(dm, points[p], PETSC_TRUE, NULL, &closures[p]));
5351:   PetscCall(PetscFree(closures));
5352:   PetscCall(DMRestoreWorkArray(dm, numPoints * (height + 2), MPIU_INT, &offsets));
5353:   PetscCall(DMRestoreWorkArray(dm, mc, MPIU_INT, &meet[1 - i]));
5354:   PetscFunctionReturn(PETSC_SUCCESS);
5355: }

5357: /*@
5358:   DMPlexEqual - Determine if two `DM` have the same topology

5360:   Not Collective

5362:   Input Parameters:
5363: + dmA - A `DMPLEX` object
5364: - dmB - A `DMPLEX` object

5366:   Output Parameter:
5367: . equal - `PETSC_TRUE` if the topologies are identical

5369:   Level: intermediate

5371:   Note:
5372:   We are not solving graph isomorphism, so we do not permute.

5374: .seealso: [](ch_unstructured), `DM`, `DMPLEX`, `DMPlexGetCone()`
5375: @*/
5376: PetscErrorCode DMPlexEqual(DM dmA, DM dmB, PetscBool *equal)
5377: {
5378:   PetscInt depth, depthB, pStart, pEnd, pStartB, pEndB, p;

5380:   PetscFunctionBegin;
5383:   PetscAssertPointer(equal, 3);

5385:   *equal = PETSC_FALSE;
5386:   PetscCall(DMPlexGetDepth(dmA, &depth));
5387:   PetscCall(DMPlexGetDepth(dmB, &depthB));
5388:   if (depth != depthB) PetscFunctionReturn(PETSC_SUCCESS);
5389:   PetscCall(DMPlexGetChart(dmA, &pStart, &pEnd));
5390:   PetscCall(DMPlexGetChart(dmB, &pStartB, &pEndB));
5391:   if ((pStart != pStartB) || (pEnd != pEndB)) PetscFunctionReturn(PETSC_SUCCESS);
5392:   for (p = pStart; p < pEnd; ++p) {
5393:     const PetscInt *cone, *coneB, *ornt, *orntB, *support, *supportB;
5394:     PetscInt        coneSize, coneSizeB, c, supportSize, supportSizeB, s;

5396:     PetscCall(DMPlexGetConeSize(dmA, p, &coneSize));
5397:     PetscCall(DMPlexGetCone(dmA, p, &cone));
5398:     PetscCall(DMPlexGetConeOrientation(dmA, p, &ornt));
5399:     PetscCall(DMPlexGetConeSize(dmB, p, &coneSizeB));
5400:     PetscCall(DMPlexGetCone(dmB, p, &coneB));
5401:     PetscCall(DMPlexGetConeOrientation(dmB, p, &orntB));
5402:     if (coneSize != coneSizeB) PetscFunctionReturn(PETSC_SUCCESS);
5403:     for (c = 0; c < coneSize; ++c) {
5404:       if (cone[c] != coneB[c]) PetscFunctionReturn(PETSC_SUCCESS);
5405:       if (ornt[c] != orntB[c]) PetscFunctionReturn(PETSC_SUCCESS);
5406:     }
5407:     PetscCall(DMPlexGetSupportSize(dmA, p, &supportSize));
5408:     PetscCall(DMPlexGetSupport(dmA, p, &support));
5409:     PetscCall(DMPlexGetSupportSize(dmB, p, &supportSizeB));
5410:     PetscCall(DMPlexGetSupport(dmB, p, &supportB));
5411:     if (supportSize != supportSizeB) PetscFunctionReturn(PETSC_SUCCESS);
5412:     for (s = 0; s < supportSize; ++s) {
5413:       if (support[s] != supportB[s]) PetscFunctionReturn(PETSC_SUCCESS);
5414:     }
5415:   }
5416:   *equal = PETSC_TRUE;
5417:   PetscFunctionReturn(PETSC_SUCCESS);
5418: }

5420: /*@
5421:   DMPlexGetNumFaceVertices - Returns the number of vertices on a face

5423:   Not Collective

5425:   Input Parameters:
5426: + dm         - The `DMPLEX`
5427: . cellDim    - The cell dimension
5428: - numCorners - The number of vertices on a cell

5430:   Output Parameter:
5431: . numFaceVertices - The number of vertices on a face

5433:   Level: developer

5435:   Note:
5436:   Of course this can only work for a restricted set of symmetric shapes

5438: .seealso: [](ch_unstructured), `DM`, `DMPLEX`, `DMPlexGetCone()`
5439: @*/
5440: PetscErrorCode DMPlexGetNumFaceVertices(DM dm, PetscInt cellDim, PetscInt numCorners, PetscInt *numFaceVertices)
5441: {
5442:   MPI_Comm comm;

5444:   PetscFunctionBegin;
5445:   PetscCall(PetscObjectGetComm((PetscObject)dm, &comm));
5446:   PetscAssertPointer(numFaceVertices, 4);
5447:   switch (cellDim) {
5448:   case 0:
5449:     *numFaceVertices = 0;
5450:     break;
5451:   case 1:
5452:     *numFaceVertices = 1;
5453:     break;
5454:   case 2:
5455:     switch (numCorners) {
5456:     case 3:                 /* triangle */
5457:       *numFaceVertices = 2; /* Edge has 2 vertices */
5458:       break;
5459:     case 4:                 /* quadrilateral */
5460:       *numFaceVertices = 2; /* Edge has 2 vertices */
5461:       break;
5462:     case 6:                 /* quadratic triangle, tri and quad cohesive Lagrange cells */
5463:       *numFaceVertices = 3; /* Edge has 3 vertices */
5464:       break;
5465:     case 9:                 /* quadratic quadrilateral, quadratic quad cohesive Lagrange cells */
5466:       *numFaceVertices = 3; /* Edge has 3 vertices */
5467:       break;
5468:     default:
5469:       SETERRQ(comm, PETSC_ERR_ARG_OUTOFRANGE, "Invalid number of face corners %" PetscInt_FMT " for dimension %" PetscInt_FMT, numCorners, cellDim);
5470:     }
5471:     break;
5472:   case 3:
5473:     switch (numCorners) {
5474:     case 4:                 /* tetradehdron */
5475:       *numFaceVertices = 3; /* Face has 3 vertices */
5476:       break;
5477:     case 6:                 /* tet cohesive cells */
5478:       *numFaceVertices = 4; /* Face has 4 vertices */
5479:       break;
5480:     case 8:                 /* hexahedron */
5481:       *numFaceVertices = 4; /* Face has 4 vertices */
5482:       break;
5483:     case 9:                 /* tet cohesive Lagrange cells */
5484:       *numFaceVertices = 6; /* Face has 6 vertices */
5485:       break;
5486:     case 10:                /* quadratic tetrahedron */
5487:       *numFaceVertices = 6; /* Face has 6 vertices */
5488:       break;
5489:     case 12:                /* hex cohesive Lagrange cells */
5490:       *numFaceVertices = 6; /* Face has 6 vertices */
5491:       break;
5492:     case 18:                /* quadratic tet cohesive Lagrange cells */
5493:       *numFaceVertices = 6; /* Face has 6 vertices */
5494:       break;
5495:     case 27:                /* quadratic hexahedron, quadratic hex cohesive Lagrange cells */
5496:       *numFaceVertices = 9; /* Face has 9 vertices */
5497:       break;
5498:     default:
5499:       SETERRQ(comm, PETSC_ERR_ARG_OUTOFRANGE, "Invalid number of face corners %" PetscInt_FMT " for dimension %" PetscInt_FMT, numCorners, cellDim);
5500:     }
5501:     break;
5502:   default:
5503:     SETERRQ(comm, PETSC_ERR_ARG_OUTOFRANGE, "Invalid cell dimension %" PetscInt_FMT, cellDim);
5504:   }
5505:   PetscFunctionReturn(PETSC_SUCCESS);
5506: }

5508: /*@
5509:   DMPlexGetDepthLabel - Get the `DMLabel` recording the depth of each point

5511:   Not Collective

5513:   Input Parameter:
5514: . dm - The `DMPLEX` object

5516:   Output Parameter:
5517: . depthLabel - The `DMLabel` recording point depth

5519:   Level: developer

5521: .seealso: [](ch_unstructured), `DM`, `DMPLEX`, `DMPlexGetDepth()`, `DMPlexGetHeightStratum()`, `DMPlexGetDepthStratum()`, `DMPlexGetPointDepth()`
5522: @*/
5523: PetscErrorCode DMPlexGetDepthLabel(DM dm, DMLabel *depthLabel)
5524: {
5525:   PetscFunctionBegin;
5527:   PetscAssertPointer(depthLabel, 2);
5528:   *depthLabel = dm->depthLabel;
5529:   PetscFunctionReturn(PETSC_SUCCESS);
5530: }

5532: /*@
5533:   DMPlexGetDepth - Get the depth of the DAG representing this mesh

5535:   Not Collective

5537:   Input Parameter:
5538: . dm - The `DMPLEX` object

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

5543:   Level: developer

5545:   Notes:
5546:   This returns maximum of point depths over all points, i.e. maximum value of the label returned by `DMPlexGetDepthLabel()`.

5548:   The point depth is described more in detail in `DMPlexGetDepthStratum()`.

5550:   An empty mesh gives -1.

5552: .seealso: [](ch_unstructured), `DM`, `DMPLEX`, `DMPlexGetDepthLabel()`, `DMPlexGetDepthStratum()`, `DMPlexGetPointDepth()`, `DMPlexSymmetrize()`
5553: @*/
5554: PetscErrorCode DMPlexGetDepth(DM dm, PetscInt *depth)
5555: {
5556:   DM_Plex *mesh = (DM_Plex *)dm->data;
5557:   DMLabel  label;
5558:   PetscInt d = -1;

5560:   PetscFunctionBegin;
5562:   PetscAssertPointer(depth, 2);
5563:   if (mesh->tr) {
5564:     PetscCall(DMPlexTransformGetDepth(mesh->tr, depth));
5565:   } else {
5566:     PetscCall(DMPlexGetDepthLabel(dm, &label));
5567:     // Allow missing depths
5568:     if (label) PetscCall(DMLabelGetValueBounds(label, NULL, &d));
5569:     *depth = d;
5570:   }
5571:   PetscFunctionReturn(PETSC_SUCCESS);
5572: }

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

5577:   Not Collective

5579:   Input Parameters:
5580: + dm    - The `DMPLEX` object
5581: - depth - The requested depth

5583:   Output Parameters:
5584: + start - The first point at this `depth`
5585: - end   - One beyond the last point at this `depth`

5587:   Level: developer

5589:   Notes:
5590:   Depth indexing is related to topological dimension.  Depth stratum 0 contains the lowest topological dimension points,
5591:   often "vertices".  If the mesh is "interpolated" (see `DMPlexInterpolate()`), then depth stratum 1 contains the next
5592:   higher dimension, e.g., "edges".

5594: .seealso: [](ch_unstructured), `DM`, `DMPLEX`, `DMPlexGetHeightStratum()`, `DMPlexGetCellTypeStratum()`, `DMPlexGetDepth()`, `DMPlexGetDepthLabel()`, `DMPlexGetPointDepth()`, `DMPlexSymmetrize()`, `DMPlexInterpolate()`
5595: @*/
5596: PetscErrorCode DMPlexGetDepthStratum(DM dm, PetscInt depth, PeOp PetscInt *start, PeOp PetscInt *end)
5597: {
5598:   DM_Plex *mesh = (DM_Plex *)dm->data;
5599:   DMLabel  label;
5600:   PetscInt pStart, pEnd;

5602:   PetscFunctionBegin;
5604:   if (start) {
5605:     PetscAssertPointer(start, 3);
5606:     *start = 0;
5607:   }
5608:   if (end) {
5609:     PetscAssertPointer(end, 4);
5610:     *end = 0;
5611:   }
5612:   PetscCall(DMPlexGetChart(dm, &pStart, &pEnd));
5613:   if (pStart == pEnd) PetscFunctionReturn(PETSC_SUCCESS);
5614:   if (depth < 0) {
5615:     if (start) *start = pStart;
5616:     if (end) *end = pEnd;
5617:     PetscFunctionReturn(PETSC_SUCCESS);
5618:   }
5619:   if (mesh->tr) {
5620:     PetscCall(DMPlexTransformGetDepthStratum(mesh->tr, depth, start, end));
5621:   } else {
5622:     PetscCall(DMPlexGetDepthLabel(dm, &label));
5623:     PetscCheck(label, PetscObjectComm((PetscObject)dm), PETSC_ERR_ARG_WRONG, "No label named depth was found");
5624:     PetscCall(DMLabelGetStratumBounds(label, depth, start, end));
5625:   }
5626:   PetscFunctionReturn(PETSC_SUCCESS);
5627: }

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

5632:   Not Collective

5634:   Input Parameters:
5635: + dm     - The `DMPLEX` object
5636: - height - The requested height

5638:   Output Parameters:
5639: + start - The first point at this `height`
5640: - end   - One beyond the last point at this `height`

5642:   Level: developer

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

5649: .seealso: [](ch_unstructured), `DM`, `DMPLEX`, `DMPlexGetDepthStratum()`, `DMPlexGetCellTypeStratum()`, `DMPlexGetDepth()`, `DMPlexGetPointHeight()`
5650: @*/
5651: PetscErrorCode DMPlexGetHeightStratum(DM dm, PetscInt height, PeOp PetscInt *start, PeOp PetscInt *end)
5652: {
5653:   DMLabel  label;
5654:   PetscInt depth, pStart, pEnd;

5656:   PetscFunctionBegin;
5658:   if (start) {
5659:     PetscAssertPointer(start, 3);
5660:     *start = 0;
5661:   }
5662:   if (end) {
5663:     PetscAssertPointer(end, 4);
5664:     *end = 0;
5665:   }
5666:   PetscCall(DMPlexGetChart(dm, &pStart, &pEnd));
5667:   if (pStart == pEnd) PetscFunctionReturn(PETSC_SUCCESS);
5668:   if (height < 0) {
5669:     if (start) *start = pStart;
5670:     if (end) *end = pEnd;
5671:     PetscFunctionReturn(PETSC_SUCCESS);
5672:   }
5673:   PetscCall(DMPlexGetDepthLabel(dm, &label));
5674:   if (label) PetscCall(DMLabelGetNumValues(label, &depth));
5675:   else PetscCall(DMGetDimension(dm, &depth));
5676:   PetscCheck(depth >= 0, PetscObjectComm((PetscObject)dm), PETSC_ERR_ARG_WRONG, "Depth not yet computed");
5677:   PetscCall(DMPlexGetDepthStratum(dm, depth - 1 - height, start, end));
5678:   PetscFunctionReturn(PETSC_SUCCESS);
5679: }

5681: /*@
5682:   DMPlexGetPointDepth - Get the `depth` of a given point

5684:   Not Collective

5686:   Input Parameters:
5687: + dm    - The `DMPLEX` object
5688: - point - The point

5690:   Output Parameter:
5691: . depth - The depth of the `point`

5693:   Level: intermediate

5695: .seealso: [](ch_unstructured), `DM`, `DMPLEX`, `DMPlexGetCellType()`, `DMPlexGetDepthLabel()`, `DMPlexGetDepth()`, `DMPlexGetPointHeight()`
5696: @*/
5697: PetscErrorCode DMPlexGetPointDepth(DM dm, PetscInt point, PetscInt *depth)
5698: {
5699:   PetscFunctionBegin;
5701:   PetscAssertPointer(depth, 3);
5702:   PetscCall(DMLabelGetValue(dm->depthLabel, point, depth));
5703:   PetscFunctionReturn(PETSC_SUCCESS);
5704: }

5706: /*@
5707:   DMPlexGetPointHeight - Get the `height` of a given point

5709:   Not Collective

5711:   Input Parameters:
5712: + dm    - The `DMPLEX` object
5713: - point - The point

5715:   Output Parameter:
5716: . height - The height of the `point`

5718:   Level: intermediate

5720: .seealso: [](ch_unstructured), `DM`, `DMPLEX`, `DMPlexGetCellType()`, `DMPlexGetDepthLabel()`, `DMPlexGetDepth()`, `DMPlexGetPointDepth()`
5721: @*/
5722: PetscErrorCode DMPlexGetPointHeight(DM dm, PetscInt point, PetscInt *height)
5723: {
5724:   PetscInt n, pDepth;

5726:   PetscFunctionBegin;
5728:   PetscAssertPointer(height, 3);
5729:   PetscCall(DMLabelGetNumValues(dm->depthLabel, &n));
5730:   PetscCall(DMLabelGetValue(dm->depthLabel, point, &pDepth));
5731:   *height = n - 1 - pDepth; /* DAG depth is n-1 */
5732:   PetscFunctionReturn(PETSC_SUCCESS);
5733: }

5735: /*@
5736:   DMPlexGetCellTypeLabel - Get the `DMLabel` recording the polytope type of each cell

5738:   Not Collective

5740:   Input Parameter:
5741: . dm - The `DMPLEX` object

5743:   Output Parameter:
5744: . celltypeLabel - The `DMLabel` recording cell polytope type

5746:   Level: developer

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

5752: .seealso: [](ch_unstructured), `DM`, `DMPLEX`, `DMPlexGetCellType()`, `DMPlexGetDepthLabel()`, `DMCreateLabel()`
5753: @*/
5754: PetscErrorCode DMPlexGetCellTypeLabel(DM dm, DMLabel *celltypeLabel)
5755: {
5756:   PetscFunctionBegin;
5758:   PetscAssertPointer(celltypeLabel, 2);
5759:   if (!dm->celltypeLabel) PetscCall(DMPlexComputeCellTypes(dm));
5760:   *celltypeLabel = dm->celltypeLabel;
5761:   PetscFunctionReturn(PETSC_SUCCESS);
5762: }

5764: /*@
5765:   DMPlexGetCellType - Get the polytope type of a given cell

5767:   Not Collective

5769:   Input Parameters:
5770: + dm   - The `DMPLEX` object
5771: - cell - The cell

5773:   Output Parameter:
5774: . celltype - The polytope type of the cell

5776:   Level: intermediate

5778: .seealso: [](ch_unstructured), `DM`, `DMPLEX`, `DMPolytopeType`, `DMPlexGetCellTypeLabel()`, `DMPlexGetDepthLabel()`, `DMPlexGetDepth()`
5779: @*/
5780: PetscErrorCode DMPlexGetCellType(DM dm, PetscInt cell, DMPolytopeType *celltype)
5781: {
5782:   DM_Plex *mesh = (DM_Plex *)dm->data;
5783:   DMLabel  label;
5784:   PetscInt ct;

5786:   PetscFunctionBegin;
5788:   PetscAssertPointer(celltype, 3);
5789:   if (mesh->tr) {
5790:     PetscCall(DMPlexTransformGetCellType(mesh->tr, cell, celltype));
5791:   } else {
5792:     PetscInt pStart, pEnd;

5794:     PetscCall(PetscSectionGetChart(mesh->coneSection, &pStart, NULL));
5795:     if (!mesh->cellTypes) { /* XXX remove? optimize? */
5796:       PetscCall(PetscSectionGetChart(mesh->coneSection, NULL, &pEnd));
5797:       if (pEnd <= pStart) {
5798:         *celltype = DM_POLYTOPE_UNKNOWN;
5799:         PetscFunctionReturn(PETSC_SUCCESS);
5800:       }
5801:       PetscCall(PetscMalloc1(pEnd - pStart, &mesh->cellTypes));
5802:       PetscCall(DMPlexGetCellTypeLabel(dm, &label));
5803:       for (PetscInt p = pStart; p < pEnd; p++) {
5804:         PetscCall(DMLabelGetValue(label, p, &ct));
5805:         mesh->cellTypes[p - pStart].value_as_uint8 = (uint8_t)ct;
5806:       }
5807:     }
5808:     *celltype = (DMPolytopeType)mesh->cellTypes[cell - pStart].value_as_uint8;
5809:     if (PetscDefined(USE_DEBUG)) {
5810:       PetscCall(DMPlexGetCellTypeLabel(dm, &label));
5811:       PetscCall(DMLabelGetValue(label, cell, &ct));
5812:       PetscCheck(ct >= 0, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Cell %" PetscInt_FMT " has not been assigned a cell type", cell);
5813:       PetscCheck(ct == (PetscInt)*celltype, PETSC_COMM_SELF, PETSC_ERR_PLIB, "Invalid cellType for %" PetscInt_FMT ": %d != %" PetscInt_FMT, cell, (int)*celltype, ct);
5814:     }
5815:   }
5816:   PetscFunctionReturn(PETSC_SUCCESS);
5817: }

5819: /*@
5820:   DMPlexSetCellType - Set the polytope type of a given cell

5822:   Not Collective

5824:   Input Parameters:
5825: + dm       - The `DMPLEX` object
5826: . cell     - The cell
5827: - celltype - The polytope type of the cell

5829:   Level: advanced

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

5837: .seealso: [](ch_unstructured), `DM`, `DMPLEX`, `DMPlexGetCellTypeLabel()`, `DMPlexGetDepthLabel()`, `DMPlexGetDepth()`, `DMPlexComputeCellTypes()`, `DMCreateLabel()`
5838: @*/
5839: PetscErrorCode DMPlexSetCellType(DM dm, PetscInt cell, DMPolytopeType celltype)
5840: {
5841:   DM_Plex *mesh = (DM_Plex *)dm->data;
5842:   DMLabel  label;
5843:   PetscInt pStart, pEnd;

5845:   PetscFunctionBegin;
5847:   PetscCall(PetscSectionGetChart(mesh->coneSection, &pStart, &pEnd));
5848:   PetscCall(DMPlexGetCellTypeLabel(dm, &label));
5849:   PetscCall(DMLabelSetValue(label, cell, celltype));
5850:   if (!mesh->cellTypes) PetscCall(PetscMalloc1(pEnd - pStart, &mesh->cellTypes));
5851:   mesh->cellTypes[cell - pStart].value_as_uint8 = (uint8_t)celltype;
5852:   PetscFunctionReturn(PETSC_SUCCESS);
5853: }

5855: PetscErrorCode DMCreateCoordinateDM_Plex(DM dm, DM *cdm)
5856: {
5857:   PetscSection section;
5858:   PetscInt     maxHeight;
5859:   const char  *prefix;

5861:   PetscFunctionBegin;
5862:   PetscCall(DMClone(dm, cdm));
5863:   PetscCall(PetscObjectGetOptionsPrefix((PetscObject)dm, &prefix));
5864:   PetscCall(PetscObjectSetOptionsPrefix((PetscObject)*cdm, prefix));
5865:   PetscCall(PetscObjectAppendOptionsPrefix((PetscObject)*cdm, "cdm_"));
5866:   PetscCall(DMPlexGetMaxProjectionHeight(dm, &maxHeight));
5867:   PetscCall(DMPlexSetMaxProjectionHeight(*cdm, maxHeight));
5868:   PetscCall(PetscSectionCreate(PetscObjectComm((PetscObject)dm), &section));
5869:   PetscCall(DMSetLocalSection(*cdm, section));
5870:   PetscCall(PetscSectionDestroy(&section));

5872:   PetscCall(DMSetNumFields(*cdm, 1));
5873:   PetscCall(DMCreateDS(*cdm));
5874:   (*cdm)->cloneOpts = PETSC_TRUE;
5875:   if (dm->setfromoptionscalled) PetscCall(DMSetFromOptions(*cdm));
5876:   PetscFunctionReturn(PETSC_SUCCESS);
5877: }

5879: PetscErrorCode DMCreateCellCoordinateDM_Plex(DM dm, DM *cdm)
5880: {
5881:   DM           cgcdm;
5882:   PetscSection section;
5883:   const char  *prefix;

5885:   PetscFunctionBegin;
5886:   PetscCall(DMGetCoordinateDM(dm, &cgcdm));
5887:   PetscCall(DMClone(cgcdm, cdm));
5888:   PetscCall(PetscObjectGetOptionsPrefix((PetscObject)dm, &prefix));
5889:   PetscCall(PetscObjectSetOptionsPrefix((PetscObject)*cdm, prefix));
5890:   PetscCall(PetscObjectAppendOptionsPrefix((PetscObject)*cdm, "cellcdm_"));
5891:   PetscCall(PetscSectionCreate(PetscObjectComm((PetscObject)dm), &section));
5892:   PetscCall(DMSetLocalSection(*cdm, section));
5893:   PetscCall(PetscSectionDestroy(&section));
5894:   PetscCall(DMSetNumFields(*cdm, 1));
5895:   PetscCall(DMCreateDS(*cdm));
5896:   (*cdm)->cloneOpts = PETSC_TRUE;
5897:   if (dm->setfromoptionscalled) PetscCall(DMSetFromOptions(*cdm));
5898:   PetscFunctionReturn(PETSC_SUCCESS);
5899: }

5901: PetscErrorCode DMCreateCoordinateField_Plex(DM dm, DMField *field)
5902: {
5903:   Vec coordsLocal, cellCoordsLocal;
5904:   DM  coordsDM, cellCoordsDM;

5906:   PetscFunctionBegin;
5907:   *field = NULL;
5908:   PetscCall(DMGetCoordinatesLocal(dm, &coordsLocal));
5909:   PetscCall(DMGetCoordinateDM(dm, &coordsDM));
5910:   PetscCall(DMGetCellCoordinatesLocal(dm, &cellCoordsLocal));
5911:   PetscCall(DMGetCellCoordinateDM(dm, &cellCoordsDM));
5912:   if (coordsLocal && coordsDM) {
5913:     if (cellCoordsLocal && cellCoordsDM) PetscCall(DMFieldCreateDSWithDG(coordsDM, cellCoordsDM, 0, coordsLocal, cellCoordsLocal, field));
5914:     else PetscCall(DMFieldCreateDS(coordsDM, 0, coordsLocal, field));
5915:   }
5916:   PetscFunctionReturn(PETSC_SUCCESS);
5917: }

5919: /*@
5920:   DMPlexGetConeSection - Return a section which describes the layout of cone data

5922:   Not Collective

5924:   Input Parameter:
5925: . dm - The `DMPLEX` object

5927:   Output Parameter:
5928: . section - The `PetscSection` object

5930:   Level: developer

5932: .seealso: [](ch_unstructured), `DM`, `DMPLEX`, `DMPlexGetSupportSection()`, `DMPlexGetCones()`, `DMPlexGetConeOrientations()`, `PetscSection`
5933: @*/
5934: PetscErrorCode DMPlexGetConeSection(DM dm, PetscSection *section)
5935: {
5936:   DM_Plex *mesh = (DM_Plex *)dm->data;

5938:   PetscFunctionBegin;
5940:   if (section) *section = mesh->coneSection;
5941:   PetscFunctionReturn(PETSC_SUCCESS);
5942: }

5944: /*@
5945:   DMPlexGetSupportSection - Return a section which describes the layout of support data

5947:   Not Collective

5949:   Input Parameter:
5950: . dm - The `DMPLEX` object

5952:   Output Parameter:
5953: . section - The `PetscSection` object

5955:   Level: developer

5957: .seealso: [](ch_unstructured), `DM`, `DMPLEX`, `DMPlexGetConeSection()`, `PetscSection`
5958: @*/
5959: PetscErrorCode DMPlexGetSupportSection(DM dm, PetscSection *section)
5960: {
5961:   DM_Plex *mesh = (DM_Plex *)dm->data;

5963:   PetscFunctionBegin;
5965:   if (section) *section = mesh->supportSection;
5966:   PetscFunctionReturn(PETSC_SUCCESS);
5967: }

5969: /*@C
5970:   DMPlexGetCones - Return cone data

5972:   Not Collective

5974:   Input Parameter:
5975: . dm - The `DMPLEX` object

5977:   Output Parameter:
5978: . cones - The cone for each point

5980:   Level: developer

5982: .seealso: [](ch_unstructured), `DM`, `DMPLEX`, `DMPlexGetConeSection()`
5983: @*/
5984: PetscErrorCode DMPlexGetCones(DM dm, PetscInt *cones[])
5985: {
5986:   DM_Plex *mesh = (DM_Plex *)dm->data;

5988:   PetscFunctionBegin;
5990:   if (cones) *cones = mesh->cones;
5991:   PetscFunctionReturn(PETSC_SUCCESS);
5992: }

5994: /*@C
5995:   DMPlexGetConeOrientations - Return cone orientation data

5997:   Not Collective

5999:   Input Parameter:
6000: . dm - The `DMPLEX` object

6002:   Output Parameter:
6003: . coneOrientations - The array of cone orientations for all points

6005:   Level: developer

6007:   Notes:
6008:   The `PetscSection` returned by `DMPlexGetConeSection()` partitions coneOrientations into cone orientations of particular points
6009:   as returned by `DMPlexGetConeOrientation()`.

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

6013: .seealso: [](ch_unstructured), `DM`, `DMPLEX`, `DMPlexGetConeSection()`, `DMPlexGetConeOrientation()`, `PetscSection`
6014: @*/
6015: PetscErrorCode DMPlexGetConeOrientations(DM dm, PetscInt *coneOrientations[])
6016: {
6017:   DM_Plex *mesh = (DM_Plex *)dm->data;

6019:   PetscFunctionBegin;
6021:   if (coneOrientations) *coneOrientations = mesh->coneOrientations;
6022:   PetscFunctionReturn(PETSC_SUCCESS);
6023: }

6025: /* FEM Support */

6027: PetscErrorCode DMPlexGetAllCells_Internal(DM plex, IS *cellIS)
6028: {
6029:   PetscInt depth;

6031:   PetscFunctionBegin;
6032:   PetscCall(DMPlexGetDepth(plex, &depth));
6033:   PetscCall(DMGetStratumIS(plex, "dim", depth, cellIS));
6034:   if (!*cellIS) PetscCall(DMGetStratumIS(plex, "depth", depth, cellIS));
6035:   PetscFunctionReturn(PETSC_SUCCESS);
6036: }

6038: PetscErrorCode DMPlexGetAllFaces_Internal(DM plex, IS *faceIS)
6039: {
6040:   PetscInt depth;

6042:   PetscFunctionBegin;
6043:   PetscCall(DMPlexGetDepth(plex, &depth));
6044:   PetscCall(DMGetStratumIS(plex, "dim", depth - 1, faceIS));
6045:   if (!*faceIS) PetscCall(DMGetStratumIS(plex, "depth", depth - 1, faceIS));
6046:   PetscFunctionReturn(PETSC_SUCCESS);
6047: }

6049: /*
6050:  Returns number of components and tensor degree for the field.  For interpolated meshes, line should be a point
6051:  representing a line in the section.
6052: */
6053: static PetscErrorCode PetscSectionFieldGetTensorDegree_Private(DM dm, PetscSection section, PetscInt field, PetscInt line, PetscInt *Nc, PetscInt *k, PetscBool *continuous, PetscBool *tensor)
6054: {
6055:   PetscObject  obj;
6056:   PetscClassId id;
6057:   PetscFE      fe = NULL;

6059:   PetscFunctionBeginHot;
6060:   PetscCall(PetscSectionGetFieldComponents(section, field, Nc));
6061:   PetscCall(DMGetField(dm, field, NULL, &obj));
6062:   PetscCall(PetscObjectGetClassId(obj, &id));
6063:   if (id == PETSCFE_CLASSID) fe = (PetscFE)obj;

6065:   if (!fe) {
6066:     /* Assume the full interpolated mesh is in the chart; lines in particular */
6067:     /* An order k SEM disc has k-1 dofs on an edge */
6068:     PetscCall(PetscSectionGetFieldDof(section, line, field, k));
6069:     *k = *k / *Nc + 1;
6070:   } else {
6071:     PetscInt       dual_space_size, dim;
6072:     PetscDualSpace dsp;

6074:     PetscCall(DMGetDimension(dm, &dim));
6075:     PetscCall(PetscFEGetDualSpace(fe, &dsp));
6076:     PetscCall(PetscDualSpaceGetDimension(dsp, &dual_space_size));
6077:     PetscCall(PetscDualSpaceLagrangeGetContinuity(dsp, continuous));
6078:     PetscCall(PetscDualSpaceLagrangeGetTensor(dsp, tensor));
6079:     if (*tensor) {
6080:       *k = (PetscInt)PetscCeilReal(PetscPowReal(dual_space_size / *Nc, 1.0 / dim)) - 1;
6081:     } else {
6082:       switch (dim) {
6083:       case 1:
6084:         *k = (dual_space_size / *Nc) - 1;
6085:         break;
6086:       case 2:
6087:         // N = (k + 1) (k + 2) / 2, k^2 + 3 k - 2 (N - 1) = 0, k = (sqrt(8 N + 1) - 3) / 2
6088:         *k = (PetscInt)PetscCeilReal((PetscSqrtReal(8 * dual_space_size / *Nc + 1) - 3) / 2);
6089:         break;
6090:       case 3: {
6091:         // N = (k + 1) (k + 2) (k + 3) / 6, k = (sqrt(3) sqrt(243 N^2 - 1) + 27 N)^(1/3)/3^(2/3) + 1/(3^(1/3) (sqrt(3) sqrt(243 N^2 - 1) + 27 N)^(1/3)) - 2
6092:         PetscInt N = dual_space_size / *Nc;
6093:         *k         = (PetscInt)PetscCeilReal(PetscPowReal((PetscSqrtReal(3 * (243 * N * N - 1)) + 27 * N) / 9, 1.0 / 3.0) + 1 / PetscPowReal(3 * (PetscSqrtReal(3 * (243 * N * N - 1)) + 27 * N), 1.0 / 3.0)) - 2;
6094:       } break;
6095:       default:
6096:         *k = -1;
6097:       }
6098:     }
6099:   }
6100:   PetscFunctionReturn(PETSC_SUCCESS);
6101: }

6103: static PetscErrorCode GetFieldSize_Private(PetscInt dim, PetscInt k, PetscBool tensor, PetscInt *dof)
6104: {
6105:   PetscFunctionBeginHot;
6106:   if (tensor) {
6107:     *dof = PetscPowInt(k + 1, dim);
6108:   } else {
6109:     switch (dim) {
6110:     case 1:
6111:       *dof = k + 1;
6112:       break;
6113:     case 2:
6114:       *dof = ((k + 1) * (k + 2)) / 2;
6115:       break;
6116:     case 3:
6117:       *dof = ((k + 1) * (k + 2) * (k + 3)) / 6;
6118:       break;
6119:     default:
6120:       *dof = 0;
6121:     }
6122:   }
6123:   PetscFunctionReturn(PETSC_SUCCESS);
6124: }

6126: /*@
6127:   DMPlexSetClosurePermutationTensor - Create a permutation from the default (BFS) point ordering in the closure, to a
6128:   lexicographic ordering over the tensor product cell (i.e., line, quad, hex, etc.), and set this permutation in the
6129:   section provided (or the section of the `DM`).

6131:   Not Collective

6133:   Input Parameters:
6134: + dm      - The `DM`
6135: . point   - Either a cell (highest dim point) or an edge (dim 1 point), or `PETSC_DETERMINE`
6136: - section - The `PetscSection` to reorder, or `NULL` for the default section

6138:   Example:
6139:   A typical interpolated single-quad mesh might order points as
6140: .vb
6141:   [c0, v1, v2, v3, v4, e5, e6, e7, e8]

6143:   v4 -- e6 -- v3
6144:   |           |
6145:   e7    c0    e8
6146:   |           |
6147:   v1 -- e5 -- v2
6148: .ve

6150:   (There is no significance to the ordering described here.)  The default section for a Q3 quad might typically assign
6151:   dofs in the order of points, e.g.,
6152: .vb
6153:     c0 -> [0,1,2,3]
6154:     v1 -> [4]
6155:     ...
6156:     e5 -> [8, 9]
6157: .ve

6159:   which corresponds to the dofs
6160: .vb
6161:     6   10  11  7
6162:     13  2   3   15
6163:     12  0   1   14
6164:     4   8   9   5
6165: .ve

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

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

6177:   Level: developer

6179:   Notes:
6180:   The point is used to determine the number of dofs/field on an edge. For SEM, this is related to the polynomial
6181:   degree of the basis.

6183:   This is required to run with libCEED.

6185: .seealso: [](ch_unstructured), `DM`, `DMPLEX`, `DMGetLocalSection()`, `PetscSectionSetClosurePermutation()`, `DMPlexSetClosurePermutationLexicographic()`, `DMSetGlobalSection()`
6186: @*/
6187: PetscErrorCode DMPlexSetClosurePermutationTensor(DM dm, PetscInt point, PetscSection section)
6188: {
6189:   DMLabel   label;
6190:   PetscInt  dim, depth = -1, eStart = -1, Nf;
6191:   PetscBool continuous = PETSC_TRUE, tensor = PETSC_TRUE;

6193:   PetscFunctionBegin;
6196:   PetscCall(DMGetDimension(dm, &dim));
6197:   if (dim < 1) PetscFunctionReturn(PETSC_SUCCESS);
6198:   if (point < 0) {
6199:     PetscInt sStart, sEnd;

6201:     PetscCall(DMPlexGetDepthStratum(dm, 1, &sStart, &sEnd));
6202:     point = sEnd - sStart ? sStart : point;
6203:   }
6204:   PetscCall(DMPlexGetDepthLabel(dm, &label));
6205:   if (point >= 0) PetscCall(DMLabelGetValue(label, point, &depth));
6206:   if (!section) PetscCall(DMGetLocalSection(dm, &section));
6207:   if (depth == 1) {
6208:     eStart = point;
6209:   } else if (depth == dim) {
6210:     const PetscInt *cone;

6212:     PetscCall(DMPlexGetCone(dm, point, &cone));
6213:     if (dim == 2) eStart = cone[0];
6214:     else if (dim == 3) {
6215:       const PetscInt *cone2;
6216:       PetscCall(DMPlexGetCone(dm, cone[0], &cone2));
6217:       eStart = cone2[0];
6218:     } 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);
6219:   } else PetscCheck(depth < 0, 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);

6221:   PetscCall(PetscSectionGetNumFields(section, &Nf));
6222:   for (PetscInt d = 1; d <= dim; d++) {
6223:     PetscInt  k, f, Nc, c, i, j, size = 0, offset = 0, foffset = 0;
6224:     PetscInt *perm;

6226:     for (f = 0; f < Nf; ++f) {
6227:       PetscInt dof;

6229:       PetscCall(PetscSectionFieldGetTensorDegree_Private(dm, section, f, eStart, &Nc, &k, &continuous, &tensor));
6230:       PetscCheck(dim == 1 || tensor || !continuous, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Continuous field %" PetscInt_FMT " must have a tensor product discretization", f);
6231:       if (!continuous && d < dim) continue;
6232:       PetscCall(GetFieldSize_Private(d, k, tensor, &dof));
6233:       size += dof * Nc;
6234:     }
6235:     PetscCall(PetscMalloc1(size, &perm));
6236:     for (f = 0; f < Nf; ++f) {
6237:       switch (d) {
6238:       case 1:
6239:         PetscCall(PetscSectionFieldGetTensorDegree_Private(dm, section, f, eStart, &Nc, &k, &continuous, &tensor));
6240:         if (!continuous && d < dim) continue;
6241:         /*
6242:          Original ordering is [ edge of length k-1; vtx0; vtx1 ]
6243:          We want              [ vtx0; edge of length k-1; vtx1 ]
6244:          */
6245:         if (continuous) {
6246:           for (c = 0; c < Nc; c++, offset++) perm[offset] = (k - 1) * Nc + c + foffset;
6247:           for (i = 0; i < k - 1; i++)
6248:             for (c = 0; c < Nc; c++, offset++) perm[offset] = i * Nc + c + foffset;
6249:           for (c = 0; c < Nc; c++, offset++) perm[offset] = k * Nc + c + foffset;
6250:           foffset = offset;
6251:         } else {
6252:           PetscInt dof;

6254:           PetscCall(GetFieldSize_Private(d, k, tensor, &dof));
6255:           for (i = 0; i < dof * Nc; ++i, ++offset) perm[offset] = i + foffset;
6256:           foffset = offset;
6257:         }
6258:         break;
6259:       case 2:
6260:         /* The original quad closure is oriented clockwise, {f, e_b, e_r, e_t, e_l, v_lb, v_rb, v_tr, v_tl} */
6261:         PetscCall(PetscSectionFieldGetTensorDegree_Private(dm, section, f, eStart, &Nc, &k, &continuous, &tensor));
6262:         if (!continuous && d < dim) continue;
6263:         /* The SEM order is

6265:          v_lb, {e_b}, v_rb,
6266:          e^{(k-1)-i}_l, {f^{i*(k-1)}}, e^i_r,
6267:          v_lt, reverse {e_t}, v_rt
6268:          */
6269:         if (continuous) {
6270:           const PetscInt of   = 0;
6271:           const PetscInt oeb  = of + PetscSqr(k - 1);
6272:           const PetscInt oer  = oeb + (k - 1);
6273:           const PetscInt oet  = oer + (k - 1);
6274:           const PetscInt oel  = oet + (k - 1);
6275:           const PetscInt ovlb = oel + (k - 1);
6276:           const PetscInt ovrb = ovlb + 1;
6277:           const PetscInt ovrt = ovrb + 1;
6278:           const PetscInt ovlt = ovrt + 1;
6279:           PetscInt       o;

6281:           /* bottom */
6282:           for (c = 0; c < Nc; ++c, ++offset) perm[offset] = ovlb * Nc + c + foffset;
6283:           for (o = oeb; o < oer; ++o)
6284:             for (c = 0; c < Nc; ++c, ++offset) perm[offset] = o * Nc + c + foffset;
6285:           for (c = 0; c < Nc; ++c, ++offset) perm[offset] = ovrb * Nc + c + foffset;
6286:           /* middle */
6287:           for (i = 0; i < k - 1; ++i) {
6288:             for (c = 0; c < Nc; ++c, ++offset) perm[offset] = (oel + (k - 2) - i) * Nc + c + foffset;
6289:             for (o = of + (k - 1) * i; o < of + (k - 1) * (i + 1); ++o)
6290:               for (c = 0; c < Nc; ++c, ++offset) perm[offset] = o * Nc + c + foffset;
6291:             for (c = 0; c < Nc; ++c, ++offset) perm[offset] = (oer + i) * Nc + c + foffset;
6292:           }
6293:           /* top */
6294:           for (c = 0; c < Nc; ++c, ++offset) perm[offset] = ovlt * Nc + c + foffset;
6295:           for (o = oel - 1; o >= oet; --o)
6296:             for (c = 0; c < Nc; ++c, ++offset) perm[offset] = o * Nc + c + foffset;
6297:           for (c = 0; c < Nc; ++c, ++offset) perm[offset] = ovrt * Nc + c + foffset;
6298:           foffset = offset;
6299:         } else {
6300:           PetscInt dof;

6302:           PetscCall(GetFieldSize_Private(d, k, tensor, &dof));
6303:           for (i = 0; i < dof * Nc; ++i, ++offset) perm[offset] = i + foffset;
6304:           foffset = offset;
6305:         }
6306:         break;
6307:       case 3:
6308:         /* The original hex closure is

6310:          {c,
6311:          f_b, f_t, f_f, f_b, f_r, f_l,
6312:          e_bl, e_bb, e_br, e_bf,  e_tf, e_tr, e_tb, e_tl,  e_rf, e_lf, e_lb, e_rb,
6313:          v_blf, v_blb, v_brb, v_brf, v_tlf, v_trf, v_trb, v_tlb}
6314:          */
6315:         PetscCall(PetscSectionFieldGetTensorDegree_Private(dm, section, f, eStart, &Nc, &k, &continuous, &tensor));
6316:         if (!continuous && d < dim) continue;
6317:         /* The SEM order is
6318:          Bottom Slice
6319:          v_blf, {e^{(k-1)-n}_bf}, v_brf,
6320:          e^{i}_bl, f^{n*(k-1)+(k-1)-i}_b, e^{(k-1)-i}_br,
6321:          v_blb, {e_bb}, v_brb,

6323:          Middle Slice (j)
6324:          {e^{(k-1)-j}_lf}, {f^{j*(k-1)+n}_f}, e^j_rf,
6325:          f^{i*(k-1)+j}_l, {c^{(j*(k-1) + i)*(k-1)+n}_t}, f^{j*(k-1)+i}_r,
6326:          e^j_lb, {f^{j*(k-1)+(k-1)-n}_b}, e^{(k-1)-j}_rb,

6328:          Top Slice
6329:          v_tlf, {e_tf}, v_trf,
6330:          e^{(k-1)-i}_tl, {f^{i*(k-1)}_t}, e^{i}_tr,
6331:          v_tlb, {e^{(k-1)-n}_tb}, v_trb,
6332:          */
6333:         if (continuous) {
6334:           const PetscInt oc    = 0;
6335:           const PetscInt ofb   = oc + PetscSqr(k - 1) * (k - 1);
6336:           const PetscInt oft   = ofb + PetscSqr(k - 1);
6337:           const PetscInt off   = oft + PetscSqr(k - 1);
6338:           const PetscInt ofk   = off + PetscSqr(k - 1);
6339:           const PetscInt ofr   = ofk + PetscSqr(k - 1);
6340:           const PetscInt ofl   = ofr + PetscSqr(k - 1);
6341:           const PetscInt oebl  = ofl + PetscSqr(k - 1);
6342:           const PetscInt oebb  = oebl + (k - 1);
6343:           const PetscInt oebr  = oebb + (k - 1);
6344:           const PetscInt oebf  = oebr + (k - 1);
6345:           const PetscInt oetf  = oebf + (k - 1);
6346:           const PetscInt oetr  = oetf + (k - 1);
6347:           const PetscInt oetb  = oetr + (k - 1);
6348:           const PetscInt oetl  = oetb + (k - 1);
6349:           const PetscInt oerf  = oetl + (k - 1);
6350:           const PetscInt oelf  = oerf + (k - 1);
6351:           const PetscInt oelb  = oelf + (k - 1);
6352:           const PetscInt oerb  = oelb + (k - 1);
6353:           const PetscInt ovblf = oerb + (k - 1);
6354:           const PetscInt ovblb = ovblf + 1;
6355:           const PetscInt ovbrb = ovblb + 1;
6356:           const PetscInt ovbrf = ovbrb + 1;
6357:           const PetscInt ovtlf = ovbrf + 1;
6358:           const PetscInt ovtrf = ovtlf + 1;
6359:           const PetscInt ovtrb = ovtrf + 1;
6360:           const PetscInt ovtlb = ovtrb + 1;
6361:           PetscInt       o, n;

6363:           /* Bottom Slice */
6364:           /*   bottom */
6365:           for (c = 0; c < Nc; ++c, ++offset) perm[offset] = ovblf * Nc + c + foffset;
6366:           for (o = oetf - 1; o >= oebf; --o)
6367:             for (c = 0; c < Nc; ++c, ++offset) perm[offset] = o * Nc + c + foffset;
6368:           for (c = 0; c < Nc; ++c, ++offset) perm[offset] = ovbrf * Nc + c + foffset;
6369:           /*   middle */
6370:           for (i = 0; i < k - 1; ++i) {
6371:             for (c = 0; c < Nc; ++c, ++offset) perm[offset] = (oebl + i) * Nc + c + foffset;
6372:             for (n = 0; n < k - 1; ++n) {
6373:               o = ofb + n * (k - 1) + i;
6374:               for (c = 0; c < Nc; ++c, ++offset) perm[offset] = o * Nc + c + foffset;
6375:             }
6376:             for (c = 0; c < Nc; ++c, ++offset) perm[offset] = (oebr + (k - 2) - i) * Nc + c + foffset;
6377:           }
6378:           /*   top */
6379:           for (c = 0; c < Nc; ++c, ++offset) perm[offset] = ovblb * Nc + c + foffset;
6380:           for (o = oebb; o < oebr; ++o)
6381:             for (c = 0; c < Nc; ++c, ++offset) perm[offset] = o * Nc + c + foffset;
6382:           for (c = 0; c < Nc; ++c, ++offset) perm[offset] = ovbrb * Nc + c + foffset;

6384:           /* Middle Slice */
6385:           for (j = 0; j < k - 1; ++j) {
6386:             /*   bottom */
6387:             for (c = 0; c < Nc; ++c, ++offset) perm[offset] = (oelf + (k - 2) - j) * Nc + c + foffset;
6388:             for (o = off + j * (k - 1); o < off + (j + 1) * (k - 1); ++o)
6389:               for (c = 0; c < Nc; ++c, ++offset) perm[offset] = o * Nc + c + foffset;
6390:             for (c = 0; c < Nc; ++c, ++offset) perm[offset] = (oerf + j) * Nc + c + foffset;
6391:             /*   middle */
6392:             for (i = 0; i < k - 1; ++i) {
6393:               for (c = 0; c < Nc; ++c, ++offset) perm[offset] = (ofl + i * (k - 1) + j) * Nc + c + foffset;
6394:               for (n = 0; n < k - 1; ++n)
6395:                 for (c = 0; c < Nc; ++c, ++offset) perm[offset] = (oc + (j * (k - 1) + i) * (k - 1) + n) * Nc + c + foffset;
6396:               for (c = 0; c < Nc; ++c, ++offset) perm[offset] = (ofr + j * (k - 1) + i) * Nc + c + foffset;
6397:             }
6398:             /*   top */
6399:             for (c = 0; c < Nc; ++c, ++offset) perm[offset] = (oelb + j) * Nc + c + foffset;
6400:             for (o = ofk + j * (k - 1) + (k - 2); o >= ofk + j * (k - 1); --o)
6401:               for (c = 0; c < Nc; ++c, ++offset) perm[offset] = o * Nc + c + foffset;
6402:             for (c = 0; c < Nc; ++c, ++offset) perm[offset] = (oerb + (k - 2) - j) * Nc + c + foffset;
6403:           }

6405:           /* Top Slice */
6406:           /*   bottom */
6407:           for (c = 0; c < Nc; ++c, ++offset) perm[offset] = ovtlf * Nc + c + foffset;
6408:           for (o = oetf; o < oetr; ++o)
6409:             for (c = 0; c < Nc; ++c, ++offset) perm[offset] = o * Nc + c + foffset;
6410:           for (c = 0; c < Nc; ++c, ++offset) perm[offset] = ovtrf * Nc + c + foffset;
6411:           /*   middle */
6412:           for (i = 0; i < k - 1; ++i) {
6413:             for (c = 0; c < Nc; ++c, ++offset) perm[offset] = (oetl + (k - 2) - i) * Nc + c + foffset;
6414:             for (n = 0; n < k - 1; ++n)
6415:               for (c = 0; c < Nc; ++c, ++offset) perm[offset] = (oft + i * (k - 1) + n) * Nc + c + foffset;
6416:             for (c = 0; c < Nc; ++c, ++offset) perm[offset] = (oetr + i) * Nc + c + foffset;
6417:           }
6418:           /*   top */
6419:           for (c = 0; c < Nc; ++c, ++offset) perm[offset] = ovtlb * Nc + c + foffset;
6420:           for (o = oetl - 1; o >= oetb; --o)
6421:             for (c = 0; c < Nc; ++c, ++offset) perm[offset] = o * Nc + c + foffset;
6422:           for (c = 0; c < Nc; ++c, ++offset) perm[offset] = ovtrb * Nc + c + foffset;

6424:           foffset = offset;
6425:         } else {
6426:           PetscInt dof;

6428:           PetscCall(GetFieldSize_Private(d, k, tensor, &dof));
6429:           for (i = 0; i < dof * Nc; ++i, ++offset) perm[offset] = i + foffset;
6430:           foffset = offset;
6431:         }
6432:         break;
6433:       default:
6434:         SETERRQ(PetscObjectComm((PetscObject)dm), PETSC_ERR_ARG_OUTOFRANGE, "No spectral ordering for dimension %" PetscInt_FMT, d);
6435:       }
6436:     }
6437:     PetscCheck(offset == size, PetscObjectComm((PetscObject)dm), PETSC_ERR_PLIB, "Number of permutation entries %" PetscInt_FMT " != %" PetscInt_FMT, offset, size);
6438:     /* Check permutation */
6439:     {
6440:       PetscInt *check;

6442:       PetscCall(PetscMalloc1(size, &check));
6443:       for (i = 0; i < size; ++i) {
6444:         check[i] = -1;
6445:         PetscCheck(perm[i] >= 0 && perm[i] < size, PetscObjectComm((PetscObject)dm), PETSC_ERR_PLIB, "Invalid permutation index p[%" PetscInt_FMT "] = %" PetscInt_FMT, i, perm[i]);
6446:       }
6447:       for (i = 0; i < size; ++i) check[perm[i]] = i;
6448:       for (i = 0; i < size; ++i) PetscCheck(check[i] >= 0, PetscObjectComm((PetscObject)dm), PETSC_ERR_PLIB, "Missing permutation index %" PetscInt_FMT, i);
6449:       PetscCall(PetscFree(check));
6450:     }
6451:     PetscCall(PetscSectionSetClosurePermutation_Internal(section, (PetscObject)dm, d, size, PETSC_OWN_POINTER, perm));
6452:     if (d == dim) { // Add permutation for localized (in case this is a coordinate DM)
6453:       PetscInt *loc_perm;
6454:       PetscCall(PetscMalloc1(size * 2, &loc_perm));
6455:       for (PetscInt i = 0; i < size; i++) {
6456:         loc_perm[i]        = perm[i];
6457:         loc_perm[size + i] = size + perm[i];
6458:       }
6459:       PetscCall(PetscSectionSetClosurePermutation_Internal(section, (PetscObject)dm, d, size * 2, PETSC_OWN_POINTER, loc_perm));
6460:     }
6461:   }
6462:   PetscFunctionReturn(PETSC_SUCCESS);
6463: }

6465: /*@
6466:   DMPlexSetClosurePermutationLexicographic - Create a permutation from the default (BFS) point ordering in the closure, to a
6467:   lexicographic ordering over the simplex (i.e., line, tri, tet, etc.), and set this permutation in the
6468:   section provided (or the section of the `DM`).

6470:   Not Collective

6472:   Input Parameters:
6473: + dm      - The `DM`
6474: . point   - Either a cell (highest dim point) or an edge (dim 1 point), or `PETSC_DETERMINE`
6475: - section - The `PetscSection` to reorder, or `NULL` for the default section

6477:   Example:
6478:   A typical interpolated single-tri mesh might order points as
6479: .vb
6480:   [c0, v1, v2, v3, e4, e5, e6]

6482:   v3
6483:   |  \
6484:   |    \
6485:   e6    e5
6486:   |  c0   \
6487:   |         \
6488:   v1 -- e4 -- v2
6489: .ve

6491:   (There is no significance to the ordering described here.)  The default section for a P3 tri might typically assign
6492:   dofs in the order of points, e.g.,
6493: .vb
6494:     c0 -> [0]
6495:     v1 -> [1]
6496:     ...
6497:     e4 -> [4, 5]
6498: .ve

6500:   which corresponds to the dofs
6501: .vb
6502:     3
6503:     8  7
6504:     9  0   6
6505:     1  4   5   2
6506: .ve

6508:   The closure in BFS ordering works through height strata (cells, edges, vertices) to produce the ordering
6509: .vb
6510:   0 4 5 6 7 8 9 1 2 3
6511: .ve

6513:   After calling DMPlexSetClosurePermutationLexicographic(), the closure will be ordered lexicographically,
6514: .vb
6515:    1 4 5 2 9 0 6 8 7 3
6516: .ve

6518:   Level: developer

6520:   Notes:
6521:   The point is used to determine the number of dofs/field on an edge. For SEM, this is related to the polynomial
6522:   degree of the basis.

6524:   The lexicographic order starts along the left edge, not the front, to match codes like GMsh with a bottom face oriented into the volume.

6526: .seealso: [](ch_unstructured), `DM`, `DMPLEX`, `DMGetLocalSection()`, `PetscSectionSetClosurePermutation()`, `DMPlexSetClosurePermutationTensor()`, `DMSetGlobalSection()`
6527: @*/
6528: PetscErrorCode DMPlexSetClosurePermutationLexicographic(DM dm, PetscInt point, PetscSection section)
6529: {
6530:   DMLabel   label;
6531:   PetscInt  dim, depth = -1, eStart = -1, Nf;
6532:   PetscBool continuous = PETSC_TRUE, tensor = PETSC_TRUE;

6534:   PetscFunctionBegin;
6537:   // TODO: This needs to be tested for P4-6 using Plex ex3 with a linear field to check the permutations
6538:   PetscCall(DMGetDimension(dm, &dim));
6539:   if (dim < 1) PetscFunctionReturn(PETSC_SUCCESS);
6540:   if (point < 0) {
6541:     PetscInt sStart, sEnd;

6543:     PetscCall(DMPlexGetDepthStratum(dm, 1, &sStart, &sEnd));
6544:     point = sEnd - sStart ? sStart : point;
6545:   }
6546:   PetscCall(DMPlexGetDepthLabel(dm, &label));
6547:   if (point >= 0) PetscCall(DMLabelGetValue(label, point, &depth));
6548:   if (!section) PetscCall(DMGetLocalSection(dm, &section));
6549:   if (depth == 1) {
6550:     eStart = point;
6551:   } else if (depth == dim) {
6552:     const PetscInt *cone;

6554:     PetscCall(DMPlexGetCone(dm, point, &cone));
6555:     if (dim == 2) eStart = cone[0];
6556:     else if (dim == 3) {
6557:       const PetscInt *cone2;
6558:       PetscCall(DMPlexGetCone(dm, cone[0], &cone2));
6559:       eStart = cone2[0];
6560:     } 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);
6561:   } else PetscCheck(depth < 0, 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);

6563:   PetscCall(PetscSectionGetNumFields(section, &Nf));
6564:   for (PetscInt d = 1; d <= dim; d++) {
6565:     PetscInt  k, f, Nc, c, i, j, size = 0, offset = 0, foffset = 0;
6566:     PetscInt *perm;

6568:     for (f = 0; f < Nf; ++f) {
6569:       PetscInt dof;

6571:       PetscCall(PetscSectionFieldGetTensorDegree_Private(dm, section, f, eStart, &Nc, &k, &continuous, &tensor));
6572:       PetscCheck(dim == 1 || !tensor, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Field %" PetscInt_FMT " should not have a tensor product discretization", f);
6573:       if (!continuous && d < dim) continue;
6574:       PetscCall(GetFieldSize_Private(d, k, tensor, &dof));
6575:       size += dof * Nc;
6576:     }
6577:     PetscCall(PetscMalloc1(size, &perm));
6578:     for (f = 0; f < Nf; ++f) {
6579:       switch (d) {
6580:       case 1:
6581:         PetscCall(PetscSectionFieldGetTensorDegree_Private(dm, section, f, eStart, &Nc, &k, &continuous, &tensor));
6582:         if (!continuous && d < dim) continue;
6583:         /*
6584:          Original ordering is [ edge of length k-1; vtx0; vtx1 ]
6585:          We want              [ vtx0; edge of length k-1; vtx1 ]
6586:          */
6587:         if (continuous) {
6588:           for (c = 0; c < Nc; c++, offset++) perm[offset] = (k - 1) * Nc + c + foffset;
6589:           for (i = 0; i < k - 1; i++)
6590:             for (c = 0; c < Nc; c++, offset++) perm[offset] = i * Nc + c + foffset;
6591:           for (c = 0; c < Nc; c++, offset++) perm[offset] = k * Nc + c + foffset;
6592:           foffset = offset;
6593:         } else {
6594:           PetscInt dof;

6596:           PetscCall(GetFieldSize_Private(d, k, tensor, &dof));
6597:           for (i = 0; i < dof * Nc; ++i, ++offset) perm[offset] = i + foffset;
6598:           foffset = offset;
6599:         }
6600:         break;
6601:       case 2:
6602:         /* The original tri closure is oriented clockwise, {f, e_b, e_r, e_l, v_lb, v_rb, v_lt} */
6603:         PetscCall(PetscSectionFieldGetTensorDegree_Private(dm, section, f, eStart, &Nc, &k, &continuous, &tensor));
6604:         if (!continuous && d < dim) continue;
6605:         /* The SEM order is

6607:          v_lb, {e_b}, v_rb,
6608:          e^{(k-1)-i}_l, {f^{i*(k-1-i)}}, e^i_r,
6609:          v_lt
6610:          */
6611:         if (continuous) {
6612:           const PetscInt of   = 0;
6613:           const PetscInt oeb  = of + (k - 2) * (k - 1) / 2;
6614:           const PetscInt oer  = oeb + (k - 1);
6615:           const PetscInt oel  = oer + (k - 1);
6616:           const PetscInt ovlb = oel + (k - 1);
6617:           const PetscInt ovrb = ovlb + 1;
6618:           const PetscInt ovlt = ovrb + 1;
6619:           PetscInt       o;

6621:           /* bottom */
6622:           for (c = 0; c < Nc; ++c, ++offset) perm[offset] = ovlb * Nc + c + foffset;
6623:           for (o = oeb; o < oer; ++o)
6624:             for (c = 0; c < Nc; ++c, ++offset) perm[offset] = o * Nc + c + foffset;
6625:           for (c = 0; c < Nc; ++c, ++offset) perm[offset] = ovrb * Nc + c + foffset;
6626:           /* middle */
6627:           for (i = 0; i < k - 1; ++i) {
6628:             for (c = 0; c < Nc; ++c, ++offset) perm[offset] = (oel + (k - 2) - i) * Nc + c + foffset;
6629:             // (k - 2) (k - 1) / 2 - (k - 2 - i) (k - 1 - i) / 2 = i (2 k - 3 - i) / 2
6630:             for (o = of + i * (2 * k - 3 - i) / 2; o < of + (i + 1) * (2 * k - 4 - i) / 2; ++o)
6631:               for (c = 0; c < Nc; ++c, ++offset) perm[offset] = o * Nc + c + foffset;
6632:             for (c = 0; c < Nc; ++c, ++offset) perm[offset] = (oer + i) * Nc + c + foffset;
6633:           }
6634:           /* top */
6635:           for (c = 0; c < Nc; ++c, ++offset) perm[offset] = ovlt * Nc + c + foffset;
6636:           foffset = offset;
6637:         } else {
6638:           PetscInt dof;

6640:           PetscCall(GetFieldSize_Private(d, k, tensor, &dof));
6641:           for (i = 0; i < dof * Nc; ++i, ++offset) perm[offset] = i + foffset;
6642:           foffset = offset;
6643:         }
6644:         break;
6645:       case 3:
6646:         /* The original tet closure is

6648:          {c,
6649:          f_b, f_l, f_f, f_r,
6650:          e_bl, e_br, e_bf,  e_lf, e_rf, e_rb,
6651:          v_blf, v_blb, v_brf, v_tlf}
6652:          */
6653:         PetscCall(PetscSectionFieldGetTensorDegree_Private(dm, section, f, eStart, &Nc, &k, &continuous, &tensor));
6654:         if (!continuous && d < dim) continue;
6655:         /* The SEM order (starting on the left edge since GMsh flips the bottom face) is
6656:          Bottom Slice
6657:          v_blb, {e^{-n}_bl}, v_blf,
6658:          e^{i}_br, f^{i,-n}_b, e^{-i}_bf,
6659:          v_brf,

6661:          Middle Slice (j)
6662:          e^{-j}_rb, {f^{-n,j}_l}, e^{j}_lf,
6663:          f^{-n,j}_r, {c^{j,-n,i}}, f^{j,i}_f,
6664:          e^{j}_rf,

6666:          Top Slice
6667:          v_tlf,
6668:          */
6669:         if (continuous) {
6670:           const PetscInt oc    = 0;
6671:           const PetscInt ofb   = oc + (k - 3) * (k - 2) * (k - 1) / 6;
6672:           const PetscInt ofl   = ofb + (k - 2) * (k - 1) / 2;
6673:           const PetscInt off   = ofl + (k - 2) * (k - 1) / 2;
6674:           const PetscInt ofr   = off + (k - 2) * (k - 1) / 2;
6675:           const PetscInt oebl  = ofr + (k - 2) * (k - 1) / 2;
6676:           const PetscInt oebr  = oebl + (k - 1);
6677:           const PetscInt oebf  = oebr + (k - 1);
6678:           const PetscInt oelf  = oebf + (k - 1);
6679:           const PetscInt oerb  = oelf + (k - 1);
6680:           const PetscInt oerf  = oerb + (k - 1);
6681:           const PetscInt ovblf = oerf + (k - 1);
6682:           const PetscInt ovblb = ovblf + 1;
6683:           const PetscInt ovbrf = ovblb + 1;
6684:           const PetscInt ovtlf = ovbrf + 1;
6685:           PetscInt       o;

6687:           /* Bottom Slice */
6688:           /*   bottom */
6689:           for (c = 0; c < Nc; ++c, ++offset) perm[offset] = ovblb * Nc + c + foffset;
6690:           for (o = oebr - 1; o >= oebl; --o)
6691:             for (c = 0; c < Nc; ++c, ++offset) perm[offset] = o * Nc + c + foffset;
6692:           for (c = 0; c < Nc; ++c, ++offset) perm[offset] = ovblf * Nc + c + foffset;
6693:           /*   middle */
6694:           for (i = 0; i < k - 1; ++i) {
6695:             for (c = 0; c < Nc; ++c, ++offset) perm[offset] = (oebr + i) * Nc + c + foffset;
6696:             for (PetscInt n = 0; n < k - 2 - i; ++n) {
6697:               // (k - 2) (k - 1) / 2 - (k - 2 - i) (k - 1 - i) / 2 = i (2 k - 3 - i) / 2
6698:               o = ofb + i * (2 * k - 3 - i) / 2 + (k - 2 - i - 1 - n);
6699:               for (c = 0; c < Nc; ++c, ++offset) perm[offset] = o * Nc + c + foffset;
6700:             }
6701:             for (c = 0; c < Nc; ++c, ++offset) perm[offset] = (oebf + (k - 2) - i) * Nc + c + foffset;
6702:           }
6703:           /*   top */
6704:           for (c = 0; c < Nc; ++c, ++offset) perm[offset] = ovbrf * Nc + c + foffset;

6706:           /* Middle Slice */
6707:           for (j = 0; j < k - 1; ++j) {
6708:             /*   bottom */
6709:             for (c = 0; c < Nc; ++c, ++offset) perm[offset] = (oerb + k - 2 - j) * Nc + c + foffset;
6710:             for (PetscInt n = k - 3 - j; n >= 0; --n) {
6711:               // (k - 2) (k - 1) / 2 - (k - 2 - i) (k - 1 - i) / 2 = i (2 k - 3 - i) / 2
6712:               o = ofl + n * (2 * k - 3 - n) / 2 + j;
6713:               for (c = 0; c < Nc; ++c, ++offset) perm[offset] = o * Nc + c + foffset;
6714:             }
6715:             for (c = 0; c < Nc; ++c, ++offset) perm[offset] = (oelf + j) * Nc + c + foffset;
6716:             /*   middle */
6717:             for (i = 0; i < k - 2 - j; ++i) {
6718:               for (c = 0; c < Nc; ++c, ++offset) perm[offset] = (ofr + i * (2 * k - 1 - i) / 2 + j) * Nc + c + foffset;
6719:               for (PetscInt n = k - 4 - j - i; n >= 0; --n) {
6720:                 // (k - 2) (k - 1) k / 6 - (k - 2 - j) (k - 1 - j) (k - j) / 6 = j (j^2 - 1 - 3 (k - 1) (j + k - 1)) / 6
6721:                 for (c = 0; c < Nc; ++c, ++offset) perm[offset] = (oc + j * (j * j - 1 - 3 * (k - 1) * (j + k - 1)) / 6 + n * (2 * k - 3 - n) + i) * Nc + c + foffset;
6722:               }
6723:               for (c = 0; c < Nc; ++c, ++offset) perm[offset] = (off + j * (2 * k - 3 - j) / 2 + i) * Nc + c + foffset;
6724:             }
6725:             /*   top */
6726:             for (c = 0; c < Nc; ++c, ++offset) perm[offset] = (oerf + j) * Nc + c + foffset;
6727:           }

6729:           /* Top Slice */
6730:           for (c = 0; c < Nc; ++c, ++offset) perm[offset] = ovtlf * Nc + c + foffset;

6732:           foffset = offset;
6733:         } else {
6734:           PetscInt dof;

6736:           PetscCall(GetFieldSize_Private(d, k, tensor, &dof));
6737:           for (i = 0; i < dof * Nc; ++i, ++offset) perm[offset] = i + foffset;
6738:           foffset = offset;
6739:         }
6740:         break;
6741:       default:
6742:         SETERRQ(PetscObjectComm((PetscObject)dm), PETSC_ERR_ARG_OUTOFRANGE, "No spectral ordering for dimension %" PetscInt_FMT, d);
6743:       }
6744:     }
6745:     PetscCheck(offset == size, PetscObjectComm((PetscObject)dm), PETSC_ERR_PLIB, "Number of permutation entries %" PetscInt_FMT " != %" PetscInt_FMT, offset, size);
6746:     /* Check permutation */
6747:     {
6748:       PetscInt *check;

6750:       PetscCall(PetscMalloc1(size, &check));
6751:       for (i = 0; i < size; ++i) {
6752:         check[i] = -1;
6753:         PetscCheck(perm[i] >= 0 && perm[i] < size, PetscObjectComm((PetscObject)dm), PETSC_ERR_PLIB, "Invalid permutation index p[%" PetscInt_FMT "] = %" PetscInt_FMT, i, perm[i]);
6754:       }
6755:       for (i = 0; i < size; ++i) check[perm[i]] = i;
6756:       for (i = 0; i < size; ++i) PetscCheck(check[i] >= 0, PetscObjectComm((PetscObject)dm), PETSC_ERR_PLIB, "Missing permutation index %" PetscInt_FMT " out of %" PetscInt_FMT, i, size);
6757:       PetscCall(PetscFree(check));
6758:     }
6759:     PetscCall(PetscSectionSetClosurePermutation_Internal(section, (PetscObject)dm, d, size, PETSC_OWN_POINTER, perm));
6760:     if (d == dim) { // Add permutation for localized (in case this is a coordinate DM)
6761:       PetscInt *loc_perm;
6762:       PetscCall(PetscMalloc1(size * 2, &loc_perm));
6763:       for (PetscInt i = 0; i < size; i++) {
6764:         loc_perm[i]        = perm[i];
6765:         loc_perm[size + i] = size + perm[i];
6766:       }
6767:       PetscCall(PetscSectionSetClosurePermutation_Internal(section, (PetscObject)dm, d, size * 2, PETSC_OWN_POINTER, loc_perm));
6768:     }
6769:   }
6770:   PetscFunctionReturn(PETSC_SUCCESS);
6771: }

6773: PetscErrorCode DMPlexGetPointDualSpaceFEM(DM dm, PetscInt point, PetscInt field, PetscDualSpace *dspace)
6774: {
6775:   PetscDS  prob;
6776:   PetscInt depth, Nf, h;
6777:   DMLabel  label;

6779:   PetscFunctionBeginHot;
6780:   PetscCall(DMGetDS(dm, &prob));
6781:   Nf      = prob->Nf;
6782:   label   = dm->depthLabel;
6783:   *dspace = NULL;
6784:   if (field < Nf) {
6785:     PetscObject disc = prob->disc[field];

6787:     if (disc->classid == PETSCFE_CLASSID) {
6788:       PetscDualSpace dsp;

6790:       PetscCall(PetscFEGetDualSpace((PetscFE)disc, &dsp));
6791:       PetscCall(DMLabelGetNumValues(label, &depth));
6792:       PetscCall(DMLabelGetValue(label, point, &h));
6793:       h = depth - 1 - h;
6794:       if (h) PetscCall(PetscDualSpaceGetHeightSubspace(dsp, h, dspace));
6795:       else *dspace = dsp;
6796:     }
6797:   }
6798:   PetscFunctionReturn(PETSC_SUCCESS);
6799: }

6801: static inline PetscErrorCode DMPlexVecGetClosure_Depth1_Static(DM dm, PetscSection section, Vec v, PetscInt point, PetscInt *csize, PetscScalar *values[])
6802: {
6803:   PetscScalar       *array;
6804:   const PetscScalar *vArray;
6805:   const PetscInt    *cone, *coneO;
6806:   PetscInt           pStart, pEnd, p, numPoints, size = 0, offset = 0;

6808:   PetscFunctionBeginHot;
6809:   PetscCall(PetscSectionGetChart(section, &pStart, &pEnd));
6810:   PetscCall(DMPlexGetConeSize(dm, point, &numPoints));
6811:   PetscCall(DMPlexGetCone(dm, point, &cone));
6812:   PetscCall(DMPlexGetConeOrientation(dm, point, &coneO));
6813:   if (!values || !*values) {
6814:     if ((point >= pStart) && (point < pEnd)) {
6815:       PetscInt dof;

6817:       PetscCall(PetscSectionGetDof(section, point, &dof));
6818:       size += dof;
6819:     }
6820:     for (p = 0; p < numPoints; ++p) {
6821:       const PetscInt cp = cone[p];
6822:       PetscInt       dof;

6824:       if ((cp < pStart) || (cp >= pEnd)) continue;
6825:       PetscCall(PetscSectionGetDof(section, cp, &dof));
6826:       size += dof;
6827:     }
6828:     if (!values) {
6829:       if (csize) *csize = size;
6830:       PetscFunctionReturn(PETSC_SUCCESS);
6831:     }
6832:     PetscCall(DMGetWorkArray(dm, size, MPIU_SCALAR, &array));
6833:   } else {
6834:     array = *values;
6835:   }
6836:   size = 0;
6837:   PetscCall(VecGetArrayRead(v, &vArray));
6838:   if ((point >= pStart) && (point < pEnd)) {
6839:     PetscInt           dof, off, d;
6840:     const PetscScalar *varr;

6842:     PetscCall(PetscSectionGetDof(section, point, &dof));
6843:     PetscCall(PetscSectionGetOffset(section, point, &off));
6844:     varr = PetscSafePointerPlusOffset(vArray, off);
6845:     for (d = 0; d < dof; ++d, ++offset) array[offset] = varr[d];
6846:     size += dof;
6847:   }
6848:   for (p = 0; p < numPoints; ++p) {
6849:     const PetscInt     cp = cone[p];
6850:     PetscInt           o  = coneO[p];
6851:     PetscInt           dof, off, d;
6852:     const PetscScalar *varr;

6854:     if ((cp < pStart) || (cp >= pEnd)) continue;
6855:     PetscCall(PetscSectionGetDof(section, cp, &dof));
6856:     PetscCall(PetscSectionGetOffset(section, cp, &off));
6857:     varr = PetscSafePointerPlusOffset(vArray, off);
6858:     if (o >= 0) {
6859:       for (d = 0; d < dof; ++d, ++offset) array[offset] = varr[d];
6860:     } else {
6861:       for (d = dof - 1; d >= 0; --d, ++offset) array[offset] = varr[d];
6862:     }
6863:     size += dof;
6864:   }
6865:   PetscCall(VecRestoreArrayRead(v, &vArray));
6866:   if (!*values) {
6867:     if (csize) *csize = size;
6868:     *values = array;
6869:   } else {
6870:     PetscCheck(size <= *csize, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Size of input array %" PetscInt_FMT " < actual size %" PetscInt_FMT, *csize, size);
6871:     *csize = size;
6872:   }
6873:   PetscFunctionReturn(PETSC_SUCCESS);
6874: }

6876: /* Compress out points not in the section */
6877: static inline PetscErrorCode CompressPoints_Private(PetscSection section, PetscInt *numPoints, PetscInt points[])
6878: {
6879:   const PetscInt np = *numPoints;
6880:   PetscInt       pStart, pEnd, p, q;

6882:   PetscCall(PetscSectionGetChart(section, &pStart, &pEnd));
6883:   for (p = 0, q = 0; p < np; ++p) {
6884:     const PetscInt r = points[p * 2];
6885:     if ((r >= pStart) && (r < pEnd)) {
6886:       points[q * 2]     = r;
6887:       points[q * 2 + 1] = points[p * 2 + 1];
6888:       ++q;
6889:     }
6890:   }
6891:   *numPoints = q;
6892:   return PETSC_SUCCESS;
6893: }

6895: /* Compressed closure does not apply closure permutation */
6896: PetscErrorCode DMPlexGetCompressedClosure(DM dm, PetscSection section, PetscInt point, PetscInt ornt, PetscInt *numPoints, PetscInt **points, PetscSection *clSec, IS *clPoints, const PetscInt **clp)
6897: {
6898:   const PetscInt *cla = NULL;
6899:   PetscInt        np, *pts = NULL;

6901:   PetscFunctionBeginHot;
6902:   PetscCall(PetscSectionGetClosureIndex(section, (PetscObject)dm, clSec, clPoints));
6903:   if (!ornt && *clPoints) {
6904:     PetscInt dof, off;

6906:     PetscCall(PetscSectionGetDof(*clSec, point, &dof));
6907:     PetscCall(PetscSectionGetOffset(*clSec, point, &off));
6908:     PetscCall(ISGetIndices(*clPoints, &cla));
6909:     np  = dof / 2;
6910:     pts = PetscSafePointerPlusOffset((PetscInt *)cla, off);
6911:   } else {
6912:     PetscCall(DMPlexGetTransitiveClosure_Internal(dm, point, ornt, PETSC_TRUE, &np, &pts));
6913:     PetscCall(CompressPoints_Private(section, &np, pts));
6914:   }
6915:   *numPoints = np;
6916:   *points    = pts;
6917:   *clp       = cla;
6918:   PetscFunctionReturn(PETSC_SUCCESS);
6919: }

6921: PetscErrorCode DMPlexRestoreCompressedClosure(DM dm, PetscSection section, PetscInt point, PetscInt *numPoints, PetscInt **points, PetscSection *clSec, IS *clPoints, const PetscInt **clp)
6922: {
6923:   PetscFunctionBeginHot;
6924:   if (!*clPoints) {
6925:     PetscCall(DMPlexRestoreTransitiveClosure(dm, point, PETSC_TRUE, numPoints, points));
6926:   } else {
6927:     PetscCall(ISRestoreIndices(*clPoints, clp));
6928:   }
6929:   *numPoints = 0;
6930:   *points    = NULL;
6931:   *clSec     = NULL;
6932:   *clPoints  = NULL;
6933:   *clp       = NULL;
6934:   PetscFunctionReturn(PETSC_SUCCESS);
6935: }

6937: static inline PetscErrorCode DMPlexVecGetClosure_Static(DM dm, PetscSection section, PetscInt numPoints, const PetscInt points[], const PetscInt clperm[], const PetscScalar vArray[], PetscInt *size, PetscScalar array[])
6938: {
6939:   PetscInt            offset = 0, p;
6940:   const PetscInt    **perms  = NULL;
6941:   const PetscScalar **flips  = NULL;

6943:   PetscFunctionBeginHot;
6944:   *size = 0;
6945:   PetscCall(PetscSectionGetPointSyms(section, numPoints, points, &perms, &flips));
6946:   for (p = 0; p < numPoints; p++) {
6947:     const PetscInt     point = points[2 * p];
6948:     const PetscInt    *perm  = perms ? perms[p] : NULL;
6949:     const PetscScalar *flip  = flips ? flips[p] : NULL;
6950:     PetscInt           dof, off, d;
6951:     const PetscScalar *varr;

6953:     PetscCall(PetscSectionGetDof(section, point, &dof));
6954:     PetscCall(PetscSectionGetOffset(section, point, &off));
6955:     varr = PetscSafePointerPlusOffset(vArray, off);
6956:     if (clperm) {
6957:       if (perm) {
6958:         for (d = 0; d < dof; d++) array[clperm[offset + perm[d]]] = varr[d];
6959:       } else {
6960:         for (d = 0; d < dof; d++) array[clperm[offset + d]] = varr[d];
6961:       }
6962:       if (flip) {
6963:         for (d = 0; d < dof; d++) array[clperm[offset + d]] *= flip[d];
6964:       }
6965:     } else {
6966:       if (perm) {
6967:         for (d = 0; d < dof; d++) array[offset + perm[d]] = varr[d];
6968:       } else {
6969:         for (d = 0; d < dof; d++) array[offset + d] = varr[d];
6970:       }
6971:       if (flip) {
6972:         for (d = 0; d < dof; d++) array[offset + d] *= flip[d];
6973:       }
6974:     }
6975:     offset += dof;
6976:   }
6977:   PetscCall(PetscSectionRestorePointSyms(section, numPoints, points, &perms, &flips));
6978:   *size = offset;
6979:   PetscFunctionReturn(PETSC_SUCCESS);
6980: }

6982: 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[])
6983: {
6984:   PetscInt offset = 0, f;

6986:   PetscFunctionBeginHot;
6987:   *size = 0;
6988:   for (f = 0; f < numFields; ++f) {
6989:     PetscInt            p;
6990:     const PetscInt    **perms = NULL;
6991:     const PetscScalar **flips = NULL;

6993:     PetscCall(PetscSectionGetFieldPointSyms(section, f, numPoints, points, &perms, &flips));
6994:     for (p = 0; p < numPoints; p++) {
6995:       const PetscInt     point = points[2 * p];
6996:       PetscInt           fdof, foff, b;
6997:       const PetscScalar *varr;
6998:       const PetscInt    *perm = perms ? perms[p] : NULL;
6999:       const PetscScalar *flip = flips ? flips[p] : NULL;

7001:       PetscCall(PetscSectionGetFieldDof(section, point, f, &fdof));
7002:       PetscCall(PetscSectionGetFieldOffset(section, point, f, &foff));
7003:       varr = &vArray[foff];
7004:       if (clperm) {
7005:         if (perm) {
7006:           for (b = 0; b < fdof; b++) array[clperm[offset + perm[b]]] = varr[b];
7007:         } else {
7008:           for (b = 0; b < fdof; b++) array[clperm[offset + b]] = varr[b];
7009:         }
7010:         if (flip) {
7011:           for (b = 0; b < fdof; b++) array[clperm[offset + b]] *= flip[b];
7012:         }
7013:       } else {
7014:         if (perm) {
7015:           for (b = 0; b < fdof; b++) array[offset + perm[b]] = varr[b];
7016:         } else {
7017:           for (b = 0; b < fdof; b++) array[offset + b] = varr[b];
7018:         }
7019:         if (flip) {
7020:           for (b = 0; b < fdof; b++) array[offset + b] *= flip[b];
7021:         }
7022:       }
7023:       offset += fdof;
7024:     }
7025:     PetscCall(PetscSectionRestoreFieldPointSyms(section, f, numPoints, points, &perms, &flips));
7026:   }
7027:   *size = offset;
7028:   PetscFunctionReturn(PETSC_SUCCESS);
7029: }

7031: /*@C
7032:   DMPlexVecGetOrientedClosure - Get an array of the values on the closure of 'point' with a given orientation, optionally applying the closure permutation.

7034:   Not collective

7036:   Input Parameters:
7037: + dm        - The `DM`
7038: . section   - The section describing the layout in `v`, or `NULL` to use the default section
7039: . useClPerm - Flag for whether the provided closure permutation should be applied to the values
7040: . v         - The local vector
7041: . point     - The point in the `DM`
7042: - ornt      - The orientation of the cell, an integer giving the prescription for cone traversal. Typically, this will be 0.

7044:   Input/Output Parameters:
7045: + csize  - The size of the input values array, or `NULL`; on output the number of values in the closure
7046: - values - An array to use for the values, or *values = `NULL` to have it allocated automatically;
7047:            if the user provided `NULL`, it is a borrowed array and should not be freed, use  `DMPlexVecRestoreClosure()` to return it

7049:   Level: advanced

7051:   Notes:
7052:   `DMPlexVecGetOrientedClosure()`/`DMPlexVecRestoreClosure()` only allocates the values array if it set to `NULL` in the
7053:   calling function. This is because `DMPlexVecGetOrientedClosure()` is typically called in the inner loop of a `Vec` or `Mat`
7054:   assembly function, and a user may already have allocated storage for this operation.

7056:   Fortran Notes:
7057:   The `csize` argument is present in the Fortran binding. Since the Fortran `values` array contains its length information this argument may not be needed.
7058:   In that case one may pass `PETSC_NULL_INTEGER` for `csize`.

7060:   `values` must be declared with
7061: .vb
7062:   PetscScalar,dimension(:),pointer   :: values
7063: .ve
7064:   and it will be allocated internally by PETSc to hold the values returned

7066: .seealso: [](ch_unstructured), `DM`, `DMPLEX`, `DMPlexVecGetClosure()`, `DMPlexGetCellCoordinates()`, `DMPlexVecRestoreClosure()`, `DMPlexVecSetClosure()`
7067: @*/
7068: PetscErrorCode DMPlexVecGetOrientedClosure(DM dm, PetscSection section, PetscBool useClPerm, Vec v, PetscInt point, PetscInt ornt, PetscInt *csize, PetscScalar *values[])
7069: {
7070:   PetscSection    clSection;
7071:   IS              clPoints;
7072:   PetscInt       *points = NULL;
7073:   const PetscInt *clp, *perm = NULL;
7074:   PetscInt        depth, numFields, numPoints, asize;

7076:   PetscFunctionBeginHot;
7078:   if (!section) PetscCall(DMGetLocalSection(dm, &section));
7081:   PetscCall(DMPlexGetDepth(dm, &depth));
7082:   PetscCall(PetscSectionGetNumFields(section, &numFields));
7083:   if (depth == 1 && numFields < 2) {
7084:     PetscCall(DMPlexVecGetClosure_Depth1_Static(dm, section, v, point, csize, values));
7085:     PetscFunctionReturn(PETSC_SUCCESS);
7086:   }
7087:   /* Get points */
7088:   PetscCall(DMPlexGetCompressedClosure(dm, section, point, ornt, &numPoints, &points, &clSection, &clPoints, &clp));
7089:   /* Get sizes */
7090:   asize = 0;
7091:   for (PetscInt p = 0; p < numPoints * 2; p += 2) {
7092:     PetscInt dof;
7093:     PetscCall(PetscSectionGetDof(section, points[p], &dof));
7094:     asize += dof;
7095:   }
7096:   if (values) {
7097:     const PetscScalar *vArray;
7098:     PetscInt           size;

7100:     if (*values) {
7101:       PetscCheck(*csize >= asize, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Provided array size %" PetscInt_FMT " not sufficient to hold closure size %" PetscInt_FMT, *csize, asize);
7102:     } else PetscCall(DMGetWorkArray(dm, asize, MPIU_SCALAR, values));
7103:     if (useClPerm) PetscCall(PetscSectionGetClosureInversePermutation_Internal(section, (PetscObject)dm, depth, asize, &perm));
7104:     PetscCall(VecGetArrayRead(v, &vArray));
7105:     /* Get values */
7106:     if (numFields > 0) PetscCall(DMPlexVecGetClosure_Fields_Static(dm, section, numPoints, points, numFields, perm, vArray, &size, *values));
7107:     else PetscCall(DMPlexVecGetClosure_Static(dm, section, numPoints, points, perm, vArray, &size, *values));
7108:     PetscCheck(asize == size, PETSC_COMM_SELF, PETSC_ERR_PLIB, "Section size %" PetscInt_FMT " does not match Vec closure size %" PetscInt_FMT, asize, size);
7109:     /* Cleanup array */
7110:     PetscCall(VecRestoreArrayRead(v, &vArray));
7111:   }
7112:   if (csize) *csize = asize;
7113:   /* Cleanup points */
7114:   PetscCall(DMPlexRestoreCompressedClosure(dm, section, point, &numPoints, &points, &clSection, &clPoints, &clp));
7115:   PetscFunctionReturn(PETSC_SUCCESS);
7116: }

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

7121:   Not collective

7123:   Input Parameters:
7124: + dm      - The `DM`
7125: . section - The section describing the layout in `v`, or `NULL` to use the default section
7126: . v       - The local vector
7127: - point   - The point in the `DM`

7129:   Input/Output Parameters:
7130: + csize  - The size of the input values array, or `NULL`; on output the number of values in the closure
7131: - values - An array to use for the values, or *values = `NULL` to have it allocated automatically;
7132:            if the user provided `NULL`, it is a borrowed array and should not be freed, use  `DMPlexVecRestoreClosure()` to return it

7134:   Level: intermediate

7136:   Notes:
7137:   This is used for getting the all values in a `Vec` in the closure of a mesh point.
7138:   To get only the values in the closure of a mesh point at a specific depth (for example, at mesh vertices), use `DMPlexVecGetClosureAtDepth()`.

7140:   `DMPlexVecGetClosure()`/`DMPlexVecRestoreClosure()` only allocates the values array if it set to `NULL` in the
7141:   calling function. This is because `DMPlexVecGetClosure()` is typically called in the inner loop of a `Vec` or `Mat`
7142:   assembly function, and a user may already have allocated storage for this operation.

7144:   A typical use could be
7145: .vb
7146:    values = NULL;
7147:    PetscCall(DMPlexVecGetClosure(dm, NULL, v, p, &clSize, &values));
7148:    for (cl = 0; cl < clSize; ++cl) {
7149:      <Compute on closure>
7150:    }
7151:    PetscCall(DMPlexVecRestoreClosure(dm, NULL, v, p, &clSize, &values));
7152: .ve
7153:   or
7154: .vb
7155:    PetscMalloc1(clMaxSize, &values);
7156:    for (p = pStart; p < pEnd; ++p) {
7157:      clSize = clMaxSize;
7158:      PetscCall(DMPlexVecGetClosure(dm, NULL, v, p, &clSize, &values));
7159:      for (cl = 0; cl < clSize; ++cl) {
7160:        <Compute on closure>
7161:      }
7162:    }
7163:    PetscFree(values);
7164: .ve

7166:   Fortran Notes:
7167:   The `csize` argument is present in the Fortran binding. Since the Fortran `values` array contains its length information this argument may not be needed.
7168:   In that case one may pass `PETSC_NULL_INTEGER` for `csize`.

7170:   `values` must be declared with
7171: .vb
7172:   PetscScalar,dimension(:),pointer   :: values
7173: .ve
7174:   and it will be allocated internally by PETSc to hold the values returned

7176: .seealso: [](ch_unstructured), `DM`, `DMPLEX`, `DMPlexVecGetClosureAtDepth()`, `DMPlexVecRestoreClosure()`, `DMPlexVecSetClosure()`, `DMPlexMatSetClosure()`
7177: @*/
7178: PetscErrorCode DMPlexVecGetClosure(DM dm, PetscSection section, Vec v, PetscInt point, PetscInt *csize, PetscScalar *values[])
7179: {
7180:   PetscFunctionBeginHot;
7181:   PetscCall(DMPlexVecGetOrientedClosure(dm, section, PETSC_TRUE, v, point, 0, csize, values));
7182:   PetscFunctionReturn(PETSC_SUCCESS);
7183: }

7185: /*@C
7186:   DMPlexVecGetClosureAtDepth - Get an array of the values on the closure of 'point' that are at a specific depth

7188:   Not collective

7190:   Input Parameters:
7191: + dm      - The `DM`
7192: . section - The section describing the layout in `v`, or `NULL` to use the default section
7193: . v       - The local vector
7194: . depth   - The depth of mesh points that should be returned
7195: - point   - The point in the `DM`

7197:   Input/Output Parameters:
7198: + csize  - The size of the input values array, or `NULL`; on output the number of values in the closure
7199: - values - An array to use for the values, or *values = `NULL` to have it allocated automatically;
7200:            if the user provided `NULL`, it is a borrowed array and should not be freed, use  `DMPlexVecRestoreClosure()` to return it

7202:   Level: intermediate

7204:   Notes:
7205:   This is used for getting the values in a `Vec` associated with specific mesh points.
7206:   For example, to get only the values at mesh vertices, pass `depth=0`. To get all the values in the closure of a mesh point, use `DMPlexVecGetClosure()`.

7208:   `DMPlexVecGetClosureAtDepth()`/`DMPlexVecRestoreClosure()` only allocates the values array if it set to `NULL` in the
7209:   calling function. This is because `DMPlexVecGetClosureAtDepth()` is typically called in the inner loop of a `Vec` or `Mat`
7210:   assembly function, and a user may already have allocated storage for this operation.

7212:   A typical use could be
7213: .vb
7214:    values = NULL;
7215:    PetscCall(DMPlexVecGetClosureAtDepth(dm, NULL, v, p, depth, &clSize, &values));
7216:    for (cl = 0; cl < clSize; ++cl) {
7217:      <Compute on closure>
7218:    }
7219:    PetscCall(DMPlexVecRestoreClosure(dm, NULL, v, p, &clSize, &values));
7220: .ve
7221:   or
7222: .vb
7223:    PetscMalloc1(clMaxSize, &values);
7224:    for (p = pStart; p < pEnd; ++p) {
7225:      clSize = clMaxSize;
7226:      PetscCall(DMPlexVecGetClosureAtDepth(dm, NULL, v, p, depth, &clSize, &values));
7227:      for (cl = 0; cl < clSize; ++cl) {
7228:        <Compute on closure>
7229:      }
7230:    }
7231:    PetscFree(values);
7232: .ve

7234:   Fortran Notes:
7235:   The `csize` argument is present in the Fortran binding. Since the Fortran `values` array contains its length information this argument may not be needed.
7236:   In that case one may pass `PETSC_NULL_INTEGER` for `csize`.

7238:   `values` must be declared with
7239: .vb
7240:   PetscScalar,dimension(:),pointer   :: values
7241: .ve
7242:   and it will be allocated internally by PETSc to hold the values returned

7244: .seealso: [](ch_unstructured), `DM`, `DMPLEX`, `DMPlexVecGetClosure()`, `DMPlexVecRestoreClosure()`, `DMPlexVecSetClosure()`, `DMPlexMatSetClosure()`
7245: @*/
7246: PetscErrorCode DMPlexVecGetClosureAtDepth(DM dm, PetscSection section, Vec v, PetscInt point, PetscInt depth, PetscInt *csize, PetscScalar *values[])
7247: {
7248:   DMLabel            depthLabel;
7249:   PetscSection       clSection;
7250:   IS                 clPoints;
7251:   PetscScalar       *array;
7252:   const PetscScalar *vArray;
7253:   PetscInt          *points = NULL;
7254:   const PetscInt    *clp, *perm = NULL;
7255:   PetscInt           mdepth, numFields, numPoints, Np = 0, p, clsize, size;

7257:   PetscFunctionBeginHot;
7259:   if (!section) PetscCall(DMGetLocalSection(dm, &section));
7262:   PetscCall(DMPlexGetDepth(dm, &mdepth));
7263:   PetscCall(DMPlexGetDepthLabel(dm, &depthLabel));
7264:   PetscCall(PetscSectionGetNumFields(section, &numFields));
7265:   if (mdepth == 1 && numFields < 2) {
7266:     PetscCall(DMPlexVecGetClosure_Depth1_Static(dm, section, v, point, csize, values));
7267:     PetscFunctionReturn(PETSC_SUCCESS);
7268:   }
7269:   /* Get points */
7270:   PetscCall(DMPlexGetCompressedClosure(dm, section, point, 0, &numPoints, &points, &clSection, &clPoints, &clp));
7271:   for (clsize = 0, p = 0; p < Np; p++) {
7272:     PetscInt dof;
7273:     PetscCall(PetscSectionGetDof(section, points[2 * p], &dof));
7274:     clsize += dof;
7275:   }
7276:   PetscCall(PetscSectionGetClosureInversePermutation_Internal(section, (PetscObject)dm, depth, clsize, &perm));
7277:   /* Filter points */
7278:   for (p = 0; p < numPoints * 2; p += 2) {
7279:     PetscInt dep;

7281:     PetscCall(DMLabelGetValue(depthLabel, points[p], &dep));
7282:     if (dep != depth) continue;
7283:     points[Np * 2 + 0] = points[p];
7284:     points[Np * 2 + 1] = points[p + 1];
7285:     ++Np;
7286:   }
7287:   /* Get array */
7288:   if (!values || !*values) {
7289:     PetscInt asize = 0, dof;

7291:     for (p = 0; p < Np * 2; p += 2) {
7292:       PetscCall(PetscSectionGetDof(section, points[p], &dof));
7293:       asize += dof;
7294:     }
7295:     if (!values) {
7296:       PetscCall(DMPlexRestoreCompressedClosure(dm, section, point, &numPoints, &points, &clSection, &clPoints, &clp));
7297:       if (csize) *csize = asize;
7298:       PetscFunctionReturn(PETSC_SUCCESS);
7299:     }
7300:     PetscCall(DMGetWorkArray(dm, asize, MPIU_SCALAR, &array));
7301:   } else {
7302:     array = *values;
7303:   }
7304:   PetscCall(VecGetArrayRead(v, &vArray));
7305:   /* Get values */
7306:   if (numFields > 0) PetscCall(DMPlexVecGetClosure_Fields_Static(dm, section, Np, points, numFields, perm, vArray, &size, array));
7307:   else PetscCall(DMPlexVecGetClosure_Static(dm, section, Np, points, perm, vArray, &size, array));
7308:   /* Cleanup points */
7309:   PetscCall(DMPlexRestoreCompressedClosure(dm, section, point, &numPoints, &points, &clSection, &clPoints, &clp));
7310:   /* Cleanup array */
7311:   PetscCall(VecRestoreArrayRead(v, &vArray));
7312:   if (!*values) {
7313:     if (csize) *csize = size;
7314:     *values = array;
7315:   } else {
7316:     PetscCheck(size <= *csize, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Size of input array %" PetscInt_FMT " < actual size %" PetscInt_FMT, *csize, size);
7317:     *csize = size;
7318:   }
7319:   PetscFunctionReturn(PETSC_SUCCESS);
7320: }

7322: /*@C
7323:   DMPlexVecRestoreClosure - Restore the array of the values on the closure of 'point' obtained with `DMPlexVecGetClosure()`

7325:   Not collective

7327:   Input Parameters:
7328: + dm      - The `DM`
7329: . section - The section describing the layout in `v`, or `NULL` to use the default section
7330: . v       - The local vector
7331: . point   - The point in the `DM`
7332: . csize   - The number of values in the closure, or `NULL`
7333: - values  - The array of values

7335:   Level: intermediate

7337:   Note:
7338:   The array values are discarded and not copied back into `v`. In order to copy values back to `v`, use `DMPlexVecSetClosure()`

7340:   Fortran Note:
7341:   The `csize` argument is present in the Fortran binding. Since the Fortran `values` array contains its length information this argument may not be needed.
7342:   In that case one may pass `PETSC_NULL_INTEGER` for `csize`.

7344: .seealso: [](ch_unstructured), `DM`, `DMPLEX`, `DMPlexVecGetClosure()`, `DMPlexVecSetClosure()`, `DMPlexMatSetClosure()`
7345: @*/
7346: PetscErrorCode DMPlexVecRestoreClosure(DM dm, PetscSection section, Vec v, PetscInt point, PetscInt *csize, PetscScalar *values[])
7347: {
7348:   PetscInt size = 0;

7350:   PetscFunctionBegin;
7351:   /* Should work without recalculating size */
7352:   PetscCall(DMRestoreWorkArray(dm, size, MPIU_SCALAR, (void *)values));
7353:   *values = NULL;
7354:   PetscFunctionReturn(PETSC_SUCCESS);
7355: }

7357: static inline void add(PetscScalar *x, PetscScalar y)
7358: {
7359:   *x += y;
7360: }
7361: static inline void insert(PetscScalar *x, PetscScalar y)
7362: {
7363:   *x = y;
7364: }

7366: 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[])
7367: {
7368:   PetscInt        cdof;  /* The number of constraints on this point */
7369:   const PetscInt *cdofs; /* The indices of the constrained dofs on this point */
7370:   PetscScalar    *a;
7371:   PetscInt        off, cind = 0, k;

7373:   PetscFunctionBegin;
7374:   PetscCall(PetscSectionGetConstraintDof(section, point, &cdof));
7375:   PetscCall(PetscSectionGetOffset(section, point, &off));
7376:   a = &array[off];
7377:   if (!cdof || setBC) {
7378:     if (clperm) {
7379:       if (perm) {
7380:         for (k = 0; k < dof; ++k) fuse(&a[k], values[clperm[offset + perm[k]]] * (flip ? flip[perm[k]] : 1.));
7381:       } else {
7382:         for (k = 0; k < dof; ++k) fuse(&a[k], values[clperm[offset + k]] * (flip ? flip[k] : 1.));
7383:       }
7384:     } else {
7385:       if (perm) {
7386:         for (k = 0; k < dof; ++k) fuse(&a[k], values[offset + perm[k]] * (flip ? flip[perm[k]] : 1.));
7387:       } else {
7388:         for (k = 0; k < dof; ++k) fuse(&a[k], values[offset + k] * (flip ? flip[k] : 1.));
7389:       }
7390:     }
7391:   } else {
7392:     PetscCall(PetscSectionGetConstraintIndices(section, point, &cdofs));
7393:     if (clperm) {
7394:       if (perm) {
7395:         for (k = 0; k < dof; ++k) {
7396:           if ((cind < cdof) && (k == cdofs[cind])) {
7397:             ++cind;
7398:             continue;
7399:           }
7400:           fuse(&a[k], values[clperm[offset + perm[k]]] * (flip ? flip[perm[k]] : 1.));
7401:         }
7402:       } else {
7403:         for (k = 0; k < dof; ++k) {
7404:           if ((cind < cdof) && (k == cdofs[cind])) {
7405:             ++cind;
7406:             continue;
7407:           }
7408:           fuse(&a[k], values[clperm[offset + k]] * (flip ? flip[k] : 1.));
7409:         }
7410:       }
7411:     } else {
7412:       if (perm) {
7413:         for (k = 0; k < dof; ++k) {
7414:           if ((cind < cdof) && (k == cdofs[cind])) {
7415:             ++cind;
7416:             continue;
7417:           }
7418:           fuse(&a[k], values[offset + perm[k]] * (flip ? flip[perm[k]] : 1.));
7419:         }
7420:       } else {
7421:         for (k = 0; k < dof; ++k) {
7422:           if ((cind < cdof) && (k == cdofs[cind])) {
7423:             ++cind;
7424:             continue;
7425:           }
7426:           fuse(&a[k], values[offset + k] * (flip ? flip[k] : 1.));
7427:         }
7428:       }
7429:     }
7430:   }
7431:   PetscFunctionReturn(PETSC_SUCCESS);
7432: }

7434: 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[])
7435: {
7436:   PetscInt        cdof;  /* The number of constraints on this point */
7437:   const PetscInt *cdofs; /* The indices of the constrained dofs on this point */
7438:   PetscScalar    *a;
7439:   PetscInt        off, cind = 0, k;

7441:   PetscFunctionBegin;
7442:   PetscCall(PetscSectionGetConstraintDof(section, point, &cdof));
7443:   PetscCall(PetscSectionGetOffset(section, point, &off));
7444:   a = &array[off];
7445:   if (cdof) {
7446:     PetscCall(PetscSectionGetConstraintIndices(section, point, &cdofs));
7447:     if (clperm) {
7448:       if (perm) {
7449:         for (k = 0; k < dof; ++k) {
7450:           if ((cind < cdof) && (k == cdofs[cind])) {
7451:             fuse(&a[k], values[clperm[offset + perm[k]]] * (flip ? flip[perm[k]] : 1.));
7452:             cind++;
7453:           }
7454:         }
7455:       } else {
7456:         for (k = 0; k < dof; ++k) {
7457:           if ((cind < cdof) && (k == cdofs[cind])) {
7458:             fuse(&a[k], values[clperm[offset + k]] * (flip ? flip[k] : 1.));
7459:             cind++;
7460:           }
7461:         }
7462:       }
7463:     } else {
7464:       if (perm) {
7465:         for (k = 0; k < dof; ++k) {
7466:           if ((cind < cdof) && (k == cdofs[cind])) {
7467:             fuse(&a[k], values[offset + perm[k]] * (flip ? flip[perm[k]] : 1.));
7468:             cind++;
7469:           }
7470:         }
7471:       } else {
7472:         for (k = 0; k < dof; ++k) {
7473:           if ((cind < cdof) && (k == cdofs[cind])) {
7474:             fuse(&a[k], values[offset + k] * (flip ? flip[k] : 1.));
7475:             cind++;
7476:           }
7477:         }
7478:       }
7479:     }
7480:   }
7481:   PetscFunctionReturn(PETSC_SUCCESS);
7482: }

7484: 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[])
7485: {
7486:   PetscScalar    *a;
7487:   PetscInt        fdof, foff, fcdof, foffset = *offset;
7488:   const PetscInt *fcdofs; /* The indices of the constrained dofs for field f on this point */
7489:   PetscInt        cind = 0, b;

7491:   PetscFunctionBegin;
7492:   PetscCall(PetscSectionGetFieldDof(section, point, f, &fdof));
7493:   PetscCall(PetscSectionGetFieldConstraintDof(section, point, f, &fcdof));
7494:   PetscCall(PetscSectionGetFieldOffset(section, point, f, &foff));
7495:   a = &array[foff];
7496:   if (!fcdof || setBC) {
7497:     if (clperm) {
7498:       if (perm) {
7499:         for (b = 0; b < fdof; b++) fuse(&a[b], values[clperm[foffset + perm[b]]] * (flip ? flip[perm[b]] : 1.));
7500:       } else {
7501:         for (b = 0; b < fdof; b++) fuse(&a[b], values[clperm[foffset + b]] * (flip ? flip[b] : 1.));
7502:       }
7503:     } else {
7504:       if (perm) {
7505:         for (b = 0; b < fdof; b++) fuse(&a[b], values[foffset + perm[b]] * (flip ? flip[perm[b]] : 1.));
7506:       } else {
7507:         for (b = 0; b < fdof; b++) fuse(&a[b], values[foffset + b] * (flip ? flip[b] : 1.));
7508:       }
7509:     }
7510:   } else {
7511:     PetscCall(PetscSectionGetFieldConstraintIndices(section, point, f, &fcdofs));
7512:     if (clperm) {
7513:       if (perm) {
7514:         for (b = 0; b < fdof; b++) {
7515:           if ((cind < fcdof) && (b == fcdofs[cind])) {
7516:             ++cind;
7517:             continue;
7518:           }
7519:           fuse(&a[b], values[clperm[foffset + perm[b]]] * (flip ? flip[perm[b]] : 1.));
7520:         }
7521:       } else {
7522:         for (b = 0; b < fdof; b++) {
7523:           if ((cind < fcdof) && (b == fcdofs[cind])) {
7524:             ++cind;
7525:             continue;
7526:           }
7527:           fuse(&a[b], values[clperm[foffset + b]] * (flip ? flip[b] : 1.));
7528:         }
7529:       }
7530:     } else {
7531:       if (perm) {
7532:         for (b = 0; b < fdof; b++) {
7533:           if ((cind < fcdof) && (b == fcdofs[cind])) {
7534:             ++cind;
7535:             continue;
7536:           }
7537:           fuse(&a[b], values[foffset + perm[b]] * (flip ? flip[perm[b]] : 1.));
7538:         }
7539:       } else {
7540:         for (b = 0; b < fdof; b++) {
7541:           if ((cind < fcdof) && (b == fcdofs[cind])) {
7542:             ++cind;
7543:             continue;
7544:           }
7545:           fuse(&a[b], values[foffset + b] * (flip ? flip[b] : 1.));
7546:         }
7547:       }
7548:     }
7549:   }
7550:   *offset += fdof;
7551:   PetscFunctionReturn(PETSC_SUCCESS);
7552: }

7554: 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[])
7555: {
7556:   PetscScalar    *a;
7557:   PetscInt        fdof, foff, fcdof, foffset = *offset;
7558:   const PetscInt *fcdofs; /* The indices of the constrained dofs for field f on this point */
7559:   PetscInt        Nc, cind = 0, ncind = 0, b;
7560:   PetscBool       ncSet, fcSet;

7562:   PetscFunctionBegin;
7563:   PetscCall(PetscSectionGetFieldComponents(section, f, &Nc));
7564:   PetscCall(PetscSectionGetFieldDof(section, point, f, &fdof));
7565:   PetscCall(PetscSectionGetFieldConstraintDof(section, point, f, &fcdof));
7566:   PetscCall(PetscSectionGetFieldOffset(section, point, f, &foff));
7567:   a = &array[foff];
7568:   if (fcdof) {
7569:     /* We just override fcdof and fcdofs with Ncc and comps */
7570:     PetscCall(PetscSectionGetFieldConstraintIndices(section, point, f, &fcdofs));
7571:     if (clperm) {
7572:       if (perm) {
7573:         if (comps) {
7574:           for (b = 0; b < fdof; b++) {
7575:             ncSet = fcSet = PETSC_FALSE;
7576:             if (b % Nc == comps[ncind]) {
7577:               ncind = (ncind + 1) % Ncc;
7578:               ncSet = PETSC_TRUE;
7579:             }
7580:             if ((cind < fcdof) && (b == fcdofs[cind])) {
7581:               ++cind;
7582:               fcSet = PETSC_TRUE;
7583:             }
7584:             if (ncSet && fcSet) fuse(&a[b], values[clperm[foffset + perm[b]]] * (flip ? flip[perm[b]] : 1.));
7585:           }
7586:         } else {
7587:           for (b = 0; b < fdof; b++) {
7588:             if ((cind < fcdof) && (b == fcdofs[cind])) {
7589:               fuse(&a[b], values[clperm[foffset + perm[b]]] * (flip ? flip[perm[b]] : 1.));
7590:               ++cind;
7591:             }
7592:           }
7593:         }
7594:       } else {
7595:         if (comps) {
7596:           for (b = 0; b < fdof; b++) {
7597:             ncSet = fcSet = PETSC_FALSE;
7598:             if (b % Nc == comps[ncind]) {
7599:               ncind = (ncind + 1) % Ncc;
7600:               ncSet = PETSC_TRUE;
7601:             }
7602:             if ((cind < fcdof) && (b == fcdofs[cind])) {
7603:               ++cind;
7604:               fcSet = PETSC_TRUE;
7605:             }
7606:             if (ncSet && fcSet) fuse(&a[b], values[clperm[foffset + b]] * (flip ? flip[b] : 1.));
7607:           }
7608:         } else {
7609:           for (b = 0; b < fdof; b++) {
7610:             if ((cind < fcdof) && (b == fcdofs[cind])) {
7611:               fuse(&a[b], values[clperm[foffset + b]] * (flip ? flip[b] : 1.));
7612:               ++cind;
7613:             }
7614:           }
7615:         }
7616:       }
7617:     } else {
7618:       if (perm) {
7619:         if (comps) {
7620:           for (b = 0; b < fdof; b++) {
7621:             ncSet = fcSet = PETSC_FALSE;
7622:             if (b % Nc == comps[ncind]) {
7623:               ncind = (ncind + 1) % Ncc;
7624:               ncSet = PETSC_TRUE;
7625:             }
7626:             if ((cind < fcdof) && (b == fcdofs[cind])) {
7627:               ++cind;
7628:               fcSet = PETSC_TRUE;
7629:             }
7630:             if (ncSet && fcSet) fuse(&a[b], values[foffset + perm[b]] * (flip ? flip[perm[b]] : 1.));
7631:           }
7632:         } else {
7633:           for (b = 0; b < fdof; b++) {
7634:             if ((cind < fcdof) && (b == fcdofs[cind])) {
7635:               fuse(&a[b], values[foffset + perm[b]] * (flip ? flip[perm[b]] : 1.));
7636:               ++cind;
7637:             }
7638:           }
7639:         }
7640:       } else {
7641:         if (comps) {
7642:           for (b = 0; b < fdof; b++) {
7643:             ncSet = fcSet = PETSC_FALSE;
7644:             if (b % Nc == comps[ncind]) {
7645:               ncind = (ncind + 1) % Ncc;
7646:               ncSet = PETSC_TRUE;
7647:             }
7648:             if ((cind < fcdof) && (b == fcdofs[cind])) {
7649:               ++cind;
7650:               fcSet = PETSC_TRUE;
7651:             }
7652:             if (ncSet && fcSet) fuse(&a[b], values[foffset + b] * (flip ? flip[b] : 1.));
7653:           }
7654:         } else {
7655:           for (b = 0; b < fdof; b++) {
7656:             if ((cind < fcdof) && (b == fcdofs[cind])) {
7657:               fuse(&a[b], values[foffset + b] * (flip ? flip[b] : 1.));
7658:               ++cind;
7659:             }
7660:           }
7661:         }
7662:       }
7663:     }
7664:   }
7665:   *offset += fdof;
7666:   PetscFunctionReturn(PETSC_SUCCESS);
7667: }

7669: static inline PetscErrorCode DMPlexVecSetClosure_Depth1_Static(DM dm, PetscSection section, Vec v, PetscInt point, const PetscScalar values[], InsertMode mode)
7670: {
7671:   PetscScalar    *array;
7672:   const PetscInt *cone, *coneO;
7673:   PetscInt        pStart, pEnd, p, numPoints, off, dof;

7675:   PetscFunctionBeginHot;
7676:   PetscCall(PetscSectionGetChart(section, &pStart, &pEnd));
7677:   PetscCall(DMPlexGetConeSize(dm, point, &numPoints));
7678:   PetscCall(DMPlexGetCone(dm, point, &cone));
7679:   PetscCall(DMPlexGetConeOrientation(dm, point, &coneO));
7680:   PetscCall(VecGetArray(v, &array));
7681:   for (p = 0, off = 0; p <= numPoints; ++p, off += dof) {
7682:     const PetscInt cp = !p ? point : cone[p - 1];
7683:     const PetscInt o  = !p ? 0 : coneO[p - 1];

7685:     if ((cp < pStart) || (cp >= pEnd)) {
7686:       dof = 0;
7687:       continue;
7688:     }
7689:     PetscCall(PetscSectionGetDof(section, cp, &dof));
7690:     /* ADD_VALUES */
7691:     {
7692:       const PetscInt *cdofs; /* The indices of the constrained dofs on this point */
7693:       PetscScalar    *a;
7694:       PetscInt        cdof, coff, cind = 0, k;

7696:       PetscCall(PetscSectionGetConstraintDof(section, cp, &cdof));
7697:       PetscCall(PetscSectionGetOffset(section, cp, &coff));
7698:       a = &array[coff];
7699:       if (!cdof) {
7700:         if (o >= 0) {
7701:           for (k = 0; k < dof; ++k) a[k] += values[off + k];
7702:         } else {
7703:           for (k = 0; k < dof; ++k) a[k] += values[off + dof - k - 1];
7704:         }
7705:       } else {
7706:         PetscCall(PetscSectionGetConstraintIndices(section, cp, &cdofs));
7707:         if (o >= 0) {
7708:           for (k = 0; k < dof; ++k) {
7709:             if ((cind < cdof) && (k == cdofs[cind])) {
7710:               ++cind;
7711:               continue;
7712:             }
7713:             a[k] += values[off + k];
7714:           }
7715:         } else {
7716:           for (k = 0; k < dof; ++k) {
7717:             if ((cind < cdof) && (k == cdofs[cind])) {
7718:               ++cind;
7719:               continue;
7720:             }
7721:             a[k] += values[off + dof - k - 1];
7722:           }
7723:         }
7724:       }
7725:     }
7726:   }
7727:   PetscCall(VecRestoreArray(v, &array));
7728:   PetscFunctionReturn(PETSC_SUCCESS);
7729: }

7731: /*@C
7732:   DMPlexVecSetClosure - Set an array of the values on the closure of `point`

7734:   Not collective

7736:   Input Parameters:
7737: + dm      - The `DM`
7738: . section - The section describing the layout in `v`, or `NULL` to use the default section
7739: . v       - The local vector
7740: . point   - The point in the `DM`
7741: . values  - The array of values
7742: - mode    - The insert mode. One of `INSERT_ALL_VALUES`, `ADD_ALL_VALUES`, `INSERT_VALUES`, `ADD_VALUES`, `INSERT_BC_VALUES`, and `ADD_BC_VALUES`,
7743:             where `INSERT_ALL_VALUES` and `ADD_ALL_VALUES` also overwrite boundary conditions.

7745:   Level: intermediate

7747:   Note:
7748:   Usually the input arrays were obtained with `DMPlexVecGetClosure()`

7750: .seealso: [](ch_unstructured), `DM`, `DMPLEX`, `DMPlexVecGetClosure()`, `DMPlexMatSetClosure()`
7751: @*/
7752: PetscErrorCode DMPlexVecSetClosure(DM dm, PetscSection section, Vec v, PetscInt point, const PetscScalar values[], InsertMode mode)
7753: {
7754:   PetscSection    clSection;
7755:   IS              clPoints;
7756:   PetscScalar    *array;
7757:   PetscInt       *points = NULL;
7758:   const PetscInt *clp, *clperm = NULL;
7759:   PetscInt        depth, numFields, numPoints, p, clsize;

7761:   PetscFunctionBeginHot;
7763:   if (!section) PetscCall(DMGetLocalSection(dm, &section));
7766:   PetscCall(DMPlexGetDepth(dm, &depth));
7767:   PetscCall(PetscSectionGetNumFields(section, &numFields));
7768:   if (depth == 1 && numFields < 2 && mode == ADD_VALUES) {
7769:     PetscCall(DMPlexVecSetClosure_Depth1_Static(dm, section, v, point, values, mode));
7770:     PetscFunctionReturn(PETSC_SUCCESS);
7771:   }
7772:   /* Get points */
7773:   PetscCall(DMPlexGetCompressedClosure(dm, section, point, 0, &numPoints, &points, &clSection, &clPoints, &clp));
7774:   for (clsize = 0, p = 0; p < numPoints; p++) {
7775:     PetscInt dof;
7776:     PetscCall(PetscSectionGetDof(section, points[2 * p], &dof));
7777:     clsize += dof;
7778:   }
7779:   PetscCall(PetscSectionGetClosureInversePermutation_Internal(section, (PetscObject)dm, depth, clsize, &clperm));
7780:   /* Get array */
7781:   PetscCall(VecGetArray(v, &array));
7782:   /* Get values */
7783:   if (numFields > 0) {
7784:     PetscInt offset = 0, f;
7785:     for (f = 0; f < numFields; ++f) {
7786:       const PetscInt    **perms = NULL;
7787:       const PetscScalar **flips = NULL;

7789:       PetscCall(PetscSectionGetFieldPointSyms(section, f, numPoints, points, &perms, &flips));
7790:       switch (mode) {
7791:       case INSERT_VALUES:
7792:         for (p = 0; p < numPoints; p++) {
7793:           const PetscInt     point = points[2 * p];
7794:           const PetscInt    *perm  = perms ? perms[p] : NULL;
7795:           const PetscScalar *flip  = flips ? flips[p] : NULL;
7796:           PetscCall(updatePointFields_private(section, point, perm, flip, f, insert, PETSC_FALSE, clperm, values, &offset, array));
7797:         }
7798:         break;
7799:       case INSERT_ALL_VALUES:
7800:         for (p = 0; p < numPoints; p++) {
7801:           const PetscInt     point = points[2 * p];
7802:           const PetscInt    *perm  = perms ? perms[p] : NULL;
7803:           const PetscScalar *flip  = flips ? flips[p] : NULL;
7804:           PetscCall(updatePointFields_private(section, point, perm, flip, f, insert, PETSC_TRUE, clperm, values, &offset, array));
7805:         }
7806:         break;
7807:       case INSERT_BC_VALUES:
7808:         for (p = 0; p < numPoints; p++) {
7809:           const PetscInt     point = points[2 * p];
7810:           const PetscInt    *perm  = perms ? perms[p] : NULL;
7811:           const PetscScalar *flip  = flips ? flips[p] : NULL;
7812:           PetscCall(updatePointFieldsBC_private(section, point, perm, flip, f, -1, NULL, insert, clperm, values, &offset, array));
7813:         }
7814:         break;
7815:       case ADD_VALUES:
7816:         for (p = 0; p < numPoints; p++) {
7817:           const PetscInt     point = points[2 * p];
7818:           const PetscInt    *perm  = perms ? perms[p] : NULL;
7819:           const PetscScalar *flip  = flips ? flips[p] : NULL;
7820:           PetscCall(updatePointFields_private(section, point, perm, flip, f, add, PETSC_FALSE, clperm, values, &offset, array));
7821:         }
7822:         break;
7823:       case ADD_ALL_VALUES:
7824:         for (p = 0; p < numPoints; p++) {
7825:           const PetscInt     point = points[2 * p];
7826:           const PetscInt    *perm  = perms ? perms[p] : NULL;
7827:           const PetscScalar *flip  = flips ? flips[p] : NULL;
7828:           PetscCall(updatePointFields_private(section, point, perm, flip, f, add, PETSC_TRUE, clperm, values, &offset, array));
7829:         }
7830:         break;
7831:       case ADD_BC_VALUES:
7832:         for (p = 0; p < numPoints; p++) {
7833:           const PetscInt     point = points[2 * p];
7834:           const PetscInt    *perm  = perms ? perms[p] : NULL;
7835:           const PetscScalar *flip  = flips ? flips[p] : NULL;
7836:           PetscCall(updatePointFieldsBC_private(section, point, perm, flip, f, -1, NULL, add, clperm, values, &offset, array));
7837:         }
7838:         break;
7839:       default:
7840:         SETERRQ(PetscObjectComm((PetscObject)dm), PETSC_ERR_ARG_OUTOFRANGE, "Invalid insert mode %d", mode);
7841:       }
7842:       PetscCall(PetscSectionRestoreFieldPointSyms(section, f, numPoints, points, &perms, &flips));
7843:     }
7844:   } else {
7845:     PetscInt            dof, off;
7846:     const PetscInt    **perms = NULL;
7847:     const PetscScalar **flips = NULL;

7849:     PetscCall(PetscSectionGetPointSyms(section, numPoints, points, &perms, &flips));
7850:     switch (mode) {
7851:     case INSERT_VALUES:
7852:       for (p = 0, off = 0; p < numPoints; p++, off += dof) {
7853:         const PetscInt     point = points[2 * p];
7854:         const PetscInt    *perm  = perms ? perms[p] : NULL;
7855:         const PetscScalar *flip  = flips ? flips[p] : NULL;
7856:         PetscCall(PetscSectionGetDof(section, point, &dof));
7857:         PetscCall(updatePoint_private(section, point, dof, insert, PETSC_FALSE, perm, flip, clperm, values, off, array));
7858:       }
7859:       break;
7860:     case INSERT_ALL_VALUES:
7861:       for (p = 0, off = 0; p < numPoints; p++, off += dof) {
7862:         const PetscInt     point = points[2 * p];
7863:         const PetscInt    *perm  = perms ? perms[p] : NULL;
7864:         const PetscScalar *flip  = flips ? flips[p] : NULL;
7865:         PetscCall(PetscSectionGetDof(section, point, &dof));
7866:         PetscCall(updatePoint_private(section, point, dof, insert, PETSC_TRUE, perm, flip, clperm, values, off, array));
7867:       }
7868:       break;
7869:     case INSERT_BC_VALUES:
7870:       for (p = 0, off = 0; p < numPoints; p++, off += dof) {
7871:         const PetscInt     point = points[2 * p];
7872:         const PetscInt    *perm  = perms ? perms[p] : NULL;
7873:         const PetscScalar *flip  = flips ? flips[p] : NULL;
7874:         PetscCall(PetscSectionGetDof(section, point, &dof));
7875:         PetscCall(updatePointBC_private(section, point, dof, insert, perm, flip, clperm, values, off, array));
7876:       }
7877:       break;
7878:     case ADD_VALUES:
7879:       for (p = 0, off = 0; p < numPoints; p++, off += dof) {
7880:         const PetscInt     point = points[2 * p];
7881:         const PetscInt    *perm  = perms ? perms[p] : NULL;
7882:         const PetscScalar *flip  = flips ? flips[p] : NULL;
7883:         PetscCall(PetscSectionGetDof(section, point, &dof));
7884:         PetscCall(updatePoint_private(section, point, dof, add, PETSC_FALSE, perm, flip, clperm, values, off, array));
7885:       }
7886:       break;
7887:     case ADD_ALL_VALUES:
7888:       for (p = 0, off = 0; p < numPoints; p++, off += dof) {
7889:         const PetscInt     point = points[2 * p];
7890:         const PetscInt    *perm  = perms ? perms[p] : NULL;
7891:         const PetscScalar *flip  = flips ? flips[p] : NULL;
7892:         PetscCall(PetscSectionGetDof(section, point, &dof));
7893:         PetscCall(updatePoint_private(section, point, dof, add, PETSC_TRUE, perm, flip, clperm, values, off, array));
7894:       }
7895:       break;
7896:     case ADD_BC_VALUES:
7897:       for (p = 0, off = 0; p < numPoints; p++, off += dof) {
7898:         const PetscInt     point = points[2 * p];
7899:         const PetscInt    *perm  = perms ? perms[p] : NULL;
7900:         const PetscScalar *flip  = flips ? flips[p] : NULL;
7901:         PetscCall(PetscSectionGetDof(section, point, &dof));
7902:         PetscCall(updatePointBC_private(section, point, dof, add, perm, flip, clperm, values, off, array));
7903:       }
7904:       break;
7905:     default:
7906:       SETERRQ(PetscObjectComm((PetscObject)dm), PETSC_ERR_ARG_OUTOFRANGE, "Invalid insert mode %d", mode);
7907:     }
7908:     PetscCall(PetscSectionRestorePointSyms(section, numPoints, points, &perms, &flips));
7909:   }
7910:   /* Cleanup points */
7911:   PetscCall(DMPlexRestoreCompressedClosure(dm, section, point, &numPoints, &points, &clSection, &clPoints, &clp));
7912:   /* Cleanup array */
7913:   PetscCall(VecRestoreArray(v, &array));
7914:   PetscFunctionReturn(PETSC_SUCCESS);
7915: }

7917: /* Check whether the given point is in the label. If not, update the offset to skip this point */
7918: static inline PetscErrorCode CheckPoint_Private(DMLabel label, PetscInt labelId, PetscSection section, PetscInt point, PetscInt f, PetscInt *offset, PetscBool *contains)
7919: {
7920:   PetscFunctionBegin;
7921:   *contains = PETSC_TRUE;
7922:   if (label) {
7923:     PetscInt fdof;

7925:     PetscCall(DMLabelStratumHasPoint(label, labelId, point, contains));
7926:     if (!*contains) {
7927:       PetscCall(PetscSectionGetFieldDof(section, point, f, &fdof));
7928:       *offset += fdof;
7929:       PetscFunctionReturn(PETSC_SUCCESS);
7930:     }
7931:   }
7932:   PetscFunctionReturn(PETSC_SUCCESS);
7933: }

7935: /* Unlike DMPlexVecSetClosure(), this uses plex-native closure permutation, not a user-specified permutation such as DMPlexSetClosurePermutationTensor(). */
7936: 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)
7937: {
7938:   PetscSection    clSection;
7939:   IS              clPoints;
7940:   PetscScalar    *array;
7941:   PetscInt       *points = NULL;
7942:   const PetscInt *clp;
7943:   PetscInt        numFields, numPoints, p;
7944:   PetscInt        offset = 0, f;

7946:   PetscFunctionBeginHot;
7948:   if (!section) PetscCall(DMGetLocalSection(dm, &section));
7951:   PetscCall(PetscSectionGetNumFields(section, &numFields));
7952:   /* Get points */
7953:   PetscCall(DMPlexGetCompressedClosure(dm, section, point, 0, &numPoints, &points, &clSection, &clPoints, &clp));
7954:   /* Get array */
7955:   PetscCall(VecGetArray(v, &array));
7956:   /* Get values */
7957:   for (f = 0; f < numFields; ++f) {
7958:     const PetscInt    **perms = NULL;
7959:     const PetscScalar **flips = NULL;
7960:     PetscBool           contains;

7962:     if (!fieldActive[f]) {
7963:       for (p = 0; p < numPoints * 2; p += 2) {
7964:         PetscInt fdof;
7965:         PetscCall(PetscSectionGetFieldDof(section, points[p], f, &fdof));
7966:         offset += fdof;
7967:       }
7968:       continue;
7969:     }
7970:     PetscCall(PetscSectionGetFieldPointSyms(section, f, numPoints, points, &perms, &flips));
7971:     switch (mode) {
7972:     case INSERT_VALUES:
7973:       for (p = 0; p < numPoints; p++) {
7974:         const PetscInt     point = points[2 * p];
7975:         const PetscInt    *perm  = perms ? perms[p] : NULL;
7976:         const PetscScalar *flip  = flips ? flips[p] : NULL;
7977:         PetscCall(CheckPoint_Private(label, labelId, section, point, f, &offset, &contains));
7978:         if (!contains) continue;
7979:         PetscCall(updatePointFields_private(section, point, perm, flip, f, insert, PETSC_FALSE, NULL, values, &offset, array));
7980:       }
7981:       break;
7982:     case INSERT_ALL_VALUES:
7983:       for (p = 0; p < numPoints; p++) {
7984:         const PetscInt     point = points[2 * p];
7985:         const PetscInt    *perm  = perms ? perms[p] : NULL;
7986:         const PetscScalar *flip  = flips ? flips[p] : NULL;
7987:         PetscCall(CheckPoint_Private(label, labelId, section, point, f, &offset, &contains));
7988:         if (!contains) continue;
7989:         PetscCall(updatePointFields_private(section, point, perm, flip, f, insert, PETSC_TRUE, NULL, values, &offset, array));
7990:       }
7991:       break;
7992:     case INSERT_BC_VALUES:
7993:       for (p = 0; p < numPoints; p++) {
7994:         const PetscInt     point = points[2 * p];
7995:         const PetscInt    *perm  = perms ? perms[p] : NULL;
7996:         const PetscScalar *flip  = flips ? flips[p] : NULL;
7997:         PetscCall(CheckPoint_Private(label, labelId, section, point, f, &offset, &contains));
7998:         if (!contains) continue;
7999:         PetscCall(updatePointFieldsBC_private(section, point, perm, flip, f, Ncc, comps, insert, NULL, values, &offset, array));
8000:       }
8001:       break;
8002:     case ADD_VALUES:
8003:       for (p = 0; p < numPoints; p++) {
8004:         const PetscInt     point = points[2 * p];
8005:         const PetscInt    *perm  = perms ? perms[p] : NULL;
8006:         const PetscScalar *flip  = flips ? flips[p] : NULL;
8007:         PetscCall(CheckPoint_Private(label, labelId, section, point, f, &offset, &contains));
8008:         if (!contains) continue;
8009:         PetscCall(updatePointFields_private(section, point, perm, flip, f, add, PETSC_FALSE, NULL, values, &offset, array));
8010:       }
8011:       break;
8012:     case ADD_ALL_VALUES:
8013:       for (p = 0; p < numPoints; p++) {
8014:         const PetscInt     point = points[2 * p];
8015:         const PetscInt    *perm  = perms ? perms[p] : NULL;
8016:         const PetscScalar *flip  = flips ? flips[p] : NULL;
8017:         PetscCall(CheckPoint_Private(label, labelId, section, point, f, &offset, &contains));
8018:         if (!contains) continue;
8019:         PetscCall(updatePointFields_private(section, point, perm, flip, f, add, PETSC_TRUE, NULL, values, &offset, array));
8020:       }
8021:       break;
8022:     default:
8023:       SETERRQ(PetscObjectComm((PetscObject)dm), PETSC_ERR_ARG_OUTOFRANGE, "Invalid insert mode %d", mode);
8024:     }
8025:     PetscCall(PetscSectionRestoreFieldPointSyms(section, f, numPoints, points, &perms, &flips));
8026:   }
8027:   /* Cleanup points */
8028:   PetscCall(DMPlexRestoreCompressedClosure(dm, section, point, &numPoints, &points, &clSection, &clPoints, &clp));
8029:   /* Cleanup array */
8030:   PetscCall(VecRestoreArray(v, &array));
8031:   PetscFunctionReturn(PETSC_SUCCESS);
8032: }

8034: static PetscErrorCode DMPlexPrintMatSetValues(PetscViewer viewer, Mat A, PetscInt point, PetscInt numRIndices, const PetscInt rindices[], PetscInt numCIndices, const PetscInt cindices[], const PetscScalar values[])
8035: {
8036:   PetscMPIInt rank;

8038:   PetscFunctionBegin;
8039:   PetscCallMPI(MPI_Comm_rank(PetscObjectComm((PetscObject)A), &rank));
8040:   PetscCall(PetscViewerASCIIPrintf(viewer, "[%d]mat for point %" PetscInt_FMT "\n", rank, point));
8041:   for (PetscInt i = 0; i < numRIndices; i++) PetscCall(PetscViewerASCIIPrintf(viewer, "[%d]mat row indices[%" PetscInt_FMT "] = %" PetscInt_FMT "\n", rank, i, rindices[i]));
8042:   for (PetscInt i = 0; i < numCIndices; i++) PetscCall(PetscViewerASCIIPrintf(viewer, "[%d]mat col indices[%" PetscInt_FMT "] = %" PetscInt_FMT "\n", rank, i, cindices[i]));
8043:   numCIndices = numCIndices ? numCIndices : numRIndices;
8044:   if (!values) PetscFunctionReturn(PETSC_SUCCESS);
8045:   for (PetscInt i = 0; i < numRIndices; i++) {
8046:     PetscCall(PetscViewerASCIIPrintf(viewer, "[%d]", rank));
8047:     for (PetscInt j = 0; j < numCIndices; j++) {
8048: #if defined(PETSC_USE_COMPLEX)
8049:       PetscCall(PetscViewerASCIIPrintf(viewer, " (%g,%g)", (double)PetscRealPart(values[i * numCIndices + j]), (double)PetscImaginaryPart(values[i * numCIndices + j])));
8050: #else
8051:       PetscCall(PetscViewerASCIIPrintf(viewer, " %g", (double)values[i * numCIndices + j]));
8052: #endif
8053:     }
8054:     PetscCall(PetscViewerASCIIPrintf(viewer, "\n"));
8055:   }
8056:   PetscFunctionReturn(PETSC_SUCCESS);
8057: }

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

8062:   Input Parameters:
8063: + section - The section for this data layout
8064: . islocal - Is the section (and thus indices being requested) local or global?
8065: . point   - The point contributing dofs with these indices
8066: . off     - The global offset of this point
8067: . loff    - The local offset of each field
8068: . setBC   - The flag determining whether to include indices of boundary values
8069: . perm    - A permutation of the dofs on this point, or NULL
8070: - indperm - A permutation of the entire indices array, or NULL

8072:   Output Parameter:
8073: . indices - Indices for dofs on this point

8075:   Level: developer

8077:   Note: The indices could be local or global, depending on the value of 'off'.
8078: */
8079: PetscErrorCode DMPlexGetIndicesPoint_Internal(PetscSection section, PetscBool islocal, PetscInt point, PetscInt off, PetscInt *loff, PetscBool setBC, const PetscInt perm[], const PetscInt indperm[], PetscInt indices[])
8080: {
8081:   PetscInt        dof;   /* The number of unknowns on this point */
8082:   PetscInt        cdof;  /* The number of constraints on this point */
8083:   const PetscInt *cdofs; /* The indices of the constrained dofs on this point */
8084:   PetscInt        cind = 0, k;

8086:   PetscFunctionBegin;
8087:   PetscCheck(islocal || !setBC, PetscObjectComm((PetscObject)section), PETSC_ERR_ARG_INCOMP, "setBC incompatible with global indices; use a local section or disable setBC");
8088:   PetscCall(PetscSectionGetDof(section, point, &dof));
8089:   PetscCall(PetscSectionGetConstraintDof(section, point, &cdof));
8090:   if (!cdof || setBC) {
8091:     for (k = 0; k < dof; ++k) {
8092:       const PetscInt preind = perm ? *loff + perm[k] : *loff + k;
8093:       const PetscInt ind    = indperm ? indperm[preind] : preind;

8095:       indices[ind] = off + k;
8096:     }
8097:   } else {
8098:     PetscCall(PetscSectionGetConstraintIndices(section, point, &cdofs));
8099:     for (k = 0; k < dof; ++k) {
8100:       const PetscInt preind = perm ? *loff + perm[k] : *loff + k;
8101:       const PetscInt ind    = indperm ? indperm[preind] : preind;

8103:       if ((cind < cdof) && (k == cdofs[cind])) {
8104:         /* Insert check for returning constrained indices */
8105:         indices[ind] = -(off + k + 1);
8106:         ++cind;
8107:       } else {
8108:         indices[ind] = off + k - (islocal ? 0 : cind);
8109:       }
8110:     }
8111:   }
8112:   *loff += dof;
8113:   PetscFunctionReturn(PETSC_SUCCESS);
8114: }

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

8119:  Input Parameters:
8120: + section - a section (global or local)
8121: - islocal - `PETSC_TRUE` if requesting local indices (i.e., section is local); `PETSC_FALSE` for global
8122: . point - point within section
8123: . off - The offset of this point in the (local or global) indexed space - should match islocal and (usually) the section
8124: . foffs - array of length numFields containing the offset in canonical point ordering (the location in indices) of each field
8125: . setBC - identify constrained (boundary condition) points via involution.
8126: . perms - perms[f][permsoff][:] is a permutation of dofs within each field
8127: . permsoff - offset
8128: - indperm - index permutation

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

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

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

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

8147:  Example:
8148:  Suppose a point contains one field with three components, and for which the unconstrained indices are {10, 11, 12}.
8149:  When the middle component is constrained, we get the array {10, -12, 12} for (islocal=TRUE, setBC=FALSE).
8150:  Note that -12 is the involution of 11, so the user can involute negative indices to recover local indices.
8151:  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.

8153:  Level: developer
8154: */
8155: 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[])
8156: {
8157:   PetscInt numFields, foff, f;

8159:   PetscFunctionBegin;
8160:   PetscCheck(islocal || !setBC, PetscObjectComm((PetscObject)section), PETSC_ERR_ARG_INCOMP, "setBC incompatible with global indices; use a local section or disable setBC");
8161:   PetscCall(PetscSectionGetNumFields(section, &numFields));
8162:   for (f = 0, foff = 0; f < numFields; ++f) {
8163:     PetscInt        fdof, cfdof;
8164:     const PetscInt *fcdofs; /* The indices of the constrained dofs for field f on this point */
8165:     PetscInt        cind = 0, b;
8166:     const PetscInt *perm = (perms && perms[f]) ? perms[f][permsoff] : NULL;

8168:     PetscCall(PetscSectionGetFieldDof(section, point, f, &fdof));
8169:     PetscCall(PetscSectionGetFieldConstraintDof(section, point, f, &cfdof));
8170:     if (!cfdof || setBC) {
8171:       for (b = 0; b < fdof; ++b) {
8172:         const PetscInt preind = perm ? foffs[f] + perm[b] : foffs[f] + b;
8173:         const PetscInt ind    = indperm ? indperm[preind] : preind;

8175:         indices[ind] = off + foff + b;
8176:       }
8177:     } else {
8178:       PetscCall(PetscSectionGetFieldConstraintIndices(section, point, f, &fcdofs));
8179:       for (b = 0; b < fdof; ++b) {
8180:         const PetscInt preind = perm ? foffs[f] + perm[b] : foffs[f] + b;
8181:         const PetscInt ind    = indperm ? indperm[preind] : preind;

8183:         if ((cind < cfdof) && (b == fcdofs[cind])) {
8184:           indices[ind] = -(off + foff + b + 1);
8185:           ++cind;
8186:         } else {
8187:           indices[ind] = off + foff + b - (islocal ? 0 : cind);
8188:         }
8189:       }
8190:     }
8191:     foff += (setBC || islocal ? fdof : (fdof - cfdof));
8192:     foffs[f] += fdof;
8193:   }
8194:   PetscFunctionReturn(PETSC_SUCCESS);
8195: }

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

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

8202:  Notes:
8203:  The semantics of this function relate to that of setBC=FALSE in DMPlexGetIndicesPointFields_Internal.
8204:  Since this function uses global indices, setBC=TRUE would be invalid, so no such argument exists.
8205: */
8206: static PetscErrorCode DMPlexGetIndicesPointFieldsSplit_Internal(PetscSection section, PetscSection globalSection, PetscInt point, PetscInt foffs[], const PetscInt ***perms, PetscInt permsoff, const PetscInt indperm[], PetscInt indices[])
8207: {
8208:   PetscInt numFields, foff, f;

8210:   PetscFunctionBegin;
8211:   PetscCall(PetscSectionGetNumFields(section, &numFields));
8212:   for (f = 0; f < numFields; ++f) {
8213:     PetscInt        fdof, cfdof;
8214:     const PetscInt *fcdofs; /* The indices of the constrained dofs for field f on this point */
8215:     PetscInt        cind = 0, b;
8216:     const PetscInt *perm = (perms && perms[f]) ? perms[f][permsoff] : NULL;

8218:     PetscCall(PetscSectionGetFieldDof(section, point, f, &fdof));
8219:     PetscCall(PetscSectionGetFieldConstraintDof(section, point, f, &cfdof));
8220:     PetscCall(PetscSectionGetFieldOffset(globalSection, point, f, &foff));
8221:     if (!cfdof) {
8222:       for (b = 0; b < fdof; ++b) {
8223:         const PetscInt preind = perm ? foffs[f] + perm[b] : foffs[f] + b;
8224:         const PetscInt ind    = indperm ? indperm[preind] : preind;

8226:         indices[ind] = foff + b;
8227:       }
8228:     } else {
8229:       PetscCall(PetscSectionGetFieldConstraintIndices(section, point, f, &fcdofs));
8230:       for (b = 0; b < fdof; ++b) {
8231:         const PetscInt preind = perm ? foffs[f] + perm[b] : foffs[f] + b;
8232:         const PetscInt ind    = indperm ? indperm[preind] : preind;

8234:         if ((cind < cfdof) && (b == fcdofs[cind])) {
8235:           indices[ind] = -(foff + b + 1);
8236:           ++cind;
8237:         } else {
8238:           indices[ind] = foff + b - cind;
8239:         }
8240:       }
8241:     }
8242:     foffs[f] += fdof;
8243:   }
8244:   PetscFunctionReturn(PETSC_SUCCESS);
8245: }

8247: static PetscErrorCode DMPlexAnchorsGetSubMatIndices(PetscInt nPoints, const PetscInt pnts[], PetscSection section, PetscSection cSec, PetscInt tmpIndices[], PetscInt fieldOffsets[], PetscInt indices[], const PetscInt ***perms)
8248: {
8249:   PetscInt numFields, sStart, sEnd, cStart, cEnd;

8251:   PetscFunctionBegin;
8252:   PetscCall(PetscSectionGetNumFields(section, &numFields));
8253:   PetscCall(PetscSectionGetChart(section, &sStart, &sEnd));
8254:   PetscCall(PetscSectionGetChart(cSec, &cStart, &cEnd));
8255:   for (PetscInt p = 0; p < nPoints; p++) {
8256:     PetscInt     b       = pnts[2 * p];
8257:     PetscInt     bSecDof = 0, bOff;
8258:     PetscInt     cSecDof = 0;
8259:     PetscSection indices_section;

8261:     if (b >= sStart && b < sEnd) PetscCall(PetscSectionGetDof(section, b, &bSecDof));
8262:     if (!bSecDof) continue;
8263:     if (b >= cStart && b < cEnd) PetscCall(PetscSectionGetDof(cSec, b, &cSecDof));
8264:     indices_section = cSecDof > 0 ? cSec : section;
8265:     if (numFields) {
8266:       PetscInt fStart[32], fEnd[32];

8268:       fStart[0] = 0;
8269:       fEnd[0]   = 0;
8270:       for (PetscInt f = 0; f < numFields; f++) {
8271:         PetscInt fDof = 0;

8273:         PetscCall(PetscSectionGetFieldDof(indices_section, b, f, &fDof));
8274:         fStart[f + 1] = fStart[f] + fDof;
8275:         fEnd[f + 1]   = fStart[f + 1];
8276:       }
8277:       PetscCall(PetscSectionGetOffset(indices_section, b, &bOff));
8278:       // only apply permutations on one side
8279:       PetscCall(DMPlexGetIndicesPointFields_Internal(indices_section, PETSC_TRUE, b, bOff, fEnd, PETSC_TRUE, perms, perms ? p : -1, NULL, tmpIndices));
8280:       for (PetscInt f = 0; f < numFields; f++) {
8281:         for (PetscInt i = fStart[f]; i < fEnd[f]; i++) indices[fieldOffsets[f]++] = (cSecDof > 0) ? tmpIndices[i] : -(tmpIndices[i] + 1);
8282:       }
8283:     } else {
8284:       PetscInt bEnd = 0;

8286:       PetscCall(PetscSectionGetOffset(indices_section, b, &bOff));
8287:       PetscCall(DMPlexGetIndicesPoint_Internal(indices_section, PETSC_TRUE, b, bOff, &bEnd, PETSC_TRUE, (perms && perms[0]) ? perms[0][p] : NULL, NULL, tmpIndices));

8289:       for (PetscInt i = 0; i < bEnd; i++) indices[fieldOffsets[0]++] = (cSecDof > 0) ? tmpIndices[i] : -(tmpIndices[i] + 1);
8290:     }
8291:   }
8292:   PetscFunctionReturn(PETSC_SUCCESS);
8293: }

8295: PETSC_INTERN PetscErrorCode DMPlexAnchorsGetSubMatModification(DM dm, PetscSection section, PetscInt numPoints, PetscInt numIndices, const PetscInt points[], const PetscInt ***perms, PetscInt *outNumPoints, PetscInt *outNumIndices, PetscInt *outPoints[], PetscInt offsets[], PetscScalar *outMat[])
8296: {
8297:   Mat             cMat;
8298:   PetscSection    aSec, cSec;
8299:   IS              aIS;
8300:   PetscInt        aStart = -1, aEnd = -1;
8301:   PetscInt        sStart = -1, sEnd = -1;
8302:   PetscInt        cStart = -1, cEnd = -1;
8303:   const PetscInt *anchors;
8304:   PetscInt        numFields, p;
8305:   PetscInt        newNumPoints = 0, newNumIndices = 0;
8306:   PetscInt       *newPoints, *indices, *newIndices, *tmpIndices, *tmpNewIndices;
8307:   PetscInt        oldOffsets[32];
8308:   PetscInt        newOffsets[32];
8309:   PetscInt        oldOffsetsCopy[32];
8310:   PetscInt        newOffsetsCopy[32];
8311:   PetscScalar    *modMat         = NULL;
8312:   PetscBool       anyConstrained = PETSC_FALSE;

8314:   PetscFunctionBegin;
8317:   PetscCall(PetscSectionGetNumFields(section, &numFields));

8319:   PetscCall(DMPlexGetAnchors(dm, &aSec, &aIS));
8320:   /* if there are point-to-point constraints */
8321:   if (aSec) {
8322:     PetscCall(PetscArrayzero(newOffsets, 32));
8323:     PetscCall(PetscArrayzero(oldOffsets, 32));
8324:     PetscCall(ISGetIndices(aIS, &anchors));
8325:     PetscCall(PetscSectionGetChart(aSec, &aStart, &aEnd));
8326:     PetscCall(PetscSectionGetChart(section, &sStart, &sEnd));
8327:     /* figure out how many points are going to be in the new element matrix
8328:      * (we allow double counting, because it's all just going to be summed
8329:      * into the global matrix anyway) */
8330:     for (p = 0; p < 2 * numPoints; p += 2) {
8331:       PetscInt b    = points[p];
8332:       PetscInt bDof = 0, bSecDof = 0;

8334:       if (b >= sStart && b < sEnd) PetscCall(PetscSectionGetDof(section, b, &bSecDof));
8335:       if (!bSecDof) continue;

8337:       for (PetscInt f = 0; f < numFields; f++) {
8338:         PetscInt fDof = 0;

8340:         PetscCall(PetscSectionGetFieldDof(section, b, f, &fDof));
8341:         oldOffsets[f + 1] += fDof;
8342:       }
8343:       if (b >= aStart && b < aEnd) PetscCall(PetscSectionGetDof(aSec, b, &bDof));
8344:       if (bDof) {
8345:         /* this point is constrained */
8346:         /* it is going to be replaced by its anchors */
8347:         PetscInt bOff;

8349:         PetscCall(PetscSectionGetOffset(aSec, b, &bOff));
8350:         for (PetscInt q = 0; q < bDof; q++) {
8351:           PetscInt a    = anchors[bOff + q];
8352:           PetscInt aDof = 0;

8354:           if (a >= sStart && a < sEnd) PetscCall(PetscSectionGetDof(section, a, &aDof));
8355:           if (aDof) {
8356:             anyConstrained = PETSC_TRUE;
8357:             newNumPoints += 1;
8358:           }
8359:           newNumIndices += aDof;
8360:           for (PetscInt f = 0; f < numFields; ++f) {
8361:             PetscInt fDof = 0;

8363:             if (a >= sStart && a < sEnd) PetscCall(PetscSectionGetFieldDof(section, a, f, &fDof));
8364:             newOffsets[f + 1] += fDof;
8365:           }
8366:         }
8367:       } else {
8368:         /* this point is not constrained */
8369:         newNumPoints++;
8370:         newNumIndices += bSecDof;
8371:         for (PetscInt f = 0; f < numFields; ++f) {
8372:           PetscInt fDof;

8374:           PetscCall(PetscSectionGetFieldDof(section, b, f, &fDof));
8375:           newOffsets[f + 1] += fDof;
8376:         }
8377:       }
8378:     }
8379:   }
8380:   if (!anyConstrained) {
8381:     if (outNumPoints) *outNumPoints = 0;
8382:     if (outNumIndices) *outNumIndices = 0;
8383:     if (outPoints) *outPoints = NULL;
8384:     if (outMat) *outMat = NULL;
8385:     if (aSec) PetscCall(ISRestoreIndices(aIS, &anchors));
8386:     PetscFunctionReturn(PETSC_SUCCESS);
8387:   }

8389:   if (outNumPoints) *outNumPoints = newNumPoints;
8390:   if (outNumIndices) *outNumIndices = newNumIndices;

8392:   for (PetscInt f = 0; f < numFields; ++f) newOffsets[f + 1] += newOffsets[f];
8393:   for (PetscInt f = 0; f < numFields; ++f) oldOffsets[f + 1] += oldOffsets[f];

8395:   if (!outPoints && !outMat) {
8396:     if (offsets) {
8397:       for (PetscInt f = 0; f <= numFields; f++) offsets[f] = newOffsets[f];
8398:     }
8399:     if (aSec) PetscCall(ISRestoreIndices(aIS, &anchors));
8400:     PetscFunctionReturn(PETSC_SUCCESS);
8401:   }

8403:   PetscCheck(!numFields || newOffsets[numFields] == newNumIndices, PETSC_COMM_SELF, PETSC_ERR_PLIB, "Invalid size for closure %" PetscInt_FMT " should be %" PetscInt_FMT, newOffsets[numFields], newNumIndices);
8404:   PetscCheck(!numFields || oldOffsets[numFields] == numIndices, PETSC_COMM_SELF, PETSC_ERR_PLIB, "Invalid size for closure %" PetscInt_FMT " should be %" PetscInt_FMT, oldOffsets[numFields], numIndices);

8406:   PetscCall(DMGetDefaultConstraints(dm, &cSec, &cMat, NULL));
8407:   PetscCall(PetscSectionGetChart(cSec, &cStart, &cEnd));

8409:   /* output arrays */
8410:   PetscCall(DMGetWorkArray(dm, 2 * newNumPoints, MPIU_INT, &newPoints));
8411:   PetscCall(PetscArrayzero(newPoints, 2 * newNumPoints));

8413:   // get the new Points
8414:   for (PetscInt p = 0, newP = 0; p < numPoints; p++) {
8415:     PetscInt b    = points[2 * p];
8416:     PetscInt bDof = 0, bSecDof = 0, bOff;

8418:     if (b >= sStart && b < sEnd) PetscCall(PetscSectionGetDof(section, b, &bSecDof));
8419:     if (!bSecDof) continue;
8420:     if (b >= aStart && b < aEnd) PetscCall(PetscSectionGetDof(aSec, b, &bDof));
8421:     if (bDof) {
8422:       PetscCall(PetscSectionGetOffset(aSec, b, &bOff));
8423:       for (PetscInt q = 0; q < bDof; q++) {
8424:         PetscInt a = anchors[bOff + q], aDof = 0;

8426:         if (a >= sStart && a < sEnd) PetscCall(PetscSectionGetDof(section, a, &aDof));
8427:         if (aDof) {
8428:           newPoints[2 * newP]     = a;
8429:           newPoints[2 * newP + 1] = 0; // orientations are accounted for in constructing the matrix, newly added points are in default orientation
8430:           newP++;
8431:         }
8432:       }
8433:     } else {
8434:       newPoints[2 * newP]     = b;
8435:       newPoints[2 * newP + 1] = points[2 * p + 1];
8436:       newP++;
8437:     }
8438:   }

8440:   if (outMat) {
8441:     PetscScalar *tmpMat;
8442:     PetscCall(PetscArraycpy(oldOffsetsCopy, oldOffsets, 32));
8443:     PetscCall(PetscArraycpy(newOffsetsCopy, newOffsets, 32));

8445:     PetscCall(DMGetWorkArray(dm, numIndices, MPIU_INT, &indices));
8446:     PetscCall(DMGetWorkArray(dm, numIndices, MPIU_INT, &tmpIndices));
8447:     PetscCall(DMGetWorkArray(dm, newNumIndices, MPIU_INT, &newIndices));
8448:     PetscCall(DMGetWorkArray(dm, newNumIndices, MPIU_INT, &tmpNewIndices));

8450:     for (PetscInt i = 0; i < numIndices; i++) indices[i] = -1;
8451:     for (PetscInt i = 0; i < newNumIndices; i++) newIndices[i] = -1;

8453:     PetscCall(DMPlexAnchorsGetSubMatIndices(numPoints, points, section, cSec, tmpIndices, oldOffsetsCopy, indices, perms));
8454:     PetscCall(DMPlexAnchorsGetSubMatIndices(newNumPoints, newPoints, section, section, tmpNewIndices, newOffsetsCopy, newIndices, NULL));

8456:     PetscCall(DMGetWorkArray(dm, numIndices * newNumIndices, MPIU_SCALAR, &modMat));
8457:     PetscCall(DMGetWorkArray(dm, numIndices * newNumIndices, MPIU_SCALAR, &tmpMat));
8458:     PetscCall(PetscArrayzero(modMat, newNumIndices * numIndices));
8459:     // for each field, insert the anchor modification into modMat
8460:     for (PetscInt f = 0; f < PetscMax(1, numFields); f++) {
8461:       PetscInt fStart    = oldOffsets[f];
8462:       PetscInt fNewStart = newOffsets[f];
8463:       for (PetscInt p = 0, o = fStart, oNew = fNewStart; p < numPoints; p++) {
8464:         PetscInt b    = points[2 * p];
8465:         PetscInt bDof = 0, bSecDof = 0, bOff;

8467:         if (b >= sStart && b < sEnd) {
8468:           if (numFields) PetscCall(PetscSectionGetFieldDof(section, b, f, &bSecDof));
8469:           else PetscCall(PetscSectionGetDof(section, b, &bSecDof));
8470:         }
8471:         if (!bSecDof) continue;
8472:         if (b >= aStart && b < aEnd) PetscCall(PetscSectionGetDof(aSec, b, &bDof));
8473:         if (bDof) {
8474:           PetscCall(PetscSectionGetOffset(aSec, b, &bOff));
8475:           for (PetscInt q = 0; q < bDof; q++) {
8476:             PetscInt a = anchors[bOff + q], aDof = 0;

8478:             if (a >= sStart && a < sEnd) {
8479:               if (numFields) PetscCall(PetscSectionGetFieldDof(section, a, f, &aDof));
8480:               else PetscCall(PetscSectionGetDof(section, a, &aDof));
8481:             }
8482:             if (aDof) {
8483:               PetscCall(MatGetValues(cMat, bSecDof, &indices[o], aDof, &newIndices[oNew], tmpMat));
8484:               for (PetscInt d = 0; d < bSecDof; d++) {
8485:                 for (PetscInt e = 0; e < aDof; e++) modMat[(o + d) * newNumIndices + oNew + e] = tmpMat[d * aDof + e];
8486:               }
8487:             }
8488:             oNew += aDof;
8489:           }
8490:         } else {
8491:           // Insert the identity matrix in this block
8492:           for (PetscInt d = 0; d < bSecDof; d++) modMat[(o + d) * newNumIndices + oNew + d] = 1;
8493:           oNew += bSecDof;
8494:         }
8495:         o += bSecDof;
8496:       }
8497:     }

8499:     *outMat = modMat;

8501:     PetscCall(DMRestoreWorkArray(dm, numIndices * newNumIndices, MPIU_SCALAR, &tmpMat));
8502:     PetscCall(DMRestoreWorkArray(dm, newNumIndices, MPIU_INT, &tmpNewIndices));
8503:     PetscCall(DMRestoreWorkArray(dm, newNumIndices, MPIU_INT, &newIndices));
8504:     PetscCall(DMRestoreWorkArray(dm, numIndices, MPIU_INT, &tmpIndices));
8505:     PetscCall(DMRestoreWorkArray(dm, numIndices, MPIU_INT, &indices));
8506:   }
8507:   PetscCall(ISRestoreIndices(aIS, &anchors));

8509:   /* output */
8510:   if (outPoints) {
8511:     *outPoints = newPoints;
8512:   } else {
8513:     PetscCall(DMRestoreWorkArray(dm, 2 * newNumPoints, MPIU_INT, &newPoints));
8514:   }
8515:   for (PetscInt f = 0; f <= numFields; f++) offsets[f] = newOffsets[f];
8516:   PetscFunctionReturn(PETSC_SUCCESS);
8517: }

8519: PETSC_INTERN PetscErrorCode DMPlexAnchorsModifyMat_Internal(DM dm, PetscSection section, PetscInt numPoints, PetscInt numIndices, const PetscInt points[], const PetscInt ***perms, PetscInt numRows, PetscInt numCols, const PetscScalar values[], PetscInt *outNumPoints, PetscInt *outNumIndices, PetscInt *outPoints[], PetscScalar *outValues[], PetscInt offsets[], PetscBool multiplyRight, PetscBool multiplyLeft)
8520: {
8521:   PetscScalar *modMat        = NULL;
8522:   PetscInt     newNumIndices = -1;

8524:   PetscFunctionBegin;
8525:   /* If M is the matrix represented by values, get the matrix C such that we will add M * C (or, if multiplyLeft, C^T * M * C) into the global matrix.
8526:      modMat is that matrix C */
8527:   PetscCall(DMPlexAnchorsGetSubMatModification(dm, section, numPoints, numIndices, points, perms, outNumPoints, &newNumIndices, outPoints, offsets, outValues ? &modMat : NULL));
8528:   if (outNumIndices) *outNumIndices = newNumIndices;
8529:   if (modMat) {
8530:     const PetscScalar *newValues = values;

8532:     if (multiplyRight) {
8533:       PetscScalar *newNewValues = NULL;
8534:       PetscBLASInt M, N, K;
8535:       PetscScalar  a = 1.0, b = 0.0;

8537:       PetscCheck(numCols == numIndices, PetscObjectComm((PetscObject)dm), PETSC_ERR_ARG_SIZ, "values matrix has the wrong number of columns: %" PetscInt_FMT ", expected %" PetscInt_FMT, numCols, numIndices);

8539:       PetscCall(PetscBLASIntCast(newNumIndices, &M));
8540:       PetscCall(PetscBLASIntCast(numRows, &N));
8541:       PetscCall(PetscBLASIntCast(numIndices, &K));
8542:       PetscCall(DMGetWorkArray(dm, numRows * newNumIndices, MPIU_SCALAR, &newNewValues));
8543:       // row-major to column-major conversion, right multiplication becomes left multiplication
8544:       PetscCallBLAS("BLASgemm", BLASgemm_("N", "N", &M, &N, &K, &a, modMat, &M, newValues, &K, &b, newNewValues, &M));
8545:       numCols   = newNumIndices;
8546:       newValues = newNewValues;
8547:     }

8549:     if (multiplyLeft) {
8550:       PetscScalar *newNewValues = NULL;
8551:       PetscBLASInt M, N, K;
8552:       PetscScalar  a = 1.0, b = 0.0;

8554:       PetscCheck(numRows == numIndices, PetscObjectComm((PetscObject)dm), PETSC_ERR_ARG_SIZ, "values matrix has the wrong number of rows: %" PetscInt_FMT ", expected %" PetscInt_FMT, numRows, numIndices);

8556:       PetscCall(PetscBLASIntCast(numCols, &M));
8557:       PetscCall(PetscBLASIntCast(newNumIndices, &N));
8558:       PetscCall(PetscBLASIntCast(numIndices, &K));
8559:       PetscCall(DMGetWorkArray(dm, newNumIndices * numCols, MPIU_SCALAR, &newNewValues));
8560:       // row-major to column-major conversion, left multiplication becomes right multiplication
8561:       PetscCallBLAS("BLASgemm", BLASgemm_("N", "T", &M, &N, &K, &a, newValues, &M, modMat, &N, &b, newNewValues, &M));
8562:       if (newValues != values) PetscCall(DMRestoreWorkArray(dm, numIndices * newNumIndices, MPIU_SCALAR, &newValues));
8563:       newValues = newNewValues;
8564:     }
8565:     *outValues = (PetscScalar *)newValues;
8566:     PetscCall(DMRestoreWorkArray(dm, numIndices * newNumIndices, MPIU_SCALAR, &modMat));
8567:   }
8568:   PetscFunctionReturn(PETSC_SUCCESS);
8569: }

8571: PETSC_INTERN 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)
8572: {
8573:   PetscFunctionBegin;
8574:   PetscCall(DMPlexAnchorsModifyMat_Internal(dm, section, numPoints, numIndices, points, perms, numIndices, numIndices, values, outNumPoints, outNumIndices, outPoints, outValues, offsets, PETSC_TRUE, multiplyLeft));
8575:   PetscFunctionReturn(PETSC_SUCCESS);
8576: }

8578: static PetscErrorCode DMPlexGetClosureIndicesSize_Internal(DM dm, PetscSection section, PetscInt point, PetscInt *closureSize)
8579: {
8580:   /* Closure ordering */
8581:   PetscSection    clSection;
8582:   IS              clPoints;
8583:   const PetscInt *clp;
8584:   PetscInt       *points;
8585:   PetscInt        Ncl, Ni = 0;

8587:   PetscFunctionBeginHot;
8588:   PetscCall(DMPlexGetCompressedClosure(dm, section, point, 0, &Ncl, &points, &clSection, &clPoints, &clp));
8589:   for (PetscInt p = 0; p < Ncl * 2; p += 2) {
8590:     PetscInt dof;

8592:     PetscCall(PetscSectionGetDof(section, points[p], &dof));
8593:     Ni += dof;
8594:   }
8595:   PetscCall(DMPlexRestoreCompressedClosure(dm, section, point, &Ncl, &points, &clSection, &clPoints, &clp));
8596:   *closureSize = Ni;
8597:   PetscFunctionReturn(PETSC_SUCCESS);
8598: }

8600: static PetscErrorCode DMPlexGetClosureIndices_Internal(DM dm, PetscSection section, PetscSection idxSection, PetscInt point, PetscBool useClPerm, PetscInt *numRows, PetscInt *numCols, PetscInt *indices[], PetscInt outOffsets[], PetscScalar *values[], PetscBool multiplyRight, PetscBool multiplyLeft)
8601: {
8602:   /* Closure ordering */
8603:   PetscSection    clSection;
8604:   IS              clPoints;
8605:   const PetscInt *clp;
8606:   PetscInt       *points;
8607:   const PetscInt *clperm = NULL;
8608:   /* Dof permutation and sign flips */
8609:   const PetscInt    **perms[32] = {NULL};
8610:   const PetscScalar **flips[32] = {NULL};
8611:   PetscScalar        *valCopy   = NULL;
8612:   /* Hanging node constraints */
8613:   PetscInt    *pointsC = NULL;
8614:   PetscScalar *valuesC = NULL;
8615:   PetscInt     NclC, NiC;

8617:   PetscInt *idx;
8618:   PetscInt  Nf, Ncl, Ni = 0, offsets[32], p, f;
8619:   PetscBool isLocal = (section == idxSection) ? PETSC_TRUE : PETSC_FALSE;
8620:   PetscInt  idxStart, idxEnd;
8621:   PetscInt  nRows, nCols;

8623:   PetscFunctionBeginHot;
8627:   PetscAssertPointer(numRows, 6);
8628:   PetscAssertPointer(numCols, 7);
8629:   if (indices) PetscAssertPointer(indices, 8);
8630:   if (outOffsets) PetscAssertPointer(outOffsets, 9);
8631:   if (values) PetscAssertPointer(values, 10);
8632:   PetscCall(PetscSectionGetNumFields(section, &Nf));
8633:   PetscCheck(Nf <= 31, PetscObjectComm((PetscObject)dm), PETSC_ERR_ARG_OUTOFRANGE, "Number of fields %" PetscInt_FMT " limited to 31", Nf);
8634:   PetscCall(PetscArrayzero(offsets, 32));
8635:   /* 1) Get points in closure */
8636:   PetscCall(DMPlexGetCompressedClosure(dm, section, point, 0, &Ncl, &points, &clSection, &clPoints, &clp));
8637:   if (useClPerm) {
8638:     PetscInt depth, clsize;
8639:     PetscCall(DMPlexGetPointDepth(dm, point, &depth));
8640:     for (clsize = 0, p = 0; p < Ncl; p++) {
8641:       PetscInt dof;
8642:       PetscCall(PetscSectionGetDof(section, points[2 * p], &dof));
8643:       clsize += dof;
8644:     }
8645:     PetscCall(PetscSectionGetClosureInversePermutation_Internal(section, (PetscObject)dm, depth, clsize, &clperm));
8646:   }
8647:   /* 2) Get number of indices on these points and field offsets from section */
8648:   for (p = 0; p < Ncl * 2; p += 2) {
8649:     PetscInt dof, fdof;

8651:     PetscCall(PetscSectionGetDof(section, points[p], &dof));
8652:     for (f = 0; f < Nf; ++f) {
8653:       PetscCall(PetscSectionGetFieldDof(section, points[p], f, &fdof));
8654:       offsets[f + 1] += fdof;
8655:     }
8656:     Ni += dof;
8657:   }
8658:   if (*numRows == -1) *numRows = Ni;
8659:   if (*numCols == -1) *numCols = Ni;
8660:   nRows = *numRows;
8661:   nCols = *numCols;
8662:   for (f = 1; f < Nf; ++f) offsets[f + 1] += offsets[f];
8663:   PetscCheck(!Nf || offsets[Nf] == Ni, PetscObjectComm((PetscObject)dm), PETSC_ERR_PLIB, "Invalid size for closure %" PetscInt_FMT " should be %" PetscInt_FMT, offsets[Nf], Ni);
8664:   /* 3) Get symmetries and sign flips. Apply sign flips to values if passed in (only works for square values matrix) */
8665:   if (multiplyRight) PetscCheck(nCols == Ni, PetscObjectComm((PetscObject)dm), PETSC_ERR_ARG_SIZ, "Expected %" PetscInt_FMT " columns, got %" PetscInt_FMT, Ni, nCols);
8666:   if (multiplyLeft) PetscCheck(nRows == Ni, PetscObjectComm((PetscObject)dm), PETSC_ERR_ARG_SIZ, "Expected %" PetscInt_FMT " rows, got %" PetscInt_FMT, Ni, nRows);
8667:   for (f = 0; f < PetscMax(1, Nf); ++f) {
8668:     if (Nf) PetscCall(PetscSectionGetFieldPointSyms(section, f, Ncl, points, &perms[f], &flips[f]));
8669:     else PetscCall(PetscSectionGetPointSyms(section, Ncl, points, &perms[f], &flips[f]));
8670:     /* may need to apply sign changes to the element matrix */
8671:     if (values && flips[f]) {
8672:       PetscInt foffset = offsets[f];

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

8678:         if (!Nf) PetscCall(PetscSectionGetDof(section, pnt, &fdof));
8679:         else PetscCall(PetscSectionGetFieldDof(section, pnt, f, &fdof));
8680:         if (flip) {
8681:           PetscInt i, j, k;

8683:           if (!valCopy) {
8684:             PetscCall(DMGetWorkArray(dm, Ni * Ni, MPIU_SCALAR, &valCopy));
8685:             for (j = 0; j < Ni * Ni; ++j) valCopy[j] = (*values)[j];
8686:             *values = valCopy;
8687:           }
8688:           for (i = 0; i < fdof; ++i) {
8689:             PetscScalar fval = flip[i];

8691:             if (multiplyRight) {
8692:               for (k = 0; k < nRows; ++k) valCopy[Ni * k + (foffset + i)] *= fval;
8693:             }
8694:             if (multiplyLeft) {
8695:               for (k = 0; k < nCols; ++k) valCopy[nCols * (foffset + i) + k] *= fval;
8696:             }
8697:           }
8698:         }
8699:         foffset += fdof;
8700:       }
8701:     }
8702:   }
8703:   /* 4) Apply hanging node constraints. Get new symmetries and replace all storage with constrained storage */
8704:   PetscCall(DMPlexAnchorsModifyMat_Internal(dm, section, Ncl, Ni, points, perms, nRows, nCols, values ? *values : NULL, &NclC, &NiC, &pointsC, values ? &valuesC : NULL, offsets, multiplyRight, multiplyLeft));
8705:   if (NclC) {
8706:     if (multiplyRight) *numCols = NiC;
8707:     if (multiplyLeft) *numRows = NiC;
8708:     if (valCopy) PetscCall(DMRestoreWorkArray(dm, Ni * Ni, MPIU_SCALAR, &valCopy));
8709:     for (f = 0; f < PetscMax(1, Nf); ++f) {
8710:       if (Nf) PetscCall(PetscSectionRestoreFieldPointSyms(section, f, Ncl, points, &perms[f], &flips[f]));
8711:       else PetscCall(PetscSectionRestorePointSyms(section, Ncl, points, &perms[f], &flips[f]));
8712:     }
8713:     for (f = 0; f < PetscMax(1, Nf); ++f) {
8714:       if (Nf) PetscCall(PetscSectionGetFieldPointSyms(section, f, NclC, pointsC, &perms[f], &flips[f]));
8715:       else PetscCall(PetscSectionGetPointSyms(section, NclC, pointsC, &perms[f], &flips[f]));
8716:     }
8717:     PetscCall(DMPlexRestoreCompressedClosure(dm, section, point, &Ncl, &points, &clSection, &clPoints, &clp));
8718:     Ncl    = NclC;
8719:     Ni     = NiC;
8720:     points = pointsC;
8721:     if (values) *values = valuesC;
8722:   }
8723:   /* 5) Calculate indices */
8724:   PetscCall(DMGetWorkArray(dm, Ni, MPIU_INT, &idx));
8725:   PetscCall(PetscSectionGetChart(idxSection, &idxStart, &idxEnd));
8726:   if (Nf) {
8727:     PetscInt  idxOff;
8728:     PetscBool useFieldOffsets;

8730:     if (outOffsets) {
8731:       for (f = 0; f <= Nf; f++) outOffsets[f] = offsets[f];
8732:     }
8733:     PetscCall(PetscSectionGetUseFieldOffsets(idxSection, &useFieldOffsets));
8734:     if (useFieldOffsets) {
8735:       for (p = 0; p < Ncl; ++p) {
8736:         const PetscInt pnt = points[p * 2];

8738:         PetscCall(DMPlexGetIndicesPointFieldsSplit_Internal(section, idxSection, pnt, offsets, perms, p, clperm, idx));
8739:       }
8740:     } else {
8741:       for (p = 0; p < Ncl; ++p) {
8742:         const PetscInt pnt = points[p * 2];

8744:         if (pnt < idxStart || pnt >= idxEnd) continue;
8745:         PetscCall(PetscSectionGetOffset(idxSection, pnt, &idxOff));
8746:         /* Note that we pass a local section even though we're using global offsets.  This is because global sections do
8747:          * not (at the time of this writing) have fields set. They probably should, in which case we would pass the
8748:          * global section. */
8749:         PetscCall(DMPlexGetIndicesPointFields_Internal(section, isLocal, pnt, idxOff < 0 ? -(idxOff + 1) : idxOff, offsets, PETSC_FALSE, perms, p, clperm, idx));
8750:       }
8751:     }
8752:   } else {
8753:     PetscInt off = 0, idxOff;

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

8759:       if (pnt < idxStart || pnt >= idxEnd) continue;
8760:       PetscCall(PetscSectionGetOffset(idxSection, pnt, &idxOff));
8761:       /* Note that we pass a local section even though we're using global offsets.  This is because global sections do
8762:        * not (at the time of this writing) have fields set. They probably should, in which case we would pass the global section. */
8763:       PetscCall(DMPlexGetIndicesPoint_Internal(section, isLocal, pnt, idxOff < 0 ? -(idxOff + 1) : idxOff, &off, PETSC_FALSE, perm, clperm, idx));
8764:     }
8765:   }
8766:   /* 6) Cleanup */
8767:   for (f = 0; f < PetscMax(1, Nf); ++f) {
8768:     if (Nf) PetscCall(PetscSectionRestoreFieldPointSyms(section, f, Ncl, points, &perms[f], &flips[f]));
8769:     else PetscCall(PetscSectionRestorePointSyms(section, Ncl, points, &perms[f], &flips[f]));
8770:   }
8771:   if (NclC) {
8772:     PetscCall(DMRestoreWorkArray(dm, NclC * 2, MPIU_INT, &pointsC));
8773:   } else {
8774:     PetscCall(DMPlexRestoreCompressedClosure(dm, section, point, &Ncl, &points, &clSection, &clPoints, &clp));
8775:   }

8777:   if (indices) *indices = idx;
8778:   PetscFunctionReturn(PETSC_SUCCESS);
8779: }

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

8784:   Not collective

8786:   Input Parameters:
8787: + dm         - The `DM`
8788: . section    - The `PetscSection` describing the points (a local section)
8789: . idxSection - The `PetscSection` from which to obtain indices (may be local or global)
8790: . point      - The point defining the closure
8791: - useClPerm  - Use the closure point permutation if available

8793:   Output Parameters:
8794: + numIndices - The number of dof indices in the closure of point with the input sections
8795: . indices    - The dof indices
8796: . outOffsets - Array, of length the number of fields plus 1, to write the field offsets into, or `NULL`
8797: - values     - The input values, which may be modified if sign flips are induced by the point symmetries, or `NULL`

8799:   Level: advanced

8801:   Notes:
8802:   Call `DMPlexRestoreClosureIndices()` to free allocated memory

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

8810: .seealso: [](ch_unstructured), `DM`, `DMPLEX`, `DMPlexRestoreClosureIndices()`, `DMPlexVecGetClosure()`, `DMPlexMatSetClosure()`, `DMGetLocalSection()`,
8811:           `PetscSection`, `DMGetGlobalSection()`
8812: @*/
8813: PetscErrorCode DMPlexGetClosureIndices(DM dm, PetscSection section, PetscSection idxSection, PetscInt point, PetscBool useClPerm, PetscInt *numIndices, PetscInt *indices[], PeOp PetscInt outOffsets[], PeOp PetscScalar *values[])
8814: {
8815:   PetscInt numRows = -1, numCols = -1;

8817:   PetscFunctionBeginHot;
8818:   PetscCall(DMPlexGetClosureIndices_Internal(dm, section, idxSection, point, useClPerm, &numRows, &numCols, indices, outOffsets, values, PETSC_TRUE, PETSC_TRUE));
8819:   PetscCheck(numRows == numCols, PETSC_COMM_SELF, PETSC_ERR_PLIB, "Symmetric matrix transformation produces rectangular dimensions (%" PetscInt_FMT ", %" PetscInt_FMT ")", numRows, numCols);
8820:   *numIndices = numRows;
8821:   PetscFunctionReturn(PETSC_SUCCESS);
8822: }

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

8827:   Not collective

8829:   Input Parameters:
8830: + dm         - The `DM`
8831: . section    - The `PetscSection` describing the points (a local section)
8832: . idxSection - The `PetscSection` from which to obtain indices (may be local or global)
8833: . point      - The point defining the closure
8834: - useClPerm  - Use the closure point permutation if available

8836:   Output Parameters:
8837: + numIndices - The number of dof indices in the closure of point with the input sections
8838: . indices    - The dof indices
8839: . outOffsets - Array to write the field offsets into, or `NULL`
8840: - values     - The input values, which may be modified if sign flips are induced by the point symmetries, or `NULL`

8842:   Level: advanced

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

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

8853: .seealso: [](ch_unstructured), `DM`, `DMPLEX`, `DMPlexGetClosureIndices()`, `DMPlexVecGetClosure()`, `DMPlexMatSetClosure()`, `DMGetLocalSection()`, `DMGetGlobalSection()`
8854: @*/
8855: PetscErrorCode DMPlexRestoreClosureIndices(DM dm, PetscSection section, PetscSection idxSection, PetscInt point, PetscBool useClPerm, PetscInt *numIndices, PetscInt *indices[], PeOp PetscInt outOffsets[], PeOp PetscScalar *values[])
8856: {
8857:   PetscFunctionBegin;
8859:   PetscAssertPointer(indices, 7);
8860:   PetscCall(DMRestoreWorkArray(dm, 0, MPIU_INT, indices));
8861:   PetscFunctionReturn(PETSC_SUCCESS);
8862: }

8864: PetscErrorCode DMPlexMatSetClosure_Internal(DM dm, PetscSection section, PetscSection globalSection, PetscBool useClPerm, Mat A, PetscInt point, const PetscScalar values[], InsertMode mode)
8865: {
8866:   DM_Plex           *mesh = (DM_Plex *)dm->data;
8867:   PetscInt          *indices;
8868:   PetscInt           numIndices;
8869:   const PetscScalar *valuesOrig = values;
8870:   PetscErrorCode     ierr;

8872:   PetscFunctionBegin;
8874:   if (!section) PetscCall(DMGetLocalSection(dm, &section));
8876:   if (!globalSection) PetscCall(DMGetGlobalSection(dm, &globalSection));

8880:   PetscCall(DMPlexGetClosureIndices(dm, section, globalSection, point, useClPerm, &numIndices, &indices, NULL, (PetscScalar **)&values));

8882:   if (mesh->printSetValues) PetscCall(DMPlexPrintMatSetValues(PETSC_VIEWER_STDOUT_SELF, A, point, numIndices, indices, 0, NULL, values));
8883:   /* TODO: fix this code to not use error codes as handle-able exceptions! */
8884:   ierr = MatSetValues(A, numIndices, indices, numIndices, indices, values, mode);
8885:   if (ierr) {
8886:     PetscMPIInt rank;

8888:     PetscCallMPI(MPI_Comm_rank(PetscObjectComm((PetscObject)A), &rank));
8889:     PetscCall((*PetscErrorPrintf)("[%d]ERROR in DMPlexMatSetClosure\n", rank));
8890:     PetscCall(DMPlexPrintMatSetValues(PETSC_VIEWER_STDERR_SELF, A, point, numIndices, indices, 0, NULL, values));
8891:     PetscCall(DMPlexRestoreClosureIndices(dm, section, globalSection, point, PETSC_TRUE, &numIndices, &indices, NULL, (PetscScalar **)&values));
8892:     if (values != valuesOrig) PetscCall(DMRestoreWorkArray(dm, 0, MPIU_SCALAR, &values));
8893:     SETERRQ(PetscObjectComm((PetscObject)dm), ierr, "Not possible to set matrix values");
8894:   }
8895:   if (mesh->printFEM > 1) {
8896:     PetscCall(PetscPrintf(PETSC_COMM_SELF, "  Indices:"));
8897:     for (PetscInt i = 0; i < numIndices; ++i) PetscCall(PetscPrintf(PETSC_COMM_SELF, " %" PetscInt_FMT, indices[i]));
8898:     PetscCall(PetscPrintf(PETSC_COMM_SELF, "\n"));
8899:   }

8901:   PetscCall(DMPlexRestoreClosureIndices(dm, section, globalSection, point, PETSC_TRUE, &numIndices, &indices, NULL, (PetscScalar **)&values));
8902:   if (values != valuesOrig) PetscCall(DMRestoreWorkArray(dm, 0, MPIU_SCALAR, &values));
8903:   PetscFunctionReturn(PETSC_SUCCESS);
8904: }

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

8909:   Not collective

8911:   Input Parameters:
8912: + dm            - The `DM`
8913: . section       - The section describing the layout in `v`, or `NULL` to use the default section
8914: . globalSection - The section describing the layout in `v`, or `NULL` to use the default global section
8915: . A             - The matrix
8916: . point         - The point in the `DM`
8917: . values        - The array of values
8918: - mode          - The insert mode, where `INSERT_ALL_VALUES` and `ADD_ALL_VALUES` also overwrite boundary conditions

8920:   Level: intermediate

8922: .seealso: [](ch_unstructured), `DM`, `DMPLEX`, `DMPlexMatSetClosureGeneral()`, `DMPlexVecGetClosure()`, `DMPlexVecSetClosure()`
8923: @*/
8924: PetscErrorCode DMPlexMatSetClosure(DM dm, PetscSection section, PetscSection globalSection, Mat A, PetscInt point, const PetscScalar values[], InsertMode mode)
8925: {
8926:   PetscFunctionBegin;
8927:   PetscCall(DMPlexMatSetClosure_Internal(dm, section, globalSection, PETSC_TRUE, A, point, values, mode));
8928:   PetscFunctionReturn(PETSC_SUCCESS);
8929: }

8931: /*@C
8932:   DMPlexMatSetClosureGeneral - Set an array of the values on the closure of 'point' using a different row and column section

8934:   Not collective

8936:   Input Parameters:
8937: + dmRow            - The `DM` for the row fields
8938: . sectionRow       - The section describing the layout, or `NULL` to use the default section in `dmRow`
8939: . useRowPerm       - The flag to use the closure permutation of the `dmRow` if available
8940: . globalSectionRow - The section describing the layout, or `NULL` to use the default global section in `dmRow`
8941: . dmCol            - The `DM` for the column fields
8942: . sectionCol       - The section describing the layout, or `NULL` to use the default section in `dmCol`
8943: . useColPerm       - The flag to use the closure permutation of the `dmCol` if available
8944: . globalSectionCol - The section describing the layout, or `NULL` to use the default global section in `dmCol`
8945: . A                - The matrix
8946: . point            - The point in the `DM`
8947: . values           - The array of values
8948: - mode             - The insert mode, where `INSERT_ALL_VALUES` and `ADD_ALL_VALUES` also overwrite boundary conditions

8950:   Level: intermediate

8952: .seealso: [](ch_unstructured), `DM`, `DMPLEX`, `DMPlexMatSetClosure()`, `DMPlexVecGetClosure()`, `DMPlexVecSetClosure()`
8953: @*/
8954: PetscErrorCode DMPlexMatSetClosureGeneral(DM dmRow, PetscSection sectionRow, PetscSection globalSectionRow, PetscBool useRowPerm, DM dmCol, PetscSection sectionCol, PetscSection globalSectionCol, PetscBool useColPerm, Mat A, PetscInt point, const PetscScalar values[], InsertMode mode)
8955: {
8956:   DM_Plex           *mesh = (DM_Plex *)dmRow->data;
8957:   PetscInt          *indicesRow, *indicesCol;
8958:   PetscInt           numIndicesRow = -1, numIndicesCol = -1;
8959:   const PetscScalar *valuesV0 = values, *valuesV1, *valuesV2;

8961:   PetscErrorCode ierr;

8963:   PetscFunctionBegin;
8965:   if (!sectionRow) PetscCall(DMGetLocalSection(dmRow, &sectionRow));
8967:   if (!globalSectionRow) PetscCall(DMGetGlobalSection(dmRow, &globalSectionRow));
8970:   if (!sectionCol) PetscCall(DMGetLocalSection(dmCol, &sectionCol));
8972:   if (!globalSectionCol) PetscCall(DMGetGlobalSection(dmCol, &globalSectionCol));

8976:   PetscCall(DMPlexGetClosureIndicesSize_Internal(dmRow, sectionRow, point, &numIndicesRow));
8977:   PetscCall(DMPlexGetClosureIndicesSize_Internal(dmCol, sectionCol, point, &numIndicesCol));
8978:   valuesV1 = valuesV0;
8979:   PetscCall(DMPlexGetClosureIndices_Internal(dmRow, sectionRow, globalSectionRow, point, useRowPerm, &numIndicesRow, &numIndicesCol, &indicesRow, NULL, (PetscScalar **)&valuesV1, PETSC_FALSE, PETSC_TRUE));
8980:   valuesV2 = valuesV1;
8981:   PetscCall(DMPlexGetClosureIndices_Internal(dmCol, sectionCol, globalSectionCol, point, useColPerm, &numIndicesRow, &numIndicesCol, &indicesCol, NULL, (PetscScalar **)&valuesV2, PETSC_TRUE, PETSC_FALSE));

8983:   if (mesh->printSetValues) PetscCall(DMPlexPrintMatSetValues(PETSC_VIEWER_STDOUT_SELF, A, point, numIndicesRow, indicesRow, numIndicesCol, indicesCol, valuesV2));
8984:   /* TODO: fix this code to not use error codes as handle-able exceptions! */
8985:   ierr = MatSetValues(A, numIndicesRow, indicesRow, numIndicesCol, indicesCol, valuesV2, mode);
8986:   if (ierr) {
8987:     PetscMPIInt rank;

8989:     PetscCallMPI(MPI_Comm_rank(PetscObjectComm((PetscObject)A), &rank));
8990:     PetscCall((*PetscErrorPrintf)("[%d]ERROR in DMPlexMatSetClosure\n", rank));
8991:     PetscCall(DMPlexPrintMatSetValues(PETSC_VIEWER_STDERR_SELF, A, point, numIndicesRow, indicesRow, numIndicesCol, indicesCol, values));
8992:     PetscCall(DMPlexRestoreClosureIndices(dmCol, sectionCol, globalSectionCol, point, PETSC_TRUE, &numIndicesCol, &indicesRow, NULL, (PetscScalar **)&valuesV2));
8993:     PetscCall(DMPlexRestoreClosureIndices(dmRow, sectionRow, globalSectionRow, point, PETSC_TRUE, &numIndicesRow, &indicesRow, NULL, (PetscScalar **)&valuesV1));
8994:     if (valuesV2 != valuesV1) PetscCall(DMRestoreWorkArray(dmCol, 0, MPIU_SCALAR, &valuesV2));
8995:     if (valuesV1 != valuesV0) PetscCall(DMRestoreWorkArray(dmRow, 0, MPIU_SCALAR, &valuesV1));
8996:   }

8998:   PetscCall(DMPlexRestoreClosureIndices(dmCol, sectionCol, globalSectionCol, point, useColPerm, &numIndicesCol, &indicesCol, NULL, (PetscScalar **)&valuesV2));
8999:   PetscCall(DMPlexRestoreClosureIndices(dmRow, sectionRow, globalSectionRow, point, useRowPerm, &numIndicesRow, &indicesRow, NULL, (PetscScalar **)&valuesV1));
9000:   if (valuesV2 != valuesV1) PetscCall(DMRestoreWorkArray(dmCol, 0, MPIU_SCALAR, &valuesV2));
9001:   if (valuesV1 != valuesV0) PetscCall(DMRestoreWorkArray(dmRow, 0, MPIU_SCALAR, &valuesV1));
9002:   PetscFunctionReturn(PETSC_SUCCESS);
9003: }

9005: PetscErrorCode DMPlexMatSetClosureRefined(DM dmf, PetscSection fsection, PetscSection globalFSection, DM dmc, PetscSection csection, PetscSection globalCSection, Mat A, PetscInt point, const PetscScalar values[], InsertMode mode)
9006: {
9007:   DM_Plex        *mesh    = (DM_Plex *)dmf->data;
9008:   PetscInt       *fpoints = NULL, *ftotpoints = NULL;
9009:   PetscInt       *cpoints = NULL;
9010:   PetscInt       *findices, *cindices;
9011:   const PetscInt *fclperm = NULL, *cclperm = NULL; /* Closure permutations cannot work here */
9012:   PetscInt        foffsets[32], coffsets[32];
9013:   DMPolytopeType  ct;
9014:   PetscInt        numFields, numSubcells, maxFPoints, numFPoints, numCPoints, numFIndices, numCIndices, dof, off, globalOff, pStart, pEnd, p, q, r, s, f;
9015:   PetscErrorCode  ierr;

9017:   PetscFunctionBegin;
9020:   if (!fsection) PetscCall(DMGetLocalSection(dmf, &fsection));
9022:   if (!csection) PetscCall(DMGetLocalSection(dmc, &csection));
9024:   if (!globalFSection) PetscCall(DMGetGlobalSection(dmf, &globalFSection));
9026:   if (!globalCSection) PetscCall(DMGetGlobalSection(dmc, &globalCSection));
9029:   PetscCall(PetscSectionGetNumFields(fsection, &numFields));
9030:   PetscCheck(numFields <= 31, PetscObjectComm((PetscObject)dmf), PETSC_ERR_ARG_OUTOFRANGE, "Number of fields %" PetscInt_FMT " limited to 31", numFields);
9031:   PetscCall(PetscArrayzero(foffsets, 32));
9032:   PetscCall(PetscArrayzero(coffsets, 32));
9033:   /* Column indices */
9034:   PetscCall(DMPlexGetTransitiveClosure(dmc, point, PETSC_TRUE, &numCPoints, &cpoints));
9035:   maxFPoints = numCPoints;
9036:   /* Compress out points not in the section */
9037:   /*   TODO: Squeeze out points with 0 dof as well */
9038:   PetscCall(PetscSectionGetChart(csection, &pStart, &pEnd));
9039:   for (p = 0, q = 0; p < numCPoints * 2; p += 2) {
9040:     if ((cpoints[p] >= pStart) && (cpoints[p] < pEnd)) {
9041:       cpoints[q * 2]     = cpoints[p];
9042:       cpoints[q * 2 + 1] = cpoints[p + 1];
9043:       ++q;
9044:     }
9045:   }
9046:   numCPoints = q;
9047:   for (p = 0, numCIndices = 0; p < numCPoints * 2; p += 2) {
9048:     PetscInt fdof;

9050:     PetscCall(PetscSectionGetDof(csection, cpoints[p], &dof));
9051:     if (!dof) continue;
9052:     for (f = 0; f < numFields; ++f) {
9053:       PetscCall(PetscSectionGetFieldDof(csection, cpoints[p], f, &fdof));
9054:       coffsets[f + 1] += fdof;
9055:     }
9056:     numCIndices += dof;
9057:   }
9058:   for (f = 1; f < numFields; ++f) coffsets[f + 1] += coffsets[f];
9059:   /* Row indices */
9060:   PetscCall(DMPlexGetCellType(dmc, point, &ct));
9061:   {
9062:     DMPlexTransform tr;
9063:     DMPolytopeType *rct;
9064:     PetscInt       *rsize, *rcone, *rornt, Nt;

9066:     PetscCall(DMPlexTransformCreate(PETSC_COMM_SELF, &tr));
9067:     PetscCall(DMPlexTransformSetType(tr, DMPLEXREFINEREGULAR));
9068:     PetscCall(DMPlexTransformCellTransform(tr, ct, point, NULL, &Nt, &rct, &rsize, &rcone, &rornt));
9069:     numSubcells = rsize[Nt - 1];
9070:     PetscCall(DMPlexTransformDestroy(&tr));
9071:   }
9072:   PetscCall(DMGetWorkArray(dmf, maxFPoints * 2 * numSubcells, MPIU_INT, &ftotpoints));
9073:   for (r = 0, q = 0; r < numSubcells; ++r) {
9074:     /* TODO Map from coarse to fine cells */
9075:     PetscCall(DMPlexGetTransitiveClosure(dmf, point * numSubcells + r, PETSC_TRUE, &numFPoints, &fpoints));
9076:     /* Compress out points not in the section */
9077:     PetscCall(PetscSectionGetChart(fsection, &pStart, &pEnd));
9078:     for (p = 0; p < numFPoints * 2; p += 2) {
9079:       if ((fpoints[p] >= pStart) && (fpoints[p] < pEnd)) {
9080:         PetscCall(PetscSectionGetDof(fsection, fpoints[p], &dof));
9081:         if (!dof) continue;
9082:         for (s = 0; s < q; ++s)
9083:           if (fpoints[p] == ftotpoints[s * 2]) break;
9084:         if (s < q) continue;
9085:         ftotpoints[q * 2]     = fpoints[p];
9086:         ftotpoints[q * 2 + 1] = fpoints[p + 1];
9087:         ++q;
9088:       }
9089:     }
9090:     PetscCall(DMPlexRestoreTransitiveClosure(dmf, point, PETSC_TRUE, &numFPoints, &fpoints));
9091:   }
9092:   numFPoints = q;
9093:   for (p = 0, numFIndices = 0; p < numFPoints * 2; p += 2) {
9094:     PetscInt fdof;

9096:     PetscCall(PetscSectionGetDof(fsection, ftotpoints[p], &dof));
9097:     if (!dof) continue;
9098:     for (f = 0; f < numFields; ++f) {
9099:       PetscCall(PetscSectionGetFieldDof(fsection, ftotpoints[p], f, &fdof));
9100:       foffsets[f + 1] += fdof;
9101:     }
9102:     numFIndices += dof;
9103:   }
9104:   for (f = 1; f < numFields; ++f) foffsets[f + 1] += foffsets[f];

9106:   PetscCheck(!numFields || foffsets[numFields] == numFIndices, PetscObjectComm((PetscObject)dmf), PETSC_ERR_PLIB, "Invalid size for closure %" PetscInt_FMT " should be %" PetscInt_FMT, foffsets[numFields], numFIndices);
9107:   PetscCheck(!numFields || coffsets[numFields] == numCIndices, PetscObjectComm((PetscObject)dmc), PETSC_ERR_PLIB, "Invalid size for closure %" PetscInt_FMT " should be %" PetscInt_FMT, coffsets[numFields], numCIndices);
9108:   PetscCall(DMGetWorkArray(dmf, numFIndices, MPIU_INT, &findices));
9109:   PetscCall(DMGetWorkArray(dmc, numCIndices, MPIU_INT, &cindices));
9110:   if (numFields) {
9111:     const PetscInt **permsF[32] = {NULL};
9112:     const PetscInt **permsC[32] = {NULL};

9114:     for (f = 0; f < numFields; f++) {
9115:       PetscCall(PetscSectionGetFieldPointSyms(fsection, f, numFPoints, ftotpoints, &permsF[f], NULL));
9116:       PetscCall(PetscSectionGetFieldPointSyms(csection, f, numCPoints, cpoints, &permsC[f], NULL));
9117:     }
9118:     for (p = 0; p < numFPoints; p++) {
9119:       PetscCall(PetscSectionGetOffset(globalFSection, ftotpoints[2 * p], &globalOff));
9120:       PetscCall(DMPlexGetIndicesPointFields_Internal(fsection, PETSC_FALSE, ftotpoints[2 * p], globalOff < 0 ? -(globalOff + 1) : globalOff, foffsets, PETSC_FALSE, permsF, p, fclperm, findices));
9121:     }
9122:     for (p = 0; p < numCPoints; p++) {
9123:       PetscCall(PetscSectionGetOffset(globalCSection, cpoints[2 * p], &globalOff));
9124:       PetscCall(DMPlexGetIndicesPointFields_Internal(csection, PETSC_FALSE, cpoints[2 * p], globalOff < 0 ? -(globalOff + 1) : globalOff, coffsets, PETSC_FALSE, permsC, p, cclperm, cindices));
9125:     }
9126:     for (f = 0; f < numFields; f++) {
9127:       PetscCall(PetscSectionRestoreFieldPointSyms(fsection, f, numFPoints, ftotpoints, &permsF[f], NULL));
9128:       PetscCall(PetscSectionRestoreFieldPointSyms(csection, f, numCPoints, cpoints, &permsC[f], NULL));
9129:     }
9130:   } else {
9131:     const PetscInt **permsF = NULL;
9132:     const PetscInt **permsC = NULL;

9134:     PetscCall(PetscSectionGetPointSyms(fsection, numFPoints, ftotpoints, &permsF, NULL));
9135:     PetscCall(PetscSectionGetPointSyms(csection, numCPoints, cpoints, &permsC, NULL));
9136:     for (p = 0, off = 0; p < numFPoints; p++) {
9137:       const PetscInt *perm = permsF ? permsF[p] : NULL;

9139:       PetscCall(PetscSectionGetOffset(globalFSection, ftotpoints[2 * p], &globalOff));
9140:       PetscCall(DMPlexGetIndicesPoint_Internal(fsection, PETSC_FALSE, ftotpoints[2 * p], globalOff < 0 ? -(globalOff + 1) : globalOff, &off, PETSC_FALSE, perm, fclperm, findices));
9141:     }
9142:     for (p = 0, off = 0; p < numCPoints; p++) {
9143:       const PetscInt *perm = permsC ? permsC[p] : NULL;

9145:       PetscCall(PetscSectionGetOffset(globalCSection, cpoints[2 * p], &globalOff));
9146:       PetscCall(DMPlexGetIndicesPoint_Internal(csection, PETSC_FALSE, cpoints[2 * p], globalOff < 0 ? -(globalOff + 1) : globalOff, &off, PETSC_FALSE, perm, cclperm, cindices));
9147:     }
9148:     PetscCall(PetscSectionRestorePointSyms(fsection, numFPoints, ftotpoints, &permsF, NULL));
9149:     PetscCall(PetscSectionRestorePointSyms(csection, numCPoints, cpoints, &permsC, NULL));
9150:   }
9151:   if (mesh->printSetValues) PetscCall(DMPlexPrintMatSetValues(PETSC_VIEWER_STDOUT_SELF, A, point, numFIndices, findices, numCIndices, cindices, values));
9152:   /* TODO: flips */
9153:   /* TODO: fix this code to not use error codes as handle-able exceptions! */
9154:   ierr = MatSetValues(A, numFIndices, findices, numCIndices, cindices, values, mode);
9155:   if (ierr) {
9156:     PetscMPIInt rank;

9158:     PetscCallMPI(MPI_Comm_rank(PetscObjectComm((PetscObject)A), &rank));
9159:     PetscCall((*PetscErrorPrintf)("[%d]ERROR in DMPlexMatSetClosure\n", rank));
9160:     PetscCall(DMPlexPrintMatSetValues(PETSC_VIEWER_STDERR_SELF, A, point, numFIndices, findices, numCIndices, cindices, values));
9161:     PetscCall(DMRestoreWorkArray(dmf, numFIndices, MPIU_INT, &findices));
9162:     PetscCall(DMRestoreWorkArray(dmc, numCIndices, MPIU_INT, &cindices));
9163:   }
9164:   PetscCall(DMRestoreWorkArray(dmf, numCPoints * 2 * 4, MPIU_INT, &ftotpoints));
9165:   PetscCall(DMPlexRestoreTransitiveClosure(dmc, point, PETSC_TRUE, &numCPoints, &cpoints));
9166:   PetscCall(DMRestoreWorkArray(dmf, numFIndices, MPIU_INT, &findices));
9167:   PetscCall(DMRestoreWorkArray(dmc, numCIndices, MPIU_INT, &cindices));
9168:   PetscFunctionReturn(PETSC_SUCCESS);
9169: }

9171: PetscErrorCode DMPlexMatGetClosureIndicesRefined(DM dmf, PetscSection fsection, PetscSection globalFSection, DM dmc, PetscSection csection, PetscSection globalCSection, PetscInt point, PetscInt cindices[], PetscInt findices[])
9172: {
9173:   PetscInt       *fpoints = NULL, *ftotpoints = NULL;
9174:   PetscInt       *cpoints      = NULL;
9175:   PetscInt        foffsets[32] = {0}, coffsets[32] = {0};
9176:   const PetscInt *fclperm = NULL, *cclperm = NULL; /* Closure permutations cannot work here */
9177:   DMPolytopeType  ct;
9178:   PetscInt        numFields, numSubcells, maxFPoints, numFPoints, numCPoints, numFIndices, numCIndices, dof, off, globalOff, pStart, pEnd, p, q, r, s, f;

9180:   PetscFunctionBegin;
9183:   if (!fsection) PetscCall(DMGetLocalSection(dmf, &fsection));
9185:   if (!csection) PetscCall(DMGetLocalSection(dmc, &csection));
9187:   if (!globalFSection) PetscCall(DMGetGlobalSection(dmf, &globalFSection));
9189:   if (!globalCSection) PetscCall(DMGetGlobalSection(dmc, &globalCSection));
9191:   PetscCall(PetscSectionGetNumFields(fsection, &numFields));
9192:   PetscCheck(numFields <= 31, PetscObjectComm((PetscObject)dmf), PETSC_ERR_ARG_OUTOFRANGE, "Number of fields %" PetscInt_FMT " limited to 31", numFields);
9193:   /* Column indices */
9194:   PetscCall(DMPlexGetTransitiveClosure(dmc, point, PETSC_TRUE, &numCPoints, &cpoints));
9195:   maxFPoints = numCPoints;
9196:   /* Compress out points not in the section */
9197:   /*   TODO: Squeeze out points with 0 dof as well */
9198:   PetscCall(PetscSectionGetChart(csection, &pStart, &pEnd));
9199:   for (p = 0, q = 0; p < numCPoints * 2; p += 2) {
9200:     if ((cpoints[p] >= pStart) && (cpoints[p] < pEnd)) {
9201:       cpoints[q * 2]     = cpoints[p];
9202:       cpoints[q * 2 + 1] = cpoints[p + 1];
9203:       ++q;
9204:     }
9205:   }
9206:   numCPoints = q;
9207:   for (p = 0, numCIndices = 0; p < numCPoints * 2; p += 2) {
9208:     PetscInt fdof;

9210:     PetscCall(PetscSectionGetDof(csection, cpoints[p], &dof));
9211:     if (!dof) continue;
9212:     for (f = 0; f < numFields; ++f) {
9213:       PetscCall(PetscSectionGetFieldDof(csection, cpoints[p], f, &fdof));
9214:       coffsets[f + 1] += fdof;
9215:     }
9216:     numCIndices += dof;
9217:   }
9218:   for (f = 1; f < numFields; ++f) coffsets[f + 1] += coffsets[f];
9219:   /* Row indices */
9220:   PetscCall(DMPlexGetCellType(dmc, point, &ct));
9221:   {
9222:     DMPlexTransform tr;
9223:     DMPolytopeType *rct;
9224:     PetscInt       *rsize, *rcone, *rornt, Nt;

9226:     PetscCall(DMPlexTransformCreate(PETSC_COMM_SELF, &tr));
9227:     PetscCall(DMPlexTransformSetType(tr, DMPLEXREFINEREGULAR));
9228:     PetscCall(DMPlexTransformCellTransform(tr, ct, point, NULL, &Nt, &rct, &rsize, &rcone, &rornt));
9229:     numSubcells = rsize[Nt - 1];
9230:     PetscCall(DMPlexTransformDestroy(&tr));
9231:   }
9232:   PetscCall(DMGetWorkArray(dmf, maxFPoints * 2 * numSubcells, MPIU_INT, &ftotpoints));
9233:   for (r = 0, q = 0; r < numSubcells; ++r) {
9234:     /* TODO Map from coarse to fine cells */
9235:     PetscCall(DMPlexGetTransitiveClosure(dmf, point * numSubcells + r, PETSC_TRUE, &numFPoints, &fpoints));
9236:     /* Compress out points not in the section */
9237:     PetscCall(PetscSectionGetChart(fsection, &pStart, &pEnd));
9238:     for (p = 0; p < numFPoints * 2; p += 2) {
9239:       if ((fpoints[p] >= pStart) && (fpoints[p] < pEnd)) {
9240:         PetscCall(PetscSectionGetDof(fsection, fpoints[p], &dof));
9241:         if (!dof) continue;
9242:         for (s = 0; s < q; ++s)
9243:           if (fpoints[p] == ftotpoints[s * 2]) break;
9244:         if (s < q) continue;
9245:         ftotpoints[q * 2]     = fpoints[p];
9246:         ftotpoints[q * 2 + 1] = fpoints[p + 1];
9247:         ++q;
9248:       }
9249:     }
9250:     PetscCall(DMPlexRestoreTransitiveClosure(dmf, point, PETSC_TRUE, &numFPoints, &fpoints));
9251:   }
9252:   numFPoints = q;
9253:   for (p = 0, numFIndices = 0; p < numFPoints * 2; p += 2) {
9254:     PetscInt fdof;

9256:     PetscCall(PetscSectionGetDof(fsection, ftotpoints[p], &dof));
9257:     if (!dof) continue;
9258:     for (f = 0; f < numFields; ++f) {
9259:       PetscCall(PetscSectionGetFieldDof(fsection, ftotpoints[p], f, &fdof));
9260:       foffsets[f + 1] += fdof;
9261:     }
9262:     numFIndices += dof;
9263:   }
9264:   for (f = 1; f < numFields; ++f) foffsets[f + 1] += foffsets[f];

9266:   PetscCheck(!numFields || foffsets[numFields] == numFIndices, PetscObjectComm((PetscObject)dmf), PETSC_ERR_PLIB, "Invalid size for closure %" PetscInt_FMT " should be %" PetscInt_FMT, foffsets[numFields], numFIndices);
9267:   PetscCheck(!numFields || coffsets[numFields] == numCIndices, PetscObjectComm((PetscObject)dmc), PETSC_ERR_PLIB, "Invalid size for closure %" PetscInt_FMT " should be %" PetscInt_FMT, coffsets[numFields], numCIndices);
9268:   if (numFields) {
9269:     const PetscInt **permsF[32] = {NULL};
9270:     const PetscInt **permsC[32] = {NULL};

9272:     for (f = 0; f < numFields; f++) {
9273:       PetscCall(PetscSectionGetFieldPointSyms(fsection, f, numFPoints, ftotpoints, &permsF[f], NULL));
9274:       PetscCall(PetscSectionGetFieldPointSyms(csection, f, numCPoints, cpoints, &permsC[f], NULL));
9275:     }
9276:     for (p = 0; p < numFPoints; p++) {
9277:       PetscCall(PetscSectionGetOffset(globalFSection, ftotpoints[2 * p], &globalOff));
9278:       PetscCall(DMPlexGetIndicesPointFields_Internal(fsection, PETSC_FALSE, ftotpoints[2 * p], globalOff < 0 ? -(globalOff + 1) : globalOff, foffsets, PETSC_FALSE, permsF, p, fclperm, findices));
9279:     }
9280:     for (p = 0; p < numCPoints; p++) {
9281:       PetscCall(PetscSectionGetOffset(globalCSection, cpoints[2 * p], &globalOff));
9282:       PetscCall(DMPlexGetIndicesPointFields_Internal(csection, PETSC_FALSE, cpoints[2 * p], globalOff < 0 ? -(globalOff + 1) : globalOff, coffsets, PETSC_FALSE, permsC, p, cclperm, cindices));
9283:     }
9284:     for (f = 0; f < numFields; f++) {
9285:       PetscCall(PetscSectionRestoreFieldPointSyms(fsection, f, numFPoints, ftotpoints, &permsF[f], NULL));
9286:       PetscCall(PetscSectionRestoreFieldPointSyms(csection, f, numCPoints, cpoints, &permsC[f], NULL));
9287:     }
9288:   } else {
9289:     const PetscInt **permsF = NULL;
9290:     const PetscInt **permsC = NULL;

9292:     PetscCall(PetscSectionGetPointSyms(fsection, numFPoints, ftotpoints, &permsF, NULL));
9293:     PetscCall(PetscSectionGetPointSyms(csection, numCPoints, cpoints, &permsC, NULL));
9294:     for (p = 0, off = 0; p < numFPoints; p++) {
9295:       const PetscInt *perm = permsF ? permsF[p] : NULL;

9297:       PetscCall(PetscSectionGetOffset(globalFSection, ftotpoints[2 * p], &globalOff));
9298:       PetscCall(DMPlexGetIndicesPoint_Internal(fsection, PETSC_FALSE, ftotpoints[2 * p], globalOff < 0 ? -(globalOff + 1) : globalOff, &off, PETSC_FALSE, perm, fclperm, findices));
9299:     }
9300:     for (p = 0, off = 0; p < numCPoints; p++) {
9301:       const PetscInt *perm = permsC ? permsC[p] : NULL;

9303:       PetscCall(PetscSectionGetOffset(globalCSection, cpoints[2 * p], &globalOff));
9304:       PetscCall(DMPlexGetIndicesPoint_Internal(csection, PETSC_FALSE, cpoints[2 * p], globalOff < 0 ? -(globalOff + 1) : globalOff, &off, PETSC_FALSE, perm, cclperm, cindices));
9305:     }
9306:     PetscCall(PetscSectionRestorePointSyms(fsection, numFPoints, ftotpoints, &permsF, NULL));
9307:     PetscCall(PetscSectionRestorePointSyms(csection, numCPoints, cpoints, &permsC, NULL));
9308:   }
9309:   PetscCall(DMRestoreWorkArray(dmf, numCPoints * 2 * 4, MPIU_INT, &ftotpoints));
9310:   PetscCall(DMPlexRestoreTransitiveClosure(dmc, point, PETSC_TRUE, &numCPoints, &cpoints));
9311:   PetscFunctionReturn(PETSC_SUCCESS);
9312: }

9314: /*@
9315:   DMPlexGetVTKCellHeight - Returns the height in the DAG used to determine which points are cells (normally 0)

9317:   Input Parameter:
9318: . dm - The `DMPLEX` object

9320:   Output Parameter:
9321: . cellHeight - The height of a cell

9323:   Level: developer

9325: .seealso: [](ch_unstructured), `DM`, `DMPLEX`, `DMPlexSetVTKCellHeight()`
9326: @*/
9327: PetscErrorCode DMPlexGetVTKCellHeight(DM dm, PetscInt *cellHeight)
9328: {
9329:   DM_Plex *mesh = (DM_Plex *)dm->data;

9331:   PetscFunctionBegin;
9333:   PetscAssertPointer(cellHeight, 2);
9334:   *cellHeight = mesh->vtkCellHeight;
9335:   PetscFunctionReturn(PETSC_SUCCESS);
9336: }

9338: /*@
9339:   DMPlexSetVTKCellHeight - Sets the height in the DAG used to determine which points are cells (normally 0)

9341:   Input Parameters:
9342: + dm         - The `DMPLEX` object
9343: - cellHeight - The height of a cell

9345:   Level: developer

9347: .seealso: [](ch_unstructured), `DM`, `DMPLEX`, `DMPlexGetVTKCellHeight()`
9348: @*/
9349: PetscErrorCode DMPlexSetVTKCellHeight(DM dm, PetscInt cellHeight)
9350: {
9351:   DM_Plex *mesh = (DM_Plex *)dm->data;

9353:   PetscFunctionBegin;
9355:   mesh->vtkCellHeight = cellHeight;
9356:   PetscFunctionReturn(PETSC_SUCCESS);
9357: }

9359: /*@
9360:   DMPlexGetCellTypeStratum - Get the range of cells of a given celltype

9362:   Input Parameters:
9363: + dm - The `DMPLEX` object
9364: - ct - The `DMPolytopeType` of the cell

9366:   Output Parameters:
9367: + start - The first cell of this type, or `NULL`
9368: - end   - The upper bound on this celltype, or `NULL`

9370:   Level: advanced

9372: .seealso: [](ch_unstructured), `DM`, `DMPLEX`, `DMPlexConstructGhostCells()`, `DMPlexGetDepthStratum()`, `DMPlexGetHeightStratum()`
9373: @*/
9374: PetscErrorCode DMPlexGetCellTypeStratum(DM dm, DMPolytopeType ct, PeOp PetscInt *start, PeOp PetscInt *end)
9375: {
9376:   DM_Plex *mesh = (DM_Plex *)dm->data;
9377:   DMLabel  label;
9378:   PetscInt pStart, pEnd;

9380:   PetscFunctionBegin;
9382:   if (start) {
9383:     PetscAssertPointer(start, 3);
9384:     *start = 0;
9385:   }
9386:   if (end) {
9387:     PetscAssertPointer(end, 4);
9388:     *end = 0;
9389:   }
9390:   PetscCall(DMPlexGetChart(dm, &pStart, &pEnd));
9391:   if (pStart == pEnd) PetscFunctionReturn(PETSC_SUCCESS);
9392:   if (mesh->tr) {
9393:     PetscCall(DMPlexTransformGetCellTypeStratum(mesh->tr, ct, start, end));
9394:   } else {
9395:     PetscCall(DMPlexGetCellTypeLabel(dm, &label));
9396:     PetscCheck(label, PetscObjectComm((PetscObject)dm), PETSC_ERR_ARG_WRONG, "No label named celltype was found");
9397:     PetscCall(DMLabelGetStratumBounds(label, ct, start, end));
9398:   }
9399:   PetscFunctionReturn(PETSC_SUCCESS);
9400: }

9402: /*@
9403:   DMPlexGetDepthStratumGlobalSize - Get the global size for a given depth stratum

9405:   Input Parameters:
9406: + dm    - The `DMPLEX` object
9407: - depth - The depth for the given point stratum

9409:   Output Parameter:
9410: . gsize - The global number of points in the stratum

9412:   Level: advanced

9414: .seealso: [](ch_unstructured), `DM`, `DMPLEX`, `DMPlexGetCellNumbering()`, `DMPlexGetVertexNumbering()`, `DMPlexGetDepthStratum()`, `DMPlexGetHeightStratum()`
9415: @*/
9416: PetscErrorCode DMPlexGetDepthStratumGlobalSize(DM dm, PetscInt depth, PetscInt *gsize)
9417: {
9418:   PetscSF         sf;
9419:   const PetscInt *leaves;
9420:   PetscInt        Nl, loc, start, end, lsize = 0;

9422:   PetscFunctionBegin;
9423:   PetscCall(DMGetPointSF(dm, &sf));
9424:   PetscCall(PetscSFGetGraph(sf, NULL, &Nl, &leaves, NULL));
9425:   PetscCall(DMPlexGetDepthStratum(dm, depth, &start, &end));
9426:   for (PetscInt p = start; p < end; ++p) {
9427:     PetscCall(PetscFindInt(p, Nl, leaves, &loc));
9428:     if (loc < 0) ++lsize;
9429:   }
9430:   PetscCallMPI(MPIU_Allreduce(&lsize, gsize, 1, MPIU_INT, MPI_SUM, PetscObjectComm((PetscObject)dm)));
9431:   PetscFunctionReturn(PETSC_SUCCESS);
9432: }

9434: PetscErrorCode DMPlexCreateNumbering_Plex(DM dm, PetscInt pStart, PetscInt pEnd, PetscInt shift, PetscInt *globalSize, PetscSF sf, IS *numbering)
9435: {
9436:   PetscSection section, globalSection;
9437:   PetscInt    *numbers, p;

9439:   PetscFunctionBegin;
9440:   if (PetscDefined(USE_DEBUG)) PetscCall(DMPlexCheckPointSF(dm, sf, PETSC_TRUE));
9441:   PetscCall(PetscSectionCreate(PetscObjectComm((PetscObject)dm), &section));
9442:   PetscCall(PetscSectionSetChart(section, pStart, pEnd));
9443:   for (p = pStart; p < pEnd; ++p) PetscCall(PetscSectionSetDof(section, p, 1));
9444:   PetscCall(PetscSectionSetUp(section));
9445:   PetscCall(PetscSectionCreateGlobalSection(section, sf, PETSC_TRUE, PETSC_FALSE, PETSC_FALSE, &globalSection));
9446:   PetscCall(PetscMalloc1(pEnd - pStart, &numbers));
9447:   for (p = pStart; p < pEnd; ++p) {
9448:     PetscCall(PetscSectionGetOffset(globalSection, p, &numbers[p - pStart]));
9449:     if (numbers[p - pStart] < 0) numbers[p - pStart] -= shift;
9450:     else numbers[p - pStart] += shift;
9451:   }
9452:   PetscCall(ISCreateGeneral(PetscObjectComm((PetscObject)dm), pEnd - pStart, numbers, PETSC_OWN_POINTER, numbering));
9453:   if (globalSize) {
9454:     PetscLayout layout;
9455:     PetscCall(PetscSectionGetPointLayout(PetscObjectComm((PetscObject)dm), globalSection, &layout));
9456:     PetscCall(PetscLayoutGetSize(layout, globalSize));
9457:     PetscCall(PetscLayoutDestroy(&layout));
9458:   }
9459:   PetscCall(PetscSectionDestroy(&section));
9460:   PetscCall(PetscSectionDestroy(&globalSection));
9461:   PetscFunctionReturn(PETSC_SUCCESS);
9462: }

9464: /*@
9465:   DMPlexCreateCellNumbering - Get a global cell numbering for all cells on this process

9467:   Input Parameters:
9468: + dm         - The `DMPLEX` object
9469: - includeAll - Whether to include all cells, or just the simplex and box cells

9471:   Output Parameter:
9472: . globalCellNumbers - Global cell numbers for all cells on this process

9474:   Level: developer

9476: .seealso: [](ch_unstructured), `DM`, `DMPLEX`, `DMPlexGetCellNumbering()`, `DMPlexGetVertexNumbering()`
9477: @*/
9478: PetscErrorCode DMPlexCreateCellNumbering(DM dm, PetscBool includeAll, IS *globalCellNumbers)
9479: {
9480:   PetscInt cellHeight, cStart, cEnd;

9482:   PetscFunctionBegin;
9483:   PetscCall(DMPlexGetVTKCellHeight(dm, &cellHeight));
9484:   if (includeAll) PetscCall(DMPlexGetHeightStratum(dm, cellHeight, &cStart, &cEnd));
9485:   else PetscCall(DMPlexGetSimplexOrBoxCells(dm, cellHeight, &cStart, &cEnd));
9486:   PetscCall(DMPlexCreateNumbering_Plex(dm, cStart, cEnd, 0, NULL, dm->sf, globalCellNumbers));
9487:   PetscFunctionReturn(PETSC_SUCCESS);
9488: }

9490: /*@
9491:   DMPlexGetCellNumbering - Get a global cell numbering for all cells on this process

9493:   Input Parameter:
9494: . dm - The `DMPLEX` object

9496:   Output Parameter:
9497: . globalCellNumbers - Global cell numbers for all cells on this process

9499:   Level: developer

9501: .seealso: [](ch_unstructured), `DM`, `DMPLEX`, `DMPlexCreateCellNumbering()`, `DMPlexGetVertexNumbering()`
9502: @*/
9503: PetscErrorCode DMPlexGetCellNumbering(DM dm, IS *globalCellNumbers)
9504: {
9505:   DM_Plex *mesh = (DM_Plex *)dm->data;

9507:   PetscFunctionBegin;
9509:   if (!mesh->globalCellNumbers) PetscCall(DMPlexCreateCellNumbering(dm, PETSC_FALSE, &mesh->globalCellNumbers));
9510:   *globalCellNumbers = mesh->globalCellNumbers;
9511:   PetscFunctionReturn(PETSC_SUCCESS);
9512: }

9514: PetscErrorCode DMPlexCreateVertexNumbering_Internal(DM dm, PetscBool includeHybrid, IS *globalVertexNumbers)
9515: {
9516:   PetscInt vStart, vEnd;

9518:   PetscFunctionBegin;
9520:   PetscCall(DMPlexGetDepthStratum(dm, 0, &vStart, &vEnd));
9521:   PetscCall(DMPlexCreateNumbering_Plex(dm, vStart, vEnd, 0, NULL, dm->sf, globalVertexNumbers));
9522:   PetscFunctionReturn(PETSC_SUCCESS);
9523: }

9525: /*@
9526:   DMPlexGetVertexNumbering - Get a global vertex numbering for all vertices on this process

9528:   Input Parameter:
9529: . dm - The `DMPLEX` object

9531:   Output Parameter:
9532: . globalVertexNumbers - Global vertex numbers for all vertices on this process

9534:   Level: developer

9536: .seealso: [](ch_unstructured), `DM`, `DMPLEX`, `DMPlexGetCellNumbering()`
9537: @*/
9538: PetscErrorCode DMPlexGetVertexNumbering(DM dm, IS *globalVertexNumbers)
9539: {
9540:   DM_Plex *mesh = (DM_Plex *)dm->data;

9542:   PetscFunctionBegin;
9544:   if (!mesh->globalVertexNumbers) PetscCall(DMPlexCreateVertexNumbering_Internal(dm, PETSC_FALSE, &mesh->globalVertexNumbers));
9545:   *globalVertexNumbers = mesh->globalVertexNumbers;
9546:   PetscFunctionReturn(PETSC_SUCCESS);
9547: }

9549: /*@
9550:   DMPlexCreatePointNumbering - Create a global numbering for all points.

9552:   Collective

9554:   Input Parameter:
9555: . dm - The `DMPLEX` object

9557:   Output Parameter:
9558: . globalPointNumbers - Global numbers for all points on this process

9560:   Level: developer

9562:   Notes:
9563:   The point numbering `IS` is parallel, with local portion indexed by local points (see `DMGetLocalSection()`). The global
9564:   points are taken as stratified, with each MPI rank owning a contiguous subset of each stratum. In the IS, owned points
9565:   will have their non-negative value while points owned by different ranks will be involuted -(idx+1). As an example,
9566:   consider a parallel mesh in which the first two elements and first two vertices are owned by rank 0.

9568:   The partitioned mesh is
9569:   ```
9570:   (2)--0--(3)--1--(4)    (1)--0--(2)
9571:   ```
9572:   and its global numbering is
9573:   ```
9574:   (3)--0--(4)--1--(5)--2--(6)
9575:   ```
9576:   Then the global numbering is provided as
9577:   ```
9578:   [0] Number of indices in set 5
9579:   [0] 0 0
9580:   [0] 1 1
9581:   [0] 2 3
9582:   [0] 3 4
9583:   [0] 4 -6
9584:   [1] Number of indices in set 3
9585:   [1] 0 2
9586:   [1] 1 5
9587:   [1] 2 6
9588:   ```

9590: .seealso: [](ch_unstructured), `DM`, `DMPLEX`, `DMPlexGetCellNumbering()`
9591: @*/
9592: PetscErrorCode DMPlexCreatePointNumbering(DM dm, IS *globalPointNumbers)
9593: {
9594:   IS        nums[4];
9595:   PetscInt  depths[4], gdepths[4], starts[4];
9596:   PetscInt  depth, d, shift = 0;
9597:   PetscBool empty = PETSC_FALSE;

9599:   PetscFunctionBegin;
9601:   PetscCall(DMPlexGetDepth(dm, &depth));
9602:   // For unstratified meshes use dim instead of depth
9603:   if (depth < 0) PetscCall(DMGetDimension(dm, &depth));
9604:   // If any stratum is empty, we must mark all empty
9605:   for (d = 0; d <= depth; ++d) {
9606:     PetscInt end;

9608:     depths[d] = depth - d;
9609:     PetscCall(DMPlexGetDepthStratum(dm, depths[d], &starts[d], &end));
9610:     if (!(starts[d] - end)) empty = PETSC_TRUE;
9611:   }
9612:   if (empty)
9613:     for (d = 0; d <= depth; ++d) {
9614:       depths[d] = -1;
9615:       starts[d] = -1;
9616:     }
9617:   else PetscCall(PetscSortIntWithArray(depth + 1, starts, depths));
9618:   PetscCallMPI(MPIU_Allreduce(depths, gdepths, depth + 1, MPIU_INT, MPI_MAX, PetscObjectComm((PetscObject)dm)));
9619:   for (d = 0; d <= depth; ++d) PetscCheck(starts[d] < 0 || depths[d] == gdepths[d], PETSC_COMM_SELF, PETSC_ERR_PLIB, "Expected depth %" PetscInt_FMT ", found %" PetscInt_FMT, depths[d], gdepths[d]);
9620:   // Note here that 'shift' is collective, so that the numbering is stratified by depth
9621:   for (d = 0; d <= depth; ++d) {
9622:     PetscInt pStart, pEnd, gsize;

9624:     PetscCall(DMPlexGetDepthStratum(dm, gdepths[d], &pStart, &pEnd));
9625:     PetscCall(DMPlexCreateNumbering_Plex(dm, pStart, pEnd, shift, &gsize, dm->sf, &nums[d]));
9626:     shift += gsize;
9627:   }
9628:   PetscCall(ISConcatenate(PETSC_COMM_SELF, depth + 1, nums, globalPointNumbers));
9629:   for (d = 0; d <= depth; ++d) PetscCall(ISDestroy(&nums[d]));
9630:   PetscFunctionReturn(PETSC_SUCCESS);
9631: }

9633: /*@
9634:   DMPlexCreateEdgeNumbering - Create a global numbering for edges.

9636:   Collective

9638:   Input Parameter:
9639: . dm - The `DMPLEX` object

9641:   Output Parameter:
9642: . globalEdgeNumbers - Global numbers for all edges on this process

9644:   Level: developer

9646:   Notes:
9647:   The point numbering `IS` is parallel, with local portion indexed by local points (see `DMGetLocalSection()`). In the IS, owned edges will have their non-negative value while edges owned by different ranks will be involuted -(idx+1).

9649: .seealso: [](ch_unstructured), `DM`, `DMPLEX`, `DMPlexGetCellNumbering()`, `DMPlexGetVertexNumbering()`, `DMPlexCreatePointNumbering()`
9650: @*/
9651: PetscErrorCode DMPlexCreateEdgeNumbering(DM dm, IS *globalEdgeNumbers)
9652: {
9653:   PetscSF  sf;
9654:   PetscInt eStart, eEnd;

9656:   PetscFunctionBegin;
9658:   PetscCall(DMGetPointSF(dm, &sf));
9659:   PetscCall(DMPlexGetDepthStratum(dm, 1, &eStart, &eEnd));
9660:   PetscCall(DMPlexCreateNumbering_Plex(dm, eStart, eEnd, 0, NULL, sf, globalEdgeNumbers));
9661:   PetscFunctionReturn(PETSC_SUCCESS);
9662: }

9664: /*@
9665:   DMPlexCreateRankField - Create a cell field whose value is the rank of the owner

9667:   Input Parameter:
9668: . dm - The `DMPLEX` object

9670:   Output Parameter:
9671: . ranks - The rank field

9673:   Options Database Key:
9674: . -dm_partition_view - Adds the rank field into the `DM` output from `-dm_view` using the same viewer

9676:   Level: intermediate

9678: .seealso: [](ch_unstructured), `DM`, `DMPLEX`, `DMView()`
9679: @*/
9680: PetscErrorCode DMPlexCreateRankField(DM dm, Vec *ranks)
9681: {
9682:   DM             rdm;
9683:   PetscFE        fe;
9684:   PetscScalar   *r;
9685:   PetscMPIInt    rank;
9686:   DMPolytopeType ct;
9687:   PetscInt       dim, cStart, cEnd, c;

9689:   PetscFunctionBeginUser;
9691:   PetscAssertPointer(ranks, 2);
9692:   PetscCallMPI(MPI_Comm_rank(PetscObjectComm((PetscObject)dm), &rank));
9693:   PetscCall(DMClone(dm, &rdm));
9694:   PetscCall(PetscObjectSetOptionsPrefix((PetscObject)rdm, "PETSc___rank_"));
9695:   PetscCall(DMGetDimension(rdm, &dim));
9696:   PetscCall(DMPlexGetHeightStratum(rdm, 0, &cStart, &cEnd));
9697:   if (cEnd > cStart) PetscCall(DMPlexGetCellType(rdm, cStart, &ct));
9698:   else ct = DM_POLYTOPE_SEGMENT;
9699:   PetscCall(PetscFECreateLagrangeByCell(PETSC_COMM_SELF, dim, 1, ct, 0, -1, &fe));
9700:   PetscCall(PetscObjectSetName((PetscObject)fe, "rank"));
9701:   PetscCall(DMSetField(rdm, 0, NULL, (PetscObject)fe));
9702:   PetscCall(PetscFEDestroy(&fe));
9703:   PetscCall(DMCreateDS(rdm));
9704:   PetscCall(DMViewFromOptions(rdm, NULL, "-dm_view"));
9705:   PetscCall(DMCreateGlobalVector(rdm, ranks));
9706:   PetscCall(PetscObjectSetName((PetscObject)*ranks, "partition"));
9707:   PetscCall(VecGetArray(*ranks, &r));
9708:   if (r) {
9709:     for (c = cStart; c < cEnd; ++c) {
9710:       PetscScalar *lr;

9712:       PetscCall(DMPlexPointGlobalRef(rdm, c, r, &lr));
9713:       if (lr) *lr = rank;
9714:     }
9715:   }
9716:   PetscCall(VecRestoreArray(*ranks, &r));
9717:   PetscCall(DMDestroy(&rdm));
9718:   PetscFunctionReturn(PETSC_SUCCESS);
9719: }

9721: /*@
9722:   DMPlexCreateLabelField - Create a field whose value is the label value for that point

9724:   Input Parameters:
9725: + dm    - The `DMPLEX`
9726: - label - The `DMLabel`

9728:   Output Parameter:
9729: . val - The label value field

9731:   Options Database Key:
9732: . -dm_label_view - Adds the label value field into the `DM` output from `-dm_view` using the same viewer

9734:   Level: intermediate

9736: .seealso: [](ch_unstructured), `DM`, `DMPLEX`, `DMView()`
9737: @*/
9738: PetscErrorCode DMPlexCreateLabelField(DM dm, DMLabel label, Vec *val)
9739: {
9740:   DM             rdm, plex;
9741:   Vec            lval;
9742:   PetscSection   section;
9743:   PetscFE        fe;
9744:   PetscScalar   *v;
9745:   PetscInt       dim, pStart, pEnd, p, cStart;
9746:   DMPolytopeType ct;
9747:   char           name[PETSC_MAX_PATH_LEN];
9748:   const char    *lname, *prefix;

9750:   PetscFunctionBeginUser;
9752:   PetscAssertPointer(label, 2);
9753:   PetscAssertPointer(val, 3);
9754:   PetscCall(DMClone(dm, &rdm));
9755:   PetscCall(DMConvert(rdm, DMPLEX, &plex));
9756:   PetscCall(DMPlexGetHeightStratum(plex, 0, &cStart, NULL));
9757:   PetscCall(DMPlexGetCellType(plex, cStart, &ct));
9758:   PetscCall(DMDestroy(&plex));
9759:   PetscCall(DMGetDimension(rdm, &dim));
9760:   PetscCall(DMGetOptionsPrefix(dm, &prefix));
9761:   PetscCall(PetscObjectGetName((PetscObject)label, &lname));
9762:   PetscCall(PetscSNPrintf(name, sizeof(name), "%s%s_", prefix ? prefix : "", lname));
9763:   PetscCall(PetscFECreateByCell(PETSC_COMM_SELF, dim, 1, ct, name, -1, &fe));
9764:   PetscCall(PetscObjectSetName((PetscObject)fe, ""));
9765:   PetscCall(DMSetField(rdm, 0, NULL, (PetscObject)fe));
9766:   PetscCall(PetscFEDestroy(&fe));
9767:   PetscCall(DMCreateDS(rdm));
9768:   PetscCall(DMCreateGlobalVector(rdm, val));
9769:   PetscCall(DMCreateLocalVector(rdm, &lval));
9770:   PetscCall(PetscObjectSetName((PetscObject)*val, lname));
9771:   PetscCall(DMGetLocalSection(rdm, &section));
9772:   PetscCall(PetscSectionGetChart(section, &pStart, &pEnd));
9773:   PetscCall(VecGetArray(lval, &v));
9774:   for (p = pStart; p < pEnd; ++p) {
9775:     PetscInt cval, dof, off;

9777:     PetscCall(PetscSectionGetDof(section, p, &dof));
9778:     if (!dof) continue;
9779:     PetscCall(DMLabelGetValue(label, p, &cval));
9780:     PetscCall(PetscSectionGetOffset(section, p, &off));
9781:     for (PetscInt d = 0; d < dof; d++) v[off + d] = cval;
9782:   }
9783:   PetscCall(VecRestoreArray(lval, &v));
9784:   PetscCall(DMLocalToGlobal(rdm, lval, INSERT_VALUES, *val));
9785:   PetscCall(VecDestroy(&lval));
9786:   PetscCall(DMDestroy(&rdm));
9787:   PetscFunctionReturn(PETSC_SUCCESS);
9788: }

9790: /*@
9791:   DMPlexCheckSymmetry - Check that the adjacency information in the mesh is symmetric.

9793:   Input Parameter:
9794: . dm - The `DMPLEX` object

9796:   Level: developer

9798:   Notes:
9799:   This is a useful diagnostic when creating meshes programmatically.

9801:   For the complete list of DMPlexCheck* functions, see `DMSetFromOptions()`.

9803: .seealso: [](ch_unstructured), `DM`, `DMPLEX`, `DMCreate()`, `DMSetFromOptions()`
9804: @*/
9805: PetscErrorCode DMPlexCheckSymmetry(DM dm)
9806: {
9807:   PetscSection    coneSection, supportSection;
9808:   const PetscInt *cone, *support;
9809:   PetscInt        coneSize, c, supportSize, s;
9810:   PetscInt        pStart, pEnd, p, pp, csize, ssize;
9811:   PetscBool       storagecheck = PETSC_TRUE;

9813:   PetscFunctionBegin;
9815:   PetscCall(DMViewFromOptions(dm, NULL, "-sym_dm_view"));
9816:   PetscCall(DMPlexGetConeSection(dm, &coneSection));
9817:   PetscCall(DMPlexGetSupportSection(dm, &supportSection));
9818:   /* Check that point p is found in the support of its cone points, and vice versa */
9819:   PetscCall(DMPlexGetChart(dm, &pStart, &pEnd));
9820:   for (p = pStart; p < pEnd; ++p) {
9821:     PetscCall(DMPlexGetConeSize(dm, p, &coneSize));
9822:     PetscCall(DMPlexGetCone(dm, p, &cone));
9823:     for (c = 0; c < coneSize; ++c) {
9824:       PetscBool dup = PETSC_FALSE;
9825:       for (PetscInt d = c - 1; d >= 0; --d) {
9826:         if (cone[c] == cone[d]) {
9827:           dup = PETSC_TRUE;
9828:           break;
9829:         }
9830:       }
9831:       PetscCall(DMPlexGetSupportSize(dm, cone[c], &supportSize));
9832:       PetscCall(DMPlexGetSupport(dm, cone[c], &support));
9833:       for (s = 0; s < supportSize; ++s) {
9834:         if (support[s] == p) break;
9835:       }
9836:       if ((s >= supportSize) || (dup && (support[s + 1] != p))) {
9837:         PetscCall(PetscPrintf(PETSC_COMM_SELF, "p: %" PetscInt_FMT " cone: ", p));
9838:         for (s = 0; s < coneSize; ++s) PetscCall(PetscPrintf(PETSC_COMM_SELF, "%" PetscInt_FMT ", ", cone[s]));
9839:         PetscCall(PetscPrintf(PETSC_COMM_SELF, "\n"));
9840:         PetscCall(PetscPrintf(PETSC_COMM_SELF, "p: %" PetscInt_FMT " support: ", cone[c]));
9841:         for (s = 0; s < supportSize; ++s) PetscCall(PetscPrintf(PETSC_COMM_SELF, "%" PetscInt_FMT ", ", support[s]));
9842:         PetscCall(PetscPrintf(PETSC_COMM_SELF, "\n"));
9843:         PetscCheck(!dup, PETSC_COMM_SELF, PETSC_ERR_PLIB, "Point %" PetscInt_FMT " not repeatedly found in support of repeated cone point %" PetscInt_FMT, p, cone[c]);
9844:         SETERRQ(PETSC_COMM_SELF, PETSC_ERR_PLIB, "Point %" PetscInt_FMT " not found in support of cone point %" PetscInt_FMT, p, cone[c]);
9845:       }
9846:     }
9847:     PetscCall(DMPlexGetTreeParent(dm, p, &pp, NULL));
9848:     if (p != pp) {
9849:       storagecheck = PETSC_FALSE;
9850:       continue;
9851:     }
9852:     PetscCall(DMPlexGetSupportSize(dm, p, &supportSize));
9853:     PetscCall(DMPlexGetSupport(dm, p, &support));
9854:     for (s = 0; s < supportSize; ++s) {
9855:       PetscCall(DMPlexGetConeSize(dm, support[s], &coneSize));
9856:       PetscCall(DMPlexGetCone(dm, support[s], &cone));
9857:       for (c = 0; c < coneSize; ++c) {
9858:         PetscCall(DMPlexGetTreeParent(dm, cone[c], &pp, NULL));
9859:         if (cone[c] != pp) {
9860:           c = 0;
9861:           break;
9862:         }
9863:         if (cone[c] == p) break;
9864:       }
9865:       if (c >= coneSize) {
9866:         PetscCall(PetscPrintf(PETSC_COMM_SELF, "p: %" PetscInt_FMT " support: ", p));
9867:         for (c = 0; c < supportSize; ++c) PetscCall(PetscPrintf(PETSC_COMM_SELF, "%" PetscInt_FMT ", ", support[c]));
9868:         PetscCall(PetscPrintf(PETSC_COMM_SELF, "\n"));
9869:         PetscCall(PetscPrintf(PETSC_COMM_SELF, "p: %" PetscInt_FMT " cone: ", support[s]));
9870:         for (c = 0; c < coneSize; ++c) PetscCall(PetscPrintf(PETSC_COMM_SELF, "%" PetscInt_FMT ", ", cone[c]));
9871:         PetscCall(PetscPrintf(PETSC_COMM_SELF, "\n"));
9872:         SETERRQ(PETSC_COMM_SELF, PETSC_ERR_PLIB, "Point %" PetscInt_FMT " not found in cone of support point %" PetscInt_FMT, p, support[s]);
9873:       }
9874:     }
9875:   }
9876:   if (storagecheck) {
9877:     PetscCall(PetscSectionGetStorageSize(coneSection, &csize));
9878:     PetscCall(PetscSectionGetStorageSize(supportSection, &ssize));
9879:     PetscCheck(csize == ssize, PETSC_COMM_SELF, PETSC_ERR_ARG_SIZ, "Total cone size %" PetscInt_FMT " != Total support size %" PetscInt_FMT, csize, ssize);
9880:   }
9881:   PetscFunctionReturn(PETSC_SUCCESS);
9882: }

9884: /*
9885:   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.
9886: */
9887: static PetscErrorCode DMPlexCellUnsplitVertices_Private(DM dm, PetscInt c, DMPolytopeType ct, PetscInt *unsplit)
9888: {
9889:   DMPolytopeType  cct;
9890:   PetscInt        ptpoints[4];
9891:   const PetscInt *cone, *ccone, *ptcone;
9892:   PetscInt        coneSize, cp, cconeSize, ccp, npt = 0, pt;

9894:   PetscFunctionBegin;
9895:   *unsplit = 0;
9896:   switch (ct) {
9897:   case DM_POLYTOPE_POINT_PRISM_TENSOR:
9898:     ptpoints[npt++] = c;
9899:     break;
9900:   case DM_POLYTOPE_SEG_PRISM_TENSOR:
9901:     PetscCall(DMPlexGetCone(dm, c, &cone));
9902:     PetscCall(DMPlexGetConeSize(dm, c, &coneSize));
9903:     for (cp = 0; cp < coneSize; ++cp) {
9904:       PetscCall(DMPlexGetCellType(dm, cone[cp], &cct));
9905:       if (cct == DM_POLYTOPE_POINT_PRISM_TENSOR) ptpoints[npt++] = cone[cp];
9906:     }
9907:     break;
9908:   case DM_POLYTOPE_TRI_PRISM_TENSOR:
9909:   case DM_POLYTOPE_QUAD_PRISM_TENSOR:
9910:     PetscCall(DMPlexGetCone(dm, c, &cone));
9911:     PetscCall(DMPlexGetConeSize(dm, c, &coneSize));
9912:     for (cp = 0; cp < coneSize; ++cp) {
9913:       PetscCall(DMPlexGetCone(dm, cone[cp], &ccone));
9914:       PetscCall(DMPlexGetConeSize(dm, cone[cp], &cconeSize));
9915:       for (ccp = 0; ccp < cconeSize; ++ccp) {
9916:         PetscCall(DMPlexGetCellType(dm, ccone[ccp], &cct));
9917:         if (cct == DM_POLYTOPE_POINT_PRISM_TENSOR) {
9918:           PetscInt p;
9919:           for (p = 0; p < npt; ++p)
9920:             if (ptpoints[p] == ccone[ccp]) break;
9921:           if (p == npt) ptpoints[npt++] = ccone[ccp];
9922:         }
9923:       }
9924:     }
9925:     break;
9926:   default:
9927:     break;
9928:   }
9929:   for (pt = 0; pt < npt; ++pt) {
9930:     PetscCall(DMPlexGetCone(dm, ptpoints[pt], &ptcone));
9931:     if (ptcone[0] == ptcone[1]) ++(*unsplit);
9932:   }
9933:   PetscFunctionReturn(PETSC_SUCCESS);
9934: }

9936: /*@
9937:   DMPlexCheckSkeleton - Check that each cell has the correct number of vertices

9939:   Input Parameters:
9940: + dm         - The `DMPLEX` object
9941: - cellHeight - Normally 0

9943:   Level: developer

9945:   Notes:
9946:   This is a useful diagnostic when creating meshes programmatically.
9947:   Currently applicable only to homogeneous simplex or tensor meshes.

9949:   For the complete list of DMPlexCheck* functions, see `DMSetFromOptions()`.

9951: .seealso: [](ch_unstructured), `DM`, `DMPLEX`, `DMCreate()`, `DMSetFromOptions()`
9952: @*/
9953: PetscErrorCode DMPlexCheckSkeleton(DM dm, PetscInt cellHeight)
9954: {
9955:   DMPlexInterpolatedFlag interp;
9956:   DMPolytopeType         ct;
9957:   PetscInt               vStart, vEnd, cStart, cEnd, c;

9959:   PetscFunctionBegin;
9961:   PetscCall(DMPlexIsInterpolated(dm, &interp));
9962:   PetscCall(DMPlexGetHeightStratum(dm, cellHeight, &cStart, &cEnd));
9963:   PetscCall(DMPlexGetDepthStratum(dm, 0, &vStart, &vEnd));
9964:   for (c = cStart; c < cEnd; ++c) {
9965:     PetscInt *closure = NULL;
9966:     PetscInt  coneSize, closureSize, cl, Nv = 0;

9968:     PetscCall(DMPlexGetCellType(dm, c, &ct));
9969:     if (ct == DM_POLYTOPE_UNKNOWN) continue;
9970:     if (interp == DMPLEX_INTERPOLATED_FULL) {
9971:       PetscCall(DMPlexGetConeSize(dm, c, &coneSize));
9972:       PetscCheck(coneSize == DMPolytopeTypeGetConeSize(ct), PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Cell %" PetscInt_FMT " of type %s has cone size %" PetscInt_FMT " != %" PetscInt_FMT, c, DMPolytopeTypes[ct], coneSize, DMPolytopeTypeGetConeSize(ct));
9973:     }
9974:     PetscCall(DMPlexGetTransitiveClosure(dm, c, PETSC_TRUE, &closureSize, &closure));
9975:     for (cl = 0; cl < closureSize * 2; cl += 2) {
9976:       const PetscInt p = closure[cl];
9977:       if ((p >= vStart) && (p < vEnd)) ++Nv;
9978:     }
9979:     PetscCall(DMPlexRestoreTransitiveClosure(dm, c, PETSC_TRUE, &closureSize, &closure));
9980:     /* Special Case: Tensor faces with identified vertices */
9981:     if (Nv < DMPolytopeTypeGetNumVertices(ct)) {
9982:       PetscInt unsplit;

9984:       PetscCall(DMPlexCellUnsplitVertices_Private(dm, c, ct, &unsplit));
9985:       if (Nv + unsplit == DMPolytopeTypeGetNumVertices(ct)) continue;
9986:     }
9987:     PetscCheck(Nv == DMPolytopeTypeGetNumVertices(ct), PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Cell %" PetscInt_FMT " of type %s has %" PetscInt_FMT " vertices != %" PetscInt_FMT, c, DMPolytopeTypes[ct], Nv, DMPolytopeTypeGetNumVertices(ct));
9988:   }
9989:   PetscFunctionReturn(PETSC_SUCCESS);
9990: }

9992: /*@
9993:   DMPlexCheckFaces - Check that the faces of each cell give a vertex order this is consistent with what we expect from the cell type

9995:   Collective

9997:   Input Parameters:
9998: + dm         - The `DMPLEX` object
9999: - cellHeight - Normally 0

10001:   Level: developer

10003:   Notes:
10004:   This is a useful diagnostic when creating meshes programmatically.
10005:   This routine is only relevant for meshes that are fully interpolated across all ranks.
10006:   It will error out if a partially interpolated mesh is given on some rank.
10007:   It will do nothing for locally uninterpolated mesh (as there is nothing to check).

10009:   For the complete list of DMPlexCheck* functions, see `DMSetFromOptions()`.

10011: .seealso: [](ch_unstructured), `DM`, `DMPLEX`, `DMCreate()`, `DMPlexGetVTKCellHeight()`, `DMSetFromOptions()`
10012: @*/
10013: PetscErrorCode DMPlexCheckFaces(DM dm, PetscInt cellHeight)
10014: {
10015:   PetscInt               dim, depth, vStart, vEnd, cStart, cEnd, c, h;
10016:   DMPlexInterpolatedFlag interpEnum;

10018:   PetscFunctionBegin;
10020:   PetscCall(DMPlexIsInterpolatedCollective(dm, &interpEnum));
10021:   if (interpEnum == DMPLEX_INTERPOLATED_NONE) PetscFunctionReturn(PETSC_SUCCESS);
10022:   if (interpEnum != DMPLEX_INTERPOLATED_FULL) {
10023:     PetscCall(PetscPrintf(PetscObjectComm((PetscObject)dm), "DMPlexCheckFaces() warning: Mesh is only partially interpolated, this is currently not supported"));
10024:     PetscFunctionReturn(PETSC_SUCCESS);
10025:   }

10027:   PetscCall(DMGetDimension(dm, &dim));
10028:   PetscCall(DMPlexGetDepth(dm, &depth));
10029:   PetscCall(DMPlexGetDepthStratum(dm, 0, &vStart, &vEnd));
10030:   for (h = cellHeight; h < PetscMin(depth, dim); ++h) {
10031:     PetscCall(DMPlexGetHeightStratum(dm, h, &cStart, &cEnd));
10032:     for (c = cStart; c < cEnd; ++c) {
10033:       const PetscInt       *cone, *ornt, *faceSizes, *faces;
10034:       const DMPolytopeType *faceTypes;
10035:       DMPolytopeType        ct;
10036:       PetscInt              numFaces, coneSize, f;
10037:       PetscInt             *closure = NULL, closureSize, cl, numCorners = 0, fOff = 0, unsplit;

10039:       PetscCall(DMPlexGetCellType(dm, c, &ct));
10040:       PetscCall(DMPlexCellUnsplitVertices_Private(dm, c, ct, &unsplit));
10041:       if (unsplit) continue;
10042:       PetscCall(DMPlexGetConeSize(dm, c, &coneSize));
10043:       PetscCall(DMPlexGetCone(dm, c, &cone));
10044:       PetscCall(DMPlexGetConeOrientation(dm, c, &ornt));
10045:       PetscCall(DMPlexGetTransitiveClosure(dm, c, PETSC_TRUE, &closureSize, &closure));
10046:       for (cl = 0; cl < closureSize * 2; cl += 2) {
10047:         const PetscInt p = closure[cl];
10048:         if ((p >= vStart) && (p < vEnd)) closure[numCorners++] = p;
10049:       }
10050:       PetscCall(DMPlexGetRawFaces_Internal(dm, ct, closure, &numFaces, &faceTypes, &faceSizes, &faces));
10051:       PetscCheck(coneSize == numFaces, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Cell %" PetscInt_FMT " of type %s has %" PetscInt_FMT " faces but should have %" PetscInt_FMT, c, DMPolytopeTypes[ct], coneSize, numFaces);
10052:       for (f = 0; f < numFaces; ++f) {
10053:         DMPolytopeType fct;
10054:         PetscInt      *fclosure = NULL, fclosureSize, cl, fnumCorners = 0, v;

10056:         PetscCall(DMPlexGetCellType(dm, cone[f], &fct));
10057:         PetscCall(DMPlexGetTransitiveClosure_Internal(dm, cone[f], ornt[f], PETSC_TRUE, &fclosureSize, &fclosure));
10058:         for (cl = 0; cl < fclosureSize * 2; cl += 2) {
10059:           const PetscInt p = fclosure[cl];
10060:           if ((p >= vStart) && (p < vEnd)) fclosure[fnumCorners++] = p;
10061:         }
10062:         PetscCheck(fnumCorners == faceSizes[f], PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Face %" PetscInt_FMT " of type %s (cone idx %" PetscInt_FMT ") of cell %" PetscInt_FMT " of type %s has %" PetscInt_FMT " vertices but should have %" PetscInt_FMT, cone[f], DMPolytopeTypes[fct], f, c, DMPolytopeTypes[ct], fnumCorners, faceSizes[f]);
10063:         for (v = 0; v < fnumCorners; ++v) {
10064:           if (fclosure[v] != faces[fOff + v]) {
10065:             PetscCall(PetscPrintf(PETSC_COMM_SELF, "face closure:"));
10066:             for (PetscInt v1 = 0; v1 < fnumCorners; ++v1) PetscCall(PetscPrintf(PETSC_COMM_SELF, " %" PetscInt_FMT, fclosure[v1]));
10067:             PetscCall(PetscPrintf(PETSC_COMM_SELF, "\ncell face:"));
10068:             for (PetscInt v1 = 0; v1 < fnumCorners; ++v1) PetscCall(PetscPrintf(PETSC_COMM_SELF, " %" PetscInt_FMT, faces[fOff + v1]));
10069:             PetscCall(PetscPrintf(PETSC_COMM_SELF, "\n"));
10070:             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]);
10071:           }
10072:         }
10073:         PetscCall(DMPlexRestoreTransitiveClosure(dm, cone[f], PETSC_TRUE, &fclosureSize, &fclosure));
10074:         fOff += faceSizes[f];
10075:       }
10076:       PetscCall(DMPlexRestoreRawFaces_Internal(dm, ct, closure, &numFaces, &faceTypes, &faceSizes, &faces));
10077:       PetscCall(DMPlexRestoreTransitiveClosure(dm, c, PETSC_TRUE, &closureSize, &closure));
10078:     }
10079:   }
10080:   PetscFunctionReturn(PETSC_SUCCESS);
10081: }

10083: /*@
10084:   DMPlexCheckGeometry - Check the geometry of mesh cells

10086:   Input Parameter:
10087: . dm - The `DMPLEX` object

10089:   Level: developer

10091:   Notes:
10092:   This is a useful diagnostic when creating meshes programmatically.

10094:   For the complete list of DMPlexCheck* functions, see `DMSetFromOptions()`.

10096: .seealso: [](ch_unstructured), `DM`, `DMPLEX`, `DMCreate()`, `DMSetFromOptions()`
10097: @*/
10098: PetscErrorCode DMPlexCheckGeometry(DM dm)
10099: {
10100:   Vec       coordinates;
10101:   PetscReal detJ, J[9], refVol = 1.0;
10102:   PetscReal vol;
10103:   PetscInt  dim, depth, dE, d, cStart, cEnd, c;

10105:   PetscFunctionBegin;
10106:   PetscCall(DMGetDimension(dm, &dim));
10107:   PetscCall(DMGetCoordinateDim(dm, &dE));
10108:   if (dim != dE) PetscFunctionReturn(PETSC_SUCCESS);
10109:   PetscCall(DMPlexGetDepth(dm, &depth));
10110:   for (d = 0; d < dim; ++d) refVol *= 2.0;
10111:   PetscCall(DMPlexGetHeightStratum(dm, 0, &cStart, &cEnd));
10112:   /* Make sure local coordinates are created, because that step is collective */
10113:   PetscCall(DMGetCoordinatesLocal(dm, &coordinates));
10114:   if (!coordinates) PetscFunctionReturn(PETSC_SUCCESS);
10115:   for (c = cStart; c < cEnd; ++c) {
10116:     DMPolytopeType ct;
10117:     PetscInt       unsplit;
10118:     PetscBool      ignoreZeroVol = PETSC_FALSE;

10120:     PetscCall(DMPlexGetCellType(dm, c, &ct));
10121:     switch (ct) {
10122:     case DM_POLYTOPE_SEG_PRISM_TENSOR:
10123:     case DM_POLYTOPE_TRI_PRISM_TENSOR:
10124:     case DM_POLYTOPE_QUAD_PRISM_TENSOR:
10125:       ignoreZeroVol = PETSC_TRUE;
10126:       break;
10127:     default:
10128:       break;
10129:     }
10130:     switch (ct) {
10131:     case DM_POLYTOPE_TRI_PRISM:
10132:     case DM_POLYTOPE_TRI_PRISM_TENSOR:
10133:     case DM_POLYTOPE_QUAD_PRISM_TENSOR:
10134:     case DM_POLYTOPE_PYRAMID:
10135:       continue;
10136:     default:
10137:       break;
10138:     }
10139:     PetscCall(DMPlexCellUnsplitVertices_Private(dm, c, ct, &unsplit));
10140:     if (unsplit) continue;
10141:     PetscCall(DMPlexComputeCellGeometryFEM(dm, c, NULL, NULL, J, NULL, &detJ));
10142:     PetscCheck(detJ >= -PETSC_SMALL && (detJ > 0.0 || ignoreZeroVol), PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Mesh cell %" PetscInt_FMT " of type %s is inverted, |J| = %g", c, DMPolytopeTypes[ct], (double)detJ);
10143:     PetscCall(PetscInfo(dm, "Cell %" PetscInt_FMT " FEM Volume %g\n", c, (double)(detJ * refVol)));
10144:     /* This should work with periodicity since DG coordinates should be used */
10145:     if (depth > 1) {
10146:       PetscCall(DMPlexComputeCellGeometryFVM(dm, c, &vol, NULL, NULL));
10147:       PetscCheck(vol >= -PETSC_SMALL && (vol > 0.0 || ignoreZeroVol), PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Mesh cell %" PetscInt_FMT " of type %s is inverted, vol = %g", c, DMPolytopeTypes[ct], (double)vol);
10148:       PetscCall(PetscInfo(dm, "Cell %" PetscInt_FMT " FVM Volume %g\n", c, (double)vol));
10149:     }
10150:   }
10151:   PetscFunctionReturn(PETSC_SUCCESS);
10152: }

10154: /*@
10155:   DMPlexCheckPointSF - Check that several necessary conditions are met for the point `PetscSF` of this plex.

10157:   Collective

10159:   Input Parameters:
10160: + dm              - The `DMPLEX` object
10161: . pointSF         - The `PetscSF`, or `NULL` for `PointSF` attached to `DM`
10162: - allowExtraRoots - Flag to allow extra points not present in the `DM`

10164:   Level: developer

10166:   Notes:
10167:   This is mainly intended for debugging/testing purposes.

10169:   For the complete list of DMPlexCheck* functions, see `DMSetFromOptions()`.

10171:   Extra roots can come from periodic cuts, where additional points appear on the boundary

10173: .seealso: [](ch_unstructured), `DM`, `DMPLEX`, `DMGetPointSF()`, `DMSetFromOptions()`
10174: @*/
10175: PetscErrorCode DMPlexCheckPointSF(DM dm, PetscSF pointSF, PetscBool allowExtraRoots)
10176: {
10177:   PetscInt           l, nleaves, nroots, overlap;
10178:   const PetscInt    *locals;
10179:   const PetscSFNode *remotes;
10180:   PetscBool          distributed;
10181:   MPI_Comm           comm;
10182:   PetscMPIInt        rank;

10184:   PetscFunctionBegin;
10187:   else pointSF = dm->sf;
10188:   PetscCall(DMViewFromOptions(dm, NULL, "-dm_plex_point_sf_view"));
10189:   PetscCall(PetscSFViewFromOptions(pointSF, NULL, "-dm_plex_point_sf_view"));
10190:   PetscCall(PetscObjectGetComm((PetscObject)dm, &comm));
10191:   PetscCheck(pointSF, comm, PETSC_ERR_ARG_WRONGSTATE, "DMPlex must have Point SF attached");
10192:   PetscCallMPI(MPI_Comm_rank(comm, &rank));
10193:   {
10194:     PetscMPIInt mpiFlag;

10196:     PetscCallMPI(MPI_Comm_compare(comm, PetscObjectComm((PetscObject)pointSF), &mpiFlag));
10197:     PetscCheck(mpiFlag == MPI_CONGRUENT || mpiFlag == MPI_IDENT, PETSC_COMM_SELF, PETSC_ERR_ARG_NOTSAMECOMM, "DM and Point SF have different communicators (flag %d)", mpiFlag);
10198:   }
10199:   PetscCall(PetscSFGetGraph(pointSF, &nroots, &nleaves, &locals, &remotes));
10200:   PetscCall(DMPlexIsDistributed(dm, &distributed));
10201:   if (!distributed) {
10202:     PetscCheck(nroots < 0 || nleaves == 0, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Undistributed DMPlex cannot have non-empty PointSF (has %" PetscInt_FMT " roots, %" PetscInt_FMT " leaves)", nroots, nleaves);
10203:     PetscFunctionReturn(PETSC_SUCCESS);
10204:   }
10205:   PetscCheck(nroots >= 0, comm, PETSC_ERR_ARG_WRONGSTATE, "This DMPlex is distributed but its PointSF has no graph set (has %" PetscInt_FMT " roots, %" PetscInt_FMT " leaves)", nroots, nleaves);
10206:   PetscCall(DMPlexGetOverlap(dm, &overlap));

10208:   /* Check SF graph is compatible with DMPlex chart */
10209:   {
10210:     PetscInt pStart, pEnd, maxLeaf;

10212:     PetscCall(DMPlexGetChart(dm, &pStart, &pEnd));
10213:     PetscCall(PetscSFGetLeafRange(pointSF, NULL, &maxLeaf));
10214:     PetscCheck(allowExtraRoots || pEnd - pStart == nroots, PETSC_COMM_SELF, PETSC_ERR_PLIB, "pEnd - pStart = %" PetscInt_FMT " != nroots = %" PetscInt_FMT, pEnd - pStart, nroots);
10215:     PetscCheck(maxLeaf < pEnd, PETSC_COMM_SELF, PETSC_ERR_PLIB, "maxLeaf = %" PetscInt_FMT " >= pEnd = %" PetscInt_FMT, maxLeaf, pEnd);
10216:   }

10218:   /* Check there are no cells in interface */
10219:   if (!overlap) {
10220:     PetscInt cellHeight, cStart, cEnd;

10222:     PetscCall(DMPlexGetVTKCellHeight(dm, &cellHeight));
10223:     PetscCall(DMPlexGetHeightStratum(dm, cellHeight, &cStart, &cEnd));
10224:     for (l = 0; l < nleaves; ++l) {
10225:       const PetscInt point = locals ? locals[l] : l;

10227:       PetscCheck(point < cStart || point >= cEnd, PETSC_COMM_SELF, PETSC_ERR_PLIB, "Point SF contains %" PetscInt_FMT " which is a cell", point);
10228:     }
10229:   }

10231:   /* If some point is in interface, then all its cone points must be also in interface (either as leaves or roots) */
10232:   {
10233:     const PetscInt *rootdegree;

10235:     PetscCall(PetscSFComputeDegreeBegin(pointSF, &rootdegree));
10236:     PetscCall(PetscSFComputeDegreeEnd(pointSF, &rootdegree));
10237:     for (l = 0; l < nleaves; ++l) {
10238:       const PetscInt  point = locals ? locals[l] : l;
10239:       const PetscInt *cone;
10240:       PetscInt        coneSize, c, idx;

10242:       PetscCall(DMPlexGetConeSize(dm, point, &coneSize));
10243:       PetscCall(DMPlexGetCone(dm, point, &cone));
10244:       for (c = 0; c < coneSize; ++c) {
10245:         if (!rootdegree[cone[c]]) {
10246:           if (locals) PetscCall(PetscFindInt(cone[c], nleaves, locals, &idx));
10247:           else idx = (cone[c] < nleaves) ? cone[c] : -1;
10248:           PetscCheck(idx >= 0, PETSC_COMM_SELF, PETSC_ERR_PLIB, "Point SF contains %" PetscInt_FMT " but not %" PetscInt_FMT " from its cone", point, cone[c]);
10249:         }
10250:       }
10251:     }
10252:   }

10254:   // Depths of leaves should match depths of root
10255:   //   Does not work for geometrically non-conforming meshes
10256:   if (!((DM_Plex *)dm->data)->parentSection) {
10257:     PetscInt   *starts, *gstarts, *depths;
10258:     PetscInt    depth;
10259:     PetscMPIInt size;
10260:     PetscBool   skip = PETSC_FALSE;

10262:     PetscCallMPI(MPI_Comm_size(comm, &size));
10263:     PetscCall(DMPlexGetDepth(dm, &depth));
10264:     PetscCall(PetscMalloc3(depth + 2, &starts, size * (depth + 2), &gstarts, depth + 2, &depths));
10265:     depths[0] = depth;
10266:     depths[1] = 0;
10267:     for (PetscInt d = 2; d <= depth; ++d) depths[d] = depth + 1 - d;
10268:     depths[depth + 1] = depth + 1;
10269:     for (PetscInt d = 0; d <= depth; ++d) {
10270:       PetscCall(DMPlexGetDepthStratum(dm, d, &starts[d], NULL));
10271:     }
10272:     // This is necessary because some strata might be missing
10273:     PetscCall(DMPlexGetChart(dm, NULL, &starts[depth + 1]));
10274:     PetscCallMPI(MPI_Allgather(starts, (int)(depth + 2), MPIU_INT, gstarts, (int)(depth + 2), MPIU_INT, comm));
10275:     // Check is invalid with empty strata
10276:     for (PetscInt p = 0; p < size * (depth + 2); ++p)
10277:       if (gstarts[p] < 0) skip = PETSC_TRUE;
10278:     for (l = skip ? nleaves : 0; l < nleaves; ++l) {
10279:       const PetscInt point  = locals ? locals[l] : l;
10280:       const PetscInt rpoint = remotes[l].index;
10281:       const PetscInt rrank  = remotes[l].rank;
10282:       PetscInt       pdepth, rdepth = -1;

10284:       PetscCall(DMPlexGetPointDepth(dm, point, &pdepth));
10285:       for (PetscInt d = 0; d <= depth; ++d) {
10286:         if (gstarts[rrank * (depth + 2) + depths[d]] <= rpoint && rpoint < gstarts[rrank * (depth + 2) + depths[d + 1]]) {
10287:           rdepth = depths[d];
10288:           break;
10289:         }
10290:       }
10291:       PetscCheck(rdepth != -1, PETSC_COMM_SELF, PETSC_ERR_PLIB, "Leaf %" PetscInt_FMT " (%" PetscInt_FMT ") was not found on remote rank %" PetscInt_FMT, point, rpoint, rrank);
10292:       PetscCheck(pdepth == rdepth, PETSC_COMM_SELF, PETSC_ERR_PLIB, "Leaf %" PetscInt_FMT " has depth %" PetscInt_FMT " but remote (%" PetscInt_FMT ", %" PetscInt_FMT ") depth is %" PetscInt_FMT, point, pdepth, rpoint, rrank, rdepth);
10293:     }
10294:     PetscCall(PetscFree3(starts, gstarts, depths));
10295:   }
10296:   PetscFunctionReturn(PETSC_SUCCESS);
10297: }

10299: /*@
10300:   DMPlexCheckOrphanVertices - Check that no vertices are disconnected from the mesh, unless the mesh only consists of disconnected vertices.

10302:   Collective

10304:   Input Parameter:
10305: . dm - The `DMPLEX` object

10307:   Level: developer

10309:   Notes:
10310:   This is mainly intended for debugging/testing purposes.

10312:   Other cell types which are disconnected would be caught by the symmetry and face checks.

10314:   For the complete list of DMPlexCheck* functions, see `DMSetFromOptions()`.

10316: .seealso: [](ch_unstructured), `DM`, `DMPLEX`, `DMPlexCheck()`, `DMSetFromOptions()`
10317: @*/
10318: PetscErrorCode DMPlexCheckOrphanVertices(DM dm)
10319: {
10320:   PetscInt pStart, pEnd, vStart, vEnd;

10322:   PetscFunctionBegin;
10323:   PetscCall(DMPlexGetChart(dm, &pStart, &pEnd));
10324:   PetscCall(DMPlexGetDepthStratum(dm, 0, &vStart, &vEnd));
10325:   if (pStart == vStart && pEnd == vEnd) PetscFunctionReturn(PETSC_SUCCESS);
10326:   for (PetscInt v = vStart; v < vEnd; ++v) {
10327:     PetscInt suppSize;

10329:     PetscCall(DMPlexGetSupportSize(dm, v, &suppSize));
10330:     PetscCheck(suppSize, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Vertex %" PetscInt_FMT " is disconnected from the mesh", v);
10331:   }
10332:   PetscFunctionReturn(PETSC_SUCCESS);
10333: }

10335: /*@
10336:   DMPlexCheckTransform - If the mesh was produced by a transform, run the transform verification check on it

10338:   Collective

10340:   Input Parameter:
10341: . dm - The `DMPLEX` object

10343:   Level: developer

10345:   Notes:
10346:   This is mainly intended for debugging/testing purposes.

10348:   For the complete list of DMPlexCheck* functions, see `DMSetFromOptions()`.

10350: .seealso: [](ch_unstructured), `DM`, `DMPLEX`, `DMPlexCheck()`, `DMSetFromOptions()`
10351: @*/
10352: PetscErrorCode DMPlexCheckTransform(DM dm)
10353: {
10354:   DMPlexTransform tr;

10356:   PetscFunctionBegin;
10357:   PetscCall(DMPlexGetTransform(dm, &tr));
10358:   if (tr) PetscCall(DMPlexTransformCheck(tr, dm));
10359:   PetscFunctionReturn(PETSC_SUCCESS);
10360: }

10362: /*@
10363:   DMPlexCheck - Perform various checks of `DMPLEX` sanity

10365:   Collective

10367:   Input Parameter:
10368: . dm - The `DMPLEX` object

10370:   Level: developer

10372:   Notes:
10373:   This is a useful diagnostic when creating meshes programmatically.

10375:   For the complete list of DMPlexCheck* functions, see `DMSetFromOptions()`.

10377:   Currently does not include `DMPlexCheckCellShape()`.

10379: .seealso: [](ch_unstructured), `DM`, `DMPLEX`, `DMCreate()`, `DMSetFromOptions()`
10380: @*/
10381: PetscErrorCode DMPlexCheck(DM dm)
10382: {
10383:   PetscInt cellHeight;

10385:   PetscFunctionBegin;
10386:   PetscCall(DMPlexGetVTKCellHeight(dm, &cellHeight));
10387:   PetscCall(DMPlexCheckSymmetry(dm));
10388:   PetscCall(DMPlexCheckSkeleton(dm, cellHeight));
10389:   PetscCall(DMPlexCheckFaces(dm, cellHeight));
10390:   PetscCall(DMPlexCheckGeometry(dm));
10391:   PetscCall(DMPlexCheckPointSF(dm, NULL, PETSC_FALSE));
10392:   PetscCall(DMPlexCheckInterfaceCones(dm));
10393:   PetscCall(DMPlexCheckOrphanVertices(dm));
10394:   PetscCall(DMPlexCheckTransform(dm));
10395:   PetscFunctionReturn(PETSC_SUCCESS);
10396: }

10398: typedef struct cell_stats {
10399:   PetscReal min, max, sum, squaresum;
10400:   PetscInt  count;
10401: } cell_stats_t;

10403: static void MPIAPI cell_stats_reduce(void *a, void *b, int *len, MPI_Datatype *datatype)
10404: {
10405:   PetscInt i, N = *len;

10407:   for (i = 0; i < N; i++) {
10408:     cell_stats_t *A = (cell_stats_t *)a;
10409:     cell_stats_t *B = (cell_stats_t *)b;

10411:     B->min = PetscMin(A->min, B->min);
10412:     B->max = PetscMax(A->max, B->max);
10413:     B->sum += A->sum;
10414:     B->squaresum += A->squaresum;
10415:     B->count += A->count;
10416:   }
10417: }

10419: /*@
10420:   DMPlexCheckCellShape - Checks the Jacobian of the mapping from reference to real cells and computes some minimal statistics.

10422:   Collective

10424:   Input Parameters:
10425: + dm        - The `DMPLEX` object
10426: . output    - If true, statistics will be displayed on `stdout`
10427: - condLimit - Display all cells above this condition number, or `PETSC_DETERMINE` for no cell output

10429:   Level: developer

10431:   Notes:
10432:   The condition number $\kappa_c$ of a cell $c$ is given by
10433:   ```{math}
10434:   \kappa_c = \left\lVert J_c \right\rVert \left\lVert J^{-1}_c \right\rVert
10435:   ```
10436:   where $J_c$ is the Jacobian of the mapping from the reference cell to cell $c$.

10438:   This is mainly intended for debugging/testing purposes.

10440:   For the complete list of DMPlexCheck* functions, see `DMSetFromOptions()`.

10442: .seealso: [](ch_unstructured), `DM`, `DMPLEX`, `DMSetFromOptions()`, `DMPlexComputeOrthogonalQuality()`
10443: @*/
10444: PetscErrorCode DMPlexCheckCellShape(DM dm, PetscBool output, PetscReal condLimit)
10445: {
10446:   DM           dmCoarse;
10447:   cell_stats_t stats, globalStats;
10448:   MPI_Comm     comm = PetscObjectComm((PetscObject)dm);
10449:   PetscReal   *J, *invJ, min = 0, max = 0, mean = 0, stdev = 0;
10450:   PetscReal    limit = condLimit > 0 ? condLimit : PETSC_MAX_REAL;
10451:   PetscInt     cdim, cStart, cEnd, c, eStart, eEnd, count = 0;
10452:   PetscMPIInt  rank, size;

10454:   PetscFunctionBegin;
10456:   stats.min = PETSC_MAX_REAL;
10457:   stats.max = PETSC_MIN_REAL;
10458:   stats.sum = stats.squaresum = 0.;
10459:   stats.count                 = 0;

10461:   PetscCallMPI(MPI_Comm_size(comm, &size));
10462:   PetscCallMPI(MPI_Comm_rank(comm, &rank));
10463:   PetscCall(DMGetCoordinateDim(dm, &cdim));
10464:   PetscCall(DMGetCoordinatesLocalSetUp(dm));
10465:   PetscCall(PetscMalloc2(PetscSqr(cdim), &J, PetscSqr(cdim), &invJ));
10466:   PetscCall(DMPlexGetSimplexOrBoxCells(dm, 0, &cStart, &cEnd));
10467:   PetscCall(DMPlexGetDepthStratum(dm, 1, &eStart, &eEnd));
10468:   for (c = cStart; c < cEnd; c++) {
10469:     PetscReal frobJ = 0., frobInvJ = 0., cond2, cond, detJ;

10471:     PetscCall(DMPlexComputeCellGeometryAffineFEM(dm, c, NULL, J, invJ, &detJ));
10472:     PetscCheck(detJ >= 0.0, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Mesh cell %" PetscInt_FMT " is inverted", c);
10473:     for (PetscInt i = 0; i < PetscSqr(cdim); ++i) {
10474:       frobJ += J[i] * J[i];
10475:       frobInvJ += invJ[i] * invJ[i];
10476:     }
10477:     cond2 = frobJ * frobInvJ;
10478:     cond  = PetscSqrtReal(cond2);

10480:     stats.min = PetscMin(stats.min, cond);
10481:     stats.max = PetscMax(stats.max, cond);
10482:     stats.sum += cond;
10483:     stats.squaresum += cond2;
10484:     stats.count++;
10485:     if (output && cond > limit) {
10486:       PetscSection coordSection;
10487:       Vec          coordsLocal;
10488:       PetscScalar *coords = NULL;
10489:       PetscInt     Nv, d, clSize, cl, *closure = NULL;

10491:       PetscCall(DMGetCoordinatesLocal(dm, &coordsLocal));
10492:       PetscCall(DMGetCoordinateSection(dm, &coordSection));
10493:       PetscCall(DMPlexVecGetClosure(dm, coordSection, coordsLocal, c, &Nv, &coords));
10494:       PetscCall(PetscSynchronizedPrintf(comm, "[%d] Cell %" PetscInt_FMT " cond %g\n", rank, c, (double)cond));
10495:       for (PetscInt i = 0; i < Nv / cdim; ++i) {
10496:         PetscCall(PetscSynchronizedPrintf(comm, "  Vertex %" PetscInt_FMT ": (", i));
10497:         for (d = 0; d < cdim; ++d) {
10498:           if (d > 0) PetscCall(PetscSynchronizedPrintf(comm, ", "));
10499:           PetscCall(PetscSynchronizedPrintf(comm, "%g", (double)PetscRealPart(coords[i * cdim + d])));
10500:         }
10501:         PetscCall(PetscSynchronizedPrintf(comm, ")\n"));
10502:       }
10503:       PetscCall(DMPlexGetTransitiveClosure(dm, c, PETSC_TRUE, &clSize, &closure));
10504:       for (cl = 0; cl < clSize * 2; cl += 2) {
10505:         const PetscInt edge = closure[cl];

10507:         if ((edge >= eStart) && (edge < eEnd)) {
10508:           PetscReal len;

10510:           PetscCall(DMPlexComputeCellGeometryFVM(dm, edge, &len, NULL, NULL));
10511:           PetscCall(PetscSynchronizedPrintf(comm, "  Edge %" PetscInt_FMT ": length %g\n", edge, (double)len));
10512:         }
10513:       }
10514:       PetscCall(DMPlexRestoreTransitiveClosure(dm, c, PETSC_TRUE, &clSize, &closure));
10515:       PetscCall(DMPlexVecRestoreClosure(dm, coordSection, coordsLocal, c, &Nv, &coords));
10516:     }
10517:   }
10518:   if (output) PetscCall(PetscSynchronizedFlush(comm, NULL));

10520:   if (size > 1) {
10521:     PetscMPIInt  blockLengths[2] = {4, 1};
10522:     MPI_Aint     blockOffsets[2] = {offsetof(cell_stats_t, min), offsetof(cell_stats_t, count)};
10523:     MPI_Datatype blockTypes[2]   = {MPIU_REAL, MPIU_INT}, statType;
10524:     MPI_Op       statReduce;

10526:     PetscCallMPI(MPI_Type_create_struct(2, blockLengths, blockOffsets, blockTypes, &statType));
10527:     PetscCallMPI(MPI_Type_commit(&statType));
10528:     PetscCallMPI(MPI_Op_create(cell_stats_reduce, PETSC_TRUE, &statReduce));
10529:     PetscCallMPI(MPI_Reduce(&stats, &globalStats, 1, statType, statReduce, 0, comm));
10530:     PetscCallMPI(MPI_Op_free(&statReduce));
10531:     PetscCallMPI(MPI_Type_free(&statType));
10532:   } else {
10533:     PetscCall(PetscArraycpy(&globalStats, &stats, 1));
10534:   }
10535:   if (rank == 0) {
10536:     count = globalStats.count;
10537:     min   = globalStats.min;
10538:     max   = globalStats.max;
10539:     mean  = globalStats.sum / globalStats.count;
10540:     stdev = globalStats.count > 1 ? PetscSqrtReal(PetscMax((globalStats.squaresum - globalStats.count * mean * mean) / (globalStats.count - 1), 0)) : 0.0;
10541:   }

10543:   if (output) PetscCall(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));
10544:   PetscCall(PetscFree2(J, invJ));

10546:   PetscCall(DMGetCoarseDM(dm, &dmCoarse));
10547:   if (dmCoarse) {
10548:     PetscBool isplex;

10550:     PetscCall(PetscObjectTypeCompare((PetscObject)dmCoarse, DMPLEX, &isplex));
10551:     if (isplex) PetscCall(DMPlexCheckCellShape(dmCoarse, output, condLimit));
10552:   }
10553:   PetscFunctionReturn(PETSC_SUCCESS);
10554: }

10556: /*@
10557:   DMPlexComputeOrthogonalQuality - Compute cell-wise orthogonal quality mesh statistic. Optionally tags all cells with
10558:   orthogonal quality below given tolerance.

10560:   Collective

10562:   Input Parameters:
10563: + dm   - The `DMPLEX` object
10564: . fv   - Optional `PetscFV` object for pre-computed cell/face centroid information
10565: - atol - [0, 1] Absolute tolerance for tagging cells.

10567:   Output Parameters:
10568: + OrthQual      - `Vec` containing orthogonal quality per cell
10569: - OrthQualLabel - `DMLabel` tagging cells below atol with `DM_ADAPT_REFINE`

10571:   Options Database Keys:
10572: + -dm_plex_orthogonal_quality_label_view - view OrthQualLabel if label is requested. Currently only `PETSCVIEWERASCII` is supported.
10573: - -dm_plex_orthogonal_quality_vec_view   - view OrthQual vector.

10575:   Level: intermediate

10577:   Notes:
10578:   Orthogonal quality is given by the following formula\:

10580:   $ \min \left[ \frac{A_i \cdot f_i}{\|A_i\| \|f_i\|} , \frac{A_i \cdot c_i}{\|A_i\| \|c_i\|} \right]$

10582:   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
10583:   is the vector from the current cells centroid to the centroid of its i'th neighbor (which shares a face with the
10584:   current cell). This computes the vector similarity between each cell face and its corresponding neighbor centroid by
10585:   calculating the cosine of the angle between these vectors.

10587:   Orthogonal quality ranges from 1 (best) to 0 (worst).

10589:   This routine is mainly useful for FVM, however is not restricted to only FVM. The `PetscFV` object is optionally used to check for
10590:   pre-computed FVM cell data, but if it is not passed in then this data will be computed.

10592:   Cells are tagged if they have an orthogonal quality less than or equal to the absolute tolerance.

10594: .seealso: [](ch_unstructured), `DM`, `DMPLEX`, `DMPlexCheckCellShape()`, `DMCreateLabel()`, `PetscFV`, `DMLabel`, `Vec`
10595: @*/
10596: PetscErrorCode DMPlexComputeOrthogonalQuality(DM dm, PeOp PetscFV fv, PetscReal atol, Vec *OrthQual, DMLabel *OrthQualLabel)
10597: {
10598:   PetscInt               nc, cellHeight, cStart, cEnd, cell, cellIter = 0;
10599:   PetscInt              *idx;
10600:   PetscScalar           *oqVals;
10601:   const PetscScalar     *cellGeomArr, *faceGeomArr;
10602:   PetscReal             *ci, *fi, *Ai;
10603:   MPI_Comm               comm;
10604:   Vec                    cellgeom, facegeom;
10605:   DM                     dmFace, dmCell;
10606:   IS                     glob;
10607:   ISLocalToGlobalMapping ltog;
10608:   PetscViewer            vwr;

10610:   PetscFunctionBegin;
10613:   PetscAssertPointer(OrthQual, 4);
10614:   PetscCheck(atol >= 0.0 && atol <= 1.0, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Absolute tolerance %g not in [0,1]", (double)atol);
10615:   PetscCall(PetscObjectGetComm((PetscObject)dm, &comm));
10616:   PetscCall(DMGetDimension(dm, &nc));
10617:   PetscCheck(nc >= 2, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "DM must have dimension >= 2 (current %" PetscInt_FMT ")", nc);
10618:   {
10619:     DMPlexInterpolatedFlag interpFlag;

10621:     PetscCall(DMPlexIsInterpolated(dm, &interpFlag));
10622:     if (interpFlag != DMPLEX_INTERPOLATED_FULL) {
10623:       PetscMPIInt rank;

10625:       PetscCallMPI(MPI_Comm_rank(comm, &rank));
10626:       SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "DM must be fully interpolated, DM on rank %d is not fully interpolated", rank);
10627:     }
10628:   }
10629:   if (OrthQualLabel) {
10630:     PetscAssertPointer(OrthQualLabel, 5);
10631:     PetscCall(DMCreateLabel(dm, "Orthogonal_Quality"));
10632:     PetscCall(DMGetLabel(dm, "Orthogonal_Quality", OrthQualLabel));
10633:   } else {
10634:     *OrthQualLabel = NULL;
10635:   }
10636:   PetscCall(DMPlexGetVTKCellHeight(dm, &cellHeight));
10637:   PetscCall(DMPlexGetHeightStratum(dm, cellHeight, &cStart, &cEnd));
10638:   PetscCall(DMPlexCreateCellNumbering(dm, PETSC_TRUE, &glob));
10639:   PetscCall(ISLocalToGlobalMappingCreateIS(glob, &ltog));
10640:   PetscCall(ISLocalToGlobalMappingSetType(ltog, ISLOCALTOGLOBALMAPPINGHASH));
10641:   PetscCall(VecCreate(comm, OrthQual));
10642:   PetscCall(VecSetType(*OrthQual, VECSTANDARD));
10643:   PetscCall(VecSetSizes(*OrthQual, cEnd - cStart, PETSC_DETERMINE));
10644:   PetscCall(VecSetLocalToGlobalMapping(*OrthQual, ltog));
10645:   PetscCall(VecSetUp(*OrthQual));
10646:   PetscCall(ISDestroy(&glob));
10647:   PetscCall(ISLocalToGlobalMappingDestroy(&ltog));
10648:   PetscCall(DMPlexGetDataFVM(dm, fv, &cellgeom, &facegeom, NULL));
10649:   PetscCall(VecGetArrayRead(cellgeom, &cellGeomArr));
10650:   PetscCall(VecGetArrayRead(facegeom, &faceGeomArr));
10651:   PetscCall(VecGetDM(cellgeom, &dmCell));
10652:   PetscCall(VecGetDM(facegeom, &dmFace));
10653:   PetscCall(PetscMalloc5(cEnd - cStart, &idx, cEnd - cStart, &oqVals, nc, &ci, nc, &fi, nc, &Ai));
10654:   for (cell = cStart; cell < cEnd; cellIter++, cell++) {
10655:     PetscInt         cellneigh, cellneighiter = 0, adjSize = PETSC_DETERMINE;
10656:     PetscInt         cellarr[2], *adj = NULL;
10657:     PetscScalar     *cArr, *fArr;
10658:     PetscReal        minvalc = 1.0, minvalf = 1.0;
10659:     PetscFVCellGeom *cg;

10661:     idx[cellIter] = cell - cStart;
10662:     cellarr[0]    = cell;
10663:     /* Make indexing into cellGeom easier */
10664:     PetscCall(DMPlexPointLocalRead(dmCell, cell, cellGeomArr, &cg));
10665:     PetscCall(DMPlexGetAdjacency_Internal(dm, cell, PETSC_TRUE, PETSC_FALSE, PETSC_FALSE, &adjSize, &adj));
10666:     /* Technically 1 too big, but easier than fiddling with empty adjacency array */
10667:     PetscCall(PetscCalloc2(adjSize, &cArr, adjSize, &fArr));
10668:     for (cellneigh = 0; cellneigh < adjSize; cellneighiter++, cellneigh++) {
10669:       const PetscInt   neigh  = adj[cellneigh];
10670:       PetscReal        normci = 0, normfi = 0, normai = 0;
10671:       PetscFVCellGeom *cgneigh;
10672:       PetscFVFaceGeom *fg;

10674:       /* Don't count ourselves in the neighbor list */
10675:       if (neigh == cell) continue;
10676:       PetscCall(DMPlexPointLocalRead(dmCell, neigh, cellGeomArr, &cgneigh));
10677:       cellarr[1] = neigh;
10678:       {
10679:         PetscInt        numcovpts;
10680:         const PetscInt *covpts;

10682:         PetscCall(DMPlexGetMeet(dm, 2, cellarr, &numcovpts, &covpts));
10683:         PetscCall(DMPlexPointLocalRead(dmFace, covpts[0], faceGeomArr, &fg));
10684:         PetscCall(DMPlexRestoreMeet(dm, 2, cellarr, &numcovpts, &covpts));
10685:       }

10687:       /* Compute c_i, f_i and their norms */
10688:       for (PetscInt i = 0; i < nc; i++) {
10689:         ci[i] = cgneigh->centroid[i] - cg->centroid[i];
10690:         fi[i] = fg->centroid[i] - cg->centroid[i];
10691:         Ai[i] = fg->normal[i];
10692:         normci += PetscPowReal(ci[i], 2);
10693:         normfi += PetscPowReal(fi[i], 2);
10694:         normai += PetscPowReal(Ai[i], 2);
10695:       }
10696:       normci = PetscSqrtReal(normci);
10697:       normfi = PetscSqrtReal(normfi);
10698:       normai = PetscSqrtReal(normai);

10700:       /* Normalize and compute for each face-cell-normal pair */
10701:       for (PetscInt i = 0; i < nc; i++) {
10702:         ci[i] = ci[i] / normci;
10703:         fi[i] = fi[i] / normfi;
10704:         Ai[i] = Ai[i] / normai;
10705:         /* PetscAbs because I don't know if normals are guaranteed to point out */
10706:         cArr[cellneighiter] += PetscAbs(Ai[i] * ci[i]);
10707:         fArr[cellneighiter] += PetscAbs(Ai[i] * fi[i]);
10708:       }
10709:       if (PetscRealPart(cArr[cellneighiter]) < minvalc) minvalc = PetscRealPart(cArr[cellneighiter]);
10710:       if (PetscRealPart(fArr[cellneighiter]) < minvalf) minvalf = PetscRealPart(fArr[cellneighiter]);
10711:     }
10712:     PetscCall(PetscFree(adj));
10713:     PetscCall(PetscFree2(cArr, fArr));
10714:     /* Defer to cell if they're equal */
10715:     oqVals[cellIter] = PetscMin(minvalf, minvalc);
10716:     if (OrthQualLabel) {
10717:       if (PetscRealPart(oqVals[cellIter]) <= atol) PetscCall(DMLabelSetValue(*OrthQualLabel, cell, DM_ADAPT_REFINE));
10718:     }
10719:   }
10720:   PetscCall(VecSetValuesLocal(*OrthQual, cEnd - cStart, idx, oqVals, INSERT_VALUES));
10721:   PetscCall(VecAssemblyBegin(*OrthQual));
10722:   PetscCall(VecAssemblyEnd(*OrthQual));
10723:   PetscCall(VecRestoreArrayRead(cellgeom, &cellGeomArr));
10724:   PetscCall(VecRestoreArrayRead(facegeom, &faceGeomArr));
10725:   PetscCall(PetscOptionsCreateViewer(comm, NULL, NULL, "-dm_plex_orthogonal_quality_label_view", &vwr, NULL, NULL));
10726:   if (OrthQualLabel) {
10727:     if (vwr) PetscCall(DMLabelView(*OrthQualLabel, vwr));
10728:   }
10729:   PetscCall(PetscFree5(idx, oqVals, ci, fi, Ai));
10730:   PetscCall(PetscViewerDestroy(&vwr));
10731:   PetscCall(VecViewFromOptions(*OrthQual, NULL, "-dm_plex_orthogonal_quality_vec_view"));
10732:   PetscFunctionReturn(PETSC_SUCCESS);
10733: }

10735: /* this is here instead of DMGetOutputDM because output DM still has constraints in the local indices that affect
10736:  * interpolator construction */
10737: static PetscErrorCode DMGetFullDM(DM dm, DM *odm)
10738: {
10739:   PetscSection section, newSection, gsection;
10740:   PetscSF      sf;
10741:   PetscBool    hasConstraints, ghasConstraints;

10743:   PetscFunctionBegin;
10745:   PetscAssertPointer(odm, 2);
10746:   PetscCall(DMGetLocalSection(dm, &section));
10747:   PetscCall(PetscSectionHasConstraints(section, &hasConstraints));
10748:   PetscCallMPI(MPIU_Allreduce(&hasConstraints, &ghasConstraints, 1, MPI_C_BOOL, MPI_LOR, PetscObjectComm((PetscObject)dm)));
10749:   if (!ghasConstraints) {
10750:     PetscCall(PetscObjectReference((PetscObject)dm));
10751:     *odm = dm;
10752:     PetscFunctionReturn(PETSC_SUCCESS);
10753:   }
10754:   PetscCall(DMClone(dm, odm));
10755:   PetscCall(DMCopyFields(dm, PETSC_DETERMINE, PETSC_DETERMINE, *odm));
10756:   PetscCall(DMGetLocalSection(*odm, &newSection));
10757:   PetscCall(DMGetPointSF(*odm, &sf));
10758:   PetscCall(PetscSectionCreateGlobalSection(newSection, sf, PETSC_TRUE, PETSC_TRUE, PETSC_FALSE, &gsection));
10759:   PetscCall(DMSetGlobalSection(*odm, gsection));
10760:   PetscCall(PetscSectionDestroy(&gsection));
10761:   PetscFunctionReturn(PETSC_SUCCESS);
10762: }

10764: static PetscErrorCode DMCreateAffineInterpolationCorrection_Plex(DM dmc, DM dmf, Vec *shift)
10765: {
10766:   DM        dmco, dmfo;
10767:   Mat       interpo;
10768:   Vec       rscale;
10769:   Vec       cglobalo, clocal;
10770:   Vec       fglobal, fglobalo, flocal;
10771:   PetscBool regular;

10773:   PetscFunctionBegin;
10774:   PetscCall(DMGetFullDM(dmc, &dmco));
10775:   PetscCall(DMGetFullDM(dmf, &dmfo));
10776:   PetscCall(DMSetCoarseDM(dmfo, dmco));
10777:   PetscCall(DMPlexGetRegularRefinement(dmf, &regular));
10778:   PetscCall(DMPlexSetRegularRefinement(dmfo, regular));
10779:   PetscCall(DMCreateInterpolation(dmco, dmfo, &interpo, &rscale));
10780:   PetscCall(DMCreateGlobalVector(dmco, &cglobalo));
10781:   PetscCall(DMCreateLocalVector(dmc, &clocal));
10782:   PetscCall(DMCreateGlobalVector(dmf, &fglobal));
10783:   PetscCall(DMCreateGlobalVector(dmfo, &fglobalo));
10784:   PetscCall(DMCreateLocalVector(dmf, &flocal));
10785:   PetscCall(DMPlexInsertBoundaryValues(dmc, PETSC_TRUE, clocal, 0., NULL, NULL, NULL));
10786:   PetscCall(DMLocalToGlobalBegin(dmco, clocal, INSERT_VALUES, cglobalo));
10787:   PetscCall(DMLocalToGlobalEnd(dmco, clocal, INSERT_VALUES, cglobalo));
10788:   PetscCall(MatMult(interpo, cglobalo, fglobalo));
10789:   PetscCall(DMGlobalToLocalBegin(dmfo, fglobalo, INSERT_VALUES, flocal));
10790:   PetscCall(DMGlobalToLocalEnd(dmfo, fglobalo, INSERT_VALUES, flocal));
10791:   PetscCall(DMLocalToGlobalBegin(dmf, flocal, INSERT_VALUES, fglobal));
10792:   PetscCall(DMLocalToGlobalEnd(dmf, flocal, INSERT_VALUES, fglobal));
10793:   *shift = fglobal;
10794:   PetscCall(VecDestroy(&flocal));
10795:   PetscCall(VecDestroy(&fglobalo));
10796:   PetscCall(VecDestroy(&clocal));
10797:   PetscCall(VecDestroy(&cglobalo));
10798:   PetscCall(VecDestroy(&rscale));
10799:   PetscCall(MatDestroy(&interpo));
10800:   PetscCall(DMDestroy(&dmfo));
10801:   PetscCall(DMDestroy(&dmco));
10802:   PetscFunctionReturn(PETSC_SUCCESS);
10803: }

10805: PETSC_INTERN PetscErrorCode DMInterpolateSolution_Plex(DM coarse, DM fine, Mat interp, Vec coarseSol, Vec fineSol)
10806: {
10807:   PetscObject shifto;
10808:   Vec         shift;

10810:   PetscFunctionBegin;
10811:   if (!interp) {
10812:     Vec rscale;

10814:     PetscCall(DMCreateInterpolation(coarse, fine, &interp, &rscale));
10815:     PetscCall(VecDestroy(&rscale));
10816:   } else {
10817:     PetscCall(PetscObjectReference((PetscObject)interp));
10818:   }
10819:   PetscCall(PetscObjectQuery((PetscObject)interp, "_DMInterpolateSolution_Plex_Vec", &shifto));
10820:   if (!shifto) {
10821:     PetscCall(DMCreateAffineInterpolationCorrection_Plex(coarse, fine, &shift));
10822:     PetscCall(PetscObjectCompose((PetscObject)interp, "_DMInterpolateSolution_Plex_Vec", (PetscObject)shift));
10823:     shifto = (PetscObject)shift;
10824:     PetscCall(VecDestroy(&shift));
10825:   }
10826:   shift = (Vec)shifto;
10827:   PetscCall(MatInterpolate(interp, coarseSol, fineSol));
10828:   PetscCall(VecAXPY(fineSol, 1.0, shift));
10829:   PetscCall(MatDestroy(&interp));
10830:   PetscFunctionReturn(PETSC_SUCCESS);
10831: }

10833: /* Pointwise interpolation
10834:      Just code FEM for now
10835:      u^f = I u^c
10836:      sum_k u^f_k phi^f_k = I sum_j u^c_j phi^c_j
10837:      u^f_i = sum_j psi^f_i I phi^c_j u^c_j
10838:      I_{ij} = psi^f_i phi^c_j
10839: */
10840: PetscErrorCode DMCreateInterpolation_Plex(DM dmCoarse, DM dmFine, Mat *interpolation, Vec *scaling)
10841: {
10842:   PetscSection gsc, gsf;
10843:   PetscInt     m, n;
10844:   void        *ctx;
10845:   DM           cdm;
10846:   PetscBool    regular, ismatis, isRefined = dmCoarse->data == dmFine->data ? PETSC_FALSE : PETSC_TRUE;

10848:   PetscFunctionBegin;
10849:   PetscCall(DMGetGlobalSection(dmFine, &gsf));
10850:   PetscCall(PetscSectionGetConstrainedStorageSize(gsf, &m));
10851:   PetscCall(DMGetGlobalSection(dmCoarse, &gsc));
10852:   PetscCall(PetscSectionGetConstrainedStorageSize(gsc, &n));

10854:   PetscCall(PetscStrcmp(dmCoarse->mattype, MATIS, &ismatis));
10855:   PetscCall(MatCreate(PetscObjectComm((PetscObject)dmCoarse), interpolation));
10856:   PetscCall(MatSetSizes(*interpolation, m, n, PETSC_DETERMINE, PETSC_DETERMINE));
10857:   PetscCall(MatSetType(*interpolation, ismatis ? MATAIJ : dmCoarse->mattype));
10858:   PetscCall(DMGetApplicationContext(dmFine, &ctx));

10860:   PetscCall(DMGetCoarseDM(dmFine, &cdm));
10861:   PetscCall(DMPlexGetRegularRefinement(dmFine, &regular));
10862:   if (!isRefined || (regular && cdm == dmCoarse)) PetscCall(DMPlexComputeInterpolatorNested(dmCoarse, dmFine, isRefined, *interpolation, ctx));
10863:   else PetscCall(DMPlexComputeInterpolatorGeneral(dmCoarse, dmFine, *interpolation, ctx));
10864:   PetscCall(MatViewFromOptions(*interpolation, NULL, "-interp_mat_view"));
10865:   if (scaling) {
10866:     /* Use naive scaling */
10867:     PetscCall(DMCreateInterpolationScale(dmCoarse, dmFine, *interpolation, scaling));
10868:   }
10869:   PetscFunctionReturn(PETSC_SUCCESS);
10870: }

10872: PetscErrorCode DMCreateInjection_Plex(DM dmCoarse, DM dmFine, Mat *mat)
10873: {
10874:   VecScatter ctx;

10876:   PetscFunctionBegin;
10877:   PetscCall(DMPlexComputeInjectorFEM(dmCoarse, dmFine, &ctx, NULL));
10878:   PetscCall(MatCreateScatter(PetscObjectComm((PetscObject)ctx), ctx, mat));
10879:   PetscCall(VecScatterDestroy(&ctx));
10880:   PetscFunctionReturn(PETSC_SUCCESS);
10881: }

10883: 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[])
10884: {
10885:   const PetscInt f  = (PetscInt)PetscRealPart(constants[numConstants]);
10886:   const PetscInt Nc = uOff[f + 1] - uOff[f];
10887:   for (PetscInt c = 0; c < Nc; ++c) g0[c * Nc + c] = 1.0;
10888: }

10890: // The assumption here is that the test field is a vector and the basis field is a scalar (so we need the gradient)
10891: static void g1_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 g1[])
10892: {
10893:   for (PetscInt c = 0; c < dim; ++c) g1[c * dim + c] = 1.0;
10894: }

10896: PetscErrorCode DMCreateMassMatrixLumped_Plex(DM dm, Vec *lmass, Vec *mass)
10897: {
10898:   DM           dmc;
10899:   PetscDS      ds;
10900:   Vec          ones, locmass;
10901:   IS           cellIS;
10902:   PetscFormKey key;
10903:   PetscInt     depth;

10905:   PetscFunctionBegin;
10906:   PetscCall(DMClone(dm, &dmc));
10907:   PetscCall(DMCopyDisc(dm, dmc));
10908:   PetscCall(DMGetDS(dmc, &ds));
10909:   for (PetscInt f = 0; f < dmc->Nf; ++f) PetscCall(PetscDSSetJacobian(ds, f, f, g0_identity_private, NULL, NULL, NULL));
10910:   if (mass) PetscCall(DMCreateGlobalVector(dm, mass));
10911:   if (lmass) PetscCall(DMCreateLocalVector(dm, &locmass));
10912:   else PetscCall(DMGetLocalVector(dm, &locmass));
10913:   PetscCall(DMGetLocalVector(dm, &ones));
10914:   PetscCall(DMPlexGetDepth(dm, &depth));
10915:   PetscCall(DMGetStratumIS(dm, "depth", depth, &cellIS));
10916:   PetscCall(VecSet(locmass, 0.0));
10917:   PetscCall(VecSet(ones, 1.0));
10918:   key.label = NULL;
10919:   key.value = 0;
10920:   key.field = 0;
10921:   key.part  = 0;
10922:   PetscCall(DMPlexComputeJacobianActionByKey(dmc, key, cellIS, 0.0, 0.0, ones, NULL, ones, locmass, NULL));
10923:   PetscCall(ISDestroy(&cellIS));
10924:   if (mass) {
10925:     PetscCall(DMLocalToGlobalBegin(dm, locmass, ADD_VALUES, *mass));
10926:     PetscCall(DMLocalToGlobalEnd(dm, locmass, ADD_VALUES, *mass));
10927:   }
10928:   PetscCall(DMRestoreLocalVector(dm, &ones));
10929:   if (lmass) *lmass = locmass;
10930:   else PetscCall(DMRestoreLocalVector(dm, &locmass));
10931:   PetscCall(DMDestroy(&dmc));
10932:   PetscFunctionReturn(PETSC_SUCCESS);
10933: }

10935: PetscErrorCode DMCreateMassMatrix_Plex(DM dmCoarse, DM dmFine, Mat *mass)
10936: {
10937:   PetscSection gsc, gsf;
10938:   PetscInt     m, n;
10939:   void        *ctx;
10940:   DM           cdm;
10941:   PetscBool    regular;

10943:   PetscFunctionBegin;
10944:   if (dmFine == dmCoarse) {
10945:     DM            dmc;
10946:     PetscDS       ds;
10947:     PetscWeakForm wf;
10948:     Vec           u;
10949:     IS            cellIS;
10950:     PetscFormKey  key;
10951:     PetscInt      depth;

10953:     PetscCall(DMClone(dmFine, &dmc));
10954:     PetscCall(DMCopyDisc(dmFine, dmc));
10955:     PetscCall(DMGetDS(dmc, &ds));
10956:     PetscCall(PetscDSGetWeakForm(ds, &wf));
10957:     PetscCall(PetscWeakFormClear(wf));
10958:     for (PetscInt f = 0; f < dmc->Nf; ++f) PetscCall(PetscDSSetJacobian(ds, f, f, g0_identity_private, NULL, NULL, NULL));
10959:     PetscCall(DMCreateMatrix(dmc, mass));
10960:     PetscCall(DMGetLocalVector(dmc, &u));
10961:     PetscCall(DMPlexGetDepth(dmc, &depth));
10962:     PetscCall(DMGetStratumIS(dmc, "depth", depth, &cellIS));
10963:     PetscCall(MatZeroEntries(*mass));
10964:     key.label = NULL;
10965:     key.value = 0;
10966:     key.field = 0;
10967:     key.part  = 0;
10968:     PetscCall(DMPlexComputeJacobianByKey(dmc, key, cellIS, 0.0, 0.0, u, NULL, *mass, *mass, NULL));
10969:     PetscCall(ISDestroy(&cellIS));
10970:     PetscCall(DMRestoreLocalVector(dmc, &u));
10971:     PetscCall(DMDestroy(&dmc));
10972:   } else {
10973:     PetscCall(DMGetGlobalSection(dmFine, &gsf));
10974:     PetscCall(PetscSectionGetConstrainedStorageSize(gsf, &m));
10975:     PetscCall(DMGetGlobalSection(dmCoarse, &gsc));
10976:     PetscCall(PetscSectionGetConstrainedStorageSize(gsc, &n));

10978:     PetscCall(MatCreate(PetscObjectComm((PetscObject)dmCoarse), mass));
10979:     PetscCall(MatSetSizes(*mass, m, n, PETSC_DETERMINE, PETSC_DETERMINE));
10980:     PetscCall(MatSetType(*mass, dmCoarse->mattype));
10981:     PetscCall(DMGetApplicationContext(dmFine, &ctx));

10983:     PetscCall(DMGetCoarseDM(dmFine, &cdm));
10984:     PetscCall(DMPlexGetRegularRefinement(dmFine, &regular));
10985:     if (regular && cdm == dmCoarse) PetscCall(DMPlexComputeMassMatrixNested(dmCoarse, dmFine, *mass, ctx));
10986:     else PetscCall(DMPlexComputeMassMatrixGeneral(dmCoarse, dmFine, *mass, ctx));
10987:   }
10988:   PetscCall(MatViewFromOptions(*mass, NULL, "-mass_mat_view"));
10989:   PetscFunctionReturn(PETSC_SUCCESS);
10990: }

10992: PetscErrorCode DMCreateGradientMatrix_Plex(DM dmc, DM dmr, Mat *derv)
10993: {
10994:   PetscSection gsc, gsf;
10995:   PetscInt     m, n;
10996:   void        *ctx;

10998:   PetscFunctionBegin;
10999:   PetscCall(DMGetGlobalSection(dmr, &gsf));
11000:   PetscCall(PetscSectionGetConstrainedStorageSize(gsf, &m));
11001:   PetscCall(DMGetGlobalSection(dmc, &gsc));
11002:   PetscCall(PetscSectionGetConstrainedStorageSize(gsc, &n));

11004:   PetscCall(MatCreate(PetscObjectComm((PetscObject)dmc), derv));
11005:   PetscCall(PetscObjectSetName((PetscObject)*derv, "Plex Derivative Matrix"));
11006:   PetscCall(MatSetSizes(*derv, m, n, PETSC_DETERMINE, PETSC_DETERMINE));
11007:   PetscCall(MatSetType(*derv, dmc->mattype));

11009:   PetscCall(DMGetApplicationContext(dmr, &ctx));
11010:   {
11011:     DM            ndmr;
11012:     PetscDS       ds;
11013:     PetscWeakForm wf;
11014:     Vec           u;
11015:     IS            cellIS;
11016:     PetscFormKey  key;
11017:     PetscInt      depth, Nf;

11019:     PetscCall(DMClone(dmr, &ndmr));
11020:     PetscCall(DMCopyDisc(dmr, ndmr));
11021:     PetscCall(DMGetDS(ndmr, &ds));
11022:     PetscCall(PetscDSGetWeakForm(ds, &wf));
11023:     PetscCall(PetscWeakFormClear(wf));
11024:     PetscCall(PetscDSGetNumFields(ds, &Nf));
11025:     for (PetscInt f = 0; f < Nf; ++f) PetscCall(PetscDSSetJacobian(ds, f, f, NULL, g1_identity_private, NULL, NULL));
11026:     PetscCall(DMGetLocalVector(ndmr, &u));
11027:     PetscCall(DMPlexGetDepth(ndmr, &depth));
11028:     PetscCall(DMGetStratumIS(ndmr, "depth", depth, &cellIS));
11029:     PetscCall(MatZeroEntries(*derv));
11030:     key.label = NULL;
11031:     key.value = 0;
11032:     key.field = 0;
11033:     key.part  = 0;
11034:     PetscCall(DMPlexComputeJacobianByKeyGeneral(ndmr, dmc, key, cellIS, 0.0, 0.0, u, NULL, *derv, *derv, NULL));
11035:     PetscCall(ISDestroy(&cellIS));
11036:     PetscCall(DMRestoreLocalVector(ndmr, &u));
11037:     PetscCall(DMDestroy(&ndmr));
11038:   }
11039:   PetscCall(MatViewFromOptions(*derv, NULL, "-gradient_mat_view"));
11040:   PetscFunctionReturn(PETSC_SUCCESS);
11041: }

11043: /*@
11044:   DMPlexGetRegularRefinement - Get the flag indicating that this mesh was obtained by regular refinement from its coarse mesh

11046:   Input Parameter:
11047: . dm - The `DMPLEX` object

11049:   Output Parameter:
11050: . regular - The flag

11052:   Level: intermediate

11054: .seealso: [](ch_unstructured), `DM`, `DMPLEX`, `DMPlexSetRegularRefinement()`
11055: @*/
11056: PetscErrorCode DMPlexGetRegularRefinement(DM dm, PetscBool *regular)
11057: {
11058:   PetscFunctionBegin;
11060:   PetscAssertPointer(regular, 2);
11061:   *regular = ((DM_Plex *)dm->data)->regularRefinement;
11062:   PetscFunctionReturn(PETSC_SUCCESS);
11063: }

11065: /*@
11066:   DMPlexSetRegularRefinement - Set the flag indicating that this mesh was obtained by regular refinement from its coarse mesh

11068:   Input Parameters:
11069: + dm      - The `DMPLEX` object
11070: - regular - The flag

11072:   Level: intermediate

11074: .seealso: [](ch_unstructured), `DM`, `DMPLEX`, `DMPlexGetRegularRefinement()`
11075: @*/
11076: PetscErrorCode DMPlexSetRegularRefinement(DM dm, PetscBool regular)
11077: {
11078:   PetscFunctionBegin;
11080:   ((DM_Plex *)dm->data)->regularRefinement = regular;
11081:   PetscFunctionReturn(PETSC_SUCCESS);
11082: }

11084: /*@
11085:   DMPlexGetAnchors - Get the layout of the anchor (point-to-point) constraints.  Typically, the user will not have to
11086:   call DMPlexGetAnchors() directly: if there are anchors, then `DMPlexGetAnchors()` is called during `DMGetDefaultConstraints()`.

11088:   Not Collective

11090:   Input Parameter:
11091: . dm - The `DMPLEX` object

11093:   Output Parameters:
11094: + anchorSection - If not `NULL`, set to the section describing which points anchor the constrained points.
11095: - anchorIS      - If not `NULL`, set to the list of anchors indexed by `anchorSection`

11097:   Level: intermediate

11099: .seealso: [](ch_unstructured), `DM`, `DMPLEX`, `DMPlexSetAnchors()`, `DMGetDefaultConstraints()`, `DMSetDefaultConstraints()`, `IS`, `PetscSection`
11100: @*/
11101: PetscErrorCode DMPlexGetAnchors(DM dm, PeOp PetscSection *anchorSection, PeOp IS *anchorIS)
11102: {
11103:   DM_Plex *plex = (DM_Plex *)dm->data;

11105:   PetscFunctionBegin;
11107:   if (!plex->anchorSection && !plex->anchorIS && plex->createanchors) PetscCall((*plex->createanchors)(dm));
11108:   if (anchorSection) *anchorSection = plex->anchorSection;
11109:   if (anchorIS) *anchorIS = plex->anchorIS;
11110:   PetscFunctionReturn(PETSC_SUCCESS);
11111: }

11113: /*@
11114:   DMPlexSetAnchors - Set the layout of the local anchor (point-to-point) constraints.

11116:   Collective

11118:   Input Parameters:
11119: + dm            - The `DMPLEX` object
11120: . anchorSection - The section that describes the mapping from constrained points to the anchor points listed in anchorIS.
11121:                   Must have a local communicator (`PETSC_COMM_SELF` or derivative).
11122: - anchorIS      - The list of all anchor points.  Must have a local communicator (`PETSC_COMM_SELF` or derivative).

11124:   Level: intermediate

11126:   Notes:
11127:   Unlike boundary conditions, when a point's degrees of freedom in a section are constrained to
11128:   an outside value, the anchor constraints set a point's degrees of freedom to be a linear
11129:   combination of other points' degrees of freedom.

11131:   After specifying the layout of constraints with `DMPlexSetAnchors()`, one specifies the constraints by calling
11132:   `DMGetDefaultConstraints()` and filling in the entries in the constraint matrix.

11134:   The reference counts of `anchorSection` and `anchorIS` are incremented.

11136: .seealso: [](ch_unstructured), `DM`, `DMPLEX`, `DMPlexGetAnchors()`, `DMGetDefaultConstraints()`, `DMSetDefaultConstraints()`
11137: @*/
11138: PetscErrorCode DMPlexSetAnchors(DM dm, PetscSection anchorSection, IS anchorIS)
11139: {
11140:   DM_Plex    *plex = (DM_Plex *)dm->data;
11141:   PetscMPIInt result;

11143:   PetscFunctionBegin;
11145:   if (anchorSection) {
11147:     PetscCallMPI(MPI_Comm_compare(PETSC_COMM_SELF, PetscObjectComm((PetscObject)anchorSection), &result));
11148:     PetscCheck(result == MPI_CONGRUENT || result == MPI_IDENT, PETSC_COMM_SELF, PETSC_ERR_ARG_NOTSAMECOMM, "anchor section must have local communicator");
11149:   }
11150:   if (anchorIS) {
11152:     PetscCallMPI(MPI_Comm_compare(PETSC_COMM_SELF, PetscObjectComm((PetscObject)anchorIS), &result));
11153:     PetscCheck(result == MPI_CONGRUENT || result == MPI_IDENT, PETSC_COMM_SELF, PETSC_ERR_ARG_NOTSAMECOMM, "anchor IS must have local communicator");
11154:   }

11156:   PetscCall(PetscObjectReference((PetscObject)anchorSection));
11157:   PetscCall(PetscSectionDestroy(&plex->anchorSection));
11158:   plex->anchorSection = anchorSection;

11160:   PetscCall(PetscObjectReference((PetscObject)anchorIS));
11161:   PetscCall(ISDestroy(&plex->anchorIS));
11162:   plex->anchorIS = anchorIS;

11164:   if (PetscUnlikelyDebug(anchorIS && anchorSection)) {
11165:     PetscInt        size, a, pStart, pEnd;
11166:     const PetscInt *anchors;

11168:     PetscCall(PetscSectionGetChart(anchorSection, &pStart, &pEnd));
11169:     PetscCall(ISGetLocalSize(anchorIS, &size));
11170:     PetscCall(ISGetIndices(anchorIS, &anchors));
11171:     for (a = 0; a < size; a++) {
11172:       PetscInt p;

11174:       p = anchors[a];
11175:       if (p >= pStart && p < pEnd) {
11176:         PetscInt dof;

11178:         PetscCall(PetscSectionGetDof(anchorSection, p, &dof));
11179:         if (dof) {
11180:           PetscCall(ISRestoreIndices(anchorIS, &anchors));
11181:           SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_INCOMP, "Point %" PetscInt_FMT " cannot be constrained and an anchor", p);
11182:         }
11183:       }
11184:     }
11185:     PetscCall(ISRestoreIndices(anchorIS, &anchors));
11186:   }
11187:   /* reset the generic constraints */
11188:   PetscCall(DMSetDefaultConstraints(dm, NULL, NULL, NULL));
11189:   PetscFunctionReturn(PETSC_SUCCESS);
11190: }

11192: static PetscErrorCode DMPlexCreateConstraintSection_Anchors(DM dm, PetscSection section, PetscSection *cSec)
11193: {
11194:   PetscSection anchorSection;
11195:   PetscInt     pStart, pEnd, sStart, sEnd, p, dof, numFields, f;

11197:   PetscFunctionBegin;
11199:   PetscCall(DMPlexGetAnchors(dm, &anchorSection, NULL));
11200:   PetscCall(PetscSectionCreate(PETSC_COMM_SELF, cSec));
11201:   PetscCall(PetscSectionGetNumFields(section, &numFields));
11202:   if (numFields) {
11203:     PetscInt f;
11204:     PetscCall(PetscSectionSetNumFields(*cSec, numFields));

11206:     for (f = 0; f < numFields; f++) {
11207:       PetscInt numComp;

11209:       PetscCall(PetscSectionGetFieldComponents(section, f, &numComp));
11210:       PetscCall(PetscSectionSetFieldComponents(*cSec, f, numComp));
11211:     }
11212:   }
11213:   PetscCall(PetscSectionGetChart(anchorSection, &pStart, &pEnd));
11214:   PetscCall(PetscSectionGetChart(section, &sStart, &sEnd));
11215:   pStart = PetscMax(pStart, sStart);
11216:   pEnd   = PetscMin(pEnd, sEnd);
11217:   pEnd   = PetscMax(pStart, pEnd);
11218:   PetscCall(PetscSectionSetChart(*cSec, pStart, pEnd));
11219:   for (p = pStart; p < pEnd; p++) {
11220:     PetscCall(PetscSectionGetDof(anchorSection, p, &dof));
11221:     if (dof) {
11222:       PetscCall(PetscSectionGetDof(section, p, &dof));
11223:       PetscCall(PetscSectionSetDof(*cSec, p, dof));
11224:       for (f = 0; f < numFields; f++) {
11225:         PetscCall(PetscSectionGetFieldDof(section, p, f, &dof));
11226:         PetscCall(PetscSectionSetFieldDof(*cSec, p, f, dof));
11227:       }
11228:     }
11229:   }
11230:   PetscCall(PetscSectionSetUp(*cSec));
11231:   PetscCall(PetscObjectSetName((PetscObject)*cSec, "Constraint Section"));
11232:   PetscFunctionReturn(PETSC_SUCCESS);
11233: }

11235: static PetscErrorCode DMPlexCreateConstraintMatrix_Anchors(DM dm, PetscSection section, PetscSection cSec, Mat *cMat)
11236: {
11237:   PetscSection    aSec;
11238:   PetscInt        pStart, pEnd, p, sStart, sEnd, dof, aDof, aOff, off, nnz, annz, m, n, q, a, offset, *i, *j;
11239:   const PetscInt *anchors;
11240:   PetscInt        numFields, f;
11241:   IS              aIS;
11242:   MatType         mtype;
11243:   PetscBool       iscuda, iskokkos;

11245:   PetscFunctionBegin;
11247:   PetscCall(PetscSectionGetStorageSize(cSec, &m));
11248:   PetscCall(PetscSectionGetStorageSize(section, &n));
11249:   PetscCall(MatCreate(PETSC_COMM_SELF, cMat));
11250:   PetscCall(MatSetSizes(*cMat, m, n, m, n));
11251:   PetscCall(PetscStrcmp(dm->mattype, MATSEQAIJCUSPARSE, &iscuda));
11252:   if (!iscuda) PetscCall(PetscStrcmp(dm->mattype, MATMPIAIJCUSPARSE, &iscuda));
11253:   PetscCall(PetscStrcmp(dm->mattype, MATSEQAIJKOKKOS, &iskokkos));
11254:   if (!iskokkos) PetscCall(PetscStrcmp(dm->mattype, MATMPIAIJKOKKOS, &iskokkos));
11255:   if (iscuda) mtype = MATSEQAIJCUSPARSE;
11256:   else if (iskokkos) mtype = MATSEQAIJKOKKOS;
11257:   else mtype = MATSEQAIJ;
11258:   PetscCall(MatSetType(*cMat, mtype));
11259:   PetscCall(DMPlexGetAnchors(dm, &aSec, &aIS));
11260:   PetscCall(ISGetIndices(aIS, &anchors));
11261:   /* cSec will be a subset of aSec and section */
11262:   PetscCall(PetscSectionGetChart(cSec, &pStart, &pEnd));
11263:   PetscCall(PetscSectionGetChart(section, &sStart, &sEnd));
11264:   PetscCall(PetscMalloc1(m + 1, &i));
11265:   i[0] = 0;
11266:   PetscCall(PetscSectionGetNumFields(section, &numFields));
11267:   for (p = pStart; p < pEnd; p++) {
11268:     PetscInt rDof, rOff, r;

11270:     PetscCall(PetscSectionGetDof(aSec, p, &rDof));
11271:     if (!rDof) continue;
11272:     PetscCall(PetscSectionGetOffset(aSec, p, &rOff));
11273:     if (numFields) {
11274:       for (f = 0; f < numFields; f++) {
11275:         annz = 0;
11276:         for (r = 0; r < rDof; r++) {
11277:           a = anchors[rOff + r];
11278:           if (a < sStart || a >= sEnd) continue;
11279:           PetscCall(PetscSectionGetFieldDof(section, a, f, &aDof));
11280:           annz += aDof;
11281:         }
11282:         PetscCall(PetscSectionGetFieldDof(cSec, p, f, &dof));
11283:         PetscCall(PetscSectionGetFieldOffset(cSec, p, f, &off));
11284:         for (q = 0; q < dof; q++) i[off + q + 1] = i[off + q] + annz;
11285:       }
11286:     } else {
11287:       annz = 0;
11288:       PetscCall(PetscSectionGetDof(cSec, p, &dof));
11289:       for (q = 0; q < dof; q++) {
11290:         a = anchors[rOff + q];
11291:         if (a < sStart || a >= sEnd) continue;
11292:         PetscCall(PetscSectionGetDof(section, a, &aDof));
11293:         annz += aDof;
11294:       }
11295:       PetscCall(PetscSectionGetDof(cSec, p, &dof));
11296:       PetscCall(PetscSectionGetOffset(cSec, p, &off));
11297:       for (q = 0; q < dof; q++) i[off + q + 1] = i[off + q] + annz;
11298:     }
11299:   }
11300:   nnz = i[m];
11301:   PetscCall(PetscMalloc1(nnz, &j));
11302:   offset = 0;
11303:   for (p = pStart; p < pEnd; p++) {
11304:     if (numFields) {
11305:       for (f = 0; f < numFields; f++) {
11306:         PetscCall(PetscSectionGetFieldDof(cSec, p, f, &dof));
11307:         for (q = 0; q < dof; q++) {
11308:           PetscInt rDof, rOff, r;
11309:           PetscCall(PetscSectionGetDof(aSec, p, &rDof));
11310:           PetscCall(PetscSectionGetOffset(aSec, p, &rOff));
11311:           for (r = 0; r < rDof; r++) {
11312:             a = anchors[rOff + r];
11313:             if (a < sStart || a >= sEnd) continue;
11314:             PetscCall(PetscSectionGetFieldDof(section, a, f, &aDof));
11315:             PetscCall(PetscSectionGetFieldOffset(section, a, f, &aOff));
11316:             for (PetscInt s = 0; s < aDof; s++) j[offset++] = aOff + s;
11317:           }
11318:         }
11319:       }
11320:     } else {
11321:       PetscCall(PetscSectionGetDof(cSec, p, &dof));
11322:       for (q = 0; q < dof; q++) {
11323:         PetscInt rDof, rOff, r;
11324:         PetscCall(PetscSectionGetDof(aSec, p, &rDof));
11325:         PetscCall(PetscSectionGetOffset(aSec, p, &rOff));
11326:         for (r = 0; r < rDof; r++) {
11327:           a = anchors[rOff + r];
11328:           if (a < sStart || a >= sEnd) continue;
11329:           PetscCall(PetscSectionGetDof(section, a, &aDof));
11330:           PetscCall(PetscSectionGetOffset(section, a, &aOff));
11331:           for (PetscInt s = 0; s < aDof; s++) j[offset++] = aOff + s;
11332:         }
11333:       }
11334:     }
11335:   }
11336:   PetscCall(MatSeqAIJSetPreallocationCSR(*cMat, i, j, NULL));
11337:   PetscCall(PetscFree(i));
11338:   PetscCall(PetscFree(j));
11339:   PetscCall(ISRestoreIndices(aIS, &anchors));
11340:   PetscFunctionReturn(PETSC_SUCCESS);
11341: }

11343: PetscErrorCode DMCreateDefaultConstraints_Plex(DM dm)
11344: {
11345:   DM_Plex     *plex = (DM_Plex *)dm->data;
11346:   PetscSection anchorSection, section, cSec;
11347:   Mat          cMat;

11349:   PetscFunctionBegin;
11351:   PetscCall(DMPlexGetAnchors(dm, &anchorSection, NULL));
11352:   if (anchorSection) {
11353:     PetscInt Nf;

11355:     PetscCall(DMGetLocalSection(dm, &section));
11356:     PetscCall(DMPlexCreateConstraintSection_Anchors(dm, section, &cSec));
11357:     PetscCall(DMPlexCreateConstraintMatrix_Anchors(dm, section, cSec, &cMat));
11358:     PetscCall(DMGetNumFields(dm, &Nf));
11359:     if (Nf && plex->computeanchormatrix) PetscCall((*plex->computeanchormatrix)(dm, section, cSec, cMat));
11360:     PetscCall(DMSetDefaultConstraints(dm, cSec, cMat, NULL));
11361:     PetscCall(PetscSectionDestroy(&cSec));
11362:     PetscCall(MatDestroy(&cMat));
11363:   }
11364:   PetscFunctionReturn(PETSC_SUCCESS);
11365: }

11367: PetscErrorCode DMCreateSubDomainDM_Plex(DM dm, DMLabel label, PetscInt value, IS *is, DM *subdm)
11368: {
11369:   IS           subis;
11370:   PetscSection section, subsection;

11372:   PetscFunctionBegin;
11373:   PetscCall(DMGetLocalSection(dm, &section));
11374:   PetscCheck(section, PetscObjectComm((PetscObject)dm), PETSC_ERR_ARG_WRONG, "Must set default section for DM before splitting subdomain");
11375:   PetscCheck(subdm, PetscObjectComm((PetscObject)dm), PETSC_ERR_ARG_WRONG, "Must set output subDM for splitting subdomain");
11376:   /* Create subdomain */
11377:   PetscCall(DMPlexFilter(dm, label, value, PETSC_FALSE, PETSC_FALSE, PetscObjectComm((PetscObject)dm), NULL, subdm));
11378:   /* Create submodel */
11379:   PetscCall(DMPlexGetSubpointIS(*subdm, &subis));
11380:   PetscCall(PetscSectionCreateSubmeshSection(section, subis, &subsection));
11381:   PetscCall(DMSetLocalSection(*subdm, subsection));
11382:   PetscCall(PetscSectionDestroy(&subsection));
11383:   PetscCall(DMCopyDisc(dm, *subdm));
11384:   /* Create map from submodel to global model */
11385:   if (is) {
11386:     PetscSection    sectionGlobal, subsectionGlobal;
11387:     IS              spIS;
11388:     const PetscInt *spmap;
11389:     PetscInt       *subIndices;
11390:     PetscInt        subSize = 0, subOff = 0, pStart, pEnd, p;
11391:     PetscInt        Nf, f, bs = -1, bsLocal[2], bsMinMax[2];

11393:     PetscCall(DMPlexGetSubpointIS(*subdm, &spIS));
11394:     PetscCall(ISGetIndices(spIS, &spmap));
11395:     PetscCall(PetscSectionGetNumFields(section, &Nf));
11396:     PetscCall(DMGetGlobalSection(dm, &sectionGlobal));
11397:     PetscCall(DMGetGlobalSection(*subdm, &subsectionGlobal));
11398:     PetscCall(PetscSectionGetChart(subsection, &pStart, &pEnd));
11399:     for (p = pStart; p < pEnd; ++p) {
11400:       PetscInt gdof, pSubSize = 0;

11402:       PetscCall(PetscSectionGetDof(sectionGlobal, p, &gdof));
11403:       if (gdof > 0) {
11404:         for (f = 0; f < Nf; ++f) {
11405:           PetscInt fdof, fcdof;

11407:           PetscCall(PetscSectionGetFieldDof(subsection, p, f, &fdof));
11408:           PetscCall(PetscSectionGetFieldConstraintDof(subsection, p, f, &fcdof));
11409:           pSubSize += fdof - fcdof;
11410:         }
11411:         subSize += pSubSize;
11412:         if (pSubSize) {
11413:           if (bs < 0) {
11414:             bs = pSubSize;
11415:           } else if (bs != pSubSize) {
11416:             /* Layout does not admit a pointwise block size */
11417:             bs = 1;
11418:           }
11419:         }
11420:       }
11421:     }
11422:     /* Must have same blocksize on all procs (some might have no points) */
11423:     bsLocal[0] = bs < 0 ? PETSC_INT_MAX : bs;
11424:     bsLocal[1] = bs;
11425:     PetscCall(PetscGlobalMinMaxInt(PetscObjectComm((PetscObject)dm), bsLocal, bsMinMax));
11426:     if (bsMinMax[0] != bsMinMax[1]) bs = 1;
11427:     else bs = bsMinMax[0];
11428:     PetscCall(PetscMalloc1(subSize, &subIndices));
11429:     for (p = pStart; p < pEnd; ++p) {
11430:       PetscInt gdof, goff;

11432:       PetscCall(PetscSectionGetDof(subsectionGlobal, p, &gdof));
11433:       if (gdof > 0) {
11434:         const PetscInt point = spmap[p];

11436:         PetscCall(PetscSectionGetOffset(sectionGlobal, point, &goff));
11437:         for (f = 0; f < Nf; ++f) {
11438:           PetscInt fdof, fcdof, fc, f2, poff = 0;

11440:           /* Can get rid of this loop by storing field information in the global section */
11441:           for (f2 = 0; f2 < f; ++f2) {
11442:             PetscCall(PetscSectionGetFieldDof(section, p, f2, &fdof));
11443:             PetscCall(PetscSectionGetFieldConstraintDof(section, p, f2, &fcdof));
11444:             poff += fdof - fcdof;
11445:           }
11446:           PetscCall(PetscSectionGetFieldDof(section, p, f, &fdof));
11447:           PetscCall(PetscSectionGetFieldConstraintDof(section, p, f, &fcdof));
11448:           for (fc = 0; fc < fdof - fcdof; ++fc, ++subOff) subIndices[subOff] = goff + poff + fc;
11449:         }
11450:       }
11451:     }
11452:     PetscCall(ISRestoreIndices(spIS, &spmap));
11453:     PetscCall(ISCreateGeneral(PetscObjectComm((PetscObject)dm), subSize, subIndices, PETSC_OWN_POINTER, is));
11454:     if (bs > 1) {
11455:       /* We need to check that the block size does not come from non-contiguous fields */
11456:       PetscInt i, j, set = 1;
11457:       for (i = 0; i < subSize; i += bs) {
11458:         for (j = 0; j < bs; ++j) {
11459:           if (subIndices[i + j] != subIndices[i] + j) {
11460:             set = 0;
11461:             break;
11462:           }
11463:         }
11464:       }
11465:       if (set) PetscCall(ISSetBlockSize(*is, bs));
11466:     }
11467:     // Attach nullspace
11468:     if (dm->nullspaceConstructors) {
11469:       for (f = 0; f < Nf; ++f) {
11470:         (*subdm)->nullspaceConstructors[f] = dm->nullspaceConstructors[f];
11471:         if ((*subdm)->nullspaceConstructors[f]) break;
11472:       }
11473:       if (f < Nf) {
11474:         MatNullSpace nullSpace;
11475:         PetscCall((*(*subdm)->nullspaceConstructors[f])(*subdm, f, f, &nullSpace));

11477:         PetscCall(PetscObjectCompose((PetscObject)*is, "nullspace", (PetscObject)nullSpace));
11478:         PetscCall(MatNullSpaceDestroy(&nullSpace));
11479:       }
11480:     }
11481:   }
11482:   PetscFunctionReturn(PETSC_SUCCESS);
11483: }

11485: /*@
11486:   DMPlexMonitorThroughput - Report the cell throughput of FE integration

11488:   Input Parameters:
11489: + dm     - The `DM`
11490: - unused - unused argument

11492:   Options Database Key:
11493: . -dm_plex_monitor_throughput - Activate the monitor

11495:   Level: developer

11497: .seealso: [](ch_unstructured), `DM`, `DMPLEX`, `DMSetFromOptions()`, `DMPlexCreate()`
11498: @*/
11499: PetscErrorCode DMPlexMonitorThroughput(DM dm, void *unused)
11500: {
11501:   PetscLogHandler default_handler;

11503:   PetscFunctionBegin;
11505:   PetscCall(PetscLogGetDefaultHandler(&default_handler));
11506:   if (default_handler) {
11507:     PetscLogEvent      event;
11508:     PetscEventPerfInfo eventInfo;
11509:     PetscLogDouble     cellRate, flopRate;
11510:     PetscInt           cStart, cEnd, Nf, N;
11511:     const char        *name;

11513:     PetscCall(PetscObjectGetName((PetscObject)dm, &name));
11514:     PetscCall(DMPlexGetHeightStratum(dm, 0, &cStart, &cEnd));
11515:     PetscCall(DMGetNumFields(dm, &Nf));
11516:     PetscCall(PetscLogEventGetId("DMPlexResidualFE", &event));
11517:     PetscCall(PetscLogEventGetPerfInfo(PETSC_DEFAULT, event, &eventInfo));
11518:     N        = (cEnd - cStart) * Nf * eventInfo.count;
11519:     flopRate = eventInfo.flops / eventInfo.time;
11520:     cellRate = N / eventInfo.time;
11521:     PetscCall(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, cellRate, flopRate / 1.e6));
11522:   } else {
11523:     SETERRQ(PetscObjectComm((PetscObject)dm), PETSC_ERR_SUP, "Plex Throughput Monitor is not supported if logging is turned off or the default log handler is not running. Reconfigure using --with-log and run with -log_view.");
11524:   }
11525:   PetscFunctionReturn(PETSC_SUCCESS);
11526: }

11528: static inline PetscInt DMPlex_GlobalID(PetscInt point)
11529: {
11530:   return point >= 0 ? point : -(point + 1);
11531: }

11533: /*
11534:    Computes the graph laplacian L at the given depth.
11535:       L = D - A, with D = degree matrix and A = adjacency matrix
11536: */
11537: static PetscErrorCode DMPlexCreateGraphLaplacian_Private(DM dm, PetscInt depth, Mat *oL)
11538: {
11539:   Mat             L, preall;
11540:   Vec             x, y;
11541:   IS              pointNumbering;
11542:   const PetscInt *pointNum;
11543:   PetscInt       *i, *j, numVertices, numEdges, shift, maxnnzrow, dim, *numDof, numFields;
11544:   PetscInt        pStart, pEnd;
11545:   PetscScalar    *vals;
11546:   PetscSection    s;

11548:   PetscFunctionBeginUser;
11549:   PetscCall(DMGetDimension(dm, &dim));
11550:   {
11551:     /* XXX this generalizes DMPlexCreatePartitionerGraph to any height and adjacency */
11552:     PetscCall(DMPlexGetDepthStratum(dm, depth, &pStart, &pEnd));
11553:     PetscCall(DMPlexCreatePointNumbering(dm, &pointNumbering));
11554:     PetscCall(ISGetIndices(pointNumbering, &pointNum));
11555:     shift = DMPlex_GlobalID(pointNum[pStart]);
11556:     PetscCallMPI(MPIU_Allreduce(MPI_IN_PLACE, &shift, 1, MPIU_INT, MPI_MIN, PetscObjectComm((PetscObject)dm)));
11557:     /* Determine sizes */
11558:     numVertices = 0;
11559:     for (PetscInt p = pStart; p < pEnd; p++) {
11560:       /* Skip non-owned cells in parallel */
11561:       if (pointNum[p] < 0) continue;
11562:       numVertices++;
11563:     }
11564:     numEdges = 0;
11565:     for (PetscInt p = pStart; p < pEnd; p++) {
11566:       PetscInt  nadj = PETSC_DETERMINE;
11567:       PetscInt *adj  = NULL;
11568:       /* Skip non-owned cells in parallel */
11569:       if (pointNum[p] < 0) continue;
11570:       PetscCall(DMPlexGetAdjacency(dm, p, &nadj, &adj));
11571:       for (PetscInt a = 0; a < nadj; a++)
11572:         if (adj[a] != p && pStart <= adj[a] && adj[a] < pEnd) numEdges++;
11573:       PetscCall(PetscFree(adj));
11574:     }
11575:     /* Determine adjacency */
11576:     PetscCall(PetscMalloc1(numVertices + 1, &i));
11577:     PetscCall(PetscMalloc1(numEdges, &j));
11578:     PetscInt iptr = 0;
11579:     i[0]          = iptr;
11580:     for (PetscInt p = pStart; p < pEnd; p++) {
11581:       PetscInt  nadj = PETSC_DETERMINE;
11582:       PetscInt *adj  = NULL;
11583:       /* Skip non-owned cells in parallel */
11584:       if (pointNum[p] < 0) continue;
11585:       PetscCall(DMPlexGetAdjacency(dm, p, &nadj, &adj));
11586:       for (PetscInt a = 0; a < nadj; a++)
11587:         if (adj[a] != p && pStart <= adj[a] && adj[a] < pEnd) j[iptr++] = DMPlex_GlobalID(pointNum[adj[a]]) - shift;
11588:       PetscCall(PetscFree(adj));
11589:       i[p - pStart + 1] = iptr;
11590:       /* Sort adjacencies (not strictly necessary) */
11591:       PetscCall(PetscSortInt(iptr - i[p - pStart], &j[i[p - pStart]]));
11592:     }
11593:     PetscCall(ISRestoreIndices(pointNumbering, &pointNum));
11594:     PetscCall(ISDestroy(&pointNumbering));
11595:   }
11596:   /* First create a matrix object */
11597:   PetscCall(MatCreate(PetscObjectComm((PetscObject)dm), &L));
11598:   PetscCall(MatSetSizes(L, numVertices, numVertices, PETSC_DECIDE, PETSC_DECIDE));
11599:   PetscCall(MatSetOptionsPrefix(L, "dm_plex_laplacian_"));
11600:   PetscCall(MatSetFromOptions(L));
11601:   /* Preallocation */
11602:   PetscCall(MatCreate(PetscObjectComm((PetscObject)dm), &preall));
11603:   PetscCall(MatSetSizes(preall, numVertices, numVertices, PETSC_DECIDE, PETSC_DECIDE));
11604:   PetscCall(MatSetType(preall, MATPREALLOCATOR));
11605:   PetscCall(MatSetUp(preall));
11606:   PetscCall(MatGetOwnershipRange(preall, &shift, NULL));
11607:   maxnnzrow = 0;
11608:   for (PetscInt k = 0; k < numVertices; k++) {
11609:     PetscInt  nnzrow = i[k + 1] - i[k];
11610:     PetscInt  row    = shift + k;
11611:     PetscInt *col    = j + i[k];
11612:     maxnnzrow        = PetscMax(maxnnzrow, nnzrow);
11613:     /* Add adjacency connection */
11614:     PetscCall(MatSetValues(preall, 1, &row, nnzrow, col, NULL, INSERT_VALUES));
11615:     /* The graph CSR does not represent self-to-self connections, we need them
11616:        for the graph laplacian */
11617:     PetscCall(MatSetValues(preall, 1, &row, 1, &row, NULL, INSERT_VALUES));
11618:   }
11619:   PetscCall(MatAssemblyBegin(preall, MAT_FINAL_ASSEMBLY));
11620:   PetscCall(MatAssemblyEnd(preall, MAT_FINAL_ASSEMBLY));
11621:   /* Preallocate the graph laplacian matrix */
11622:   PetscCall(MatPreallocatorPreallocate(preall, PETSC_TRUE, L));
11623:   PetscCall(MatDestroy(&preall));
11624:   /* Set values. We first set all values to -1.0 to obtain -A,
11625:      and then use matrix API to modify for our needs and add the diagonal D matrix */
11626:   PetscCall(PetscMalloc1(maxnnzrow, &vals));
11627:   for (PetscInt k = 0; k < maxnnzrow; k++) vals[k] = -1.0;
11628:   for (PetscInt k = 0; k < numVertices; k++) {
11629:     PetscInt  nnzrow = i[k + 1] - i[k];
11630:     PetscInt  row    = shift + k;
11631:     PetscInt *col    = j + i[k];
11632:     PetscCall(MatSetValues(L, 1, &row, nnzrow, col, vals, INSERT_VALUES));
11633:   }
11634:   PetscCall(MatAssemblyBegin(L, MAT_FINAL_ASSEMBLY));
11635:   PetscCall(MatAssemblyEnd(L, MAT_FINAL_ASSEMBLY));
11636:   /* Add D. Here we use the fact that D = rowsum(A) */
11637:   PetscCall(MatCreateVecs(L, &x, &y));
11638:   PetscCall(VecSet(x, -1.0));
11639:   PetscCall(MatMult(L, x, y));
11640:   PetscCall(MatDiagonalSet(L, y, INSERT_VALUES));
11641:   PetscCall(MatAssemblyBegin(L, MAT_FINAL_ASSEMBLY));
11642:   PetscCall(MatAssemblyEnd(L, MAT_FINAL_ASSEMBLY));
11643:   PetscCall(VecDestroy(&x));
11644:   PetscCall(VecDestroy(&y));
11645:   /* Clean up */
11646:   PetscCall(PetscFree(vals));
11647:   PetscCall(PetscFree(i));
11648:   PetscCall(PetscFree(j));
11649:   /* Allow command line view via -laplacian_view */
11650:   PetscCall(MatViewFromOptions(L, NULL, "-view"));
11651:   /*
11652:     For visualization purposes, we attach a DM to the matrix.
11653:     Cloning makes a shallow (pointer) copy of the mesh topology and geometry,
11654:     and allows us to consider different discretization spaces.
11655:     In this case, we specify a one-field discretization with a PetscSection object.
11656:   */
11657:   PetscCall(DMClone(dm, &dm));
11658:   numFields = 1;
11659:   PetscCall(DMSetNumFields(dm, numFields));
11660:   PetscCall(PetscCalloc1(dim + 1, &numDof));
11661:   numDof[depth] = 1;
11662:   PetscCall(DMPlexCreateSection(dm, NULL, &numFields, numDof, 0, NULL, NULL, NULL, NULL, &s));
11663:   PetscCall(DMSetLocalSection(dm, s));
11664:   PetscCall(PetscSectionDestroy(&s));
11665:   PetscCall(PetscFree(numDof));
11666:   /* Attach the DM to the matrix */
11667:   PetscCall(MatSetDM(L, dm));
11668:   /* the matrix holds a reference to the DM, we can decrease reference counting */
11669:   PetscCall(DMDestroy(&dm));
11670:   /* Return matrix to caller */
11671:   *oL = L;
11672:   PetscFunctionReturn(PETSC_SUCCESS);
11673: }

11675: /*@
11676:   DMPlexCreateColoring - Gets coloring of the connectivity graph of the `DMPlex` points at a given depth.

11678:   Collective

11680:   Input Parameters:
11681: + dm       - the `DMPlex` object
11682: . depth    - the dimension of the entities in the connectivity graph.
11683: - distance - the distance of the coloring (either 1 or 2).

11685:   Output Parameter:
11686: . coloring - the coloring

11688:   Level: developer

11690:   Notes:
11691:   Unlike `DMCreateColoring`, the graph used for the coloring does not represent the operator matrix associated with the discretization of a PDE on the `DM`.
11692:   Here the coloring is computed from the connectivity graph of the mesh entities.

11694:   Coloring of matrices can also be computed directly from the sparse matrix nonzero structure via the `MatColoring` object or from the mesh from which the
11695:   matrix comes from (what this function provides). In general using the mesh produces a more optimal coloring (fewer colors).

11697:   Mesh colorings are useful for additive and multiplicative Schwarz methods.
11698:   In particular, they mitigate overhead costs associated with setting up individual KSPs and PCs on many subdomains per process.
11699:   A coloring of the vertices (`depth=0`) with `distance=1` can be use can be used to group non-overlapping vertex-star patches into multi-patch subdomains.
11700:   Similarly, a vertex coloring with `distance=2` can be used to group non-overlapping Vanka patches into multi-patch subdomains.

11702: .seealso: [](ch_unstructured), `DMPlex`, `ISColoring`, `MatColoring`, `DMCreateColoring()`
11703: @*/
11704: PetscErrorCode DMPlexCreateColoring(DM dm, PetscInt depth, PetscInt distance, ISColoring *coloring)
11705: {
11706:   Mat         L        = NULL;
11707:   MatColoring mc       = NULL;
11708:   IS         *iscolors = NULL;
11709:   PetscInt    pStart = 0, offset = 0, ncolors = 0;

11711:   PetscFunctionBegin;
11712:   /* Create a graph Laplacian */
11713:   PetscCall(DMPlexCreateGraphLaplacian_Private(dm, depth, &L));
11714:   /* Compute offset */
11715:   PetscCall(MatGetOwnershipRange(L, &offset, NULL));
11716:   PetscCall(DMPlexGetDepthStratum(dm, depth, &pStart, NULL));
11717:   offset = pStart - offset;
11718:   /* Obtain ISColoring via MatColoring */
11719:   PetscCall(MatColoringCreate(L, &mc));
11720:   PetscCall(MatColoringSetType(mc, MATCOLORINGGREEDY));
11721:   PetscCall(MatColoringSetDistance(mc, distance));
11722:   PetscCall(MatColoringSetFromOptions(mc));
11723:   PetscCall(MatColoringApply(mc, coloring));
11724:   PetscCall(MatColoringDestroy(&mc));
11725:   /* Destroy the graph Laplacian */
11726:   PetscCall(MatDestroy(&L));
11727:   /* Shift ISColoring to align with the DMPlex numbering */
11728:   PetscCall(ISColoringGetIS(*coloring, PETSC_USE_POINTER, &ncolors, &iscolors));
11729:   for (PetscInt c = 0; c < ncolors; c++) {
11730:     PetscCall(ISShift(iscolors[c], offset, iscolors[c]));
11731:   }
11732:   PetscCall(ISColoringRestoreIS(*coloring, PETSC_USE_POINTER, &iscolors));
11733:   PetscFunctionReturn(PETSC_SUCCESS);
11734: }