Actual source code: plex.c

petsc-3.13.6 2020-09-29
Report Typos and Errors
  1:  #include <petsc/private/dmpleximpl.h>
  2:  #include <petsc/private/isimpl.h>
  3:  #include <petsc/private/vecimpl.h>
  4:  #include <petsc/private/glvisvecimpl.h>
  5:  #include <petscsf.h>
  6:  #include <petscds.h>
  7:  #include <petscdraw.h>
  8:  #include <petscdmfield.h>

 10: /* Logging support */
 11: PetscLogEvent DMPLEX_Interpolate, DMPLEX_Partition, DMPLEX_Distribute, DMPLEX_DistributeCones, DMPLEX_DistributeLabels, DMPLEX_DistributeSF, DMPLEX_DistributeOverlap, DMPLEX_DistributeField, DMPLEX_DistributeData, DMPLEX_Migrate, DMPLEX_InterpolateSF, DMPLEX_GlobalToNaturalBegin, DMPLEX_GlobalToNaturalEnd, DMPLEX_NaturalToGlobalBegin, DMPLEX_NaturalToGlobalEnd, DMPLEX_Stratify, DMPLEX_Symmetrize, DMPLEX_Preallocate, DMPLEX_ResidualFEM, DMPLEX_JacobianFEM, DMPLEX_InterpolatorFEM, DMPLEX_InjectorFEM, DMPLEX_IntegralFEM, DMPLEX_CreateGmsh, DMPLEX_RebalanceSharedPoints, DMPLEX_PartSelf, DMPLEX_PartLabelInvert, DMPLEX_PartLabelCreateSF, DMPLEX_PartStratSF, DMPLEX_CreatePointSF;

 13: PETSC_EXTERN PetscErrorCode VecView_MPI(Vec, PetscViewer);

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

 18:   Input Parameter:
 19: + dm     - The DMPlex object
 20: - height - The cell height in the Plex, 0 is the default

 22:   Output Parameters:
 23: + cStart - The first "normal" cell
 24: - cEnd   - The upper bound on "normal"" cells

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

 28:   Level: developer

 30: .seealso DMPlexConstructGhostCells(), DMPlexSetGhostCellStratum()
 31: @*/
 32: PetscErrorCode DMPlexGetSimplexOrBoxCells(DM dm, PetscInt height, PetscInt *cStart, PetscInt *cEnd)
 33: {
 34:   DMPolytopeType ct = DM_POLYTOPE_UNKNOWN;
 35:   PetscInt       cS, cE, c;

 39:   DMPlexGetHeightStratum(dm, PetscMax(height, 0), &cS, &cE);
 40:   for (c = cS; c < cE; ++c) {
 41:     DMPolytopeType cct;

 43:     DMPlexGetCellType(dm, c, &cct);
 44:     if ((PetscInt) cct < 0) break;
 45:     switch (cct) {
 46:       case DM_POLYTOPE_POINT:
 47:       case DM_POLYTOPE_SEGMENT:
 48:       case DM_POLYTOPE_TRIANGLE:
 49:       case DM_POLYTOPE_QUADRILATERAL:
 50:       case DM_POLYTOPE_TETRAHEDRON:
 51:       case DM_POLYTOPE_HEXAHEDRON:
 52:         ct = cct;
 53:         break;
 54:       default: break;
 55:     }
 56:     if (ct != DM_POLYTOPE_UNKNOWN) break;
 57:   }
 58:   if (ct != DM_POLYTOPE_UNKNOWN) {
 59:     DMLabel ctLabel;

 61:     DMPlexGetCellTypeLabel(dm, &ctLabel);
 62:     DMLabelGetStratumBounds(ctLabel, ct, &cS, &cE);
 63:   }
 64:   if (cStart) *cStart = cS;
 65:   if (cEnd)   *cEnd   = cE;
 66:   return(0);
 67: }

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

 76:   *ft  = PETSC_VTK_INVALID;
 77:   DMGetCoordinateDim(dm, &cdim);
 78:   DMPlexGetDepthStratum(dm, 0, &vStart, &vEnd);
 79:   DMPlexGetSimplexOrBoxCells(dm, 0, &cStart, &cEnd);
 80:   PetscSectionGetChart(section, &pStart, &pEnd);
 81:   if (field >= 0) {
 82:     if ((vStart >= pStart) && (vStart < pEnd)) {PetscSectionGetFieldDof(section, vStart, field, &vcdof[0]);}
 83:     if ((cStart >= pStart) && (cStart < pEnd)) {PetscSectionGetFieldDof(section, cStart, field, &vcdof[1]);}
 84:   } else {
 85:     if ((vStart >= pStart) && (vStart < pEnd)) {PetscSectionGetDof(section, vStart, &vcdof[0]);}
 86:     if ((cStart >= pStart) && (cStart < pEnd)) {PetscSectionGetDof(section, cStart, &vcdof[1]);}
 87:   }
 88:   MPI_Allreduce(vcdof, globalvcdof, 2, MPIU_INT, MPI_MAX, PetscObjectComm((PetscObject)dm));
 89:   if (globalvcdof[0]) {
 90:     *sStart = vStart;
 91:     *sEnd   = vEnd;
 92:     if (globalvcdof[0] == cdim) *ft = PETSC_VTK_POINT_VECTOR_FIELD;
 93:     else                        *ft = PETSC_VTK_POINT_FIELD;
 94:   } else if (globalvcdof[1]) {
 95:     *sStart = cStart;
 96:     *sEnd   = cEnd;
 97:     if (globalvcdof[1] == cdim) *ft = PETSC_VTK_CELL_VECTOR_FIELD;
 98:     else                        *ft = PETSC_VTK_CELL_FIELD;
 99:   } else {
100:     if (field >= 0) {
101:       const char *fieldname;

103:       PetscSectionGetFieldName(section, field, &fieldname);
104:       PetscInfo2((PetscObject) dm, "Could not classify VTK output type of section field %D \"%s\"\n", field, fieldname);
105:     } else {
106:       PetscInfo((PetscObject) dm, "Could not classify VTK output typp of section\"%s\"\n");
107:     }
108:   }
109:   return(0);
110: }

112: static PetscErrorCode VecView_Plex_Local_Draw(Vec v, PetscViewer viewer)
113: {
114:   DM                 dm;
115:   PetscSection       s;
116:   PetscDraw          draw, popup;
117:   DM                 cdm;
118:   PetscSection       coordSection;
119:   Vec                coordinates;
120:   const PetscScalar *coords, *array;
121:   PetscReal          bound[4] = {PETSC_MAX_REAL, PETSC_MAX_REAL, PETSC_MIN_REAL, PETSC_MIN_REAL};
122:   PetscReal          vbound[2], time;
123:   PetscBool          isnull, flg;
124:   PetscInt           dim, Nf, f, Nc, comp, vStart, vEnd, cStart, cEnd, c, N, level, step, w = 0;
125:   const char        *name;
126:   char               title[PETSC_MAX_PATH_LEN];
127:   PetscErrorCode     ierr;

130:   PetscViewerDrawGetDraw(viewer, 0, &draw);
131:   PetscDrawIsNull(draw, &isnull);
132:   if (isnull) return(0);

134:   VecGetDM(v, &dm);
135:   DMGetCoordinateDim(dm, &dim);
136:   if (dim != 2) SETERRQ1(PetscObjectComm((PetscObject) dm), PETSC_ERR_SUP, "Cannot draw meshes of dimension %D. Use PETSCVIEWERGLVIS", dim);
137:   DMGetLocalSection(dm, &s);
138:   PetscSectionGetNumFields(s, &Nf);
139:   DMGetCoarsenLevel(dm, &level);
140:   DMGetCoordinateDM(dm, &cdm);
141:   DMGetLocalSection(cdm, &coordSection);
142:   DMGetCoordinatesLocal(dm, &coordinates);
143:   DMPlexGetDepthStratum(dm, 0, &vStart, &vEnd);
144:   DMPlexGetHeightStratum(dm, 0, &cStart, &cEnd);

146:   PetscObjectGetName((PetscObject) v, &name);
147:   DMGetOutputSequenceNumber(dm, &step, &time);

149:   VecGetLocalSize(coordinates, &N);
150:   VecGetArrayRead(coordinates, &coords);
151:   for (c = 0; c < N; c += dim) {
152:     bound[0] = PetscMin(bound[0], PetscRealPart(coords[c]));   bound[2] = PetscMax(bound[2], PetscRealPart(coords[c]));
153:     bound[1] = PetscMin(bound[1], PetscRealPart(coords[c+1])); bound[3] = PetscMax(bound[3], PetscRealPart(coords[c+1]));
154:   }
155:   VecRestoreArrayRead(coordinates, &coords);
156:   PetscDrawClear(draw);

158:   /* Could implement something like DMDASelectFields() */
159:   for (f = 0; f < Nf; ++f) {
160:     DM   fdm = dm;
161:     Vec  fv  = v;
162:     IS   fis;
163:     char prefix[PETSC_MAX_PATH_LEN];
164:     const char *fname;

166:     PetscSectionGetFieldComponents(s, f, &Nc);
167:     PetscSectionGetFieldName(s, f, &fname);

169:     if (v->hdr.prefix) {PetscStrncpy(prefix, v->hdr.prefix,sizeof(prefix));}
170:     else               {prefix[0] = '\0';}
171:     if (Nf > 1) {
172:       DMCreateSubDM(dm, 1, &f, &fis, &fdm);
173:       VecGetSubVector(v, fis, &fv);
174:       PetscStrlcat(prefix, fname,sizeof(prefix));
175:       PetscStrlcat(prefix, "_",sizeof(prefix));
176:     }
177:     for (comp = 0; comp < Nc; ++comp, ++w) {
178:       PetscInt nmax = 2;

180:       PetscViewerDrawGetDraw(viewer, w, &draw);
181:       if (Nc > 1) {PetscSNPrintf(title, sizeof(title), "%s:%s_%D Step: %D Time: %.4g", name, fname, comp, step, time);}
182:       else        {PetscSNPrintf(title, sizeof(title), "%s:%s Step: %D Time: %.4g", name, fname, step, time);}
183:       PetscDrawSetTitle(draw, title);

185:       /* TODO Get max and min only for this component */
186:       PetscOptionsGetRealArray(NULL, prefix, "-vec_view_bounds", vbound, &nmax, &flg);
187:       if (!flg) {
188:         VecMin(fv, NULL, &vbound[0]);
189:         VecMax(fv, NULL, &vbound[1]);
190:         if (vbound[1] <= vbound[0]) vbound[1] = vbound[0] + 1.0;
191:       }
192:       PetscDrawGetPopup(draw, &popup);
193:       PetscDrawScalePopup(popup, vbound[0], vbound[1]);
194:       PetscDrawSetCoordinates(draw, bound[0], bound[1], bound[2], bound[3]);

196:       VecGetArrayRead(fv, &array);
197:       for (c = cStart; c < cEnd; ++c) {
198:         PetscScalar *coords = NULL, *a = NULL;
199:         PetscInt     numCoords, color[4] = {-1,-1,-1,-1};

201:         DMPlexPointLocalRead(fdm, c, array, &a);
202:         if (a) {
203:           color[0] = PetscDrawRealToColor(PetscRealPart(a[comp]), vbound[0], vbound[1]);
204:           color[1] = color[2] = color[3] = color[0];
205:         } else {
206:           PetscScalar *vals = NULL;
207:           PetscInt     numVals, va;

209:           DMPlexVecGetClosure(fdm, NULL, fv, c, &numVals, &vals);
210:           if (numVals % Nc) SETERRQ2(PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "The number of components %D does not divide the number of values in the closure %D", Nc, numVals);
211:           switch (numVals/Nc) {
212:           case 3: /* P1 Triangle */
213:           case 4: /* P1 Quadrangle */
214:             for (va = 0; va < numVals/Nc; ++va) color[va] = PetscDrawRealToColor(PetscRealPart(vals[va*Nc+comp]), vbound[0], vbound[1]);
215:             break;
216:           case 6: /* P2 Triangle */
217:           case 8: /* P2 Quadrangle */
218:             for (va = 0; va < numVals/(Nc*2); ++va) color[va] = PetscDrawRealToColor(PetscRealPart(vals[va*Nc+comp + numVals/(Nc*2)]), vbound[0], vbound[1]);
219:             break;
220:           default: SETERRQ1(PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Number of values for cell closure %D cannot be handled", numVals/Nc);
221:           }
222:           DMPlexVecRestoreClosure(fdm, NULL, fv, c, &numVals, &vals);
223:         }
224:         DMPlexVecGetClosure(dm, coordSection, coordinates, c, &numCoords, &coords);
225:         switch (numCoords) {
226:         case 6:
227:           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]);
228:           break;
229:         case 8:
230:           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]);
231:           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]);
232:           break;
233:         default: SETERRQ1(PETSC_COMM_SELF, PETSC_ERR_SUP, "Cannot draw cells with %D coordinates", numCoords);
234:         }
235:         DMPlexVecRestoreClosure(dm, coordSection, coordinates, c, &numCoords, &coords);
236:       }
237:       VecRestoreArrayRead(fv, &array);
238:       PetscDrawFlush(draw);
239:       PetscDrawPause(draw);
240:       PetscDrawSave(draw);
241:     }
242:     if (Nf > 1) {
243:       VecRestoreSubVector(v, fis, &fv);
244:       ISDestroy(&fis);
245:       DMDestroy(&fdm);
246:     }
247:   }
248:   return(0);
249: }

251: static PetscErrorCode VecView_Plex_Local_VTK(Vec v, PetscViewer viewer)
252: {
253:   DM                      dm;
254:   Vec                     locv;
255:   const char              *name;
256:   PetscSection            section;
257:   PetscInt                pStart, pEnd;
258:   PetscInt                numFields;
259:   PetscViewerVTKFieldType ft;
260:   PetscErrorCode          ierr;

263:   VecGetDM(v, &dm);
264:   DMCreateLocalVector(dm, &locv); /* VTK viewer requires exclusive ownership of the vector */
265:   PetscObjectGetName((PetscObject) v, &name);
266:   PetscObjectSetName((PetscObject) locv, name);
267:   VecCopy(v, locv);
268:   DMGetLocalSection(dm, &section);
269:   PetscSectionGetNumFields(section, &numFields);
270:   if (!numFields) {
271:     DMPlexGetFieldType_Internal(dm, section, PETSC_DETERMINE, &pStart, &pEnd, &ft);
272:     PetscViewerVTKAddField(viewer, (PetscObject) dm, DMPlexVTKWriteAll, PETSC_DEFAULT, ft, PETSC_TRUE,(PetscObject) locv);
273:   } else {
274:     PetscInt f;

276:     for (f = 0; f < numFields; f++) {
277:       DMPlexGetFieldType_Internal(dm, section, f, &pStart, &pEnd, &ft);
278:       if (ft == PETSC_VTK_INVALID) continue;
279:       PetscObjectReference((PetscObject)locv);
280:       PetscViewerVTKAddField(viewer, (PetscObject) dm, DMPlexVTKWriteAll, f, ft, PETSC_TRUE,(PetscObject) locv);
281:     }
282:     VecDestroy(&locv);
283:   }
284:   return(0);
285: }

287: PetscErrorCode VecView_Plex_Local(Vec v, PetscViewer viewer)
288: {
289:   DM             dm;
290:   PetscBool      isvtk, ishdf5, isdraw, isglvis;

294:   VecGetDM(v, &dm);
295:   if (!dm) SETERRQ(PetscObjectComm((PetscObject)v), PETSC_ERR_ARG_WRONG, "Vector not generated from a DM");
296:   PetscObjectTypeCompare((PetscObject) viewer, PETSCVIEWERVTK,   &isvtk);
297:   PetscObjectTypeCompare((PetscObject) viewer, PETSCVIEWERHDF5,  &ishdf5);
298:   PetscObjectTypeCompare((PetscObject) viewer, PETSCVIEWERDRAW,  &isdraw);
299:   PetscObjectTypeCompare((PetscObject) viewer, PETSCVIEWERGLVIS, &isglvis);
300:   if (isvtk || ishdf5 || isdraw || isglvis) {
301:     PetscInt    i,numFields;
302:     PetscObject fe;
303:     PetscBool   fem = PETSC_FALSE;
304:     Vec         locv = v;
305:     const char  *name;
306:     PetscInt    step;
307:     PetscReal   time;

309:     DMGetNumFields(dm, &numFields);
310:     for (i=0; i<numFields; i++) {
311:       DMGetField(dm, i, NULL, &fe);
312:       if (fe->classid == PETSCFE_CLASSID) { fem = PETSC_TRUE; break; }
313:     }
314:     if (fem) {
315:       DMGetLocalVector(dm, &locv);
316:       PetscObjectGetName((PetscObject) v, &name);
317:       PetscObjectSetName((PetscObject) locv, name);
318:       VecCopy(v, locv);
319:       DMGetOutputSequenceNumber(dm, NULL, &time);
320:       DMPlexInsertBoundaryValues(dm, PETSC_TRUE, locv, time, NULL, NULL, NULL);
321:     }
322:     if (isvtk) {
323:       VecView_Plex_Local_VTK(locv, viewer);
324:     } else if (ishdf5) {
325: #if defined(PETSC_HAVE_HDF5)
326:       VecView_Plex_Local_HDF5_Internal(locv, viewer);
327: #else
328:       SETERRQ(PetscObjectComm((PetscObject) dm), PETSC_ERR_SUP, "HDF5 not supported in this build.\nPlease reconfigure using --download-hdf5");
329: #endif
330:     } else if (isdraw) {
331:       VecView_Plex_Local_Draw(locv, viewer);
332:     } else if (isglvis) {
333:       DMGetOutputSequenceNumber(dm, &step, NULL);
334:       PetscViewerGLVisSetSnapId(viewer, step);
335:       VecView_GLVis(locv, viewer);
336:     }
337:     if (fem) {DMRestoreLocalVector(dm, &locv);}
338:   } else {
339:     PetscBool isseq;

341:     PetscObjectTypeCompare((PetscObject) v, VECSEQ, &isseq);
342:     if (isseq) {VecView_Seq(v, viewer);}
343:     else       {VecView_MPI(v, viewer);}
344:   }
345:   return(0);
346: }

348: PetscErrorCode VecView_Plex(Vec v, PetscViewer viewer)
349: {
350:   DM             dm;
351:   PetscBool      isvtk, ishdf5, isdraw, isglvis;

355:   VecGetDM(v, &dm);
356:   if (!dm) SETERRQ(PetscObjectComm((PetscObject)v), PETSC_ERR_ARG_WRONG, "Vector not generated from a DM");
357:   PetscObjectTypeCompare((PetscObject) viewer, PETSCVIEWERVTK,   &isvtk);
358:   PetscObjectTypeCompare((PetscObject) viewer, PETSCVIEWERHDF5,  &ishdf5);
359:   PetscObjectTypeCompare((PetscObject) viewer, PETSCVIEWERDRAW,  &isdraw);
360:   PetscObjectTypeCompare((PetscObject) viewer, PETSCVIEWERGLVIS, &isglvis);
361:   if (isvtk || isdraw || isglvis) {
362:     Vec         locv;
363:     const char *name;

365:     DMGetLocalVector(dm, &locv);
366:     PetscObjectGetName((PetscObject) v, &name);
367:     PetscObjectSetName((PetscObject) locv, name);
368:     DMGlobalToLocalBegin(dm, v, INSERT_VALUES, locv);
369:     DMGlobalToLocalEnd(dm, v, INSERT_VALUES, locv);
370:     VecView_Plex_Local(locv, viewer);
371:     DMRestoreLocalVector(dm, &locv);
372:   } else if (ishdf5) {
373: #if defined(PETSC_HAVE_HDF5)
374:     VecView_Plex_HDF5_Internal(v, viewer);
375: #else
376:     SETERRQ(PetscObjectComm((PetscObject) dm), PETSC_ERR_SUP, "HDF5 not supported in this build.\nPlease reconfigure using --download-hdf5");
377: #endif
378:   } else {
379:     PetscBool isseq;

381:     PetscObjectTypeCompare((PetscObject) v, VECSEQ, &isseq);
382:     if (isseq) {VecView_Seq(v, viewer);}
383:     else       {VecView_MPI(v, viewer);}
384:   }
385:   return(0);
386: }

388: PetscErrorCode VecView_Plex_Native(Vec originalv, PetscViewer viewer)
389: {
390:   DM                dm;
391:   MPI_Comm          comm;
392:   PetscViewerFormat format;
393:   Vec               v;
394:   PetscBool         isvtk, ishdf5;
395:   PetscErrorCode    ierr;

398:   VecGetDM(originalv, &dm);
399:   PetscObjectGetComm((PetscObject) originalv, &comm);
400:   if (!dm) SETERRQ(comm, PETSC_ERR_ARG_WRONG, "Vector not generated from a DM");
401:   PetscViewerGetFormat(viewer, &format);
402:   PetscObjectTypeCompare((PetscObject) viewer, PETSCVIEWERHDF5, &ishdf5);
403:   PetscObjectTypeCompare((PetscObject) viewer, PETSCVIEWERVTK,  &isvtk);
404:   if (format == PETSC_VIEWER_NATIVE) {
405:     /* Natural ordering is the common case for DMDA, NATIVE means plain vector, for PLEX is the opposite */
406:     /* this need a better fix */
407:     if (dm->useNatural) {
408:       if (dm->sfNatural) {
409:         const char *vecname;
410:         PetscInt    n, nroots;

412:         VecGetLocalSize(originalv, &n);
413:         PetscSFGetGraph(dm->sfNatural, &nroots, NULL, NULL, NULL);
414:         if (n == nroots) {
415:           DMGetGlobalVector(dm, &v);
416:           DMPlexGlobalToNaturalBegin(dm, originalv, v);
417:           DMPlexGlobalToNaturalEnd(dm, originalv, v);
418:           PetscObjectGetName((PetscObject) originalv, &vecname);
419:           PetscObjectSetName((PetscObject) v, vecname);
420:         } else SETERRQ(comm, PETSC_ERR_ARG_WRONG, "DM global to natural SF only handles global vectors");
421:       } else SETERRQ(comm, PETSC_ERR_ARG_WRONGSTATE, "DM global to natural SF was not created");
422:     } else v = originalv;
423:   } else v = originalv;

425:   if (ishdf5) {
426: #if defined(PETSC_HAVE_HDF5)
427:     VecView_Plex_HDF5_Native_Internal(v, viewer);
428: #else
429:     SETERRQ(comm, PETSC_ERR_SUP, "HDF5 not supported in this build.\nPlease reconfigure using --download-hdf5");
430: #endif
431:   } else if (isvtk) {
432:     SETERRQ(comm, PETSC_ERR_SUP, "VTK format does not support viewing in natural order. Please switch to HDF5.");
433:   } else {
434:     PetscBool isseq;

436:     PetscObjectTypeCompare((PetscObject) v, VECSEQ, &isseq);
437:     if (isseq) {VecView_Seq(v, viewer);}
438:     else       {VecView_MPI(v, viewer);}
439:   }
440:   if (v != originalv) {DMRestoreGlobalVector(dm, &v);}
441:   return(0);
442: }

444: PetscErrorCode VecLoad_Plex_Local(Vec v, PetscViewer viewer)
445: {
446:   DM             dm;
447:   PetscBool      ishdf5;

451:   VecGetDM(v, &dm);
452:   if (!dm) SETERRQ(PetscObjectComm((PetscObject)v), PETSC_ERR_ARG_WRONG, "Vector not generated from a DM");
453:   PetscObjectTypeCompare((PetscObject) viewer, PETSCVIEWERHDF5, &ishdf5);
454:   if (ishdf5) {
455:     DM          dmBC;
456:     Vec         gv;
457:     const char *name;

459:     DMGetOutputDM(dm, &dmBC);
460:     DMGetGlobalVector(dmBC, &gv);
461:     PetscObjectGetName((PetscObject) v, &name);
462:     PetscObjectSetName((PetscObject) gv, name);
463:     VecLoad_Default(gv, viewer);
464:     DMGlobalToLocalBegin(dmBC, gv, INSERT_VALUES, v);
465:     DMGlobalToLocalEnd(dmBC, gv, INSERT_VALUES, v);
466:     DMRestoreGlobalVector(dmBC, &gv);
467:   } else {
468:     VecLoad_Default(v, viewer);
469:   }
470:   return(0);
471: }

473: PetscErrorCode VecLoad_Plex(Vec v, PetscViewer viewer)
474: {
475:   DM             dm;
476:   PetscBool      ishdf5;

480:   VecGetDM(v, &dm);
481:   if (!dm) SETERRQ(PetscObjectComm((PetscObject)v), PETSC_ERR_ARG_WRONG, "Vector not generated from a DM");
482:   PetscObjectTypeCompare((PetscObject) viewer, PETSCVIEWERHDF5, &ishdf5);
483:   if (ishdf5) {
484: #if defined(PETSC_HAVE_HDF5)
485:     VecLoad_Plex_HDF5_Internal(v, viewer);
486: #else
487:     SETERRQ(PetscObjectComm((PetscObject) dm), PETSC_ERR_SUP, "HDF5 not supported in this build.\nPlease reconfigure using --download-hdf5");
488: #endif
489:   } else {
490:     VecLoad_Default(v, viewer);
491:   }
492:   return(0);
493: }

495: PetscErrorCode VecLoad_Plex_Native(Vec originalv, PetscViewer viewer)
496: {
497:   DM                dm;
498:   PetscViewerFormat format;
499:   PetscBool         ishdf5;
500:   PetscErrorCode    ierr;

503:   VecGetDM(originalv, &dm);
504:   if (!dm) SETERRQ(PetscObjectComm((PetscObject) originalv), PETSC_ERR_ARG_WRONG, "Vector not generated from a DM");
505:   PetscViewerGetFormat(viewer, &format);
506:   PetscObjectTypeCompare((PetscObject) viewer, PETSCVIEWERHDF5, &ishdf5);
507:   if (format == PETSC_VIEWER_NATIVE) {
508:     if (dm->useNatural) {
509:       if (dm->sfNatural) {
510:         if (ishdf5) {
511: #if defined(PETSC_HAVE_HDF5)
512:           Vec         v;
513:           const char *vecname;

515:           DMGetGlobalVector(dm, &v);
516:           PetscObjectGetName((PetscObject) originalv, &vecname);
517:           PetscObjectSetName((PetscObject) v, vecname);
518:           VecLoad_Plex_HDF5_Native_Internal(v, viewer);
519:           DMPlexNaturalToGlobalBegin(dm, v, originalv);
520:           DMPlexNaturalToGlobalEnd(dm, v, originalv);
521:           DMRestoreGlobalVector(dm, &v);
522: #else
523:           SETERRQ(PetscObjectComm((PetscObject) dm), PETSC_ERR_SUP, "HDF5 not supported in this build.\nPlease reconfigure using --download-hdf5");
524: #endif
525:         } else SETERRQ(PetscObjectComm((PetscObject) dm), PETSC_ERR_SUP, "Reading in natural order is not supported for anything but HDF5.");
526:       }
527:     } else {
528:       VecLoad_Default(originalv, viewer);
529:     }
530:   }
531:   return(0);
532: }

534: PETSC_UNUSED static PetscErrorCode DMPlexView_Ascii_Geometry(DM dm, PetscViewer viewer)
535: {
536:   PetscSection       coordSection;
537:   Vec                coordinates;
538:   DMLabel            depthLabel, celltypeLabel;
539:   const char        *name[4];
540:   const PetscScalar *a;
541:   PetscInt           dim, pStart, pEnd, cStart, cEnd, c;
542:   PetscErrorCode     ierr;

545:   DMGetDimension(dm, &dim);
546:   DMGetCoordinatesLocal(dm, &coordinates);
547:   DMGetCoordinateSection(dm, &coordSection);
548:   DMPlexGetDepthLabel(dm, &depthLabel);
549:   DMPlexGetCellTypeLabel(dm, &celltypeLabel);
550:   DMPlexGetHeightStratum(dm, 0, &cStart, &cEnd);
551:   PetscSectionGetChart(coordSection, &pStart, &pEnd);
552:   VecGetArrayRead(coordinates, &a);
553:   name[0]     = "vertex";
554:   name[1]     = "edge";
555:   name[dim-1] = "face";
556:   name[dim]   = "cell";
557:   for (c = cStart; c < cEnd; ++c) {
558:     PetscInt *closure = NULL;
559:     PetscInt  closureSize, cl, ct;

561:     DMLabelGetValue(celltypeLabel, c, &ct);
562:     PetscViewerASCIIPrintf(viewer, "Geometry for cell %D polytope type %s:\n", c, DMPolytopeTypes[ct]);
563:     DMPlexGetTransitiveClosure(dm, c, PETSC_TRUE, &closureSize, &closure);
564:     PetscViewerASCIIPushTab(viewer);
565:     for (cl = 0; cl < closureSize*2; cl += 2) {
566:       PetscInt point = closure[cl], depth, dof, off, d, p;

568:       if ((point < pStart) || (point >= pEnd)) continue;
569:       PetscSectionGetDof(coordSection, point, &dof);
570:       if (!dof) continue;
571:       DMLabelGetValue(depthLabel, point, &depth);
572:       PetscSectionGetOffset(coordSection, point, &off);
573:       PetscViewerASCIIPrintf(viewer, "%s %D coords:", name[depth], point);
574:       for (p = 0; p < dof/dim; ++p) {
575:         PetscViewerASCIIPrintf(viewer, " (");
576:         for (d = 0; d < dim; ++d) {
577:           if (d > 0) {PetscViewerASCIIPrintf(viewer, ", ");}
578:           PetscViewerASCIIPrintf(viewer, "%g", (double) PetscRealPart(a[off+p*dim+d]));
579:         }
580:         PetscViewerASCIIPrintf(viewer, ")");
581:       }
582:       PetscViewerASCIIPrintf(viewer, "\n");
583:     }
584:     DMPlexRestoreTransitiveClosure(dm, c, PETSC_TRUE, &closureSize, &closure);
585:     PetscViewerASCIIPopTab(viewer);
586:   }
587:   VecRestoreArrayRead(coordinates, &a);
588:   return(0);
589: }

591: static PetscErrorCode DMPlexView_Ascii(DM dm, PetscViewer viewer)
592: {
593:   DM_Plex          *mesh = (DM_Plex*) dm->data;
594:   DM                cdm;
595:   DMLabel           markers, celltypes;
596:   PetscSection      coordSection;
597:   Vec               coordinates;
598:   PetscViewerFormat format;
599:   PetscErrorCode    ierr;

602:   DMGetCoordinateDM(dm, &cdm);
603:   DMGetLocalSection(cdm, &coordSection);
604:   DMGetCoordinatesLocal(dm, &coordinates);
605:   PetscViewerGetFormat(viewer, &format);
606:   if (format == PETSC_VIEWER_ASCII_INFO_DETAIL) {
607:     const char *name;
608:     PetscInt    dim, cellHeight, maxConeSize, maxSupportSize;
609:     PetscInt    pStart, pEnd, p;
610:     PetscMPIInt rank, size;

612:     MPI_Comm_rank(PetscObjectComm((PetscObject)dm), &rank);
613:     MPI_Comm_size(PetscObjectComm((PetscObject)dm), &size);
614:     PetscObjectGetName((PetscObject) dm, &name);
615:     DMPlexGetChart(dm, &pStart, &pEnd);
616:     DMPlexGetMaxSizes(dm, &maxConeSize, &maxSupportSize);
617:     DMGetDimension(dm, &dim);
618:     DMPlexGetVTKCellHeight(dm, &cellHeight);
619:     if (name) {PetscViewerASCIIPrintf(viewer, "%s in %D dimension%s:\n", name, dim, dim == 1 ? "" : "s");}
620:     else      {PetscViewerASCIIPrintf(viewer, "Mesh in %D dimension%s:\n", dim, dim == 1 ? "" : "s");}
621:     if (cellHeight) {PetscViewerASCIIPrintf(viewer, "  Cells are at height %D\n", cellHeight);}
622:     PetscViewerASCIIPrintf(viewer, "Supports:\n", name);
623:     PetscViewerASCIIPushSynchronized(viewer);
624:     PetscViewerASCIISynchronizedPrintf(viewer, "[%d] Max support size: %D\n", rank, maxSupportSize);
625:     for (p = pStart; p < pEnd; ++p) {
626:       PetscInt dof, off, s;

628:       PetscSectionGetDof(mesh->supportSection, p, &dof);
629:       PetscSectionGetOffset(mesh->supportSection, p, &off);
630:       for (s = off; s < off+dof; ++s) {
631:         PetscViewerASCIISynchronizedPrintf(viewer, "[%d]: %D ----> %D\n", rank, p, mesh->supports[s]);
632:       }
633:     }
634:     PetscViewerFlush(viewer);
635:     PetscViewerASCIIPrintf(viewer, "Cones:\n", name);
636:     PetscViewerASCIISynchronizedPrintf(viewer, "[%d] Max cone size: %D\n", rank, maxConeSize);
637:     for (p = pStart; p < pEnd; ++p) {
638:       PetscInt dof, off, c;

640:       PetscSectionGetDof(mesh->coneSection, p, &dof);
641:       PetscSectionGetOffset(mesh->coneSection, p, &off);
642:       for (c = off; c < off+dof; ++c) {
643:         PetscViewerASCIISynchronizedPrintf(viewer, "[%d]: %D <---- %D (%D)\n", rank, p, mesh->cones[c], mesh->coneOrientations[c]);
644:       }
645:     }
646:     PetscViewerFlush(viewer);
647:     PetscViewerASCIIPopSynchronized(viewer);
648:     if (coordSection && coordinates) {
649:       PetscSectionVecView(coordSection, coordinates, viewer);
650:     }
651:     DMGetLabel(dm, "marker", &markers);
652:     if (markers) {DMLabelView(markers,viewer);}
653:     DMPlexGetCellTypeLabel(dm, &celltypes);
654:     if (celltypes) {DMLabelView(celltypes, viewer);}
655:     if (size > 1) {
656:       PetscSF sf;

658:       DMGetPointSF(dm, &sf);
659:       PetscSFView(sf, viewer);
660:     }
661:     PetscViewerFlush(viewer);
662:   } else if (format == PETSC_VIEWER_ASCII_LATEX) {
663:     const char  *name, *color;
664:     const char  *defcolors[3]  = {"gray", "orange", "green"};
665:     const char  *deflcolors[4] = {"blue", "cyan", "red", "magenta"};
666:     char         lname[PETSC_MAX_PATH_LEN];
667:     PetscReal    scale         = 2.0;
668:     PetscReal    tikzscale     = 1.0;
669:     PetscBool    useNumbers    = PETSC_TRUE, useLabels, useColors;
670:     double       tcoords[3];
671:     PetscScalar *coords;
672:     PetscInt     numLabels, l, numColors, numLColors, dim, depth, cStart, cEnd, c, vStart, vEnd, v, eStart = 0, eEnd = 0, e, p;
673:     PetscMPIInt  rank, size;
674:     char         **names, **colors, **lcolors;
675:     PetscBool    plotEdges, flg, lflg;
676:     PetscBT      wp = NULL;
677:     PetscInt     pEnd, pStart;

679:     DMGetDimension(dm, &dim);
680:     DMPlexGetDepth(dm, &depth);
681:     DMGetNumLabels(dm, &numLabels);
682:     numLabels  = PetscMax(numLabels, 10);
683:     numColors  = 10;
684:     numLColors = 10;
685:     PetscCalloc3(numLabels, &names, numColors, &colors, numLColors, &lcolors);
686:     PetscOptionsGetReal(((PetscObject) viewer)->options,((PetscObject) viewer)->prefix, "-dm_plex_view_scale", &scale, NULL);
687:     PetscOptionsGetReal(((PetscObject) viewer)->options,((PetscObject) viewer)->prefix, "-dm_plex_view_tikzscale", &tikzscale, NULL);
688:     PetscOptionsGetBool(((PetscObject) viewer)->options,((PetscObject) viewer)->prefix, "-dm_plex_view_numbers", &useNumbers, NULL);
689:     PetscOptionsGetStringArray(((PetscObject) viewer)->options,((PetscObject) viewer)->prefix, "-dm_plex_view_labels", names, &numLabels, &useLabels);
690:     if (!useLabels) numLabels = 0;
691:     PetscOptionsGetStringArray(((PetscObject) viewer)->options,((PetscObject) viewer)->prefix, "-dm_plex_view_colors", colors, &numColors, &useColors);
692:     if (!useColors) {
693:       numColors = 3;
694:       for (c = 0; c < numColors; ++c) {PetscStrallocpy(defcolors[c], &colors[c]);}
695:     }
696:     PetscOptionsGetStringArray(((PetscObject) viewer)->options,((PetscObject) viewer)->prefix, "-dm_plex_view_lcolors", lcolors, &numLColors, &useColors);
697:     if (!useColors) {
698:       numLColors = 4;
699:       for (c = 0; c < numLColors; ++c) {PetscStrallocpy(deflcolors[c], &lcolors[c]);}
700:     }
701:     PetscOptionsGetString(((PetscObject) viewer)->options, ((PetscObject) viewer)->prefix, "-dm_plex_view_label_filter", lname, PETSC_MAX_PATH_LEN, &lflg);
702:     plotEdges = (PetscBool)(depth > 1 && useNumbers && dim < 3);
703:     PetscOptionsGetBool(((PetscObject) viewer)->options,((PetscObject) viewer)->prefix, "-dm_plex_view_edges", &plotEdges, &flg);
704:     if (flg && plotEdges && depth < dim) SETERRQ(PetscObjectComm((PetscObject) dm), PETSC_ERR_SUP, "Mesh must be interpolated");
705:     if (depth < dim) plotEdges = PETSC_FALSE;

707:     /* filter points with labelvalue != labeldefaultvalue */
708:     DMPlexGetChart(dm, &pStart, &pEnd);
709:     if (lflg) {
710:       DMLabel lbl;

712:       DMGetLabel(dm, lname, &lbl);
713:       if (lbl) {
714:         PetscInt val, defval;

716:         DMLabelGetDefaultValue(lbl, &defval);
717:         PetscBTCreate(pEnd-pStart, &wp);
718:         for (c = pStart;  c < pEnd; c++) {
719:           PetscInt *closure = NULL;
720:           PetscInt  closureSize;

722:           DMLabelGetValue(lbl, c, &val);
723:           if (val == defval) continue;

725:           DMPlexGetTransitiveClosure(dm, c, PETSC_TRUE, &closureSize, &closure);
726:           for (p = 0; p < closureSize*2; p += 2) {
727:             PetscBTSet(wp, closure[p] - pStart);
728:           }
729:           DMPlexRestoreTransitiveClosure(dm, c, PETSC_TRUE, &closureSize, &closure);
730:         }
731:       }
732:     }

734:     MPI_Comm_rank(PetscObjectComm((PetscObject)dm), &rank);
735:     MPI_Comm_size(PetscObjectComm((PetscObject)dm), &size);
736:     PetscObjectGetName((PetscObject) dm, &name);
737:     PetscViewerASCIIPrintf(viewer, "\
738: \\documentclass[tikz]{standalone}\n\n\
739: \\usepackage{pgflibraryshapes}\n\
740: \\usetikzlibrary{backgrounds}\n\
741: \\usetikzlibrary{arrows}\n\
742: \\begin{document}\n");
743:     if (size > 1) {
744:       PetscViewerASCIIPrintf(viewer, "%s for process ", name);
745:       for (p = 0; p < size; ++p) {
746:         if (p > 0 && p == size-1) {
747:           PetscViewerASCIIPrintf(viewer, ", and ", colors[p%numColors], p);
748:         } else if (p > 0) {
749:           PetscViewerASCIIPrintf(viewer, ", ", colors[p%numColors], p);
750:         }
751:         PetscViewerASCIIPrintf(viewer, "{\\textcolor{%s}%D}", colors[p%numColors], p);
752:       }
753:       PetscViewerASCIIPrintf(viewer, ".\n\n\n");
754:     }
755:     PetscViewerASCIIPrintf(viewer, "\\begin{tikzpicture}[scale = %g,font=\\fontsize{8}{8}\\selectfont]\n", (double) tikzscale);

757:     /* Plot vertices */
758:     DMPlexGetDepthStratum(dm, 0, &vStart, &vEnd);
759:     VecGetArray(coordinates, &coords);
760:     PetscViewerASCIIPushSynchronized(viewer);
761:     for (v = vStart; v < vEnd; ++v) {
762:       PetscInt  off, dof, d;
763:       PetscBool isLabeled = PETSC_FALSE;

765:       if (wp && !PetscBTLookup(wp,v - pStart)) continue;
766:       PetscSectionGetDof(coordSection, v, &dof);
767:       PetscSectionGetOffset(coordSection, v, &off);
768:       PetscViewerASCIISynchronizedPrintf(viewer, "\\path (");
769:       if (PetscUnlikely(dof > 3)) SETERRQ2(PETSC_COMM_SELF,PETSC_ERR_PLIB,"coordSection vertex %D has dof %D > 3",v,dof);
770:       for (d = 0; d < dof; ++d) {
771:         tcoords[d] = (double) (scale*PetscRealPart(coords[off+d]));
772:         tcoords[d] = PetscAbs(tcoords[d]) < 1e-10 ? 0.0 : tcoords[d];
773:       }
774:       /* Rotate coordinates since PGF makes z point out of the page instead of up */
775:       if (dim == 3) {PetscReal tmp = tcoords[1]; tcoords[1] = tcoords[2]; tcoords[2] = -tmp;}
776:       for (d = 0; d < dof; ++d) {
777:         if (d > 0) {PetscViewerASCIISynchronizedPrintf(viewer, ",");}
778:         PetscViewerASCIISynchronizedPrintf(viewer, "%g", (double) tcoords[d]);
779:       }
780:       color = colors[rank%numColors];
781:       for (l = 0; l < numLabels; ++l) {
782:         PetscInt val;
783:         DMGetLabelValue(dm, names[l], v, &val);
784:         if (val >= 0) {color = lcolors[l%numLColors]; isLabeled = PETSC_TRUE; break;}
785:       }
786:       if (useNumbers) {
787:         PetscViewerASCIISynchronizedPrintf(viewer, ") node(%D_%d) [draw,shape=circle,color=%s] {%D};\n", v, rank, color, v);
788:       } else {
789:         PetscViewerASCIISynchronizedPrintf(viewer, ") node(%D_%d) [fill,inner sep=%dpt,shape=circle,color=%s] {};\n", v, rank, !isLabeled ? 1 : 2, color);
790:       }
791:     }
792:     VecRestoreArray(coordinates, &coords);
793:     PetscViewerFlush(viewer);
794:     /* Plot cells */
795:     DMPlexGetHeightStratum(dm, 0, &cStart, &cEnd);
796:     DMPlexGetDepthStratum(dm, 1, &eStart, &eEnd);
797:     if (dim == 3 || !useNumbers) {
798:       for (e = eStart; e < eEnd; ++e) {
799:         const PetscInt *cone;

801:         if (wp && !PetscBTLookup(wp,e - pStart)) continue;
802:         color = colors[rank%numColors];
803:         for (l = 0; l < numLabels; ++l) {
804:           PetscInt val;
805:           DMGetLabelValue(dm, names[l], e, &val);
806:           if (val >= 0) {color = lcolors[l%numLColors]; break;}
807:         }
808:         DMPlexGetCone(dm, e, &cone);
809:         PetscViewerASCIISynchronizedPrintf(viewer, "\\draw[color=%s] (%D_%d) -- (%D_%d);\n", color, cone[0], rank, cone[1], rank);
810:       }
811:     } else {
812:       for (c = cStart; c < cEnd; ++c) {
813:         PetscInt *closure = NULL;
814:         PetscInt  closureSize, firstPoint = -1;

816:         if (wp && !PetscBTLookup(wp,c - pStart)) continue;
817:         DMPlexGetTransitiveClosure(dm, c, PETSC_TRUE, &closureSize, &closure);
818:         PetscViewerASCIISynchronizedPrintf(viewer, "\\draw[color=%s] ", colors[rank%numColors]);
819:         for (p = 0; p < closureSize*2; p += 2) {
820:           const PetscInt point = closure[p];

822:           if ((point < vStart) || (point >= vEnd)) continue;
823:           if (firstPoint >= 0) {PetscViewerASCIISynchronizedPrintf(viewer, " -- ");}
824:           PetscViewerASCIISynchronizedPrintf(viewer, "(%D_%d)", point, rank);
825:           if (firstPoint < 0) firstPoint = point;
826:         }
827:         /* Why doesn't this work? PetscViewerASCIISynchronizedPrintf(viewer, " -- cycle;\n"); */
828:         PetscViewerASCIISynchronizedPrintf(viewer, " -- (%D_%d);\n", firstPoint, rank);
829:         DMPlexRestoreTransitiveClosure(dm, c, PETSC_TRUE, &closureSize, &closure);
830:       }
831:     }
832:     VecGetArray(coordinates, &coords);
833:     for (c = cStart; c < cEnd; ++c) {
834:       double    ccoords[3] = {0.0, 0.0, 0.0};
835:       PetscBool isLabeled  = PETSC_FALSE;
836:       PetscInt *closure    = NULL;
837:       PetscInt  closureSize, dof, d, n = 0;

839:       if (wp && !PetscBTLookup(wp,c - pStart)) continue;
840:       DMPlexGetTransitiveClosure(dm, c, PETSC_TRUE, &closureSize, &closure);
841:       PetscViewerASCIISynchronizedPrintf(viewer, "\\path (");
842:       for (p = 0; p < closureSize*2; p += 2) {
843:         const PetscInt point = closure[p];
844:         PetscInt       off;

846:         if ((point < vStart) || (point >= vEnd)) continue;
847:         PetscSectionGetDof(coordSection, point, &dof);
848:         PetscSectionGetOffset(coordSection, point, &off);
849:         for (d = 0; d < dof; ++d) {
850:           tcoords[d] = (double) (scale*PetscRealPart(coords[off+d]));
851:           tcoords[d] = PetscAbs(tcoords[d]) < 1e-10 ? 0.0 : tcoords[d];
852:         }
853:         /* Rotate coordinates since PGF makes z point out of the page instead of up */
854:         if (dof == 3) {PetscReal tmp = tcoords[1]; tcoords[1] = tcoords[2]; tcoords[2] = -tmp;}
855:         for (d = 0; d < dof; ++d) {ccoords[d] += tcoords[d];}
856:         ++n;
857:       }
858:       for (d = 0; d < dof; ++d) {ccoords[d] /= n;}
859:       DMPlexRestoreTransitiveClosure(dm, c, PETSC_TRUE, &closureSize, &closure);
860:       for (d = 0; d < dof; ++d) {
861:         if (d > 0) {PetscViewerASCIISynchronizedPrintf(viewer, ",");}
862:         PetscViewerASCIISynchronizedPrintf(viewer, "%g", (double) ccoords[d]);
863:       }
864:       color = colors[rank%numColors];
865:       for (l = 0; l < numLabels; ++l) {
866:         PetscInt val;
867:         DMGetLabelValue(dm, names[l], c, &val);
868:         if (val >= 0) {color = lcolors[l%numLColors]; isLabeled = PETSC_TRUE; break;}
869:       }
870:       if (useNumbers) {
871:         PetscViewerASCIISynchronizedPrintf(viewer, ") node(%D_%d) [draw,shape=circle,color=%s] {%D};\n", c, rank, color, c);
872:       } else {
873:         PetscViewerASCIISynchronizedPrintf(viewer, ") node(%D_%d) [fill,inner sep=%dpt,shape=circle,color=%s] {};\n", c, rank, !isLabeled ? 1 : 2, color);
874:       }
875:     }
876:     VecRestoreArray(coordinates, &coords);
877:     /* Plot edges */
878:     if (plotEdges) {
879:       VecGetArray(coordinates, &coords);
880:       PetscViewerASCIIPrintf(viewer, "\\path\n");
881:       for (e = eStart; e < eEnd; ++e) {
882:         const PetscInt *cone;
883:         PetscInt        coneSize, offA, offB, dof, d;

885:         if (wp && !PetscBTLookup(wp,e - pStart)) continue;
886:         DMPlexGetConeSize(dm, e, &coneSize);
887:         if (coneSize != 2) SETERRQ2(PetscObjectComm((PetscObject)dm), PETSC_ERR_ARG_WRONG, "Edge %D cone should have two vertices, not %D", e, coneSize);
888:         DMPlexGetCone(dm, e, &cone);
889:         PetscSectionGetDof(coordSection, cone[0], &dof);
890:         PetscSectionGetOffset(coordSection, cone[0], &offA);
891:         PetscSectionGetOffset(coordSection, cone[1], &offB);
892:         PetscViewerASCIISynchronizedPrintf(viewer, "(");
893:         for (d = 0; d < dof; ++d) {
894:           tcoords[d] = (double) (0.5*scale*PetscRealPart(coords[offA+d]+coords[offB+d]));
895:           tcoords[d] = PetscAbs(tcoords[d]) < 1e-10 ? 0.0 : tcoords[d];
896:         }
897:         /* Rotate coordinates since PGF makes z point out of the page instead of up */
898:         if (dim == 3) {PetscReal tmp = tcoords[1]; tcoords[1] = tcoords[2]; tcoords[2] = -tmp;}
899:         for (d = 0; d < dof; ++d) {
900:           if (d > 0) {PetscViewerASCIISynchronizedPrintf(viewer, ",");}
901:           PetscViewerASCIISynchronizedPrintf(viewer, "%g", (double)tcoords[d]);
902:         }
903:         color = colors[rank%numColors];
904:         for (l = 0; l < numLabels; ++l) {
905:           PetscInt val;
906:           DMGetLabelValue(dm, names[l], v, &val);
907:           if (val >= 0) {color = lcolors[l%numLColors]; break;}
908:         }
909:         PetscViewerASCIISynchronizedPrintf(viewer, ") node(%D_%d) [draw,shape=circle,color=%s] {%D} --\n", e, rank, color, e);
910:       }
911:       VecRestoreArray(coordinates, &coords);
912:       PetscViewerFlush(viewer);
913:       PetscViewerASCIIPrintf(viewer, "(0,0);\n");
914:     }
915:     PetscViewerFlush(viewer);
916:     PetscViewerASCIIPopSynchronized(viewer);
917:     PetscViewerASCIIPrintf(viewer, "\\end{tikzpicture}\n");
918:     PetscViewerASCIIPrintf(viewer, "\\end{document}\n", name);
919:     for (l = 0; l < numLabels;  ++l) {PetscFree(names[l]);}
920:     for (c = 0; c < numColors;  ++c) {PetscFree(colors[c]);}
921:     for (c = 0; c < numLColors; ++c) {PetscFree(lcolors[c]);}
922:     PetscFree3(names, colors, lcolors);
923:     PetscBTDestroy(&wp);
924:   } else if (format == PETSC_VIEWER_LOAD_BALANCE) {
925:     Vec                    cown,acown;
926:     VecScatter             sct;
927:     ISLocalToGlobalMapping g2l;
928:     IS                     gid,acis;
929:     MPI_Comm               comm,ncomm = MPI_COMM_NULL;
930:     MPI_Group              ggroup,ngroup;
931:     PetscScalar            *array,nid;
932:     const PetscInt         *idxs;
933:     PetscInt               *idxs2,*start,*adjacency,*work;
934:     PetscInt64             lm[3],gm[3];
935:     PetscInt               i,c,cStart,cEnd,cum,numVertices,ect,ectn,cellHeight;
936:     PetscMPIInt            d1,d2,rank;

938:     PetscObjectGetComm((PetscObject)dm,&comm);
939:     MPI_Comm_rank(comm,&rank);
940: #if defined(PETSC_HAVE_MPI_PROCESS_SHARED_MEMORY)
941:     MPI_Comm_split_type(comm,MPI_COMM_TYPE_SHARED,rank,MPI_INFO_NULL,&ncomm);
942: #endif
943:     if (ncomm != MPI_COMM_NULL) {
944:       MPI_Comm_group(comm,&ggroup);
945:       MPI_Comm_group(ncomm,&ngroup);
946:       d1   = 0;
947:       MPI_Group_translate_ranks(ngroup,1,&d1,ggroup,&d2);
948:       nid  = d2;
949:       MPI_Group_free(&ggroup);
950:       MPI_Group_free(&ngroup);
951:       MPI_Comm_free(&ncomm);
952:     } else nid = 0.0;

954:     /* Get connectivity */
955:     DMPlexGetVTKCellHeight(dm,&cellHeight);
956:     DMPlexCreatePartitionerGraph(dm,cellHeight,&numVertices,&start,&adjacency,&gid);

958:     /* filter overlapped local cells */
959:     DMPlexGetHeightStratum(dm,cellHeight,&cStart,&cEnd);
960:     ISGetIndices(gid,&idxs);
961:     ISGetLocalSize(gid,&cum);
962:     PetscMalloc1(cum,&idxs2);
963:     for (c = cStart, cum = 0; c < cEnd; c++) {
964:       if (idxs[c-cStart] < 0) continue;
965:       idxs2[cum++] = idxs[c-cStart];
966:     }
967:     ISRestoreIndices(gid,&idxs);
968:     if (numVertices != cum) SETERRQ2(PETSC_COMM_SELF,PETSC_ERR_PLIB,"Unexpected %D != %D",numVertices,cum);
969:     ISDestroy(&gid);
970:     ISCreateGeneral(comm,numVertices,idxs2,PETSC_OWN_POINTER,&gid);

972:     /* support for node-aware cell locality */
973:     ISCreateGeneral(comm,start[numVertices],adjacency,PETSC_USE_POINTER,&acis);
974:     VecCreateSeq(PETSC_COMM_SELF,start[numVertices],&acown);
975:     VecCreateMPI(comm,numVertices,PETSC_DECIDE,&cown);
976:     VecGetArray(cown,&array);
977:     for (c = 0; c < numVertices; c++) array[c] = nid;
978:     VecRestoreArray(cown,&array);
979:     VecScatterCreate(cown,acis,acown,NULL,&sct);
980:     VecScatterBegin(sct,cown,acown,INSERT_VALUES,SCATTER_FORWARD);
981:     VecScatterEnd(sct,cown,acown,INSERT_VALUES,SCATTER_FORWARD);
982:     ISDestroy(&acis);
983:     VecScatterDestroy(&sct);
984:     VecDestroy(&cown);

986:     /* compute edgeCut */
987:     for (c = 0, cum = 0; c < numVertices; c++) cum = PetscMax(cum,start[c+1]-start[c]);
988:     PetscMalloc1(cum,&work);
989:     ISLocalToGlobalMappingCreateIS(gid,&g2l);
990:     ISLocalToGlobalMappingSetType(g2l,ISLOCALTOGLOBALMAPPINGHASH);
991:     ISDestroy(&gid);
992:     VecGetArray(acown,&array);
993:     for (c = 0, ect = 0, ectn = 0; c < numVertices; c++) {
994:       PetscInt totl;

996:       totl = start[c+1]-start[c];
997:       ISGlobalToLocalMappingApply(g2l,IS_GTOLM_MASK,totl,adjacency+start[c],NULL,work);
998:       for (i = 0; i < totl; i++) {
999:         if (work[i] < 0) {
1000:           ect  += 1;
1001:           ectn += (array[i + start[c]] != nid) ? 0 : 1;
1002:         }
1003:       }
1004:     }
1005:     PetscFree(work);
1006:     VecRestoreArray(acown,&array);
1007:     lm[0] = numVertices > 0 ?  numVertices : PETSC_MAX_INT;
1008:     lm[1] = -numVertices;
1009:     MPIU_Allreduce(lm,gm,2,MPIU_INT64,MPI_MIN,comm);
1010:     PetscViewerASCIIPrintf(viewer,"  Cell balance: %.2f (max %D, min %D",-((double)gm[1])/((double)gm[0]),-(PetscInt)gm[1],(PetscInt)gm[0]);
1011:     lm[0] = ect; /* edgeCut */
1012:     lm[1] = ectn; /* node-aware edgeCut */
1013:     lm[2] = numVertices > 0 ? 0 : 1; /* empty processes */
1014:     MPIU_Allreduce(lm,gm,3,MPIU_INT64,MPI_SUM,comm);
1015:     PetscViewerASCIIPrintf(viewer,", empty %D)\n",(PetscInt)gm[2]);
1016: #if defined(PETSC_HAVE_MPI_PROCESS_SHARED_MEMORY)
1017:     PetscViewerASCIIPrintf(viewer,"  Edge Cut: %D (on node %.3f)\n",(PetscInt)(gm[0]/2),gm[0] ? ((double)(gm[1]))/((double)gm[0]) : 1.);
1018: #else
1019:     PetscViewerASCIIPrintf(viewer,"  Edge Cut: %D (on node %.3f)\n",(PetscInt)(gm[0]/2),0.0);
1020: #endif
1021:     ISLocalToGlobalMappingDestroy(&g2l);
1022:     PetscFree(start);
1023:     PetscFree(adjacency);
1024:     VecDestroy(&acown);
1025:   } else {
1026:     const char    *name;
1027:     PetscInt      *sizes, *hybsizes, *ghostsizes;
1028:     PetscInt       locDepth, depth, cellHeight, dim, d;
1029:     PetscInt       pStart, pEnd, p, gcStart, gcEnd, gcNum;
1030:     PetscInt       numLabels, l;
1031:     DMPolytopeType ct0;
1032:     MPI_Comm       comm;
1033:     PetscMPIInt    size, rank;

1035:     PetscObjectGetComm((PetscObject) dm, &comm);
1036:     MPI_Comm_size(comm, &size);
1037:     MPI_Comm_rank(comm, &rank);
1038:     DMGetDimension(dm, &dim);
1039:     DMPlexGetVTKCellHeight(dm, &cellHeight);
1040:     PetscObjectGetName((PetscObject) dm, &name);
1041:     if (name) {PetscViewerASCIIPrintf(viewer, "%s in %D dimension%s:\n", name, dim, dim == 1 ? "" : "s");}
1042:     else      {PetscViewerASCIIPrintf(viewer, "Mesh in %D dimension%s:\n", dim, dim == 1 ? "" : "s");}
1043:     if (cellHeight) {PetscViewerASCIIPrintf(viewer, "  Cells are at height %D\n", cellHeight);}
1044:     DMPlexGetDepth(dm, &locDepth);
1045:     MPIU_Allreduce(&locDepth, &depth, 1, MPIU_INT, MPI_MAX, comm);
1046:     DMPlexGetGhostCellStratum(dm, &gcStart, &gcEnd);
1047:     gcNum = gcEnd - gcStart;
1048:     PetscCalloc3(size,&sizes,size,&hybsizes,size,&ghostsizes);
1049:     for (d = 0; d <= depth; d++) {
1050:       PetscInt Nc[2] = {0, 0}, ict;

1052:       DMPlexGetDepthStratum(dm, d, &pStart, &pEnd);
1053:       DMPlexGetCellType(dm, pStart, &ct0);
1054:       ict  = ct0;
1055:       MPI_Bcast(&ict, 1, MPIU_INT, 0, comm);
1056:       ct0  = (DMPolytopeType) ict;
1057:       for (p = pStart; p < pEnd; ++p) {
1058:         DMPolytopeType ct;

1060:         DMPlexGetCellType(dm, p, &ct);
1061:         if (ct == ct0) ++Nc[0];
1062:         else           ++Nc[1];
1063:       }
1064:       MPI_Gather(&Nc[0], 1, MPIU_INT, sizes,    1, MPIU_INT, 0, comm);
1065:       MPI_Gather(&Nc[1], 1, MPIU_INT, hybsizes, 1, MPIU_INT, 0, comm);
1066:       if (d == depth) {MPI_Gather(&gcNum, 1, MPIU_INT, ghostsizes, 1, MPIU_INT, 0, comm);}
1067:       PetscViewerASCIIPrintf(viewer, "  %D-cells:", (depth == 1) && d ? dim : d);
1068:       for (p = 0; p < size; ++p) {
1069:         if (!rank) {
1070:           PetscViewerASCIIPrintf(viewer, " %D", sizes[p]+hybsizes[p]);
1071:           if (hybsizes[p]   > 0) {PetscViewerASCIIPrintf(viewer, " (%D)", hybsizes[p]);}
1072:           if (ghostsizes[p] > 0) {PetscViewerASCIIPrintf(viewer, " [%D]", ghostsizes[p]);}
1073:         }
1074:       }
1075:       PetscViewerASCIIPrintf(viewer, "\n");
1076:     }
1077:     PetscFree3(sizes,hybsizes,ghostsizes);
1078:     DMGetNumLabels(dm, &numLabels);
1079:     if (numLabels) {PetscViewerASCIIPrintf(viewer, "Labels:\n");}
1080:     for (l = 0; l < numLabels; ++l) {
1081:       DMLabel         label;
1082:       const char     *name;
1083:       IS              valueIS;
1084:       const PetscInt *values;
1085:       PetscInt        numValues, v;

1087:       DMGetLabelName(dm, l, &name);
1088:       DMGetLabel(dm, name, &label);
1089:       DMLabelGetNumValues(label, &numValues);
1090:       PetscViewerASCIIPrintf(viewer, "  %s: %D strata with value/size (", name, numValues);
1091:       DMLabelGetValueIS(label, &valueIS);
1092:       ISGetIndices(valueIS, &values);
1093:       PetscViewerASCIIUseTabs(viewer, PETSC_FALSE);
1094:       for (v = 0; v < numValues; ++v) {
1095:         PetscInt size;

1097:         DMLabelGetStratumSize(label, values[v], &size);
1098:         if (v > 0) {PetscViewerASCIIPrintf(viewer, ", ");}
1099:         PetscViewerASCIIPrintf(viewer, "%D (%D)", values[v], size);
1100:       }
1101:       PetscViewerASCIIPrintf(viewer, ")\n");
1102:       PetscViewerASCIIUseTabs(viewer, PETSC_TRUE);
1103:       ISRestoreIndices(valueIS, &values);
1104:       ISDestroy(&valueIS);
1105:     }
1106:     /* If no fields are specified, people do not want to see adjacency */
1107:     if (dm->Nf) {
1108:       PetscInt f;

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

1113:         PetscObjectGetName(dm->fields[f].disc, &name);
1114:         if (numLabels) {PetscViewerASCIIPrintf(viewer, "Field %s:\n", name);}
1115:         PetscViewerASCIIPushTab(viewer);
1116:         if (dm->fields[f].label) {DMLabelView(dm->fields[f].label, viewer);}
1117:         if (dm->fields[f].adjacency[0]) {
1118:           if (dm->fields[f].adjacency[1]) {PetscViewerASCIIPrintf(viewer, "adjacency FVM++\n");}
1119:           else                            {PetscViewerASCIIPrintf(viewer, "adjacency FVM\n");}
1120:         } else {
1121:           if (dm->fields[f].adjacency[1]) {PetscViewerASCIIPrintf(viewer, "adjacency FEM\n");}
1122:           else                            {PetscViewerASCIIPrintf(viewer, "adjacency FUNKY\n");}
1123:         }
1124:         PetscViewerASCIIPopTab(viewer);
1125:       }
1126:     }
1127:     DMGetCoarseDM(dm, &cdm);
1128:     if (cdm) {
1129:       PetscViewerASCIIPushTab(viewer);
1130:       DMPlexView_Ascii(cdm, viewer);
1131:       PetscViewerASCIIPopTab(viewer);
1132:     }
1133:   }
1134:   return(0);
1135: }

1137: static PetscErrorCode DMPlexView_Draw(DM dm, PetscViewer viewer)
1138: {
1139:   PetscDraw          draw;
1140:   DM                 cdm;
1141:   PetscSection       coordSection;
1142:   Vec                coordinates;
1143:   const PetscScalar *coords;
1144:   PetscReal          xyl[2],xyr[2],bound[4] = {PETSC_MAX_REAL, PETSC_MAX_REAL, PETSC_MIN_REAL, PETSC_MIN_REAL};
1145:   PetscBool          isnull;
1146:   PetscInt           dim, vStart, vEnd, cStart, cEnd, c, N;
1147:   PetscMPIInt        rank;
1148:   PetscErrorCode     ierr;

1151:   DMGetCoordinateDim(dm, &dim);
1152:   if (dim != 2) SETERRQ1(PetscObjectComm((PetscObject) dm), PETSC_ERR_SUP, "Cannot draw meshes of dimension %D", dim);
1153:   DMGetCoordinateDM(dm, &cdm);
1154:   DMGetLocalSection(cdm, &coordSection);
1155:   DMGetCoordinatesLocal(dm, &coordinates);
1156:   DMPlexGetDepthStratum(dm, 0, &vStart, &vEnd);
1157:   DMPlexGetHeightStratum(dm, 0, &cStart, &cEnd);

1159:   PetscViewerDrawGetDraw(viewer, 0, &draw);
1160:   PetscDrawIsNull(draw, &isnull);
1161:   if (isnull) return(0);
1162:   PetscDrawSetTitle(draw, "Mesh");

1164:   VecGetLocalSize(coordinates, &N);
1165:   VecGetArrayRead(coordinates, &coords);
1166:   for (c = 0; c < N; c += dim) {
1167:     bound[0] = PetscMin(bound[0], PetscRealPart(coords[c]));   bound[2] = PetscMax(bound[2], PetscRealPart(coords[c]));
1168:     bound[1] = PetscMin(bound[1], PetscRealPart(coords[c+1])); bound[3] = PetscMax(bound[3], PetscRealPart(coords[c+1]));
1169:   }
1170:   VecRestoreArrayRead(coordinates, &coords);
1171:   MPIU_Allreduce(&bound[0],xyl,2,MPIU_REAL,MPIU_MIN,PetscObjectComm((PetscObject)dm));
1172:   MPIU_Allreduce(&bound[2],xyr,2,MPIU_REAL,MPIU_MAX,PetscObjectComm((PetscObject)dm));
1173:   PetscDrawSetCoordinates(draw, xyl[0], xyl[1], xyr[0], xyr[1]);
1174:   PetscDrawClear(draw);

1176:   MPI_Comm_rank(PetscObjectComm((PetscObject) dm), &rank);
1177:   for (c = cStart; c < cEnd; ++c) {
1178:     PetscScalar   *coords = NULL;
1179:     DMPolytopeType ct;
1180:     PetscInt       numCoords;

1182:     DMPlexGetCellType(dm, c, &ct);
1183:     DMPlexVecGetClosure(dm, coordSection, coordinates, c, &numCoords, &coords);
1184:     switch (ct) {
1185:     case DM_POLYTOPE_TRIANGLE:
1186:       PetscDrawTriangle(draw, PetscRealPart(coords[0]), PetscRealPart(coords[1]), PetscRealPart(coords[2]), PetscRealPart(coords[3]), PetscRealPart(coords[4]), PetscRealPart(coords[5]),
1187:                                PETSC_DRAW_WHITE + rank % (PETSC_DRAW_BASIC_COLORS-2) + 2,
1188:                                PETSC_DRAW_WHITE + rank % (PETSC_DRAW_BASIC_COLORS-2) + 2,
1189:                                PETSC_DRAW_WHITE + rank % (PETSC_DRAW_BASIC_COLORS-2) + 2);
1190:       break;
1191:     case DM_POLYTOPE_QUADRILATERAL:
1192:       PetscDrawTriangle(draw, PetscRealPart(coords[0]), PetscRealPart(coords[1]), PetscRealPart(coords[2]), PetscRealPart(coords[3]), PetscRealPart(coords[4]), PetscRealPart(coords[5]),
1193:                                 PETSC_DRAW_WHITE + rank % (PETSC_DRAW_BASIC_COLORS-2) + 2,
1194:                                 PETSC_DRAW_WHITE + rank % (PETSC_DRAW_BASIC_COLORS-2) + 2,
1195:                                 PETSC_DRAW_WHITE + rank % (PETSC_DRAW_BASIC_COLORS-2) + 2);
1196:       PetscDrawTriangle(draw, PetscRealPart(coords[0]), PetscRealPart(coords[1]), PetscRealPart(coords[4]), PetscRealPart(coords[5]), PetscRealPart(coords[6]), PetscRealPart(coords[7]),
1197:                                 PETSC_DRAW_WHITE + rank % (PETSC_DRAW_BASIC_COLORS-2) + 2,
1198:                                 PETSC_DRAW_WHITE + rank % (PETSC_DRAW_BASIC_COLORS-2) + 2,
1199:                                 PETSC_DRAW_WHITE + rank % (PETSC_DRAW_BASIC_COLORS-2) + 2);
1200:       break;
1201:     default: SETERRQ1(PETSC_COMM_SELF, PETSC_ERR_SUP, "Cannot draw cells of type %s", DMPolytopeTypes[ct]);
1202:     }
1203:     DMPlexVecRestoreClosure(dm, coordSection, coordinates, c, &numCoords, &coords);
1204:   }
1205:   for (c = cStart; c < cEnd; ++c) {
1206:     PetscScalar   *coords = NULL;
1207:     DMPolytopeType ct;
1208:     PetscInt       numCoords;

1210:     DMPlexGetCellType(dm, c, &ct);
1211:     DMPlexVecGetClosure(dm, coordSection, coordinates, c, &numCoords, &coords);
1212:     switch (ct) {
1213:     case DM_POLYTOPE_TRIANGLE:
1214:       PetscDrawLine(draw, PetscRealPart(coords[0]), PetscRealPart(coords[1]), PetscRealPart(coords[2]), PetscRealPart(coords[3]), PETSC_DRAW_BLACK);
1215:       PetscDrawLine(draw, PetscRealPart(coords[2]), PetscRealPart(coords[3]), PetscRealPart(coords[4]), PetscRealPart(coords[5]), PETSC_DRAW_BLACK);
1216:       PetscDrawLine(draw, PetscRealPart(coords[4]), PetscRealPart(coords[5]), PetscRealPart(coords[0]), PetscRealPart(coords[1]), PETSC_DRAW_BLACK);
1217:       break;
1218:     case DM_POLYTOPE_QUADRILATERAL:
1219:       PetscDrawLine(draw, PetscRealPart(coords[0]), PetscRealPart(coords[1]), PetscRealPart(coords[2]), PetscRealPart(coords[3]), PETSC_DRAW_BLACK);
1220:       PetscDrawLine(draw, PetscRealPart(coords[2]), PetscRealPart(coords[3]), PetscRealPart(coords[4]), PetscRealPart(coords[5]), PETSC_DRAW_BLACK);
1221:       PetscDrawLine(draw, PetscRealPart(coords[4]), PetscRealPart(coords[5]), PetscRealPart(coords[6]), PetscRealPart(coords[7]), PETSC_DRAW_BLACK);
1222:       PetscDrawLine(draw, PetscRealPart(coords[6]), PetscRealPart(coords[7]), PetscRealPart(coords[0]), PetscRealPart(coords[1]), PETSC_DRAW_BLACK);
1223:       break;
1224:     default: SETERRQ1(PETSC_COMM_SELF, PETSC_ERR_SUP, "Cannot draw cells of type %s", DMPolytopeTypes[ct]);
1225:     }
1226:     DMPlexVecRestoreClosure(dm, coordSection, coordinates, c, &numCoords, &coords);
1227:   }
1228:   PetscDrawFlush(draw);
1229:   PetscDrawPause(draw);
1230:   PetscDrawSave(draw);
1231:   return(0);
1232: }

1234: #if defined(PETSC_HAVE_EXODUSII)
1235: #include <exodusII.h>
1236: #endif

1238: PetscErrorCode DMView_Plex(DM dm, PetscViewer viewer)
1239: {
1240:   PetscBool      iascii, ishdf5, isvtk, isdraw, flg, isglvis, isexodus;
1241:   char           name[PETSC_MAX_PATH_LEN];

1247:   PetscObjectTypeCompare((PetscObject) viewer, PETSCVIEWERASCII,    &iascii);
1248:   PetscObjectTypeCompare((PetscObject) viewer, PETSCVIEWERVTK,      &isvtk);
1249:   PetscObjectTypeCompare((PetscObject) viewer, PETSCVIEWERHDF5,     &ishdf5);
1250:   PetscObjectTypeCompare((PetscObject) viewer, PETSCVIEWERDRAW,     &isdraw);
1251:   PetscObjectTypeCompare((PetscObject) viewer, PETSCVIEWERGLVIS,    &isglvis);
1252:   PetscObjectTypeCompare((PetscObject) viewer, PETSCVIEWEREXODUSII, &isexodus);
1253:   if (iascii) {
1254:     PetscViewerFormat format;
1255:     PetscViewerGetFormat(viewer, &format);
1256:     if (format == PETSC_VIEWER_ASCII_GLVIS) {
1257:       DMPlexView_GLVis(dm, viewer);
1258:     } else {
1259:       DMPlexView_Ascii(dm, viewer);
1260:     }
1261:   } else if (ishdf5) {
1262: #if defined(PETSC_HAVE_HDF5)
1263:     DMPlexView_HDF5_Internal(dm, viewer);
1264: #else
1265:     SETERRQ(PetscObjectComm((PetscObject) dm), PETSC_ERR_SUP, "HDF5 not supported in this build.\nPlease reconfigure using --download-hdf5");
1266: #endif
1267:   } else if (isvtk) {
1268:     DMPlexVTKWriteAll((PetscObject) dm,viewer);
1269:   } else if (isdraw) {
1270:     DMPlexView_Draw(dm, viewer);
1271:   } else if (isglvis) {
1272:     DMPlexView_GLVis(dm, viewer);
1273: #if defined(PETSC_HAVE_EXODUSII)
1274:   } else if (isexodus) {
1275:     int exoid;
1276:     PetscInt cStart, cEnd, c;

1278:     DMCreateLabel(dm, "Cell Sets");
1279:     DMPlexGetHeightStratum(dm, 0, &cStart, &cEnd);
1280:     for (c = cStart; c < cEnd; ++c) {DMSetLabelValue(dm, "Cell Sets", c, 1);}
1281:     PetscViewerExodusIIGetId(viewer, &exoid);
1282:     DMPlexView_ExodusII_Internal(dm, exoid, 1);
1283: #endif
1284:   } else {
1285:     SETERRQ1(PetscObjectComm((PetscObject) dm), PETSC_ERR_SUP, "Viewer type %s not yet supported for DMPlex writing", ((PetscObject)viewer)->type_name);
1286:   }
1287:   /* Optionally view the partition */
1288:   PetscOptionsHasName(((PetscObject) dm)->options, ((PetscObject) dm)->prefix, "-dm_partition_view", &flg);
1289:   if (flg) {
1290:     Vec ranks;
1291:     DMPlexCreateRankField(dm, &ranks);
1292:     VecView(ranks, viewer);
1293:     VecDestroy(&ranks);
1294:   }
1295:   /* Optionally view a label */
1296:   PetscOptionsGetString(((PetscObject) dm)->options, ((PetscObject) dm)->prefix, "-dm_label_view", name, PETSC_MAX_PATH_LEN, &flg);
1297:   if (flg) {
1298:     DMLabel label;
1299:     Vec     val;

1301:     DMGetLabel(dm, name, &label);
1302:     if (!label) SETERRQ1(PetscObjectComm((PetscObject) dm), PETSC_ERR_ARG_WRONG, "Label %s provided to -dm_label_view does not exist in this DM", name);
1303:     DMPlexCreateLabelField(dm, label, &val);
1304:     VecView(val, viewer);
1305:     VecDestroy(&val);
1306:   }
1307:   return(0);
1308: }

1310: PetscErrorCode DMLoad_Plex(DM dm, PetscViewer viewer)
1311: {
1312:   PetscBool      ishdf5;

1318:   PetscObjectTypeCompare((PetscObject) viewer, PETSCVIEWERHDF5,   &ishdf5);
1319:   if (ishdf5) {
1320: #if defined(PETSC_HAVE_HDF5)
1321:     PetscViewerFormat format;
1322:     PetscViewerGetFormat(viewer, &format);
1323:     if (format == PETSC_VIEWER_HDF5_XDMF || format == PETSC_VIEWER_HDF5_VIZ) {
1324:       DMPlexLoad_HDF5_Xdmf_Internal(dm, viewer);
1325:     } else if (format == PETSC_VIEWER_HDF5_PETSC || format == PETSC_VIEWER_DEFAULT || format == PETSC_VIEWER_NATIVE) {
1326:       DMPlexLoad_HDF5_Internal(dm, viewer);
1327:     } else SETERRQ1(PetscObjectComm((PetscObject)dm), PETSC_ERR_SUP, "PetscViewerFormat %s not supported for HDF5 input.", PetscViewerFormats[format]);
1328: #else
1329:     SETERRQ(PetscObjectComm((PetscObject) dm), PETSC_ERR_SUP, "HDF5 not supported in this build.\nPlease reconfigure using --download-hdf5");
1330: #endif
1331:   } else {
1332:     SETERRQ1(PetscObjectComm((PetscObject) dm), PETSC_ERR_SUP, "Viewer type %s not yet supported for DMPlex loading", ((PetscObject)viewer)->type_name);
1333:   }
1334:   return(0);
1335: }

1337: PetscErrorCode DMDestroy_Plex(DM dm)
1338: {
1339:   DM_Plex       *mesh = (DM_Plex*) dm->data;

1343:   PetscObjectComposeFunction((PetscObject)dm,"DMSetUpGLVisViewer_C",NULL);
1344:   PetscObjectComposeFunction((PetscObject)dm,"DMPlexInsertBoundaryValues_C", NULL);
1345:   PetscObjectComposeFunction((PetscObject)dm,"DMCreateNeumannOverlap_C", NULL);
1346:   if (--mesh->refct > 0) return(0);
1347:   PetscSectionDestroy(&mesh->coneSection);
1348:   PetscFree(mesh->cones);
1349:   PetscFree(mesh->coneOrientations);
1350:   PetscSectionDestroy(&mesh->supportSection);
1351:   PetscSectionDestroy(&mesh->subdomainSection);
1352:   PetscFree(mesh->supports);
1353:   PetscFree(mesh->facesTmp);
1354:   PetscFree(mesh->tetgenOpts);
1355:   PetscFree(mesh->triangleOpts);
1356:   PetscPartitionerDestroy(&mesh->partitioner);
1357:   DMLabelDestroy(&mesh->subpointMap);
1358:   ISDestroy(&mesh->globalVertexNumbers);
1359:   ISDestroy(&mesh->globalCellNumbers);
1360:   PetscSectionDestroy(&mesh->anchorSection);
1361:   ISDestroy(&mesh->anchorIS);
1362:   PetscSectionDestroy(&mesh->parentSection);
1363:   PetscFree(mesh->parents);
1364:   PetscFree(mesh->childIDs);
1365:   PetscSectionDestroy(&mesh->childSection);
1366:   PetscFree(mesh->children);
1367:   DMDestroy(&mesh->referenceTree);
1368:   PetscGridHashDestroy(&mesh->lbox);
1369:   PetscFree(mesh->neighbors);
1370:   /* This was originally freed in DMDestroy(), but that prevents reference counting of backend objects */
1371:   PetscFree(mesh);
1372:   return(0);
1373: }

1375: PetscErrorCode DMCreateMatrix_Plex(DM dm, Mat *J)
1376: {
1377:   PetscSection           sectionGlobal;
1378:   PetscInt               bs = -1, mbs;
1379:   PetscInt               localSize;
1380:   PetscBool              isShell, isBlock, isSeqBlock, isMPIBlock, isSymBlock, isSymSeqBlock, isSymMPIBlock, isMatIS;
1381:   PetscErrorCode         ierr;
1382:   MatType                mtype;
1383:   ISLocalToGlobalMapping ltog;

1386:   MatInitializePackage();
1387:   mtype = dm->mattype;
1388:   DMGetGlobalSection(dm, &sectionGlobal);
1389:   /* PetscSectionGetStorageSize(sectionGlobal, &localSize); */
1390:   PetscSectionGetConstrainedStorageSize(sectionGlobal, &localSize);
1391:   MatCreate(PetscObjectComm((PetscObject)dm), J);
1392:   MatSetSizes(*J, localSize, localSize, PETSC_DETERMINE, PETSC_DETERMINE);
1393:   MatSetType(*J, mtype);
1394:   MatSetFromOptions(*J);
1395:   MatGetBlockSize(*J, &mbs);
1396:   if (mbs > 1) bs = mbs;
1397:   PetscStrcmp(mtype, MATSHELL, &isShell);
1398:   PetscStrcmp(mtype, MATBAIJ, &isBlock);
1399:   PetscStrcmp(mtype, MATSEQBAIJ, &isSeqBlock);
1400:   PetscStrcmp(mtype, MATMPIBAIJ, &isMPIBlock);
1401:   PetscStrcmp(mtype, MATSBAIJ, &isSymBlock);
1402:   PetscStrcmp(mtype, MATSEQSBAIJ, &isSymSeqBlock);
1403:   PetscStrcmp(mtype, MATMPISBAIJ, &isSymMPIBlock);
1404:   PetscStrcmp(mtype, MATIS, &isMatIS);
1405:   if (!isShell) {
1406:     PetscSection subSection;
1407:     PetscBool    fillMatrix = (PetscBool)(!dm->prealloc_only && !isMatIS);
1408:     PetscInt    *dnz, *onz, *dnzu, *onzu, bsLocal[2], bsMinMax[2], *ltogidx, lsize;
1409:     PetscInt     pStart, pEnd, p, dof, cdof;

1411:     /* Set localtoglobalmapping on the matrix for MatSetValuesLocal() to work (it also creates the local matrices in case of MATIS) */
1412:     if (isMatIS) { /* need a different l2g map than the one computed by DMGetLocalToGlobalMapping */
1413:       PetscSection section;
1414:       PetscInt     size;

1416:       DMGetLocalSection(dm, &section);
1417:       PetscSectionGetStorageSize(section, &size);
1418:       PetscMalloc1(size,&ltogidx);
1419:       DMPlexGetSubdomainSection(dm, &subSection);
1420:     } else {
1421:       DMGetLocalToGlobalMapping(dm,&ltog);
1422:     }
1423:     PetscSectionGetChart(sectionGlobal, &pStart, &pEnd);
1424:     for (p = pStart, lsize = 0; p < pEnd; ++p) {
1425:       PetscInt bdof;

1427:       PetscSectionGetDof(sectionGlobal, p, &dof);
1428:       PetscSectionGetConstraintDof(sectionGlobal, p, &cdof);
1429:       dof  = dof < 0 ? -(dof+1) : dof;
1430:       bdof = cdof && (dof-cdof) ? 1 : dof;
1431:       if (dof) {
1432:         if (bs < 0)          {bs = bdof;}
1433:         else if (bs != bdof) {bs = 1; if (!isMatIS) break;}
1434:       }
1435:       if (isMatIS) {
1436:         PetscInt loff,c,off;
1437:         PetscSectionGetOffset(subSection, p, &loff);
1438:         PetscSectionGetOffset(sectionGlobal, p, &off);
1439:         for (c = 0; c < dof-cdof; ++c, ++lsize) ltogidx[loff+c] = off > -1 ? off+c : -(off+1)+c;
1440:       }
1441:     }
1442:     /* Must have same blocksize on all procs (some might have no points) */
1443:     bsLocal[0] = bs < 0 ? PETSC_MAX_INT : bs; bsLocal[1] = bs;
1444:     PetscGlobalMinMaxInt(PetscObjectComm((PetscObject) dm), bsLocal, bsMinMax);
1445:     if (bsMinMax[0] != bsMinMax[1]) {bs = 1;}
1446:     else                            {bs = bsMinMax[0];}
1447:     bs = PetscMax(1,bs);
1448:     if (isMatIS) { /* Must reduce indices by blocksize */
1449:       PetscInt l;

1451:       lsize = lsize/bs;
1452:       if (bs > 1) for (l = 0; l < lsize; ++l) ltogidx[l] = ltogidx[l*bs]/bs;
1453:       ISLocalToGlobalMappingCreate(PetscObjectComm((PetscObject)dm), bs, lsize, ltogidx, PETSC_OWN_POINTER, &ltog);
1454:     }
1455:     MatSetLocalToGlobalMapping(*J,ltog,ltog);
1456:     if (isMatIS) {
1457:       ISLocalToGlobalMappingDestroy(&ltog);
1458:     }
1459:     PetscCalloc4(localSize/bs, &dnz, localSize/bs, &onz, localSize/bs, &dnzu, localSize/bs, &onzu);
1460:     DMPlexPreallocateOperator(dm, bs, dnz, onz, dnzu, onzu, *J, fillMatrix);
1461:     PetscFree4(dnz, onz, dnzu, onzu);
1462:   }
1463:   MatSetDM(*J, dm);
1464:   return(0);
1465: }

1467: /*@
1468:   DMPlexGetSubdomainSection - Returns the section associated with the subdomain

1470:   Not collective

1472:   Input Parameter:
1473: . mesh - The DMPlex

1475:   Output Parameters:
1476: . subsection - The subdomain section

1478:   Level: developer

1480: .seealso:
1481: @*/
1482: PetscErrorCode DMPlexGetSubdomainSection(DM dm, PetscSection *subsection)
1483: {
1484:   DM_Plex       *mesh = (DM_Plex*) dm->data;

1489:   if (!mesh->subdomainSection) {
1490:     PetscSection section;
1491:     PetscSF      sf;

1493:     PetscSFCreate(PETSC_COMM_SELF,&sf);
1494:     DMGetLocalSection(dm,&section);
1495:     PetscSectionCreateGlobalSection(section,sf,PETSC_FALSE,PETSC_TRUE,&mesh->subdomainSection);
1496:     PetscSFDestroy(&sf);
1497:   }
1498:   *subsection = mesh->subdomainSection;
1499:   return(0);
1500: }

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

1505:   Not collective

1507:   Input Parameter:
1508: . mesh - The DMPlex

1510:   Output Parameters:
1511: + pStart - The first mesh point
1512: - pEnd   - The upper bound for mesh points

1514:   Level: beginner

1516: .seealso: DMPlexCreate(), DMPlexSetChart()
1517: @*/
1518: PetscErrorCode DMPlexGetChart(DM dm, PetscInt *pStart, PetscInt *pEnd)
1519: {
1520:   DM_Plex       *mesh = (DM_Plex*) dm->data;

1525:   PetscSectionGetChart(mesh->coneSection, pStart, pEnd);
1526:   return(0);
1527: }

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

1532:   Not collective

1534:   Input Parameters:
1535: + mesh - The DMPlex
1536: . pStart - The first mesh point
1537: - pEnd   - The upper bound for mesh points

1539:   Output Parameters:

1541:   Level: beginner

1543: .seealso: DMPlexCreate(), DMPlexGetChart()
1544: @*/
1545: PetscErrorCode DMPlexSetChart(DM dm, PetscInt pStart, PetscInt pEnd)
1546: {
1547:   DM_Plex       *mesh = (DM_Plex*) dm->data;

1552:   PetscSectionSetChart(mesh->coneSection, pStart, pEnd);
1553:   PetscSectionSetChart(mesh->supportSection, pStart, pEnd);
1554:   return(0);
1555: }

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

1560:   Not collective

1562:   Input Parameters:
1563: + mesh - The DMPlex
1564: - p - The point, which must lie in the chart set with DMPlexSetChart()

1566:   Output Parameter:
1567: . size - The cone size for point p

1569:   Level: beginner

1571: .seealso: DMPlexCreate(), DMPlexSetConeSize(), DMPlexSetChart()
1572: @*/
1573: PetscErrorCode DMPlexGetConeSize(DM dm, PetscInt p, PetscInt *size)
1574: {
1575:   DM_Plex       *mesh = (DM_Plex*) dm->data;

1581:   PetscSectionGetDof(mesh->coneSection, p, size);
1582:   return(0);
1583: }

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

1588:   Not collective

1590:   Input Parameters:
1591: + mesh - The DMPlex
1592: . p - The point, which must lie in the chart set with DMPlexSetChart()
1593: - size - The cone size for point p

1595:   Output Parameter:

1597:   Note:
1598:   This should be called after DMPlexSetChart().

1600:   Level: beginner

1602: .seealso: DMPlexCreate(), DMPlexGetConeSize(), DMPlexSetChart()
1603: @*/
1604: PetscErrorCode DMPlexSetConeSize(DM dm, PetscInt p, PetscInt size)
1605: {
1606:   DM_Plex       *mesh = (DM_Plex*) dm->data;

1611:   PetscSectionSetDof(mesh->coneSection, p, size);

1613:   mesh->maxConeSize = PetscMax(mesh->maxConeSize, size);
1614:   return(0);
1615: }

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

1620:   Not collective

1622:   Input Parameters:
1623: + mesh - The DMPlex
1624: . p - The point, which must lie in the chart set with DMPlexSetChart()
1625: - size - The additional cone size for point p

1627:   Output Parameter:

1629:   Note:
1630:   This should be called after DMPlexSetChart().

1632:   Level: beginner

1634: .seealso: DMPlexCreate(), DMPlexSetConeSize(), DMPlexGetConeSize(), DMPlexSetChart()
1635: @*/
1636: PetscErrorCode DMPlexAddConeSize(DM dm, PetscInt p, PetscInt size)
1637: {
1638:   DM_Plex       *mesh = (DM_Plex*) dm->data;
1639:   PetscInt       csize;

1644:   PetscSectionAddDof(mesh->coneSection, p, size);
1645:   PetscSectionGetDof(mesh->coneSection, p, &csize);

1647:   mesh->maxConeSize = PetscMax(mesh->maxConeSize, csize);
1648:   return(0);
1649: }

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

1654:   Not collective

1656:   Input Parameters:
1657: + dm - The DMPlex
1658: - p - The point, which must lie in the chart set with DMPlexSetChart()

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

1663:   Level: beginner

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

1671: .seealso: DMPlexCreate(), DMPlexSetCone(), DMPlexGetConeTuple(), DMPlexSetChart()
1672: @*/
1673: PetscErrorCode DMPlexGetCone(DM dm, PetscInt p, const PetscInt *cone[])
1674: {
1675:   DM_Plex       *mesh = (DM_Plex*) dm->data;
1676:   PetscInt       off;

1682:   PetscSectionGetOffset(mesh->coneSection, p, &off);
1683:   *cone = &mesh->cones[off];
1684:   return(0);
1685: }

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

1690:   Not collective

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

1696:   Output Parameter:
1697: + pConesSection - PetscSection describing the layout of pCones
1698: - pCones - An array of points which are on the in-edges for the point set p

1700:   Level: intermediate

1702: .seealso: DMPlexCreate(), DMPlexGetCone(), DMPlexGetConeRecursive(), DMPlexSetChart()
1703: @*/
1704: PetscErrorCode DMPlexGetConeTuple(DM dm, IS p, PetscSection *pConesSection, IS *pCones)
1705: {
1706:   PetscSection        cs, newcs;
1707:   PetscInt            *cones;
1708:   PetscInt            *newarr=NULL;
1709:   PetscInt            n;
1710:   PetscErrorCode      ierr;

1713:   DMPlexGetCones(dm, &cones);
1714:   DMPlexGetConeSection(dm, &cs);
1715:   PetscSectionExtractDofsFromArray(cs, MPIU_INT, cones, p, &newcs, pCones ? ((void**)&newarr) : NULL);
1716:   if (pConesSection) *pConesSection = newcs;
1717:   if (pCones) {
1718:     PetscSectionGetStorageSize(newcs, &n);
1719:     ISCreateGeneral(PetscObjectComm((PetscObject)p), n, newarr, PETSC_OWN_POINTER, pCones);
1720:   }
1721:   return(0);
1722: }

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

1727:   Not collective

1729:   Input Parameters:
1730: + dm - The DMPlex
1731: - points - The IS of points, which must lie in the chart set with DMPlexSetChart()

1733:   Output Parameter:
1734: . expandedPoints - An array of vertices recursively expanded from input points

1736:   Level: advanced

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

1742: .seealso: DMPlexCreate(), DMPlexGetCone(), DMPlexGetConeTuple(), DMPlexGetConeRecursive(), DMPlexRestoreConeRecursive(), DMPlexGetDepth()
1743: @*/
1744: PetscErrorCode DMPlexGetConeRecursiveVertices(DM dm, IS points, IS *expandedPoints)
1745: {
1746:   IS                  *expandedPointsAll;
1747:   PetscInt            depth;
1748:   PetscErrorCode      ierr;

1754:   DMPlexGetConeRecursive(dm, points, &depth, &expandedPointsAll, NULL);
1755:   *expandedPoints = expandedPointsAll[0];
1756:   PetscObjectReference((PetscObject)expandedPointsAll[0]);
1757:   DMPlexRestoreConeRecursive(dm, points, &depth, &expandedPointsAll, NULL);
1758:   return(0);
1759: }

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

1764:   Not collective

1766:   Input Parameters:
1767: + dm - The DMPlex
1768: - points - The IS of points, which must lie in the chart set with DMPlexSetChart()

1770:   Output Parameter:
1771: + depth - (optional) Size of the output arrays, equal to DMPlex depth, returned by DMPlexGetDepth()
1772: . expandedPoints - (optional) An array of index sets with recursively expanded cones
1773: - sections - (optional) An array of sections which describe mappings from points to their cone points

1775:   Level: advanced

1777:   Notes:
1778:   Like DMPlexGetConeTuple() but recursive.

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

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

1787: .seealso: DMPlexCreate(), DMPlexGetCone(), DMPlexGetConeTuple(), DMPlexRestoreConeRecursive(), DMPlexGetConeRecursiveVertices(), DMPlexGetDepth()
1788: @*/
1789: PetscErrorCode DMPlexGetConeRecursive(DM dm, IS points, PetscInt *depth, IS *expandedPoints[], PetscSection *sections[])
1790: {
1791:   const PetscInt      *arr0=NULL, *cone=NULL;
1792:   PetscInt            *arr=NULL, *newarr=NULL;
1793:   PetscInt            d, depth_, i, n, newn, cn, co, start, end;
1794:   IS                  *expandedPoints_;
1795:   PetscSection        *sections_;
1796:   PetscErrorCode      ierr;

1804:   ISGetLocalSize(points, &n);
1805:   ISGetIndices(points, &arr0);
1806:   DMPlexGetDepth(dm, &depth_);
1807:   PetscCalloc1(depth_, &expandedPoints_);
1808:   PetscCalloc1(depth_, &sections_);
1809:   arr = (PetscInt*) arr0; /* this is ok because first generation of arr is not modified */
1810:   for (d=depth_-1; d>=0; d--) {
1811:     PetscSectionCreate(PETSC_COMM_SELF, &sections_[d]);
1812:     PetscSectionSetChart(sections_[d], 0, n);
1813:     for (i=0; i<n; i++) {
1814:       DMPlexGetDepthStratum(dm, d+1, &start, &end);
1815:       if (arr[i] >= start && arr[i] < end) {
1816:         DMPlexGetConeSize(dm, arr[i], &cn);
1817:         PetscSectionSetDof(sections_[d], i, cn);
1818:       } else {
1819:         PetscSectionSetDof(sections_[d], i, 1);
1820:       }
1821:     }
1822:     PetscSectionSetUp(sections_[d]);
1823:     PetscSectionGetStorageSize(sections_[d], &newn);
1824:     PetscMalloc1(newn, &newarr);
1825:     for (i=0; i<n; i++) {
1826:       PetscSectionGetDof(sections_[d], i, &cn);
1827:       PetscSectionGetOffset(sections_[d], i, &co);
1828:       if (cn > 1) {
1829:         DMPlexGetCone(dm, arr[i], &cone);
1830:         PetscMemcpy(&newarr[co], cone, cn*sizeof(PetscInt));
1831:       } else {
1832:         newarr[co] = arr[i];
1833:       }
1834:     }
1835:     ISCreateGeneral(PETSC_COMM_SELF, newn, newarr, PETSC_OWN_POINTER, &expandedPoints_[d]);
1836:     arr = newarr;
1837:     n = newn;
1838:   }
1839:   ISRestoreIndices(points, &arr0);
1840:   *depth = depth_;
1841:   if (expandedPoints) *expandedPoints = expandedPoints_;
1842:   else {
1843:     for (d=0; d<depth_; d++) {ISDestroy(&expandedPoints_[d]);}
1844:     PetscFree(expandedPoints_);
1845:   }
1846:   if (sections) *sections = sections_;
1847:   else {
1848:     for (d=0; d<depth_; d++) {PetscSectionDestroy(&sections_[d]);}
1849:     PetscFree(sections_);
1850:   }
1851:   return(0);
1852: }

1854: /*@
1855:   DMPlexRestoreConeRecursive - Deallocates arrays created by DMPlexGetConeRecursive

1857:   Not collective

1859:   Input Parameters:
1860: + dm - The DMPlex
1861: - points - The IS of points, which must lie in the chart set with DMPlexSetChart()

1863:   Output Parameter:
1864: + depth - (optional) Size of the output arrays, equal to DMPlex depth, returned by DMPlexGetDepth()
1865: . expandedPoints - (optional) An array of recursively expanded cones
1866: - sections - (optional) An array of sections which describe mappings from points to their cone points

1868:   Level: advanced

1870:   Notes:
1871:   See DMPlexGetConeRecursive() for details.

1873: .seealso: DMPlexCreate(), DMPlexGetCone(), DMPlexGetConeTuple(), DMPlexGetConeRecursive(), DMPlexGetConeRecursiveVertices(), DMPlexGetDepth()
1874: @*/
1875: PetscErrorCode DMPlexRestoreConeRecursive(DM dm, IS points, PetscInt *depth, IS *expandedPoints[], PetscSection *sections[])
1876: {
1877:   PetscInt            d, depth_;
1878:   PetscErrorCode      ierr;

1881:   DMPlexGetDepth(dm, &depth_);
1882:   if (depth && *depth != depth_) SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "depth changed since last call to DMPlexGetConeRecursive");
1883:   if (depth) *depth = 0;
1884:   if (expandedPoints) {
1885:     for (d=0; d<depth_; d++) {ISDestroy(&((*expandedPoints)[d]));}
1886:     PetscFree(*expandedPoints);
1887:   }
1888:   if (sections)  {
1889:     for (d=0; d<depth_; d++) {PetscSectionDestroy(&((*sections)[d]));}
1890:     PetscFree(*sections);
1891:   }
1892:   return(0);
1893: }

1895: /*@
1896:   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

1898:   Not collective

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

1905:   Output Parameter:

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

1910:   Developer Note: Why not call this DMPlexSetCover()

1912:   Level: beginner

1914: .seealso: DMPlexCreate(), DMPlexGetCone(), DMPlexSetChart(), DMPlexSetConeSize(), DMSetUp(), DMPlexSetSupport(), DMPlexSetSupportSize()
1915: @*/
1916: PetscErrorCode DMPlexSetCone(DM dm, PetscInt p, const PetscInt cone[])
1917: {
1918:   DM_Plex       *mesh = (DM_Plex*) dm->data;
1919:   PetscInt       pStart, pEnd;
1920:   PetscInt       dof, off, c;

1925:   PetscSectionGetChart(mesh->coneSection, &pStart, &pEnd);
1926:   PetscSectionGetDof(mesh->coneSection, p, &dof);
1928:   PetscSectionGetOffset(mesh->coneSection, p, &off);
1929:   if ((p < pStart) || (p >= pEnd)) SETERRQ3(PetscObjectComm((PetscObject)dm), PETSC_ERR_ARG_OUTOFRANGE, "Mesh point %D is not in the valid range [%D, %D)", p, pStart, pEnd);
1930:   for (c = 0; c < dof; ++c) {
1931:     if ((cone[c] < pStart) || (cone[c] >= pEnd)) SETERRQ3(PetscObjectComm((PetscObject)dm), PETSC_ERR_ARG_OUTOFRANGE, "Cone point %D is not in the valid range [%D, %D)", cone[c], pStart, pEnd);
1932:     mesh->cones[off+c] = cone[c];
1933:   }
1934:   return(0);
1935: }

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

1940:   Not collective

1942:   Input Parameters:
1943: + mesh - The DMPlex
1944: - p - The point, which must lie in the chart set with DMPlexSetChart()

1946:   Output Parameter:
1947: . coneOrientation - An array of orientations which are on the in-edges for point p. An orientation is an
1948:                     integer giving the prescription for cone traversal. If it is negative, the cone is
1949:                     traversed in the opposite direction. Its value 'o', or if negative '-(o+1)', gives
1950:                     the index of the cone point on which to start.

1952:   Level: beginner

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

1960: .seealso: DMPlexCreate(), DMPlexGetCone(), DMPlexSetCone(), DMPlexSetChart()
1961: @*/
1962: PetscErrorCode DMPlexGetConeOrientation(DM dm, PetscInt p, const PetscInt *coneOrientation[])
1963: {
1964:   DM_Plex       *mesh = (DM_Plex*) dm->data;
1965:   PetscInt       off;

1970: #if defined(PETSC_USE_DEBUG)
1971:   {
1972:     PetscInt dof;
1973:     PetscSectionGetDof(mesh->coneSection, p, &dof);
1975:   }
1976: #endif
1977:   PetscSectionGetOffset(mesh->coneSection, p, &off);

1979:   *coneOrientation = &mesh->coneOrientations[off];
1980:   return(0);
1981: }

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

1986:   Not collective

1988:   Input Parameters:
1989: + mesh - The DMPlex
1990: . p - The point, which must lie in the chart set with DMPlexSetChart()
1991: - coneOrientation - An array of orientations which are on the in-edges for point p. An orientation is an
1992:                     integer giving the prescription for cone traversal. If it is negative, the cone is
1993:                     traversed in the opposite direction. Its value 'o', or if negative '-(o+1)', gives
1994:                     the index of the cone point on which to start.

1996:   Output Parameter:

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

2001:   Level: beginner

2003: .seealso: DMPlexCreate(), DMPlexGetConeOrientation(), DMPlexSetCone(), DMPlexSetChart(), DMPlexSetConeSize(), DMSetUp()
2004: @*/
2005: PetscErrorCode DMPlexSetConeOrientation(DM dm, PetscInt p, const PetscInt coneOrientation[])
2006: {
2007:   DM_Plex       *mesh = (DM_Plex*) dm->data;
2008:   PetscInt       pStart, pEnd;
2009:   PetscInt       dof, off, c;

2014:   PetscSectionGetChart(mesh->coneSection, &pStart, &pEnd);
2015:   PetscSectionGetDof(mesh->coneSection, p, &dof);
2017:   PetscSectionGetOffset(mesh->coneSection, p, &off);
2018:   if ((p < pStart) || (p >= pEnd)) SETERRQ3(PetscObjectComm((PetscObject)dm), PETSC_ERR_ARG_OUTOFRANGE, "Mesh point %D is not in the valid range [%D, %D)", p, pStart, pEnd);
2019:   for (c = 0; c < dof; ++c) {
2020:     PetscInt cdof, o = coneOrientation[c];

2022:     PetscSectionGetDof(mesh->coneSection, mesh->cones[off+c], &cdof);
2023:     if (o && ((o < -(cdof+1)) || (o >= cdof))) SETERRQ3(PetscObjectComm((PetscObject)dm), PETSC_ERR_ARG_OUTOFRANGE, "Cone orientation %D is not in the valid range [%D. %D)", o, -(cdof+1), cdof);
2024:     mesh->coneOrientations[off+c] = o;
2025:   }
2026:   return(0);
2027: }

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

2032:   Not collective

2034:   Input Parameters:
2035: + mesh - The DMPlex
2036: . p - The point, which must lie in the chart set with DMPlexSetChart()
2037: . conePos - The local index in the cone where the point should be put
2038: - conePoint - The mesh point to insert

2040:   Level: beginner

2042: .seealso: DMPlexCreate(), DMPlexGetCone(), DMPlexSetChart(), DMPlexSetConeSize(), DMSetUp()
2043: @*/
2044: PetscErrorCode DMPlexInsertCone(DM dm, PetscInt p, PetscInt conePos, PetscInt conePoint)
2045: {
2046:   DM_Plex       *mesh = (DM_Plex*) dm->data;
2047:   PetscInt       pStart, pEnd;
2048:   PetscInt       dof, off;

2053:   PetscSectionGetChart(mesh->coneSection, &pStart, &pEnd);
2054:   if ((p < pStart) || (p >= pEnd)) SETERRQ3(PetscObjectComm((PetscObject)dm), PETSC_ERR_ARG_OUTOFRANGE, "Mesh point %D is not in the valid range [%D, %D)", p, pStart, pEnd);
2055:   if ((conePoint < pStart) || (conePoint >= pEnd)) SETERRQ3(PetscObjectComm((PetscObject)dm), PETSC_ERR_ARG_OUTOFRANGE, "Cone point %D is not in the valid range [%D, %D)", conePoint, pStart, pEnd);
2056:   PetscSectionGetDof(mesh->coneSection, p, &dof);
2057:   PetscSectionGetOffset(mesh->coneSection, p, &off);
2058:   if ((conePos < 0) || (conePos >= dof)) SETERRQ3(PetscObjectComm((PetscObject)dm), PETSC_ERR_ARG_OUTOFRANGE, "Cone position %D of point %D is not in the valid range [0, %D)", conePos, p, dof);
2059:   mesh->cones[off+conePos] = conePoint;
2060:   return(0);
2061: }

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

2066:   Not collective

2068:   Input Parameters:
2069: + mesh - The DMPlex
2070: . p - The point, which must lie in the chart set with DMPlexSetChart()
2071: . conePos - The local index in the cone where the point should be put
2072: - coneOrientation - The point orientation to insert

2074:   Level: beginner

2076: .seealso: DMPlexCreate(), DMPlexGetCone(), DMPlexSetChart(), DMPlexSetConeSize(), DMSetUp()
2077: @*/
2078: PetscErrorCode DMPlexInsertConeOrientation(DM dm, PetscInt p, PetscInt conePos, PetscInt coneOrientation)
2079: {
2080:   DM_Plex       *mesh = (DM_Plex*) dm->data;
2081:   PetscInt       pStart, pEnd;
2082:   PetscInt       dof, off;

2087:   PetscSectionGetChart(mesh->coneSection, &pStart, &pEnd);
2088:   if ((p < pStart) || (p >= pEnd)) SETERRQ3(PetscObjectComm((PetscObject)dm), PETSC_ERR_ARG_OUTOFRANGE, "Mesh point %D is not in the valid range [%D, %D)", p, pStart, pEnd);
2089:   PetscSectionGetDof(mesh->coneSection, p, &dof);
2090:   PetscSectionGetOffset(mesh->coneSection, p, &off);
2091:   if ((conePos < 0) || (conePos >= dof)) SETERRQ3(PetscObjectComm((PetscObject)dm), PETSC_ERR_ARG_OUTOFRANGE, "Cone position %D of point %D is not in the valid range [0, %D)", conePos, p, dof);
2092:   mesh->coneOrientations[off+conePos] = coneOrientation;
2093:   return(0);
2094: }

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

2099:   Not collective

2101:   Input Parameters:
2102: + mesh - The DMPlex
2103: - p - The point, which must lie in the chart set with DMPlexSetChart()

2105:   Output Parameter:
2106: . size - The support size for point p

2108:   Level: beginner

2110: .seealso: DMPlexCreate(), DMPlexSetConeSize(), DMPlexSetChart(), DMPlexGetConeSize()
2111: @*/
2112: PetscErrorCode DMPlexGetSupportSize(DM dm, PetscInt p, PetscInt *size)
2113: {
2114:   DM_Plex       *mesh = (DM_Plex*) dm->data;

2120:   PetscSectionGetDof(mesh->supportSection, p, size);
2121:   return(0);
2122: }

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

2127:   Not collective

2129:   Input Parameters:
2130: + mesh - The DMPlex
2131: . p - The point, which must lie in the chart set with DMPlexSetChart()
2132: - size - The support size for point p

2134:   Output Parameter:

2136:   Note:
2137:   This should be called after DMPlexSetChart().

2139:   Level: beginner

2141: .seealso: DMPlexCreate(), DMPlexGetSupportSize(), DMPlexSetChart()
2142: @*/
2143: PetscErrorCode DMPlexSetSupportSize(DM dm, PetscInt p, PetscInt size)
2144: {
2145:   DM_Plex       *mesh = (DM_Plex*) dm->data;

2150:   PetscSectionSetDof(mesh->supportSection, p, size);

2152:   mesh->maxSupportSize = PetscMax(mesh->maxSupportSize, size);
2153:   return(0);
2154: }

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

2159:   Not collective

2161:   Input Parameters:
2162: + mesh - The DMPlex
2163: - p - The point, which must lie in the chart set with DMPlexSetChart()

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

2168:   Level: beginner

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

2176: .seealso: DMPlexCreate(), DMPlexSetCone(), DMPlexSetChart(), DMPlexGetCone()
2177: @*/
2178: PetscErrorCode DMPlexGetSupport(DM dm, PetscInt p, const PetscInt *support[])
2179: {
2180:   DM_Plex       *mesh = (DM_Plex*) dm->data;
2181:   PetscInt       off;

2187:   PetscSectionGetOffset(mesh->supportSection, p, &off);
2188:   *support = &mesh->supports[off];
2189:   return(0);
2190: }

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

2195:   Not collective

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

2202:   Output Parameter:

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

2207:   Level: beginner

2209: .seealso: DMPlexSetCone(), DMPlexSetConeSize(), DMPlexCreate(), DMPlexGetSupport(), DMPlexSetChart(), DMPlexSetSupportSize(), DMSetUp()
2210: @*/
2211: PetscErrorCode DMPlexSetSupport(DM dm, PetscInt p, const PetscInt support[])
2212: {
2213:   DM_Plex       *mesh = (DM_Plex*) dm->data;
2214:   PetscInt       pStart, pEnd;
2215:   PetscInt       dof, off, c;

2220:   PetscSectionGetChart(mesh->supportSection, &pStart, &pEnd);
2221:   PetscSectionGetDof(mesh->supportSection, p, &dof);
2223:   PetscSectionGetOffset(mesh->supportSection, p, &off);
2224:   if ((p < pStart) || (p >= pEnd)) SETERRQ3(PetscObjectComm((PetscObject)dm), PETSC_ERR_ARG_OUTOFRANGE, "Mesh point %D is not in the valid range [%D, %D)", p, pStart, pEnd);
2225:   for (c = 0; c < dof; ++c) {
2226:     if ((support[c] < pStart) || (support[c] >= pEnd)) SETERRQ3(PetscObjectComm((PetscObject)dm), PETSC_ERR_ARG_OUTOFRANGE, "Support point %D is not in the valid range [%D, %D)", support[c], pStart, pEnd);
2227:     mesh->supports[off+c] = support[c];
2228:   }
2229:   return(0);
2230: }

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

2235:   Not collective

2237:   Input Parameters:
2238: + mesh - The DMPlex
2239: . p - The point, which must lie in the chart set with DMPlexSetChart()
2240: . supportPos - The local index in the cone where the point should be put
2241: - supportPoint - The mesh point to insert

2243:   Level: beginner

2245: .seealso: DMPlexCreate(), DMPlexGetCone(), DMPlexSetChart(), DMPlexSetConeSize(), DMSetUp()
2246: @*/
2247: PetscErrorCode DMPlexInsertSupport(DM dm, PetscInt p, PetscInt supportPos, PetscInt supportPoint)
2248: {
2249:   DM_Plex       *mesh = (DM_Plex*) dm->data;
2250:   PetscInt       pStart, pEnd;
2251:   PetscInt       dof, off;

2256:   PetscSectionGetChart(mesh->supportSection, &pStart, &pEnd);
2257:   PetscSectionGetDof(mesh->supportSection, p, &dof);
2258:   PetscSectionGetOffset(mesh->supportSection, p, &off);
2259:   if ((p < pStart) || (p >= pEnd)) SETERRQ3(PetscObjectComm((PetscObject)dm), PETSC_ERR_ARG_OUTOFRANGE, "Mesh point %D is not in the valid range [%D, %D)", p, pStart, pEnd);
2260:   if ((supportPoint < pStart) || (supportPoint >= pEnd)) SETERRQ3(PetscObjectComm((PetscObject)dm), PETSC_ERR_ARG_OUTOFRANGE, "Support point %D is not in the valid range [%D, %D)", supportPoint, pStart, pEnd);
2261:   if (supportPos >= dof) SETERRQ3(PetscObjectComm((PetscObject)dm), PETSC_ERR_ARG_OUTOFRANGE, "Support position %D of point %D is not in the valid range [0, %D)", supportPos, p, dof);
2262:   mesh->supports[off+supportPos] = supportPoint;
2263:   return(0);
2264: }

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

2269:   Not collective

2271:   Input Parameters:
2272: + mesh - The DMPlex
2273: . p - The point, which must lie in the chart set with DMPlexSetChart()
2274: . useCone - PETSC_TRUE for in-edges,  otherwise use out-edges
2275: - points - If points is NULL on input, internal storage will be returned, otherwise the provided array is used

2277:   Output Parameters:
2278: + numPoints - The number of points in the closure, so points[] is of size 2*numPoints
2279: - points - The points and point orientations, interleaved as pairs [p0, o0, p1, o1, ...]

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

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

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

2290:   Level: beginner

2292: .seealso: DMPlexRestoreTransitiveClosure(), DMPlexCreate(), DMPlexSetCone(), DMPlexSetChart(), DMPlexGetCone()
2293: @*/
2294: PetscErrorCode DMPlexGetTransitiveClosure(DM dm, PetscInt p, PetscBool useCone, PetscInt *numPoints, PetscInt *points[])
2295: {
2296:   DM_Plex        *mesh = (DM_Plex*) dm->data;
2297:   PetscInt       *closure, *fifo;
2298:   const PetscInt *tmp = NULL, *tmpO = NULL;
2299:   PetscInt        tmpSize, t;
2300:   PetscInt        depth       = 0, maxSize;
2301:   PetscInt        closureSize = 2, fifoSize = 0, fifoStart = 0;
2302:   PetscErrorCode  ierr;

2306:   DMPlexGetDepth(dm, &depth);
2307:   /* This is only 1-level */
2308:   if (useCone) {
2309:     DMPlexGetConeSize(dm, p, &tmpSize);
2310:     DMPlexGetCone(dm, p, &tmp);
2311:     DMPlexGetConeOrientation(dm, p, &tmpO);
2312:   } else {
2313:     DMPlexGetSupportSize(dm, p, &tmpSize);
2314:     DMPlexGetSupport(dm, p, &tmp);
2315:   }
2316:   if (depth == 1) {
2317:     if (*points) {
2318:       closure = *points;
2319:     } else {
2320:       maxSize = 2*(PetscMax(mesh->maxConeSize, mesh->maxSupportSize)+1);
2321:       DMGetWorkArray(dm, maxSize, MPIU_INT, &closure);
2322:     }
2323:     closure[0] = p; closure[1] = 0;
2324:     for (t = 0; t < tmpSize; ++t, closureSize += 2) {
2325:       closure[closureSize]   = tmp[t];
2326:       closure[closureSize+1] = tmpO ? tmpO[t] : 0;
2327:     }
2328:     if (numPoints) *numPoints = closureSize/2;
2329:     if (points)    *points    = closure;
2330:     return(0);
2331:   }
2332:   {
2333:     PetscInt c, coneSeries, s,supportSeries;

2335:     c = mesh->maxConeSize;
2336:     coneSeries = (c > 1) ? ((PetscPowInt(c,depth+1)-1)/(c-1)) : depth+1;
2337:     s = mesh->maxSupportSize;
2338:     supportSeries = (s > 1) ? ((PetscPowInt(s,depth+1)-1)/(s-1)) : depth+1;
2339:     maxSize = 2*PetscMax(coneSeries,supportSeries);
2340:   }
2341:   DMGetWorkArray(dm, maxSize, MPIU_INT, &fifo);
2342:   if (*points) {
2343:     closure = *points;
2344:   } else {
2345:     DMGetWorkArray(dm, maxSize, MPIU_INT, &closure);
2346:   }
2347:   closure[0] = p; closure[1] = 0;
2348:   for (t = 0; t < tmpSize; ++t, closureSize += 2, fifoSize += 2) {
2349:     const PetscInt cp = tmp[t];
2350:     const PetscInt co = tmpO ? tmpO[t] : 0;

2352:     closure[closureSize]   = cp;
2353:     closure[closureSize+1] = co;
2354:     fifo[fifoSize]         = cp;
2355:     fifo[fifoSize+1]       = co;
2356:   }
2357:   /* Should kick out early when depth is reached, rather than checking all vertices for empty cones */
2358:   while (fifoSize - fifoStart) {
2359:     const PetscInt q   = fifo[fifoStart];
2360:     const PetscInt o   = fifo[fifoStart+1];
2361:     const PetscInt rev = o >= 0 ? 0 : 1;
2362:     const PetscInt off = rev ? -(o+1) : o;

2364:     if (useCone) {
2365:       DMPlexGetConeSize(dm, q, &tmpSize);
2366:       DMPlexGetCone(dm, q, &tmp);
2367:       DMPlexGetConeOrientation(dm, q, &tmpO);
2368:     } else {
2369:       DMPlexGetSupportSize(dm, q, &tmpSize);
2370:       DMPlexGetSupport(dm, q, &tmp);
2371:       tmpO = NULL;
2372:     }
2373:     for (t = 0; t < tmpSize; ++t) {
2374:       const PetscInt i  = ((rev ? tmpSize-t : t) + off)%tmpSize;
2375:       const PetscInt cp = tmp[i];
2376:       /* Must propogate orientation: When we reverse orientation, we both reverse the direction of iteration and start at the other end of the chain. */
2377:       /* HACK: It is worse to get the size here, than to change the interpretation of -(*+1)
2378:        const PetscInt co = tmpO ? (rev ? -(tmpO[i]+1) : tmpO[i]) : 0; */
2379:       PetscInt       co = tmpO ? tmpO[i] : 0;
2380:       PetscInt       c;

2382:       if (rev) {
2383:         PetscInt childSize, coff;
2384:         DMPlexGetConeSize(dm, cp, &childSize);
2385:         coff = tmpO[i] < 0 ? -(tmpO[i]+1) : tmpO[i];
2386:         co   = childSize ? -(((coff+childSize-1)%childSize)+1) : 0;
2387:       }
2388:       /* Check for duplicate */
2389:       for (c = 0; c < closureSize; c += 2) {
2390:         if (closure[c] == cp) break;
2391:       }
2392:       if (c == closureSize) {
2393:         closure[closureSize]   = cp;
2394:         closure[closureSize+1] = co;
2395:         fifo[fifoSize]         = cp;
2396:         fifo[fifoSize+1]       = co;
2397:         closureSize           += 2;
2398:         fifoSize              += 2;
2399:       }
2400:     }
2401:     fifoStart += 2;
2402:   }
2403:   if (numPoints) *numPoints = closureSize/2;
2404:   if (points)    *points    = closure;
2405:   DMRestoreWorkArray(dm, maxSize, MPIU_INT, &fifo);
2406:   return(0);
2407: }

2409: /*@C
2410:   DMPlexGetTransitiveClosure_Internal - Return the points on the transitive closure of the in-edges or out-edges for this point in the DAG with a specified initial orientation

2412:   Not collective

2414:   Input Parameters:
2415: + mesh - The DMPlex
2416: . p - The point, which must lie in the chart set with DMPlexSetChart()
2417: . orientation - The orientation of the point
2418: . useCone - PETSC_TRUE for in-edges,  otherwise use out-edges
2419: - points - If points is NULL on input, internal storage will be returned, otherwise the provided array is used

2421:   Output Parameters:
2422: + numPoints - The number of points in the closure, so points[] is of size 2*numPoints
2423: - points - The points and point orientations, interleaved as pairs [p0, o0, p1, o1, ...]

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

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

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

2434:   Level: beginner

2436: .seealso: DMPlexRestoreTransitiveClosure(), DMPlexCreate(), DMPlexSetCone(), DMPlexSetChart(), DMPlexGetCone()
2437: @*/
2438: PetscErrorCode DMPlexGetTransitiveClosure_Internal(DM dm, PetscInt p, PetscInt ornt, PetscBool useCone, PetscInt *numPoints, PetscInt *points[])
2439: {
2440:   DM_Plex        *mesh = (DM_Plex*) dm->data;
2441:   PetscInt       *closure, *fifo;
2442:   const PetscInt *tmp = NULL, *tmpO = NULL;
2443:   PetscInt        tmpSize, t;
2444:   PetscInt        depth       = 0, maxSize;
2445:   PetscInt        closureSize = 2, fifoSize = 0, fifoStart = 0;
2446:   PetscErrorCode  ierr;

2450:   DMPlexGetDepth(dm, &depth);
2451:   /* This is only 1-level */
2452:   if (useCone) {
2453:     DMPlexGetConeSize(dm, p, &tmpSize);
2454:     DMPlexGetCone(dm, p, &tmp);
2455:     DMPlexGetConeOrientation(dm, p, &tmpO);
2456:   } else {
2457:     DMPlexGetSupportSize(dm, p, &tmpSize);
2458:     DMPlexGetSupport(dm, p, &tmp);
2459:   }
2460:   if (depth == 1) {
2461:     if (*points) {
2462:       closure = *points;
2463:     } else {
2464:       maxSize = 2*(PetscMax(mesh->maxConeSize, mesh->maxSupportSize)+1);
2465:       DMGetWorkArray(dm, maxSize, MPIU_INT, &closure);
2466:     }
2467:     closure[0] = p; closure[1] = ornt;
2468:     for (t = 0; t < tmpSize; ++t, closureSize += 2) {
2469:       const PetscInt i = ornt >= 0 ? (t+ornt)%tmpSize : (-(ornt+1) + tmpSize-t)%tmpSize;
2470:       closure[closureSize]   = tmp[i];
2471:       closure[closureSize+1] = tmpO ? tmpO[i] : 0;
2472:     }
2473:     if (numPoints) *numPoints = closureSize/2;
2474:     if (points)    *points    = closure;
2475:     return(0);
2476:   }
2477:   {
2478:     PetscInt c, coneSeries, s,supportSeries;

2480:     c = mesh->maxConeSize;
2481:     coneSeries = (c > 1) ? ((PetscPowInt(c,depth+1)-1)/(c-1)) : depth+1;
2482:     s = mesh->maxSupportSize;
2483:     supportSeries = (s > 1) ? ((PetscPowInt(s,depth+1)-1)/(s-1)) : depth+1;
2484:     maxSize = 2*PetscMax(coneSeries,supportSeries);
2485:   }
2486:   DMGetWorkArray(dm, maxSize, MPIU_INT, &fifo);
2487:   if (*points) {
2488:     closure = *points;
2489:   } else {
2490:     DMGetWorkArray(dm, maxSize, MPIU_INT, &closure);
2491:   }
2492:   closure[0] = p; closure[1] = ornt;
2493:   for (t = 0; t < tmpSize; ++t, closureSize += 2, fifoSize += 2) {
2494:     const PetscInt i  = ornt >= 0 ? (t+ornt)%tmpSize : (-(ornt+1) + tmpSize-t)%tmpSize;
2495:     const PetscInt cp = tmp[i];
2496:     PetscInt       co = tmpO ? tmpO[i] : 0;

2498:     if (ornt < 0) {
2499:       PetscInt childSize, coff;
2500:       DMPlexGetConeSize(dm, cp, &childSize);
2501:       coff = co < 0 ? -(tmpO[i]+1) : tmpO[i];
2502:       co   = childSize ? -(((coff+childSize-1)%childSize)+1) : 0;
2503:     }
2504:     closure[closureSize]   = cp;
2505:     closure[closureSize+1] = co;
2506:     fifo[fifoSize]         = cp;
2507:     fifo[fifoSize+1]       = co;
2508:   }
2509:   /* Should kick out early when depth is reached, rather than checking all vertices for empty cones */
2510:   while (fifoSize - fifoStart) {
2511:     const PetscInt q   = fifo[fifoStart];
2512:     const PetscInt o   = fifo[fifoStart+1];
2513:     const PetscInt rev = o >= 0 ? 0 : 1;
2514:     const PetscInt off = rev ? -(o+1) : o;

2516:     if (useCone) {
2517:       DMPlexGetConeSize(dm, q, &tmpSize);
2518:       DMPlexGetCone(dm, q, &tmp);
2519:       DMPlexGetConeOrientation(dm, q, &tmpO);
2520:     } else {
2521:       DMPlexGetSupportSize(dm, q, &tmpSize);
2522:       DMPlexGetSupport(dm, q, &tmp);
2523:       tmpO = NULL;
2524:     }
2525:     for (t = 0; t < tmpSize; ++t) {
2526:       const PetscInt i  = ((rev ? tmpSize-t : t) + off)%tmpSize;
2527:       const PetscInt cp = tmp[i];
2528:       /* Must propogate orientation: When we reverse orientation, we both reverse the direction of iteration and start at the other end of the chain. */
2529:       /* HACK: It is worse to get the size here, than to change the interpretation of -(*+1)
2530:        const PetscInt co = tmpO ? (rev ? -(tmpO[i]+1) : tmpO[i]) : 0; */
2531:       PetscInt       co = tmpO ? tmpO[i] : 0;
2532:       PetscInt       c;

2534:       if (rev) {
2535:         PetscInt childSize, coff;
2536:         DMPlexGetConeSize(dm, cp, &childSize);
2537:         coff = tmpO[i] < 0 ? -(tmpO[i]+1) : tmpO[i];
2538:         co   = childSize ? -(((coff+childSize-1)%childSize)+1) : 0;
2539:       }
2540:       /* Check for duplicate */
2541:       for (c = 0; c < closureSize; c += 2) {
2542:         if (closure[c] == cp) break;
2543:       }
2544:       if (c == closureSize) {
2545:         closure[closureSize]   = cp;
2546:         closure[closureSize+1] = co;
2547:         fifo[fifoSize]         = cp;
2548:         fifo[fifoSize+1]       = co;
2549:         closureSize           += 2;
2550:         fifoSize              += 2;
2551:       }
2552:     }
2553:     fifoStart += 2;
2554:   }
2555:   if (numPoints) *numPoints = closureSize/2;
2556:   if (points)    *points    = closure;
2557:   DMRestoreWorkArray(dm, maxSize, MPIU_INT, &fifo);
2558:   return(0);
2559: }

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

2564:   Not collective

2566:   Input Parameters:
2567: + mesh - The DMPlex
2568: . p - The point, which must lie in the chart set with DMPlexSetChart()
2569: . useCone - PETSC_TRUE for in-edges,  otherwise use out-edges
2570: . numPoints - The number of points in the closure, so points[] is of size 2*numPoints, zeroed on exit
2571: - points - The points and point orientations, interleaved as pairs [p0, o0, p1, o1, ...], zeroed on exit

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

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

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

2582:   Level: beginner

2584: .seealso: DMPlexGetTransitiveClosure(), DMPlexCreate(), DMPlexSetCone(), DMPlexSetChart(), DMPlexGetCone()
2585: @*/
2586: PetscErrorCode DMPlexRestoreTransitiveClosure(DM dm, PetscInt p, PetscBool useCone, PetscInt *numPoints, PetscInt *points[])
2587: {

2594:   DMRestoreWorkArray(dm, 0, MPIU_INT, points);
2595:   if (numPoints) *numPoints = 0;
2596:   return(0);
2597: }

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

2602:   Not collective

2604:   Input Parameter:
2605: . mesh - The DMPlex

2607:   Output Parameters:
2608: + maxConeSize - The maximum number of in-edges
2609: - maxSupportSize - The maximum number of out-edges

2611:   Level: beginner

2613: .seealso: DMPlexCreate(), DMPlexSetConeSize(), DMPlexSetChart()
2614: @*/
2615: PetscErrorCode DMPlexGetMaxSizes(DM dm, PetscInt *maxConeSize, PetscInt *maxSupportSize)
2616: {
2617:   DM_Plex *mesh = (DM_Plex*) dm->data;

2621:   if (maxConeSize)    *maxConeSize    = mesh->maxConeSize;
2622:   if (maxSupportSize) *maxSupportSize = mesh->maxSupportSize;
2623:   return(0);
2624: }

2626: PetscErrorCode DMSetUp_Plex(DM dm)
2627: {
2628:   DM_Plex       *mesh = (DM_Plex*) dm->data;
2629:   PetscInt       size;

2634:   PetscSectionSetUp(mesh->coneSection);
2635:   PetscSectionGetStorageSize(mesh->coneSection, &size);
2636:   PetscMalloc1(size, &mesh->cones);
2637:   PetscCalloc1(size, &mesh->coneOrientations);
2638:   if (mesh->maxSupportSize) {
2639:     PetscSectionSetUp(mesh->supportSection);
2640:     PetscSectionGetStorageSize(mesh->supportSection, &size);
2641:     PetscMalloc1(size, &mesh->supports);
2642:   }
2643:   return(0);
2644: }

2646: PetscErrorCode DMCreateSubDM_Plex(DM dm, PetscInt numFields, const PetscInt fields[], IS *is, DM *subdm)
2647: {

2651:   if (subdm) {DMClone(dm, subdm);}
2652:   DMCreateSectionSubDM(dm, numFields, fields, is, subdm);
2653:   if (subdm) {(*subdm)->useNatural = dm->useNatural;}
2654:   if (dm->useNatural && dm->sfMigration) {
2655:     PetscSF        sfMigrationInv,sfNatural;
2656:     PetscSection   section, sectionSeq;

2658:     (*subdm)->sfMigration = dm->sfMigration;
2659:     PetscObjectReference((PetscObject) dm->sfMigration);
2660:     DMGetLocalSection((*subdm), &section);
2661:     PetscSFCreateInverseSF((*subdm)->sfMigration, &sfMigrationInv);
2662:     PetscSectionCreate(PetscObjectComm((PetscObject) (*subdm)), &sectionSeq);
2663:     PetscSFDistributeSection(sfMigrationInv, section, NULL, sectionSeq);

2665:     DMPlexCreateGlobalToNaturalSF(*subdm, sectionSeq, (*subdm)->sfMigration, &sfNatural);
2666:     (*subdm)->sfNatural = sfNatural;
2667:     PetscSectionDestroy(&sectionSeq);
2668:     PetscSFDestroy(&sfMigrationInv);
2669:   }
2670:   return(0);
2671: }

2673: PetscErrorCode DMCreateSuperDM_Plex(DM dms[], PetscInt len, IS **is, DM *superdm)
2674: {
2676:   PetscInt       i = 0;

2679:   DMClone(dms[0], superdm);
2680:   DMCreateSectionSuperDM(dms, len, is, superdm);
2681:   (*superdm)->useNatural = PETSC_FALSE;
2682:   for (i = 0; i < len; i++){
2683:     if (dms[i]->useNatural && dms[i]->sfMigration) {
2684:       PetscSF        sfMigrationInv,sfNatural;
2685:       PetscSection   section, sectionSeq;

2687:       (*superdm)->sfMigration = dms[i]->sfMigration;
2688:       PetscObjectReference((PetscObject) dms[i]->sfMigration);
2689:       (*superdm)->useNatural = PETSC_TRUE;
2690:       DMGetLocalSection((*superdm), &section);
2691:       PetscSFCreateInverseSF((*superdm)->sfMigration, &sfMigrationInv);
2692:       PetscSectionCreate(PetscObjectComm((PetscObject) (*superdm)), &sectionSeq);
2693:       PetscSFDistributeSection(sfMigrationInv, section, NULL, sectionSeq);

2695:       DMPlexCreateGlobalToNaturalSF(*superdm, sectionSeq, (*superdm)->sfMigration, &sfNatural);
2696:       (*superdm)->sfNatural = sfNatural;
2697:       PetscSectionDestroy(&sectionSeq);
2698:       PetscSFDestroy(&sfMigrationInv);
2699:       break;
2700:     }
2701:   }
2702:   return(0);
2703: }

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

2708:   Not collective

2710:   Input Parameter:
2711: . mesh - The DMPlex

2713:   Output Parameter:

2715:   Note:
2716:   This should be called after all calls to DMPlexSetCone()

2718:   Level: beginner

2720: .seealso: DMPlexCreate(), DMPlexSetChart(), DMPlexSetConeSize(), DMPlexSetCone()
2721: @*/
2722: PetscErrorCode DMPlexSymmetrize(DM dm)
2723: {
2724:   DM_Plex       *mesh = (DM_Plex*) dm->data;
2725:   PetscInt      *offsets;
2726:   PetscInt       supportSize;
2727:   PetscInt       pStart, pEnd, p;

2732:   if (mesh->supports) SETERRQ(PetscObjectComm((PetscObject)dm), PETSC_ERR_ARG_WRONGSTATE, "Supports were already setup in this DMPlex");
2733:   PetscLogEventBegin(DMPLEX_Symmetrize,dm,0,0,0);
2734:   /* Calculate support sizes */
2735:   DMPlexGetChart(dm, &pStart, &pEnd);
2736:   for (p = pStart; p < pEnd; ++p) {
2737:     PetscInt dof, off, c;

2739:     PetscSectionGetDof(mesh->coneSection, p, &dof);
2740:     PetscSectionGetOffset(mesh->coneSection, p, &off);
2741:     for (c = off; c < off+dof; ++c) {
2742:       PetscSectionAddDof(mesh->supportSection, mesh->cones[c], 1);
2743:     }
2744:   }
2745:   for (p = pStart; p < pEnd; ++p) {
2746:     PetscInt dof;

2748:     PetscSectionGetDof(mesh->supportSection, p, &dof);

2750:     mesh->maxSupportSize = PetscMax(mesh->maxSupportSize, dof);
2751:   }
2752:   PetscSectionSetUp(mesh->supportSection);
2753:   /* Calculate supports */
2754:   PetscSectionGetStorageSize(mesh->supportSection, &supportSize);
2755:   PetscMalloc1(supportSize, &mesh->supports);
2756:   PetscCalloc1(pEnd - pStart, &offsets);
2757:   for (p = pStart; p < pEnd; ++p) {
2758:     PetscInt dof, off, c;

2760:     PetscSectionGetDof(mesh->coneSection, p, &dof);
2761:     PetscSectionGetOffset(mesh->coneSection, p, &off);
2762:     for (c = off; c < off+dof; ++c) {
2763:       const PetscInt q = mesh->cones[c];
2764:       PetscInt       offS;

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

2768:       mesh->supports[offS+offsets[q]] = p;
2769:       ++offsets[q];
2770:     }
2771:   }
2772:   PetscFree(offsets);
2773:   PetscLogEventEnd(DMPLEX_Symmetrize,dm,0,0,0);
2774:   return(0);
2775: }

2777: static PetscErrorCode DMPlexCreateDepthStratum(DM dm, DMLabel label, PetscInt depth, PetscInt pStart, PetscInt pEnd)
2778: {
2779:   IS             stratumIS;

2783:   if (pStart >= pEnd) return(0);
2784: #if defined(PETSC_USE_DEBUG)
2785:   {
2786:     PetscInt  qStart, qEnd, numLevels, level;
2787:     PetscBool overlap = PETSC_FALSE;
2788:     DMLabelGetNumValues(label, &numLevels);
2789:     for (level = 0; level < numLevels; level++) {
2790:       DMLabelGetStratumBounds(label, level, &qStart, &qEnd);
2791:       if ((pStart >= qStart && pStart < qEnd) || (pEnd > qStart && pEnd <= qEnd)) {overlap = PETSC_TRUE; break;}
2792:     }
2793:     if (overlap) SETERRQ6(PETSC_COMM_SELF, PETSC_ERR_PLIB, "New depth %D range [%D,%D) overlaps with depth %D range [%D,%D)", depth, pStart, pEnd, level, qStart, qEnd);
2794:   }
2795: #endif
2796:   ISCreateStride(PETSC_COMM_SELF, pEnd-pStart, pStart, 1, &stratumIS);
2797:   DMLabelSetStratumIS(label, depth, stratumIS);
2798:   ISDestroy(&stratumIS);
2799:   return(0);
2800: }

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

2808:   Collective on dm

2810:   Input Parameter:
2811: . mesh - The DMPlex

2813:   Output Parameter:

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

2822:   The depth of a point is calculated by executing a breadth-first search (BFS) on the DAG. This could produce surprising results
2823:   if run on a partially interpolated mesh, meaning one that had some edges and faces, but not others. For example, suppose that
2824:   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
2825:   to interpolate only that one (e0), so that
2826: $  cone(c0) = {e0, v2}
2827: $  cone(e0) = {v0, v1}
2828:   If DMPlexStratify() is run on this mesh, it will give depths
2829: $  depth 0 = {v0, v1, v2}
2830: $  depth 1 = {e0, c0}
2831:   where the triangle has been given depth 1, instead of 2, because it is reachable from vertex v2.

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

2835:   Level: beginner

2837: .seealso: DMPlexCreate(), DMPlexSymmetrize(), DMPlexComputeCellTypes()
2838: @*/
2839: PetscErrorCode DMPlexStratify(DM dm)
2840: {
2841:   DM_Plex       *mesh = (DM_Plex*) dm->data;
2842:   DMLabel        label;
2843:   PetscInt       pStart, pEnd, p;
2844:   PetscInt       numRoots = 0, numLeaves = 0;

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

2851:   /* Create depth label */
2852:   DMPlexGetChart(dm, &pStart, &pEnd);
2853:   DMCreateLabel(dm, "depth");
2854:   DMPlexGetDepthLabel(dm, &label);

2856:   {
2857:     /* Initialize roots and count leaves */
2858:     PetscInt sMin = PETSC_MAX_INT;
2859:     PetscInt sMax = PETSC_MIN_INT;
2860:     PetscInt coneSize, supportSize;

2862:     for (p = pStart; p < pEnd; ++p) {
2863:       DMPlexGetConeSize(dm, p, &coneSize);
2864:       DMPlexGetSupportSize(dm, p, &supportSize);
2865:       if (!coneSize && supportSize) {
2866:         sMin = PetscMin(p, sMin);
2867:         sMax = PetscMax(p, sMax);
2868:         ++numRoots;
2869:       } else if (!supportSize && coneSize) {
2870:         ++numLeaves;
2871:       } else if (!supportSize && !coneSize) {
2872:         /* Isolated points */
2873:         sMin = PetscMin(p, sMin);
2874:         sMax = PetscMax(p, sMax);
2875:       }
2876:     }
2877:     DMPlexCreateDepthStratum(dm, label, 0, sMin, sMax+1);
2878:   }

2880:   if (numRoots + numLeaves == (pEnd - pStart)) {
2881:     PetscInt sMin = PETSC_MAX_INT;
2882:     PetscInt sMax = PETSC_MIN_INT;
2883:     PetscInt coneSize, supportSize;

2885:     for (p = pStart; p < pEnd; ++p) {
2886:       DMPlexGetConeSize(dm, p, &coneSize);
2887:       DMPlexGetSupportSize(dm, p, &supportSize);
2888:       if (!supportSize && coneSize) {
2889:         sMin = PetscMin(p, sMin);
2890:         sMax = PetscMax(p, sMax);
2891:       }
2892:     }
2893:     DMPlexCreateDepthStratum(dm, label, 1, sMin, sMax+1);
2894:   } else {
2895:     PetscInt level = 0;
2896:     PetscInt qStart, qEnd, q;

2898:     DMLabelGetStratumBounds(label, level, &qStart, &qEnd);
2899:     while (qEnd > qStart) {
2900:       PetscInt sMin = PETSC_MAX_INT;
2901:       PetscInt sMax = PETSC_MIN_INT;

2903:       for (q = qStart; q < qEnd; ++q) {
2904:         const PetscInt *support;
2905:         PetscInt        supportSize, s;

2907:         DMPlexGetSupportSize(dm, q, &supportSize);
2908:         DMPlexGetSupport(dm, q, &support);
2909:         for (s = 0; s < supportSize; ++s) {
2910:           sMin = PetscMin(support[s], sMin);
2911:           sMax = PetscMax(support[s], sMax);
2912:         }
2913:       }
2914:       DMLabelGetNumValues(label, &level);
2915:       DMPlexCreateDepthStratum(dm, label, level, sMin, sMax+1);
2916:       DMLabelGetStratumBounds(label, level, &qStart, &qEnd);
2917:     }
2918:   }
2919:   { /* just in case there is an empty process */
2920:     PetscInt numValues, maxValues = 0, v;

2922:     DMLabelGetNumValues(label, &numValues);
2923:     MPI_Allreduce(&numValues,&maxValues,1,MPIU_INT,MPI_MAX,PetscObjectComm((PetscObject)dm));
2924:     for (v = numValues; v < maxValues; v++) {
2925:       DMLabelAddStratum(label, v);
2926:     }
2927:   }
2928:   PetscObjectStateGet((PetscObject) label, &mesh->depthState);
2929:   PetscLogEventEnd(DMPLEX_Stratify,dm,0,0,0);
2930:   return(0);
2931: }

2933: PetscErrorCode DMPlexComputeCellType_Internal(DM dm, PetscInt p, PetscInt pdepth, DMPolytopeType *pt)
2934: {
2935:   DMPolytopeType ct = DM_POLYTOPE_UNKNOWN;
2936:   PetscInt       dim, depth, pheight, coneSize;

2940:   DMGetDimension(dm, &dim);
2941:   DMPlexGetDepth(dm, &depth);
2942:   DMPlexGetConeSize(dm, p, &coneSize);
2943:   pheight = depth - pdepth;
2944:   if (depth <= 1) {
2945:     switch (pdepth) {
2946:       case 0: ct = DM_POLYTOPE_POINT;break;
2947:       case 1:
2948:         switch (coneSize) {
2949:           case 2: ct = DM_POLYTOPE_SEGMENT;break;
2950:           case 3: ct = DM_POLYTOPE_TRIANGLE;break;
2951:           case 4:
2952:           switch (dim) {
2953:             case 2: ct = DM_POLYTOPE_QUADRILATERAL;break;
2954:             case 3: ct = DM_POLYTOPE_TETRAHEDRON;break;
2955:             default: break;
2956:           }
2957:           break;
2958:         case 6: ct = DM_POLYTOPE_TRI_PRISM_TENSOR;break;
2959:         case 8: ct = DM_POLYTOPE_HEXAHEDRON;break;
2960:         default: break;
2961:       }
2962:     }
2963:   } else {
2964:     if (pdepth == 0) {
2965:       ct = DM_POLYTOPE_POINT;
2966:     } else if (pheight == 0) {
2967:       switch (dim) {
2968:         case 1:
2969:           switch (coneSize) {
2970:             case 2: ct = DM_POLYTOPE_SEGMENT;break;
2971:             default: break;
2972:           }
2973:           break;
2974:         case 2:
2975:           switch (coneSize) {
2976:             case 3: ct = DM_POLYTOPE_TRIANGLE;break;
2977:             case 4: ct = DM_POLYTOPE_QUADRILATERAL;break;
2978:             default: break;
2979:           }
2980:           break;
2981:         case 3:
2982:           switch (coneSize) {
2983:             case 4: ct = DM_POLYTOPE_TETRAHEDRON;break;
2984:             case 5: ct = DM_POLYTOPE_TRI_PRISM_TENSOR;break;
2985:             case 6: ct = DM_POLYTOPE_HEXAHEDRON;break;
2986:             default: break;
2987:           }
2988:           break;
2989:         default: break;
2990:       }
2991:     } else if (pheight > 0) {
2992:       switch (coneSize) {
2993:         case 2: ct = DM_POLYTOPE_SEGMENT;break;
2994:         case 3: ct = DM_POLYTOPE_TRIANGLE;break;
2995:         case 4: ct = DM_POLYTOPE_QUADRILATERAL;break;
2996:         default: break;
2997:       }
2998:     }
2999:   }
3000:   *pt = ct;
3001:   return(0);
3002: }

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

3007:   Collective on dm

3009:   Input Parameter:
3010: . mesh - The DMPlex

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

3014:   Level: developer

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

3020: .seealso: DMPlexCreate(), DMPlexSymmetrize(), DMPlexStratify(), DMGetLabel(), DMCreateLabel()
3021: @*/
3022: PetscErrorCode DMPlexComputeCellTypes(DM dm)
3023: {
3024:   DM_Plex       *mesh;
3025:   DMLabel        ctLabel;
3026:   PetscInt       pStart, pEnd, p;

3031:   mesh = (DM_Plex *) dm->data;
3032:   DMCreateLabel(dm, "celltype");
3033:   DMPlexGetCellTypeLabel(dm, &ctLabel);
3034:   DMPlexGetChart(dm, &pStart, &pEnd);
3035:   for (p = pStart; p < pEnd; ++p) {
3036:     DMPolytopeType ct = DM_POLYTOPE_UNKNOWN;
3037:     PetscInt       pdepth;

3039:     DMPlexGetPointDepth(dm, p, &pdepth);
3040:     DMPlexComputeCellType_Internal(dm, p, pdepth, &ct);
3041:     if (ct == DM_POLYTOPE_UNKNOWN) SETERRQ1(PETSC_COMM_SELF, PETSC_ERR_SUP, "Point %D is screwed up", p);
3042:     DMLabelSetValue(ctLabel, p, ct);
3043:   }
3044:   PetscObjectStateGet((PetscObject) ctLabel, &mesh->celltypeState);
3045:   PetscObjectViewFromOptions((PetscObject) ctLabel, NULL, "-dm_plex_celltypes_view");
3046:   return(0);
3047: }

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

3052:   Not Collective

3054:   Input Parameters:
3055: + dm - The DMPlex object
3056: . numPoints - The number of input points for the join
3057: - points - The input points

3059:   Output Parameters:
3060: + numCoveredPoints - The number of points in the join
3061: - coveredPoints - The points in the join

3063:   Level: intermediate

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

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

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

3073: .seealso: DMPlexRestoreJoin(), DMPlexGetMeet()
3074: @*/
3075: PetscErrorCode DMPlexGetJoin(DM dm, PetscInt numPoints, const PetscInt points[], PetscInt *numCoveredPoints, const PetscInt **coveredPoints)
3076: {
3077:   DM_Plex       *mesh = (DM_Plex*) dm->data;
3078:   PetscInt      *join[2];
3079:   PetscInt       joinSize, i = 0;
3080:   PetscInt       dof, off, p, c, m;

3088:   DMGetWorkArray(dm, mesh->maxSupportSize, MPIU_INT, &join[0]);
3089:   DMGetWorkArray(dm, mesh->maxSupportSize, MPIU_INT, &join[1]);
3090:   /* Copy in support of first point */
3091:   PetscSectionGetDof(mesh->supportSection, points[0], &dof);
3092:   PetscSectionGetOffset(mesh->supportSection, points[0], &off);
3093:   for (joinSize = 0; joinSize < dof; ++joinSize) {
3094:     join[i][joinSize] = mesh->supports[off+joinSize];
3095:   }
3096:   /* Check each successive support */
3097:   for (p = 1; p < numPoints; ++p) {
3098:     PetscInt newJoinSize = 0;

3100:     PetscSectionGetDof(mesh->supportSection, points[p], &dof);
3101:     PetscSectionGetOffset(mesh->supportSection, points[p], &off);
3102:     for (c = 0; c < dof; ++c) {
3103:       const PetscInt point = mesh->supports[off+c];

3105:       for (m = 0; m < joinSize; ++m) {
3106:         if (point == join[i][m]) {
3107:           join[1-i][newJoinSize++] = point;
3108:           break;
3109:         }
3110:       }
3111:     }
3112:     joinSize = newJoinSize;
3113:     i        = 1-i;
3114:   }
3115:   *numCoveredPoints = joinSize;
3116:   *coveredPoints    = join[i];
3117:   DMRestoreWorkArray(dm, mesh->maxSupportSize, MPIU_INT, &join[1-i]);
3118:   return(0);
3119: }

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

3124:   Not Collective

3126:   Input Parameters:
3127: + dm - The DMPlex object
3128: . numPoints - The number of input points for the join
3129: - points - The input points

3131:   Output Parameters:
3132: + numCoveredPoints - The number of points in the join
3133: - coveredPoints - The points in the join

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

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

3141:   Level: intermediate

3143: .seealso: DMPlexGetJoin(), DMPlexGetFullJoin(), DMPlexGetMeet()
3144: @*/
3145: PetscErrorCode DMPlexRestoreJoin(DM dm, PetscInt numPoints, const PetscInt points[], PetscInt *numCoveredPoints, const PetscInt **coveredPoints)
3146: {

3154:   DMRestoreWorkArray(dm, 0, MPIU_INT, (void*) coveredPoints);
3155:   if (numCoveredPoints) *numCoveredPoints = 0;
3156:   return(0);
3157: }

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

3162:   Not Collective

3164:   Input Parameters:
3165: + dm - The DMPlex object
3166: . numPoints - The number of input points for the join
3167: - points - The input points

3169:   Output Parameters:
3170: + numCoveredPoints - The number of points in the join
3171: - coveredPoints - The points in the join

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

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

3179:   Level: intermediate

3181: .seealso: DMPlexGetJoin(), DMPlexRestoreJoin(), DMPlexGetMeet()
3182: @*/
3183: PetscErrorCode DMPlexGetFullJoin(DM dm, PetscInt numPoints, const PetscInt points[], PetscInt *numCoveredPoints, const PetscInt **coveredPoints)
3184: {
3185:   DM_Plex       *mesh = (DM_Plex*) dm->data;
3186:   PetscInt      *offsets, **closures;
3187:   PetscInt      *join[2];
3188:   PetscInt       depth = 0, maxSize, joinSize = 0, i = 0;
3189:   PetscInt       p, d, c, m, ms;


3198:   DMPlexGetDepth(dm, &depth);
3199:   PetscCalloc1(numPoints, &closures);
3200:   DMGetWorkArray(dm, numPoints*(depth+2), MPIU_INT, &offsets);
3201:   ms      = mesh->maxSupportSize;
3202:   maxSize = (ms > 1) ? ((PetscPowInt(ms,depth+1)-1)/(ms-1)) : depth + 1;
3203:   DMGetWorkArray(dm, maxSize, MPIU_INT, &join[0]);
3204:   DMGetWorkArray(dm, maxSize, MPIU_INT, &join[1]);

3206:   for (p = 0; p < numPoints; ++p) {
3207:     PetscInt closureSize;

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

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

3215:       DMPlexGetDepthStratum(dm, d, &pStart, &pEnd);
3216:       for (i = offsets[p*(depth+2)+d]; i < closureSize; ++i) {
3217:         if ((pStart > closures[p][i*2]) || (pEnd <= closures[p][i*2])) {
3218:           offsets[p*(depth+2)+d+1] = i;
3219:           break;
3220:         }
3221:       }
3222:       if (i == closureSize) offsets[p*(depth+2)+d+1] = i;
3223:     }
3224:     if (offsets[p*(depth+2)+depth+1] != closureSize) SETERRQ2(PetscObjectComm((PetscObject)dm), PETSC_ERR_PLIB, "Total size of closure %D should be %D", offsets[p*(depth+2)+depth+1], closureSize);
3225:   }
3226:   for (d = 0; d < depth+1; ++d) {
3227:     PetscInt dof;

3229:     /* Copy in support of first point */
3230:     dof = offsets[d+1] - offsets[d];
3231:     for (joinSize = 0; joinSize < dof; ++joinSize) {
3232:       join[i][joinSize] = closures[0][(offsets[d]+joinSize)*2];
3233:     }
3234:     /* Check each successive cone */
3235:     for (p = 1; p < numPoints && joinSize; ++p) {
3236:       PetscInt newJoinSize = 0;

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

3242:         for (m = 0; m < joinSize; ++m) {
3243:           if (point == join[i][m]) {
3244:             join[1-i][newJoinSize++] = point;
3245:             break;
3246:           }
3247:         }
3248:       }
3249:       joinSize = newJoinSize;
3250:       i        = 1-i;
3251:     }
3252:     if (joinSize) break;
3253:   }
3254:   *numCoveredPoints = joinSize;
3255:   *coveredPoints    = join[i];
3256:   for (p = 0; p < numPoints; ++p) {
3257:     DMPlexRestoreTransitiveClosure(dm, points[p], PETSC_FALSE, NULL, &closures[p]);
3258:   }
3259:   PetscFree(closures);
3260:   DMRestoreWorkArray(dm, numPoints*(depth+2), MPIU_INT, &offsets);
3261:   DMRestoreWorkArray(dm, mesh->maxSupportSize, MPIU_INT, &join[1-i]);
3262:   return(0);
3263: }

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

3268:   Not Collective

3270:   Input Parameters:
3271: + dm - The DMPlex object
3272: . numPoints - The number of input points for the meet
3273: - points - The input points

3275:   Output Parameters:
3276: + numCoveredPoints - The number of points in the meet
3277: - coveredPoints - The points in the meet

3279:   Level: intermediate

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

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

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

3289: .seealso: DMPlexRestoreMeet(), DMPlexGetJoin()
3290: @*/
3291: PetscErrorCode DMPlexGetMeet(DM dm, PetscInt numPoints, const PetscInt points[], PetscInt *numCoveringPoints, const PetscInt **coveringPoints)
3292: {
3293:   DM_Plex       *mesh = (DM_Plex*) dm->data;
3294:   PetscInt      *meet[2];
3295:   PetscInt       meetSize, i = 0;
3296:   PetscInt       dof, off, p, c, m;

3304:   DMGetWorkArray(dm, mesh->maxConeSize, MPIU_INT, &meet[0]);
3305:   DMGetWorkArray(dm, mesh->maxConeSize, MPIU_INT, &meet[1]);
3306:   /* Copy in cone of first point */
3307:   PetscSectionGetDof(mesh->coneSection, points[0], &dof);
3308:   PetscSectionGetOffset(mesh->coneSection, points[0], &off);
3309:   for (meetSize = 0; meetSize < dof; ++meetSize) {
3310:     meet[i][meetSize] = mesh->cones[off+meetSize];
3311:   }
3312:   /* Check each successive cone */
3313:   for (p = 1; p < numPoints; ++p) {
3314:     PetscInt newMeetSize = 0;

3316:     PetscSectionGetDof(mesh->coneSection, points[p], &dof);
3317:     PetscSectionGetOffset(mesh->coneSection, points[p], &off);
3318:     for (c = 0; c < dof; ++c) {
3319:       const PetscInt point = mesh->cones[off+c];

3321:       for (m = 0; m < meetSize; ++m) {
3322:         if (point == meet[i][m]) {
3323:           meet[1-i][newMeetSize++] = point;
3324:           break;
3325:         }
3326:       }
3327:     }
3328:     meetSize = newMeetSize;
3329:     i        = 1-i;
3330:   }
3331:   *numCoveringPoints = meetSize;
3332:   *coveringPoints    = meet[i];
3333:   DMRestoreWorkArray(dm, mesh->maxConeSize, MPIU_INT, &meet[1-i]);
3334:   return(0);
3335: }

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

3340:   Not Collective

3342:   Input Parameters:
3343: + dm - The DMPlex object
3344: . numPoints - The number of input points for the meet
3345: - points - The input points

3347:   Output Parameters:
3348: + numCoveredPoints - The number of points in the meet
3349: - coveredPoints - The points in the meet

3351:   Level: intermediate

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

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

3359: .seealso: DMPlexGetMeet(), DMPlexGetFullMeet(), DMPlexGetJoin()
3360: @*/
3361: PetscErrorCode DMPlexRestoreMeet(DM dm, PetscInt numPoints, const PetscInt points[], PetscInt *numCoveredPoints, const PetscInt **coveredPoints)
3362: {

3370:   DMRestoreWorkArray(dm, 0, MPIU_INT, (void*) coveredPoints);
3371:   if (numCoveredPoints) *numCoveredPoints = 0;
3372:   return(0);
3373: }

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

3378:   Not Collective

3380:   Input Parameters:
3381: + dm - The DMPlex object
3382: . numPoints - The number of input points for the meet
3383: - points - The input points

3385:   Output Parameters:
3386: + numCoveredPoints - The number of points in the meet
3387: - coveredPoints - The points in the meet

3389:   Level: intermediate

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

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

3397: .seealso: DMPlexGetMeet(), DMPlexRestoreMeet(), DMPlexGetJoin()
3398: @*/
3399: PetscErrorCode DMPlexGetFullMeet(DM dm, PetscInt numPoints, const PetscInt points[], PetscInt *numCoveredPoints, const PetscInt **coveredPoints)
3400: {
3401:   DM_Plex       *mesh = (DM_Plex*) dm->data;
3402:   PetscInt      *offsets, **closures;
3403:   PetscInt      *meet[2];
3404:   PetscInt       height = 0, maxSize, meetSize = 0, i = 0;
3405:   PetscInt       p, h, c, m, mc;


3414:   DMPlexGetDepth(dm, &height);
3415:   PetscMalloc1(numPoints, &closures);
3416:   DMGetWorkArray(dm, numPoints*(height+2), MPIU_INT, &offsets);
3417:   mc      = mesh->maxConeSize;
3418:   maxSize = (mc > 1) ? ((PetscPowInt(mc,height+1)-1)/(mc-1)) : height + 1;
3419:   DMGetWorkArray(dm, maxSize, MPIU_INT, &meet[0]);
3420:   DMGetWorkArray(dm, maxSize, MPIU_INT, &meet[1]);

3422:   for (p = 0; p < numPoints; ++p) {
3423:     PetscInt closureSize;

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

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

3431:       DMPlexGetHeightStratum(dm, h, &pStart, &pEnd);
3432:       for (i = offsets[p*(height+2)+h]; i < closureSize; ++i) {
3433:         if ((pStart > closures[p][i*2]) || (pEnd <= closures[p][i*2])) {
3434:           offsets[p*(height+2)+h+1] = i;
3435:           break;
3436:         }
3437:       }
3438:       if (i == closureSize) offsets[p*(height+2)+h+1] = i;
3439:     }
3440:     if (offsets[p*(height+2)+height+1] != closureSize) SETERRQ2(PetscObjectComm((PetscObject)dm), PETSC_ERR_PLIB, "Total size of closure %D should be %D", offsets[p*(height+2)+height+1], closureSize);
3441:   }
3442:   for (h = 0; h < height+1; ++h) {
3443:     PetscInt dof;

3445:     /* Copy in cone of first point */
3446:     dof = offsets[h+1] - offsets[h];
3447:     for (meetSize = 0; meetSize < dof; ++meetSize) {
3448:       meet[i][meetSize] = closures[0][(offsets[h]+meetSize)*2];
3449:     }
3450:     /* Check each successive cone */
3451:     for (p = 1; p < numPoints && meetSize; ++p) {
3452:       PetscInt newMeetSize = 0;

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

3458:         for (m = 0; m < meetSize; ++m) {
3459:           if (point == meet[i][m]) {
3460:             meet[1-i][newMeetSize++] = point;
3461:             break;
3462:           }
3463:         }
3464:       }
3465:       meetSize = newMeetSize;
3466:       i        = 1-i;
3467:     }
3468:     if (meetSize) break;
3469:   }
3470:   *numCoveredPoints = meetSize;
3471:   *coveredPoints    = meet[i];
3472:   for (p = 0; p < numPoints; ++p) {
3473:     DMPlexRestoreTransitiveClosure(dm, points[p], PETSC_TRUE, NULL, &closures[p]);
3474:   }
3475:   PetscFree(closures);
3476:   DMRestoreWorkArray(dm, numPoints*(height+2), MPIU_INT, &offsets);
3477:   DMRestoreWorkArray(dm, mesh->maxConeSize, MPIU_INT, &meet[1-i]);
3478:   return(0);
3479: }

3481: /*@C
3482:   DMPlexEqual - Determine if two DMs have the same topology

3484:   Not Collective

3486:   Input Parameters:
3487: + dmA - A DMPlex object
3488: - dmB - A DMPlex object

3490:   Output Parameters:
3491: . equal - PETSC_TRUE if the topologies are identical

3493:   Level: intermediate

3495:   Notes:
3496:   We are not solving graph isomorphism, so we do not permutation.

3498: .seealso: DMPlexGetCone()
3499: @*/
3500: PetscErrorCode DMPlexEqual(DM dmA, DM dmB, PetscBool *equal)
3501: {
3502:   PetscInt       depth, depthB, pStart, pEnd, pStartB, pEndB, p;


3510:   *equal = PETSC_FALSE;
3511:   DMPlexGetDepth(dmA, &depth);
3512:   DMPlexGetDepth(dmB, &depthB);
3513:   if (depth != depthB) return(0);
3514:   DMPlexGetChart(dmA, &pStart,  &pEnd);
3515:   DMPlexGetChart(dmB, &pStartB, &pEndB);
3516:   if ((pStart != pStartB) || (pEnd != pEndB)) return(0);
3517:   for (p = pStart; p < pEnd; ++p) {
3518:     const PetscInt *cone, *coneB, *ornt, *orntB, *support, *supportB;
3519:     PetscInt        coneSize, coneSizeB, c, supportSize, supportSizeB, s;

3521:     DMPlexGetConeSize(dmA, p, &coneSize);
3522:     DMPlexGetCone(dmA, p, &cone);
3523:     DMPlexGetConeOrientation(dmA, p, &ornt);
3524:     DMPlexGetConeSize(dmB, p, &coneSizeB);
3525:     DMPlexGetCone(dmB, p, &coneB);
3526:     DMPlexGetConeOrientation(dmB, p, &orntB);
3527:     if (coneSize != coneSizeB) return(0);
3528:     for (c = 0; c < coneSize; ++c) {
3529:       if (cone[c] != coneB[c]) return(0);
3530:       if (ornt[c] != orntB[c]) return(0);
3531:     }
3532:     DMPlexGetSupportSize(dmA, p, &supportSize);
3533:     DMPlexGetSupport(dmA, p, &support);
3534:     DMPlexGetSupportSize(dmB, p, &supportSizeB);
3535:     DMPlexGetSupport(dmB, p, &supportB);
3536:     if (supportSize != supportSizeB) return(0);
3537:     for (s = 0; s < supportSize; ++s) {
3538:       if (support[s] != supportB[s]) return(0);
3539:     }
3540:   }
3541:   *equal = PETSC_TRUE;
3542:   return(0);
3543: }

3545: /*@C
3546:   DMPlexGetNumFaceVertices - Returns the number of vertices on a face

3548:   Not Collective

3550:   Input Parameters:
3551: + dm         - The DMPlex
3552: . cellDim    - The cell dimension
3553: - numCorners - The number of vertices on a cell

3555:   Output Parameters:
3556: . numFaceVertices - The number of vertices on a face

3558:   Level: developer

3560:   Notes:
3561:   Of course this can only work for a restricted set of symmetric shapes

3563: .seealso: DMPlexGetCone()
3564: @*/
3565: PetscErrorCode DMPlexGetNumFaceVertices(DM dm, PetscInt cellDim, PetscInt numCorners, PetscInt *numFaceVertices)
3566: {
3567:   MPI_Comm       comm;

3571:   PetscObjectGetComm((PetscObject)dm,&comm);
3573:   switch (cellDim) {
3574:   case 0:
3575:     *numFaceVertices = 0;
3576:     break;
3577:   case 1:
3578:     *numFaceVertices = 1;
3579:     break;
3580:   case 2:
3581:     switch (numCorners) {
3582:     case 3: /* triangle */
3583:       *numFaceVertices = 2; /* Edge has 2 vertices */
3584:       break;
3585:     case 4: /* quadrilateral */
3586:       *numFaceVertices = 2; /* Edge has 2 vertices */
3587:       break;
3588:     case 6: /* quadratic triangle, tri and quad cohesive Lagrange cells */
3589:       *numFaceVertices = 3; /* Edge has 3 vertices */
3590:       break;
3591:     case 9: /* quadratic quadrilateral, quadratic quad cohesive Lagrange cells */
3592:       *numFaceVertices = 3; /* Edge has 3 vertices */
3593:       break;
3594:     default:
3595:       SETERRQ2(comm, PETSC_ERR_ARG_OUTOFRANGE, "Invalid number of face corners %D for dimension %D", numCorners, cellDim);
3596:     }
3597:     break;
3598:   case 3:
3599:     switch (numCorners) {
3600:     case 4: /* tetradehdron */
3601:       *numFaceVertices = 3; /* Face has 3 vertices */
3602:       break;
3603:     case 6: /* tet cohesive cells */
3604:       *numFaceVertices = 4; /* Face has 4 vertices */
3605:       break;
3606:     case 8: /* hexahedron */
3607:       *numFaceVertices = 4; /* Face has 4 vertices */
3608:       break;
3609:     case 9: /* tet cohesive Lagrange cells */
3610:       *numFaceVertices = 6; /* Face has 6 vertices */
3611:       break;
3612:     case 10: /* quadratic tetrahedron */
3613:       *numFaceVertices = 6; /* Face has 6 vertices */
3614:       break;
3615:     case 12: /* hex cohesive Lagrange cells */
3616:       *numFaceVertices = 6; /* Face has 6 vertices */
3617:       break;
3618:     case 18: /* quadratic tet cohesive Lagrange cells */
3619:       *numFaceVertices = 6; /* Face has 6 vertices */
3620:       break;
3621:     case 27: /* quadratic hexahedron, quadratic hex cohesive Lagrange cells */
3622:       *numFaceVertices = 9; /* Face has 9 vertices */
3623:       break;
3624:     default:
3625:       SETERRQ2(comm, PETSC_ERR_ARG_OUTOFRANGE, "Invalid number of face corners %D for dimension %D", numCorners, cellDim);
3626:     }
3627:     break;
3628:   default:
3629:     SETERRQ1(comm, PETSC_ERR_ARG_OUTOFRANGE, "Invalid cell dimension %D", cellDim);
3630:   }
3631:   return(0);
3632: }

3634: /*@
3635:   DMPlexGetDepthLabel - Get the DMLabel recording the depth of each point

3637:   Not Collective

3639:   Input Parameter:
3640: . dm    - The DMPlex object

3642:   Output Parameter:
3643: . depthLabel - The DMLabel recording point depth

3645:   Level: developer

3647: .seealso: DMPlexGetDepth(), DMPlexGetHeightStratum(), DMPlexGetDepthStratum(), DMPlexGetPointDepth(), 
3648: @*/
3649: PetscErrorCode DMPlexGetDepthLabel(DM dm, DMLabel *depthLabel)
3650: {
3654:   *depthLabel = dm->depthLabel;
3655:   return(0);
3656: }

3658: /*@
3659:   DMPlexGetDepth - Get the depth of the DAG representing this mesh

3661:   Not Collective

3663:   Input Parameter:
3664: . dm    - The DMPlex object

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

3669:   Level: developer

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

3676: .seealso: DMPlexGetDepthLabel(), DMPlexGetDepthStratum(), DMPlexGetPointDepth(), DMPlexSymmetrize()
3677: @*/
3678: PetscErrorCode DMPlexGetDepth(DM dm, PetscInt *depth)
3679: {
3680:   DMLabel        label;
3681:   PetscInt       d = 0;

3687:   DMPlexGetDepthLabel(dm, &label);
3688:   if (label) {DMLabelGetNumValues(label, &d);}
3689:   *depth = d-1;
3690:   return(0);
3691: }

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

3696:   Not Collective

3698:   Input Parameters:
3699: + dm           - The DMPlex object
3700: - stratumValue - The requested depth

3702:   Output Parameters:
3703: + start - The first point at this depth
3704: - end   - One beyond the last point at this depth

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

3711:   Level: developer

3713: .seealso: DMPlexGetHeightStratum(), DMPlexGetDepth(), DMPlexGetDepthLabel(), DMPlexGetPointDepth(), DMPlexSymmetrize(), DMPlexInterpolate()
3714: @*/
3715: PetscErrorCode DMPlexGetDepthStratum(DM dm, PetscInt stratumValue, PetscInt *start, PetscInt *end)
3716: {
3717:   DMLabel        label;
3718:   PetscInt       pStart, pEnd;

3725:   DMPlexGetChart(dm, &pStart, &pEnd);
3726:   if (pStart == pEnd) return(0);
3727:   if (stratumValue < 0) {
3728:     if (start) *start = pStart;
3729:     if (end)   *end   = pEnd;
3730:     return(0);
3731:   }
3732:   DMPlexGetDepthLabel(dm, &label);
3733:   if (!label) SETERRQ(PetscObjectComm((PetscObject) dm), PETSC_ERR_ARG_WRONG, "No label named depth was found");
3734:   DMLabelGetStratumBounds(label, stratumValue, start, end);
3735:   return(0);
3736: }

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

3741:   Not Collective

3743:   Input Parameters:
3744: + dm           - The DMPlex object
3745: - stratumValue - The requested height

3747:   Output Parameters:
3748: + start - The first point at this height
3749: - end   - One beyond the last point at this height

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

3756:   Level: developer

3758: .seealso: DMPlexGetDepthStratum(), DMPlexGetDepth(), DMPlexGetPointHeight()
3759: @*/
3760: PetscErrorCode DMPlexGetHeightStratum(DM dm, PetscInt stratumValue, PetscInt *start, PetscInt *end)
3761: {
3762:   DMLabel        label;
3763:   PetscInt       depth, pStart, pEnd;

3770:   DMPlexGetChart(dm, &pStart, &pEnd);
3771:   if (pStart == pEnd) return(0);
3772:   if (stratumValue < 0) {
3773:     if (start) *start = pStart;
3774:     if (end)   *end   = pEnd;
3775:     return(0);
3776:   }
3777:   DMPlexGetDepthLabel(dm, &label);
3778:   if (!label) SETERRQ(PetscObjectComm((PetscObject) dm), PETSC_ERR_ARG_WRONG, "No label named depth was found");
3779:   DMLabelGetNumValues(label, &depth);
3780:   DMLabelGetStratumBounds(label, depth-1-stratumValue, start, end);
3781:   return(0);
3782: }

3784: /*@
3785:   DMPlexGetPointDepth - Get the depth of a given point

3787:   Not Collective

3789:   Input Parameter:
3790: + dm    - The DMPlex object
3791: - point - The point

3793:   Output Parameter:
3794: . depth - The depth of the point

3796:   Level: intermediate

3798: .seealso: DMPlexGetCellType(), DMPlexGetDepthLabel(), DMPlexGetDepth(), DMPlexGetPointHeight()
3799: @*/
3800: PetscErrorCode DMPlexGetPointDepth(DM dm, PetscInt point, PetscInt *depth)
3801: {

3807:   DMLabelGetValue(dm->depthLabel, point, depth);
3808:   return(0);
3809: }

3811: /*@
3812:   DMPlexGetPointHeight - Get the height of a given point

3814:   Not Collective

3816:   Input Parameter:
3817: + dm    - The DMPlex object
3818: - point - The point

3820:   Output Parameter:
3821: . height - The height of the point

3823:   Level: intermediate

3825: .seealso: DMPlexGetCellType(), DMPlexGetDepthLabel(), DMPlexGetDepth(), DMPlexGetPointDepth()
3826: @*/
3827: PetscErrorCode DMPlexGetPointHeight(DM dm, PetscInt point, PetscInt *height)
3828: {
3829:   PetscInt       n, pDepth;

3835:   DMLabelGetNumValues(dm->depthLabel, &n);
3836:   DMLabelGetValue(dm->depthLabel, point, &pDepth);
3837:   *height = n - 1 - pDepth;  /* DAG depth is n-1 */
3838:   return(0);
3839: }

3841: /*@
3842:   DMPlexGetCellTypeLabel - Get the DMLabel recording the polytope type of each cell

3844:   Not Collective

3846:   Input Parameter:
3847: . dm - The DMPlex object

3849:   Output Parameter:
3850: . celltypeLabel - The DMLabel recording cell polytope type

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

3855:   Level: developer

3857: .seealso: DMPlexGetCellType(), DMPlexGetDepthLabel(), DMCreateLabel()
3858: @*/
3859: PetscErrorCode DMPlexGetCellTypeLabel(DM dm, DMLabel *celltypeLabel)
3860: {

3866:   if (!dm->celltypeLabel) {DMPlexComputeCellTypes(dm);}
3867:   *celltypeLabel = dm->celltypeLabel;
3868:   return(0);
3869: }

3871: /*@
3872:   DMPlexGetCellType - Get the polytope type of a given cell

3874:   Not Collective

3876:   Input Parameter:
3877: + dm   - The DMPlex object
3878: - cell - The cell

3880:   Output Parameter:
3881: . celltype - The polytope type of the cell

3883:   Level: intermediate

3885: .seealso: DMPlexGetCellTypeLabel(), DMPlexGetDepthLabel(), DMPlexGetDepth()
3886: @*/
3887: PetscErrorCode DMPlexGetCellType(DM dm, PetscInt cell, DMPolytopeType *celltype)
3888: {
3889:   DMLabel        label;
3890:   PetscInt       ct;

3896:   DMPlexGetCellTypeLabel(dm, &label);
3897:   DMLabelGetValue(label, cell, &ct);
3898:   *celltype = (DMPolytopeType) ct;
3899:   return(0);
3900: }

3902: /*@
3903:   DMPlexSetCellType - Set the polytope type of a given cell

3905:   Not Collective

3907:   Input Parameters:
3908: + dm   - The DMPlex object
3909: . cell - The cell
3910: - celltype - The polytope type of the cell

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

3917:   Level: advanced

3919: .seealso: DMPlexGetCellTypeLabel(), DMPlexGetDepthLabel(), DMPlexGetDepth(), DMPlexComputeCellTypes(), DMCreateLabel()
3920: @*/
3921: PetscErrorCode DMPlexSetCellType(DM dm, PetscInt cell, DMPolytopeType celltype)
3922: {
3923:   DMLabel        label;

3928:   DMPlexGetCellTypeLabel(dm, &label);
3929:   DMLabelSetValue(label, cell, celltype);
3930:   return(0);
3931: }

3933: PetscErrorCode DMCreateCoordinateDM_Plex(DM dm, DM *cdm)
3934: {
3935:   PetscSection   section, s;
3936:   Mat            m;
3937:   PetscInt       maxHeight;

3941:   DMClone(dm, cdm);
3942:   DMPlexGetMaxProjectionHeight(dm, &maxHeight);
3943:   DMPlexSetMaxProjectionHeight(*cdm, maxHeight);
3944:   PetscSectionCreate(PetscObjectComm((PetscObject)dm), &section);
3945:   DMSetLocalSection(*cdm, section);
3946:   PetscSectionDestroy(&section);
3947:   PetscSectionCreate(PETSC_COMM_SELF, &s);
3948:   MatCreate(PETSC_COMM_SELF, &m);
3949:   DMSetDefaultConstraints(*cdm, s, m);
3950:   PetscSectionDestroy(&s);
3951:   MatDestroy(&m);

3953:   DMSetNumFields(*cdm, 1);
3954:   DMCreateDS(*cdm);
3955:   return(0);
3956: }

3958: PetscErrorCode DMCreateCoordinateField_Plex(DM dm, DMField *field)
3959: {
3960:   Vec            coordsLocal;
3961:   DM             coordsDM;

3965:   *field = NULL;
3966:   DMGetCoordinatesLocal(dm,&coordsLocal);
3967:   DMGetCoordinateDM(dm,&coordsDM);
3968:   if (coordsLocal && coordsDM) {
3969:     DMFieldCreateDS(coordsDM, 0, coordsLocal, field);
3970:   }
3971:   return(0);
3972: }

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

3977:   Not Collective

3979:   Input Parameters:
3980: . dm        - The DMPlex object

3982:   Output Parameter:
3983: . section - The PetscSection object

3985:   Level: developer

3987: .seealso: DMPlexGetSupportSection(), DMPlexGetCones(), DMPlexGetConeOrientations()
3988: @*/
3989: PetscErrorCode DMPlexGetConeSection(DM dm, PetscSection *section)
3990: {
3991:   DM_Plex *mesh = (DM_Plex*) dm->data;

3995:   if (section) *section = mesh->coneSection;
3996:   return(0);
3997: }

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

4002:   Not Collective

4004:   Input Parameters:
4005: . dm        - The DMPlex object

4007:   Output Parameter:
4008: . section - The PetscSection object

4010:   Level: developer

4012: .seealso: DMPlexGetConeSection()
4013: @*/
4014: PetscErrorCode DMPlexGetSupportSection(DM dm, PetscSection *section)
4015: {
4016:   DM_Plex *mesh = (DM_Plex*) dm->data;

4020:   if (section) *section = mesh->supportSection;
4021:   return(0);
4022: }

4024: /*@C
4025:   DMPlexGetCones - Return cone data

4027:   Not Collective

4029:   Input Parameters:
4030: . dm        - The DMPlex object

4032:   Output Parameter:
4033: . cones - The cone for each point

4035:   Level: developer

4037: .seealso: DMPlexGetConeSection()
4038: @*/
4039: PetscErrorCode DMPlexGetCones(DM dm, PetscInt *cones[])
4040: {
4041:   DM_Plex *mesh = (DM_Plex*) dm->data;

4045:   if (cones) *cones = mesh->cones;
4046:   return(0);
4047: }

4049: /*@C
4050:   DMPlexGetConeOrientations - Return cone orientation data

4052:   Not Collective

4054:   Input Parameters:
4055: . dm        - The DMPlex object

4057:   Output Parameter:
4058: . coneOrientations - The cone orientation for each point

4060:   Level: developer

4062: .seealso: DMPlexGetConeSection()
4063: @*/
4064: PetscErrorCode DMPlexGetConeOrientations(DM dm, PetscInt *coneOrientations[])
4065: {
4066:   DM_Plex *mesh = (DM_Plex*) dm->data;

4070:   if (coneOrientations) *coneOrientations = mesh->coneOrientations;
4071:   return(0);
4072: }

4074: /******************************** FEM Support **********************************/

4076: /*
4077:  Returns number of components and tensor degree for the field.  For interpolated meshes, line should be a point
4078:  representing a line in the section.
4079: */
4080: static PetscErrorCode PetscSectionFieldGetTensorDegree_Private(PetscSection section,PetscInt field,PetscInt line,PetscBool vertexchart,PetscInt *Nc,PetscInt *k)
4081: {

4085:   PetscSectionGetFieldComponents(section, field, Nc);
4086:   if (line < 0) {
4087:     *k = 0;
4088:     *Nc = 0;
4089:   } else if (vertexchart) {            /* If we only have a vertex chart, we must have degree k=1 */
4090:     *k = 1;
4091:   } else {                      /* Assume the full interpolated mesh is in the chart; lines in particular */
4092:     /* An order k SEM disc has k-1 dofs on an edge */
4093:     PetscSectionGetFieldDof(section, line, field, k);
4094:     *k = *k / *Nc + 1;
4095:   }
4096:   return(0);
4097: }

4099: /*@

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

4105:   Input Parameters:
4106: + dm      - The DM
4107: . point   - Either a cell (highest dim point) or an edge (dim 1 point), or PETSC_DETERMINE
4108: - section - The PetscSection to reorder, or NULL for the default section

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

4113:   Example:
4114:   A typical interpolated single-quad mesh might order points as
4115: .vb
4116:   [c0, v1, v2, v3, v4, e5, e6, e7, e8]

4118:   v4 -- e6 -- v3
4119:   |           |
4120:   e7    c0    e8
4121:   |           |
4122:   v1 -- e5 -- v2
4123: .ve

4125:   (There is no significance to the ordering described here.)  The default section for a Q3 quad might typically assign
4126:   dofs in the order of points, e.g.,
4127: .vb
4128:     c0 -> [0,1,2,3]
4129:     v1 -> [4]
4130:     ...
4131:     e5 -> [8, 9]
4132: .ve

4134:   which corresponds to the dofs
4135: .vb
4136:     6   10  11  7
4137:     13  2   3   15
4138:     12  0   1   14
4139:     4   8   9   5
4140: .ve

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

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

4152:   Level: developer

4154: .seealso: DMGetLocalSection(), PetscSectionSetClosurePermutation(), DMSetGlobalSection()
4155: @*/
4156: PetscErrorCode DMPlexSetClosurePermutationTensor(DM dm, PetscInt point, PetscSection section)
4157: {
4158:   DMLabel        label;
4159:   PetscInt      *perm;
4160:   PetscInt       dim, depth = -1, eStart = -1, k, Nf, f, Nc, c, i, j, size = 0, offset = 0, foffset = 0;
4161:   PetscBool      vertexchart;

4165:   DMGetDimension(dm, &dim);
4166:   if (dim < 1) return(0);
4167:   if (point < 0) {
4168:     PetscInt sStart,sEnd;

4170:     DMPlexGetDepthStratum(dm, 1, &sStart, &sEnd);
4171:     point = sEnd-sStart ? sStart : point;
4172:   }
4173:   DMPlexGetDepthLabel(dm, &label);
4174:   if (point >= 0) { DMLabelGetValue(label, point, &depth); }
4175:   if (!section) {DMGetLocalSection(dm, &section);}
4176:   if (depth == 1) {eStart = point;}
4177:   else if  (depth == dim) {
4178:     const PetscInt *cone;

4180:     DMPlexGetCone(dm, point, &cone);
4181:     if (dim == 2) eStart = cone[0];
4182:     else if (dim == 3) {
4183:       const PetscInt *cone2;
4184:       DMPlexGetCone(dm, cone[0], &cone2);
4185:       eStart = cone2[0];
4186:     } else SETERRQ3(PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Point %D of depth %D cannot be used to bootstrap spectral ordering for dim %D", point, depth, dim);
4187:   } else if (depth >= 0) SETERRQ3(PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Point %D of depth %D cannot be used to bootstrap spectral ordering for dim %D", point, depth, dim);
4188:   {                             /* Determine whether the chart covers all points or just vertices. */
4189:     PetscInt pStart,pEnd,cStart,cEnd;
4190:     DMPlexGetDepthStratum(dm,0,&pStart,&pEnd);
4191:     PetscSectionGetChart(section,&cStart,&cEnd);
4192:     if (pStart == cStart && pEnd == cEnd) vertexchart = PETSC_TRUE; /* Just vertices */
4193:     else vertexchart = PETSC_FALSE;                                 /* Assume all interpolated points are in chart */
4194:   }
4195:   PetscSectionGetNumFields(section, &Nf);
4196:   for (f = 0; f < Nf; ++f) {
4197:     PetscSectionFieldGetTensorDegree_Private(section,f,eStart,vertexchart,&Nc,&k);
4198:     size += PetscPowInt(k+1, dim)*Nc;
4199:   }
4200:   PetscMalloc1(size, &perm);
4201:   for (f = 0; f < Nf; ++f) {
4202:     switch (dim) {
4203:     case 1:
4204:       PetscSectionFieldGetTensorDegree_Private(section,f,eStart,vertexchart,&Nc,&k);
4205:       /*
4206:         Original ordering is [ edge of length k-1; vtx0; vtx1 ]
4207:         We want              [ vtx0; edge of length k-1; vtx1 ]
4208:       */
4209:       for (c=0; c<Nc; c++,offset++) perm[offset] = (k-1)*Nc + c + foffset;
4210:       for (i=0; i<k-1; i++) for (c=0; c<Nc; c++,offset++) perm[offset] = i*Nc + c + foffset;
4211:       for (c=0; c<Nc; c++,offset++) perm[offset] = k*Nc + c + foffset;
4212:       foffset = offset;
4213:       break;
4214:     case 2:
4215:       /* The original quad closure is oriented clockwise, {f, e_b, e_r, e_t, e_l, v_lb, v_rb, v_tr, v_tl} */
4216:       PetscSectionFieldGetTensorDegree_Private(section,f,eStart,vertexchart,&Nc,&k);
4217:       /* The SEM order is

4219:          v_lb, {e_b}, v_rb,
4220:          e^{(k-1)-i}_l, {f^{i*(k-1)}}, e^i_r,
4221:          v_lt, reverse {e_t}, v_rt
4222:       */
4223:       {
4224:         const PetscInt of   = 0;
4225:         const PetscInt oeb  = of   + PetscSqr(k-1);
4226:         const PetscInt oer  = oeb  + (k-1);
4227:         const PetscInt oet  = oer  + (k-1);
4228:         const PetscInt oel  = oet  + (k-1);
4229:         const PetscInt ovlb = oel  + (k-1);
4230:         const PetscInt ovrb = ovlb + 1;
4231:         const PetscInt ovrt = ovrb + 1;
4232:         const PetscInt ovlt = ovrt + 1;
4233:         PetscInt       o;

4235:         /* bottom */
4236:         for (c = 0; c < Nc; ++c, ++offset) perm[offset] = ovlb*Nc + c + foffset;
4237:         for (o = oeb; o < oer; ++o) for (c = 0; c < Nc; ++c, ++offset) perm[offset] = o*Nc + c + foffset;
4238:         for (c = 0; c < Nc; ++c, ++offset) perm[offset] = ovrb*Nc + c + foffset;
4239:         /* middle */
4240:         for (i = 0; i < k-1; ++i) {
4241:           for (c = 0; c < Nc; ++c, ++offset) perm[offset] = (oel+(k-2)-i)*Nc + c + foffset;
4242:           for (o = of+(k-1)*i; o < of+(k-1)*(i+1); ++o) for (c = 0; c < Nc; ++c, ++offset) perm[offset] = o*Nc + c + foffset;
4243:           for (c = 0; c < Nc; ++c, ++offset) perm[offset] = (oer+i)*Nc + c + foffset;
4244:         }
4245:         /* top */
4246:         for (c = 0; c < Nc; ++c, ++offset) perm[offset] = ovlt*Nc + c + foffset;
4247:         for (o = oel-1; o >= oet; --o) for (c = 0; c < Nc; ++c, ++offset) perm[offset] = o*Nc + c + foffset;
4248:         for (c = 0; c < Nc; ++c, ++offset) perm[offset] = ovrt*Nc + c + foffset;
4249:         foffset = offset;
4250:       }
4251:       break;
4252:     case 3:
4253:       /* The original hex closure is

4255:          {c,
4256:           f_b, f_t, f_f, f_b, f_r, f_l,
4257:           e_bl, e_bb, e_br, e_bf,  e_tf, e_tr, e_tb, e_tl,  e_rf, e_lf, e_lb, e_rb,
4258:           v_blf, v_blb, v_brb, v_brf, v_tlf, v_trf, v_trb, v_tlb}
4259:       */
4260:       PetscSectionFieldGetTensorDegree_Private(section,f,eStart,vertexchart,&Nc,&k);
4261:       /* The SEM order is
4262:          Bottom Slice
4263:          v_blf, {e^{(k-1)-n}_bf}, v_brf,
4264:          e^{i}_bl, f^{n*(k-1)+(k-1)-i}_b, e^{(k-1)-i}_br,
4265:          v_blb, {e_bb}, v_brb,

4267:          Middle Slice (j)
4268:          {e^{(k-1)-j}_lf}, {f^{j*(k-1)+n}_f}, e^j_rf,
4269:          f^{i*(k-1)+j}_l, {c^{(j*(k-1) + i)*(k-1)+n}_t}, f^{j*(k-1)+i}_r,
4270:          e^j_lb, {f^{j*(k-1)+(k-1)-n}_b}, e^{(k-1)-j}_rb,

4272:          Top Slice
4273:          v_tlf, {e_tf}, v_trf,
4274:          e^{(k-1)-i}_tl, {f^{i*(k-1)}_t}, e^{i}_tr,
4275:          v_tlb, {e^{(k-1)-n}_tb}, v_trb,
4276:       */
4277:       {
4278:         const PetscInt oc    = 0;
4279:         const PetscInt ofb   = oc    + PetscSqr(k-1)*(k-1);
4280:         const PetscInt oft   = ofb   + PetscSqr(k-1);
4281:         const PetscInt off   = oft   + PetscSqr(k-1);
4282:         const PetscInt ofk   = off   + PetscSqr(k-1);
4283:         const PetscInt ofr   = ofk   + PetscSqr(k-1);
4284:         const PetscInt ofl   = ofr   + PetscSqr(k-1);
4285:         const PetscInt oebl  = ofl   + PetscSqr(k-1);
4286:         const PetscInt oebb  = oebl  + (k-1);
4287:         const PetscInt oebr  = oebb  + (k-1);
4288:         const PetscInt oebf  = oebr  + (k-1);
4289:         const PetscInt oetf  = oebf  + (k-1);
4290:         const PetscInt oetr  = oetf  + (k-1);
4291:         const PetscInt oetb  = oetr  + (k-1);
4292:         const PetscInt oetl  = oetb  + (k-1);
4293:         const PetscInt oerf  = oetl  + (k-1);
4294:         const PetscInt oelf  = oerf  + (k-1);
4295:         const PetscInt oelb  = oelf  + (k-1);
4296:         const PetscInt oerb  = oelb  + (k-1);
4297:         const PetscInt ovblf = oerb  + (k-1);
4298:         const PetscInt ovblb = ovblf + 1;
4299:         const PetscInt ovbrb = ovblb + 1;
4300:         const PetscInt ovbrf = ovbrb + 1;
4301:         const PetscInt ovtlf = ovbrf + 1;
4302:         const PetscInt ovtrf = ovtlf + 1;
4303:         const PetscInt ovtrb = ovtrf + 1;
4304:         const PetscInt ovtlb = ovtrb + 1;
4305:         PetscInt       o, n;

4307:         /* Bottom Slice */
4308:         /*   bottom */
4309:         for (c = 0; c < Nc; ++c, ++offset) perm[offset] = ovblf*Nc + c + foffset;
4310:         for (o = oetf-1; o >= oebf; --o) for (c = 0; c < Nc; ++c, ++offset) perm[offset] = o*Nc + c + foffset;
4311:         for (c = 0; c < Nc; ++c, ++offset) perm[offset] = ovbrf*Nc + c + foffset;
4312:         /*   middle */
4313:         for (i = 0; i < k-1; ++i) {
4314:           for (c = 0; c < Nc; ++c, ++offset) perm[offset] = (oebl+i)*Nc + c + foffset;
4315:           for (n = 0; n < k-1; ++n) {o = ofb+n*(k-1)+i; for (c = 0; c < Nc; ++c, ++offset) perm[offset] = o*Nc + c + foffset;}
4316:           for (c = 0; c < Nc; ++c, ++offset) perm[offset] = (oebr+(k-2)-i)*Nc + c + foffset;
4317:         }
4318:         /*   top */
4319:         for (c = 0; c < Nc; ++c, ++offset) perm[offset] = ovblb*Nc + c + foffset;
4320:         for (o = oebb; o < oebr; ++o) for (c = 0; c < Nc; ++c, ++offset) perm[offset] = o*Nc + c + foffset;
4321:         for (c = 0; c < Nc; ++c, ++offset) perm[offset] = ovbrb*Nc + c + foffset;

4323:         /* Middle Slice */
4324:         for (j = 0; j < k-1; ++j) {
4325:           /*   bottom */
4326:           for (c = 0; c < Nc; ++c, ++offset) perm[offset] = (oelf+(k-2)-j)*Nc + c + foffset;
4327:           for (o = off+j*(k-1); o < off+(j+1)*(k-1); ++o) for (c = 0; c < Nc; ++c, ++offset) perm[offset] = o*Nc + c + foffset;
4328:           for (c = 0; c < Nc; ++c, ++offset) perm[offset] = (oerf+j)*Nc + c + foffset;
4329:           /*   middle */
4330:           for (i = 0; i < k-1; ++i) {
4331:             for (c = 0; c < Nc; ++c, ++offset) perm[offset] = (ofl+i*(k-1)+j)*Nc + c + foffset;
4332:             for (n = 0; n < k-1; ++n) for (c = 0; c < Nc; ++c, ++offset) perm[offset] = (oc+(j*(k-1)+i)*(k-1)+n)*Nc + c + foffset;
4333:             for (c = 0; c < Nc; ++c, ++offset) perm[offset] = (ofr+j*(k-1)+i)*Nc + c + foffset;
4334:           }
4335:           /*   top */
4336:           for (c = 0; c < Nc; ++c, ++offset) perm[offset] = (oelb+j)*Nc + c + foffset;
4337:           for (o = ofk+j*(k-1)+(k-2); o >= ofk+j*(k-1); --o) for (c = 0; c < Nc; ++c, ++offset) perm[offset] = o*Nc + c + foffset;
4338:           for (c = 0; c < Nc; ++c, ++offset) perm[offset] = (oerb+(k-2)-j)*Nc + c + foffset;
4339:         }

4341:         /* Top Slice */
4342:         /*   bottom */
4343:         for (c = 0; c < Nc; ++c, ++offset) perm[offset] = ovtlf*Nc + c + foffset;
4344:         for (o = oetf; o < oetr; ++o) for (c = 0; c < Nc; ++c, ++offset) perm[offset] = o*Nc + c + foffset;
4345:         for (c = 0; c < Nc; ++c, ++offset) perm[offset] = ovtrf*Nc + c + foffset;
4346:         /*   middle */
4347:         for (i = 0; i < k-1; ++i) {
4348:           for (c = 0; c < Nc; ++c, ++offset) perm[offset] = (oetl+(k-2)-i)*Nc + c + foffset;
4349:           for (n = 0; n < k-1; ++n) for (c = 0; c < Nc; ++c, ++offset) perm[offset] = (oft+i*(k-1)+n)*Nc + c + foffset;
4350:           for (c = 0; c < Nc; ++c, ++offset) perm[offset] = (oetr+i)*Nc + c + foffset;
4351:         }
4352:         /*   top */
4353:         for (c = 0; c < Nc; ++c, ++offset) perm[offset] = ovtlb*Nc + c + foffset;
4354:         for (o = oetl-1; o >= oetb; --o) for (c = 0; c < Nc; ++c, ++offset) perm[offset] = o*Nc + c + foffset;
4355:         for (c = 0; c < Nc; ++c, ++offset) perm[offset] = ovtrb*Nc + c + foffset;

4357:         foffset = offset;
4358:       }
4359:       break;
4360:     default: SETERRQ1(PetscObjectComm((PetscObject) dm), PETSC_ERR_ARG_OUTOFRANGE, "No spectral ordering for dimension %D", dim);
4361:     }
4362:   }
4363:   if (offset != size) SETERRQ2(PetscObjectComm((PetscObject) dm), PETSC_ERR_PLIB, "Number of permutation entries %D != %D", offset, size);
4364:   /* Check permutation */
4365:   {
4366:     PetscInt *check;

4368:     PetscMalloc1(size, &check);
4369:     for (i = 0; i < size; ++i) {check[i] = -1; if (perm[i] < 0 || perm[i] >= size) SETERRQ2(PetscObjectComm((PetscObject) dm), PETSC_ERR_PLIB, "Invalid permutation index p[%D] = %D", i, perm[i]);}
4370:     for (i = 0; i < size; ++i) check[perm[i]] = i;
4371:     for (i = 0; i < size; ++i) {if (check[i] < 0) SETERRQ1(PetscObjectComm((PetscObject) dm), PETSC_ERR_PLIB, "Missing permutation index %D", i);}
4372:     PetscFree(check);
4373:   }
4374:   PetscSectionSetClosurePermutation_Internal(section, (PetscObject) dm, size, PETSC_OWN_POINTER, perm);
4375:   return(0);
4376: }

4378: PetscErrorCode DMPlexGetPointDualSpaceFEM(DM dm, PetscInt point, PetscInt field, PetscDualSpace *dspace)
4379: {
4380:   PetscDS        prob;
4381:   PetscInt       depth, Nf, h;
4382:   DMLabel        label;

4386:   DMGetDS(dm, &prob);
4387:   Nf      = prob->Nf;
4388:   label   = dm->depthLabel;
4389:   *dspace = NULL;
4390:   if (field < Nf) {
4391:     PetscObject disc = prob->disc[field];

4393:     if (disc->classid == PETSCFE_CLASSID) {
4394:       PetscDualSpace dsp;

4396:       PetscFEGetDualSpace((PetscFE)disc,&dsp);
4397:       DMLabelGetNumValues(label,&depth);
4398:       DMLabelGetValue(label,point,&h);
4399:       h    = depth - 1 - h;
4400:       if (h) {
4401:         PetscDualSpaceGetHeightSubspace(dsp,h,dspace);
4402:       } else {
4403:         *dspace = dsp;
4404:       }
4405:     }
4406:   }
4407:   return(0);
4408: }


4411: PETSC_STATIC_INLINE PetscErrorCode DMPlexVecGetClosure_Depth1_Static(DM dm, PetscSection section, Vec v, PetscInt point, PetscInt *csize, PetscScalar *values[])
4412: {
4413:   PetscScalar    *array, *vArray;
4414:   const PetscInt *cone, *coneO;
4415:   PetscInt        pStart, pEnd, p, numPoints, size = 0, offset = 0;
4416:   PetscErrorCode  ierr;

4419:   PetscSectionGetChart(section, &pStart, &pEnd);
4420:   DMPlexGetConeSize(dm, point, &numPoints);
4421:   DMPlexGetCone(dm, point, &cone);
4422:   DMPlexGetConeOrientation(dm, point, &coneO);
4423:   if (!values || !*values) {
4424:     if ((point >= pStart) && (point < pEnd)) {
4425:       PetscInt dof;

4427:       PetscSectionGetDof(section, point, &dof);
4428:       size += dof;
4429:     }
4430:     for (p = 0; p < numPoints; ++p) {
4431:       const PetscInt cp = cone[p];
4432:       PetscInt       dof;

4434:       if ((cp < pStart) || (cp >= pEnd)) continue;
4435:       PetscSectionGetDof(section, cp, &dof);
4436:       size += dof;
4437:     }
4438:     if (!values) {
4439:       if (csize) *csize = size;
4440:       return(0);
4441:     }
4442:     DMGetWorkArray(dm, size, MPIU_SCALAR, &array);
4443:   } else {
4444:     array = *values;
4445:   }
4446:   size = 0;
4447:   VecGetArray(v, &vArray);
4448:   if ((point >= pStart) && (point < pEnd)) {
4449:     PetscInt     dof, off, d;
4450:     PetscScalar *varr;

4452:     PetscSectionGetDof(section, point, &dof);
4453:     PetscSectionGetOffset(section, point, &off);
4454:     varr = &vArray[off];
4455:     for (d = 0; d < dof; ++d, ++offset) {
4456:       array[offset] = varr[d];
4457:     }
4458:     size += dof;
4459:   }
4460:   for (p = 0; p < numPoints; ++p) {
4461:     const PetscInt cp = cone[p];
4462:     PetscInt       o  = coneO[p];
4463:     PetscInt       dof, off, d;
4464:     PetscScalar   *varr;

4466:     if ((cp < pStart) || (cp >= pEnd)) continue;
4467:     PetscSectionGetDof(section, cp, &dof);
4468:     PetscSectionGetOffset(section, cp, &off);
4469:     varr = &vArray[off];
4470:     if (o >= 0) {
4471:       for (d = 0; d < dof; ++d, ++offset) {
4472:         array[offset] = varr[d];
4473:       }
4474:     } else {
4475:       for (d = dof-1; d >= 0; --d, ++offset) {
4476:         array[offset] = varr[d];
4477:       }
4478:     }
4479:     size += dof;
4480:   }
4481:   VecRestoreArray(v, &vArray);
4482:   if (!*values) {
4483:     if (csize) *csize = size;
4484:     *values = array;
4485:   } else {
4486:     if (size > *csize) SETERRQ2(PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Size of input array %D < actual size %D", *csize, size);
4487:     *csize = size;
4488:   }
4489:   return(0);
4490: }

4492: /* Compressed closure does not apply closure permutation */
4493: PetscErrorCode DMPlexGetCompressedClosure(DM dm, PetscSection section, PetscInt point, PetscInt *numPoints, PetscInt **points, PetscSection *clSec, IS *clPoints, const PetscInt **clp)
4494: {
4495:   const PetscInt *cla;
4496:   PetscInt       np, *pts = NULL;

4500:   PetscSectionGetClosureIndex(section, (PetscObject) dm, clSec, clPoints);
4501:   if (!*clPoints) {
4502:     PetscInt pStart, pEnd, p, q;

4504:     PetscSectionGetChart(section, &pStart, &pEnd);
4505:     DMPlexGetTransitiveClosure(dm, point, PETSC_TRUE, &np, &pts);
4506:     /* Compress out points not in the section */
4507:     for (p = 0, q = 0; p < np; p++) {
4508:       PetscInt r = pts[2*p];
4509:       if ((r >= pStart) && (r < pEnd)) {
4510:         pts[q*2]   = r;
4511:         pts[q*2+1] = pts[2*p+1];
4512:         ++q;
4513:       }
4514:     }
4515:     np = q;
4516:     cla = NULL;
4517:   } else {
4518:     PetscInt dof, off;

4520:     PetscSectionGetDof(*clSec, point, &dof);
4521:     PetscSectionGetOffset(*clSec, point, &off);
4522:     ISGetIndices(*clPoints, &cla);
4523:     np   = dof/2;
4524:     pts  = (PetscInt *) &cla[off];
4525:   }
4526:   *numPoints = np;
4527:   *points    = pts;
4528:   *clp       = cla;

4530:   return(0);
4531: }

4533: PetscErrorCode DMPlexRestoreCompressedClosure(DM dm, PetscSection section, PetscInt point, PetscInt *numPoints, PetscInt **points, PetscSection *clSec, IS *clPoints, const PetscInt **clp)
4534: {

4538:   if (!*clPoints) {
4539:     DMPlexRestoreTransitiveClosure(dm, point, PETSC_TRUE, numPoints, points);
4540:   } else {
4541:     ISRestoreIndices(*clPoints, clp);
4542:   }
4543:   *numPoints = 0;
4544:   *points    = NULL;
4545:   *clSec     = NULL;
4546:   *clPoints  = NULL;
4547:   *clp       = NULL;
4548:   return(0);
4549: }

4551: PETSC_STATIC_INLINE PetscErrorCode DMPlexVecGetClosure_Static(DM dm, PetscSection section, PetscInt numPoints, const PetscInt points[], const PetscInt clperm[], const PetscScalar vArray[], PetscInt *size, PetscScalar array[])
4552: {
4553:   PetscInt          offset = 0, p;
4554:   const PetscInt    **perms = NULL;
4555:   const PetscScalar **flips = NULL;
4556:   PetscErrorCode    ierr;

4559:   *size = 0;
4560:   PetscSectionGetPointSyms(section,numPoints,points,&perms,&flips);
4561:   for (p = 0; p < numPoints; p++) {
4562:     const PetscInt    point = points[2*p];
4563:     const PetscInt    *perm = perms ? perms[p] : NULL;
4564:     const PetscScalar *flip = flips ? flips[p] : NULL;
4565:     PetscInt          dof, off, d;
4566:     const PetscScalar *varr;

4568:     PetscSectionGetDof(section, point, &dof);
4569:     PetscSectionGetOffset(section, point, &off);
4570:     varr = &vArray[off];
4571:     if (clperm) {
4572:       if (perm) {
4573:         for (d = 0; d < dof; d++) array[clperm[offset + perm[d]]]  = varr[d];
4574:       } else {
4575:         for (d = 0; d < dof; d++) array[clperm[offset +      d ]]  = varr[d];
4576:       }
4577:       if (flip) {
4578:         for (d = 0; d < dof; d++) array[clperm[offset +      d ]] *= flip[d];
4579:       }
4580:     } else {
4581:       if (perm) {
4582:         for (d = 0; d < dof; d++) array[offset + perm[d]]  = varr[d];
4583:       } else {
4584:         for (d = 0; d < dof; d++) array[offset +      d ]  = varr[d];
4585:       }
4586:       if (flip) {
4587:         for (d = 0; d < dof; d++) array[offset +      d ] *= flip[d];
4588:       }
4589:     }
4590:     offset += dof;
4591:   }
4592:   PetscSectionRestorePointSyms(section,numPoints,points,&perms,&flips);
4593:   *size = offset;
4594:   return(0);
4595: }

4597: PETSC_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[])
4598: {
4599:   PetscInt          offset = 0, f;
4600:   PetscErrorCode    ierr;

4603:   *size = 0;
4604:   for (f = 0; f < numFields; ++f) {
4605:     PetscInt          p;
4606:     const PetscInt    **perms = NULL;
4607:     const PetscScalar **flips = NULL;

4609:     PetscSectionGetFieldPointSyms(section,f,numPoints,points,&perms,&flips);
4610:     for (p = 0; p < numPoints; p++) {
4611:       const PetscInt    point = points[2*p];
4612:       PetscInt          fdof, foff, b;
4613:       const PetscScalar *varr;
4614:       const PetscInt    *perm = perms ? perms[p] : NULL;
4615:       const PetscScalar *flip = flips ? flips[p] : NULL;

4617:       PetscSectionGetFieldDof(section, point, f, &fdof);
4618:       PetscSectionGetFieldOffset(section, point, f, &foff);
4619:       varr = &vArray[foff];
4620:       if (clperm) {
4621:         if (perm) {for (b = 0; b < fdof; b++) {array[clperm[offset + perm[b]]]  = varr[b];}}
4622:         else      {for (b = 0; b < fdof; b++) {array[clperm[offset +      b ]]  = varr[b];}}
4623:         if (flip) {for (b = 0; b < fdof; b++) {array[clperm[offset +      b ]] *= flip[b];}}
4624:       } else {
4625:         if (perm) {for (b = 0; b < fdof; b++) {array[offset + perm[b]]  = varr[b];}}
4626:         else      {for (b = 0; b < fdof; b++) {array[offset +      b ]  = varr[b];}}
4627:         if (flip) {for (b = 0; b < fdof; b++) {array[offset +      b ] *= flip[b];}}
4628:       }
4629:       offset += fdof;
4630:     }
4631:     PetscSectionRestoreFieldPointSyms(section,f,numPoints,points,&perms,&flips);
4632:   }
4633:   *size = offset;
4634:   return(0);
4635: }

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

4640:   Not collective

4642:   Input Parameters:
4643: + dm - The DM
4644: . section - The section describing the layout in v, or NULL to use the default section
4645: . v - The local vector
4646: . point - The point in the DM
4647: . csize - The size of the input values array, or NULL
4648: - values - An array to use for the values, or NULL to have it allocated automatically

4650:   Output Parameters:
4651: + csize - The number of values in the closure
4652: - values - The array of values. If the user provided NULL, it is a borrowed array and should not be freed

4654: $ Note that DMPlexVecGetClosure/DMPlexVecRestoreClosure only allocates the values array if it set to NULL in the
4655: $ calling function. This is because DMPlexVecGetClosure() is typically called in the inner loop of a Vec or Mat
4656: $ assembly function, and a user may already have allocated storage for this operation.
4657: $
4658: $ A typical use could be
4659: $
4660: $  values = NULL;
4661: $  DMPlexVecGetClosure(dm, NULL, v, p, &clSize, &values);
4662: $  for (cl = 0; cl < clSize; ++cl) {
4663: $    <Compute on closure>
4664: $  }
4665: $  DMPlexVecRestoreClosure(dm, NULL, v, p, &clSize, &values);
4666: $
4667: $ or
4668: $
4669: $  PetscMalloc1(clMaxSize, &values);
4670: $  for (p = pStart; p < pEnd; ++p) {
4671: $    clSize = clMaxSize;
4672: $    DMPlexVecGetClosure(dm, NULL, v, p, &clSize, &values);
4673: $    for (cl = 0; cl < clSize; ++cl) {
4674: $      <Compute on closure>
4675: $    }
4676: $  }
4677: $  PetscFree(values);

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

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

4685:   Level: intermediate

4687: .seealso DMPlexVecRestoreClosure(), DMPlexVecSetClosure(), DMPlexMatSetClosure()
4688: @*/
4689: PetscErrorCode DMPlexVecGetClosure(DM dm, PetscSection section, Vec v, PetscInt point, PetscInt *csize, PetscScalar *values[])
4690: {
4691:   PetscSection       clSection;
4692:   IS                 clPoints;
4693:   PetscScalar       *array;
4694:   const PetscScalar *vArray;
4695:   PetscInt          *points = NULL;
4696:   const PetscInt    *clp, *perm;
4697:   PetscInt           depth, numFields, numPoints, size;
4698:   PetscErrorCode     ierr;

4702:   if (!section) {DMGetLocalSection(dm, &section);}
4705:   DMPlexGetDepth(dm, &depth);
4706:   PetscSectionGetNumFields(section, &numFields);
4707:   if (depth == 1 && numFields < 2) {
4708:     DMPlexVecGetClosure_Depth1_Static(dm, section, v, point, csize, values);
4709:     return(0);
4710:   }
4711:   /* Get points */
4712:   DMPlexGetCompressedClosure(dm,section,point,&numPoints,&points,&clSection,&clPoints,&clp);
4713:   PetscSectionGetClosureInversePermutation_Internal(section, (PetscObject) dm, NULL, &perm);
4714:   /* Get array */
4715:   if (!values || !*values) {
4716:     PetscInt asize = 0, dof, p;

4718:     for (p = 0; p < numPoints*2; p += 2) {
4719:       PetscSectionGetDof(section, points[p], &dof);
4720:       asize += dof;
4721:     }
4722:     if (!values) {
4723:       DMPlexRestoreCompressedClosure(dm,section,point,&numPoints,&points,&clSection,&clPoints,&clp);
4724:       if (csize) *csize = asize;
4725:       return(0);
4726:     }
4727:     DMGetWorkArray(dm, asize, MPIU_SCALAR, &array);
4728:   } else {
4729:     array = *values;
4730:   }
4731:   VecGetArrayRead(v, &vArray);
4732:   /* Get values */
4733:   if (numFields > 0) {DMPlexVecGetClosure_Fields_Static(dm, section, numPoints, points, numFields, perm, vArray, &size, array);}
4734:   else               {DMPlexVecGetClosure_Static(dm, section, numPoints, points, perm, vArray, &size, array);}
4735:   /* Cleanup points */
4736:   DMPlexRestoreCompressedClosure(dm,section,point,&numPoints,&points,&clSection,&clPoints,&clp);
4737:   /* Cleanup array */
4738:   VecRestoreArrayRead(v, &vArray);
4739:   if (!*values) {
4740:     if (csize) *csize = size;
4741:     *values = array;
4742:   } else {
4743:     if (size > *csize) SETERRQ2(PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Size of input array %D < actual size %D", *csize, size);
4744:     *csize = size;
4745:   }
4746:   return(0);
4747: }

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

4752:   Not collective

4754:   Input Parameters:
4755: + dm - The DM
4756: . section - The section describing the layout in v, or NULL to use the default section
4757: . v - The local vector
4758: . point - The point in the DM
4759: . csize - The number of values in the closure, or NULL
4760: - values - The array of values, which is a borrowed array and should not be freed

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

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

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

4770:   Level: intermediate

4772: .seealso DMPlexVecGetClosure(), DMPlexVecSetClosure(), DMPlexMatSetClosure()
4773: @*/
4774: PetscErrorCode DMPlexVecRestoreClosure(DM dm, PetscSection section, Vec v, PetscInt point, PetscInt *csize, PetscScalar *values[])
4775: {
4776:   PetscInt       size = 0;

4780:   /* Should work without recalculating size */
4781:   DMRestoreWorkArray(dm, size, MPIU_SCALAR, (void*) values);
4782:   *values = NULL;
4783:   return(0);
4784: }

4786: PETSC_STATIC_INLINE void add   (PetscScalar *x, PetscScalar y) {*x += y;}
4787: PETSC_STATIC_INLINE void insert(PetscScalar *x, PetscScalar y) {*x  = y;}

4789: PETSC_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[])
4790: {
4791:   PetscInt        cdof;   /* The number of constraints on this point */
4792:   const PetscInt *cdofs; /* The indices of the constrained dofs on this point */
4793:   PetscScalar    *a;
4794:   PetscInt        off, cind = 0, k;
4795:   PetscErrorCode  ierr;

4798:   PetscSectionGetConstraintDof(section, point, &cdof);
4799:   PetscSectionGetOffset(section, point, &off);
4800:   a    = &array[off];
4801:   if (!cdof || setBC) {
4802:     if (clperm) {
4803:       if (perm) {for (k = 0; k < dof; ++k) {fuse(&a[k], values[clperm[offset+perm[k]]] * (flip ? flip[perm[k]] : 1.));}}
4804:       else      {for (k = 0; k < dof; ++k) {fuse(&a[k], values[clperm[offset+     k ]] * (flip ? flip[     k ] : 1.));}}
4805:     } else {
4806:       if (perm) {for (k = 0; k < dof; ++k) {fuse(&a[k], values[offset+perm[k]] * (flip ? flip[perm[k]] : 1.));}}
4807:       else      {for (k = 0; k < dof; ++k) {fuse(&a[k], values[offset+     k ] * (flip ? flip[     k ] : 1.));}}
4808:     }
4809:   } else {
4810:     PetscSectionGetConstraintIndices(section, point, &cdofs);
4811:     if (clperm) {
4812:       if (perm) {for (k = 0; k < dof; ++k) {
4813:           if ((cind < cdof) && (k == cdofs[cind])) {++cind; continue;}
4814:           fuse(&a[k], values[clperm[offset+perm[k]]] * (flip ? flip[perm[k]] : 1.));
4815:         }
4816:       } else {
4817:         for (k = 0; k < dof; ++k) {
4818:           if ((cind < cdof) && (k == cdofs[cind])) {++cind; continue;}
4819:           fuse(&a[k], values[clperm[offset+     k ]] * (flip ? flip[     k ] : 1.));
4820:         }
4821:       }
4822:     } else {
4823:       if (perm) {
4824:         for (k = 0; k < dof; ++k) {
4825:           if ((cind < cdof) && (k == cdofs[cind])) {++cind; continue;}
4826:           fuse(&a[k], values[offset+perm[k]] * (flip ? flip[perm[k]] : 1.));
4827:         }
4828:       } else {
4829:         for (k = 0; k < dof; ++k) {
4830:           if ((cind < cdof) && (k == cdofs[cind])) {++cind; continue;}
4831:           fuse(&a[k], values[offset+     k ] * (flip ? flip[     k ] : 1.));
4832:         }
4833:       }
4834:     }
4835:   }
4836:   return(0);
4837: }

4839: PETSC_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[])
4840: {
4841:   PetscInt        cdof;   /* The number of constraints on this point */
4842:   const PetscInt *cdofs; /* The indices of the constrained dofs on this point */
4843:   PetscScalar    *a;
4844:   PetscInt        off, cind = 0, k;
4845:   PetscErrorCode  ierr;

4848:   PetscSectionGetConstraintDof(section, point, &cdof);
4849:   PetscSectionGetOffset(section, point, &off);
4850:   a    = &array[off];
4851:   if (cdof) {
4852:     PetscSectionGetConstraintIndices(section, point, &cdofs);
4853:     if (clperm) {
4854:       if (perm) {
4855:         for (k = 0; k < dof; ++k) {
4856:           if ((cind < cdof) && (k == cdofs[cind])) {
4857:             fuse(&a[k], values[clperm[offset+perm[k]]] * (flip ? flip[perm[k]] : 1.));
4858:             cind++;
4859:           }
4860:         }
4861:       } else {
4862:         for (k = 0; k < dof; ++k) {
4863:           if ((cind < cdof) && (k == cdofs[cind])) {
4864:             fuse(&a[k], values[clperm[offset+     k ]] * (flip ? flip[     k ] : 1.));
4865:             cind++;
4866:           }
4867:         }
4868:       }
4869:     } else {
4870:       if (perm) {
4871:         for (k = 0; k < dof; ++k) {
4872:           if ((cind < cdof) && (k == cdofs[cind])) {
4873:             fuse(&a[k], values[offset+perm[k]] * (flip ? flip[perm[k]] : 1.));
4874:             cind++;
4875:           }
4876:         }
4877:       } else {
4878:         for (k = 0; k < dof; ++k) {
4879:           if ((cind < cdof) && (k == cdofs[cind])) {
4880:             fuse(&a[k], values[offset+     k ] * (flip ? flip[     k ] : 1.));
4881:             cind++;
4882:           }
4883:         }
4884:       }
4885:     }
4886:   }
4887:   return(0);
4888: }

4890: PETSC_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[])
4891: {
4892:   PetscScalar    *a;
4893:   PetscInt        fdof, foff, fcdof, foffset = *offset;
4894:   const PetscInt *fcdofs; /* The indices of the constrained dofs for field f on this point */
4895:   PetscInt        cind = 0, b;
4896:   PetscErrorCode  ierr;

4899:   PetscSectionGetFieldDof(section, point, f, &fdof);
4900:   PetscSectionGetFieldConstraintDof(section, point, f, &fcdof);
4901:   PetscSectionGetFieldOffset(section, point, f, &foff);
4902:   a    = &array[foff];
4903:   if (!fcdof || setBC) {
4904:     if (clperm) {
4905:       if (perm) {for (b = 0; b < fdof; b++) {fuse(&a[b], values[clperm[foffset+perm[b]]] * (flip ? flip[perm[b]] : 1.));}}
4906:       else      {for (b = 0; b < fdof; b++) {fuse(&a[b], values[clperm[foffset+     b ]] * (flip ? flip[     b ] : 1.));}}
4907:     } else {
4908:       if (perm) {for (b = 0; b < fdof; b++) {fuse(&a[b], values[foffset+perm[b]] * (flip ? flip[perm[b]] : 1.));}}
4909:       else      {for (b = 0; b < fdof; b++) {fuse(&a[b], values[foffset+     b ] * (flip ? flip[     b ] : 1.));}}
4910:     }
4911:   } else {
4912:     PetscSectionGetFieldConstraintIndices(section, point, f, &fcdofs);
4913:     if (clperm) {
4914:       if (perm) {
4915:         for (b = 0; b < fdof; b++) {
4916:           if ((cind < fcdof) && (b == fcdofs[cind])) {++cind; continue;}
4917:           fuse(&a[b], values[clperm[foffset+perm[b]]] * (flip ? flip[perm[b]] : 1.));
4918:         }
4919:       } else {
4920:         for (b = 0; b < fdof; b++) {
4921:           if ((cind < fcdof) && (b == fcdofs[cind])) {++cind; continue;}
4922:           fuse(&a[b], values[clperm[foffset+     b ]] * (flip ? flip[     b ] : 1.));
4923:         }
4924:       }
4925:     } else {
4926:       if (perm) {
4927:         for (b = 0; b < fdof; b++) {
4928:           if ((cind < fcdof) && (b == fcdofs[cind])) {++cind; continue;}
4929:           fuse(&a[b], values[foffset+perm[b]] * (flip ? flip[perm[b]] : 1.));
4930:         }
4931:       } else {
4932:         for (b = 0; b < fdof; b++) {
4933:           if ((cind < fcdof) && (b == fcdofs[cind])) {++cind; continue;}
4934:           fuse(&a[b], values[foffset+     b ] * (flip ? flip[     b ] : 1.));
4935:         }
4936:       }
4937:     }
4938:   }
4939:   *offset += fdof;
4940:   return(0);
4941: }

4943: PETSC_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[])
4944: {
4945:   PetscScalar    *a;
4946:   PetscInt        fdof, foff, fcdof, foffset = *offset;
4947:   const PetscInt *fcdofs; /* The indices of the constrained dofs for field f on this point */
4948:   PetscInt        Nc, cind = 0, ncind = 0, b;
4949:   PetscBool       ncSet, fcSet;
4950:   PetscErrorCode  ierr;

4953:   PetscSectionGetFieldComponents(section, f, &Nc);
4954:   PetscSectionGetFieldDof(section, point, f, &fdof);
4955:   PetscSectionGetFieldConstraintDof(section, point, f, &fcdof);
4956:   PetscSectionGetFieldOffset(section, point, f, &foff);
4957:   a    = &array[foff];
4958:   if (fcdof) {
4959:     /* We just override fcdof and fcdofs with Ncc and comps */
4960:     PetscSectionGetFieldConstraintIndices(section, point, f, &fcdofs);
4961:     if (clperm) {
4962:       if (perm) {
4963:         if (comps) {
4964:           for (b = 0; b < fdof; b++) {
4965:             ncSet = fcSet = PETSC_FALSE;
4966:             if (b%Nc == comps[ncind]) {ncind = (ncind+1)%Ncc; ncSet = PETSC_TRUE;}
4967:             if ((cind < fcdof) && (b == fcdofs[cind])) {++cind;  fcSet = PETSC_TRUE;}
4968:             if (ncSet && fcSet) {fuse(&a[b], values[clperm[foffset+perm[b]]] * (flip ? flip[perm[b]] : 1.));}
4969:           }
4970:         } else {
4971:           for (b = 0; b < fdof; b++) {
4972:             if ((cind < fcdof) && (b == fcdofs[cind])) {
4973:               fuse(&a[b], values[clperm[foffset+perm[b]]] * (flip ? flip[perm[b]] : 1.));
4974:               ++cind;
4975:             }
4976:           }
4977:         }
4978:       } else {
4979:         if (comps) {
4980:           for (b = 0; b < fdof; b++) {
4981:             ncSet = fcSet = PETSC_FALSE;
4982:             if (b%Nc == comps[ncind]) {ncind = (ncind+1)%Ncc; ncSet = PETSC_TRUE;}
4983:             if ((cind < fcdof) && (b == fcdofs[cind])) {++cind;  fcSet = PETSC_TRUE;}
4984:             if (ncSet && fcSet) {fuse(&a[b], values[clperm[foffset+     b ]] * (flip ? flip[     b ] : 1.));}
4985:           }
4986:         } else {
4987:           for (b = 0; b < fdof; b++) {
4988:             if ((cind < fcdof) && (b == fcdofs[cind])) {
4989:               fuse(&a[b], values[clperm[foffset+     b ]] * (flip ? flip[     b ] : 1.));
4990:               ++cind;
4991:             }
4992:           }
4993:         }
4994:       }
4995:     } else {
4996:       if (perm) {
4997:         if (comps) {
4998:           for (b = 0; b < fdof; b++) {
4999:             ncSet = fcSet = PETSC_FALSE;
5000:             if (b%Nc == comps[ncind]) {ncind = (ncind+1)%Ncc; ncSet = PETSC_TRUE;}
5001:             if ((cind < fcdof) && (b == fcdofs[cind])) {++cind;  fcSet = PETSC_TRUE;}
5002:             if (ncSet && fcSet) {fuse(&a[b], values[foffset+perm[b]] * (flip ? flip[perm[b]] : 1.));}
5003:           }
5004:         } else {
5005:           for (b = 0; b < fdof; b++) {
5006:             if ((cind < fcdof) && (b == fcdofs[cind])) {
5007:               fuse(&a[b], values[foffset+perm[b]] * (flip ? flip[perm[b]] : 1.));
5008:               ++cind;
5009:             }
5010:           }
5011:         }
5012:       } else {
5013:         if (comps) {
5014:           for (b = 0; b < fdof; b++) {
5015:             ncSet = fcSet = PETSC_FALSE;
5016:             if (b%Nc == comps[ncind]) {ncind = (ncind+1)%Ncc; ncSet = PETSC_TRUE;}
5017:             if ((cind < fcdof) && (b == fcdofs[cind])) {++cind;  fcSet = PETSC_TRUE;}
5018:             if (ncSet && fcSet) {fuse(&a[b], values[foffset+     b ] * (flip ? flip[     b ] : 1.));}
5019:           }
5020:         } else {
5021:           for (b = 0; b < fdof; b++) {
5022:             if ((cind < fcdof) && (b == fcdofs[cind])) {
5023:               fuse(&a[b], values[foffset+     b ] * (flip ? flip[     b ] : 1.));
5024:               ++cind;
5025:             }
5026:           }
5027:         }
5028:       }
5029:     }
5030:   }
5031:   *offset += fdof;
5032:   return(0);
5033: }

5035: PETSC_STATIC_INLINE PetscErrorCode DMPlexVecSetClosure_Depth1_Static(DM dm, PetscSection section, Vec v, PetscInt point, const PetscScalar values[], InsertMode mode)
5036: {
5037:   PetscScalar    *array;
5038:   const PetscInt *cone, *coneO;
5039:   PetscInt        pStart, pEnd, p, numPoints, off, dof;
5040:   PetscErrorCode  ierr;

5043:   PetscSectionGetChart(section, &pStart, &pEnd);
5044:   DMPlexGetConeSize(dm, point, &numPoints);
5045:   DMPlexGetCone(dm, point, &cone);
5046:   DMPlexGetConeOrientation(dm, point, &coneO);
5047:   VecGetArray(v, &array);
5048:   for (p = 0, off = 0; p <= numPoints; ++p, off += dof) {
5049:     const PetscInt cp = !p ? point : cone[p-1];
5050:     const PetscInt o  = !p ? 0     : coneO[p-1];

5052:     if ((cp < pStart) || (cp >= pEnd)) {dof = 0; continue;}
5053:     PetscSectionGetDof(section, cp, &dof);
5054:     /* ADD_VALUES */
5055:     {
5056:       const PetscInt *cdofs; /* The indices of the constrained dofs on this point */
5057:       PetscScalar    *a;
5058:       PetscInt        cdof, coff, cind = 0, k;

5060:       PetscSectionGetConstraintDof(section, cp, &cdof);
5061:       PetscSectionGetOffset(section, cp, &coff);
5062:       a    = &array[coff];
5063:       if (!cdof) {
5064:         if (o >= 0) {
5065:           for (k = 0; k < dof; ++k) {
5066:             a[k] += values[off+k];
5067:           }
5068:         } else {
5069:           for (k = 0; k < dof; ++k) {
5070:             a[k] += values[off+dof-k-1];
5071:           }
5072:         }
5073:       } else {
5074:         PetscSectionGetConstraintIndices(section, cp, &cdofs);
5075:         if (o >= 0) {
5076:           for (k = 0; k < dof; ++k) {
5077:             if ((cind < cdof) && (k == cdofs[cind])) {++cind; continue;}
5078:             a[k] += values[off+k];
5079:           }
5080:         } else {
5081:           for (k = 0; k < dof; ++k) {
5082:             if ((cind < cdof) && (k == cdofs[cind])) {++cind; continue;}
5083:             a[k] += values[off+dof-k-1];
5084:           }
5085:         }
5086:       }
5087:     }
5088:   }
5089:   VecRestoreArray(v, &array);
5090:   return(0);
5091: }

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

5096:   Not collective

5098:   Input Parameters:
5099: + dm - The DM
5100: . section - The section describing the layout in v, or NULL to use the default section
5101: . v - The local vector
5102: . point - The point in the DM
5103: . values - The array of values
5104: - mode - The insert mode. One of INSERT_ALL_VALUES, ADD_ALL_VALUES, INSERT_VALUES, ADD_VALUES, INSERT_BC_VALUES, and ADD_BC_VALUES,
5105:          where INSERT_ALL_VALUES and ADD_ALL_VALUES also overwrite boundary conditions.

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

5110:   Level: intermediate

5112: .seealso DMPlexVecGetClosure(), DMPlexMatSetClosure()
5113: @*/
5114: PetscErrorCode DMPlexVecSetClosure(DM dm, PetscSection section, Vec v, PetscInt point, const PetscScalar values[], InsertMode mode)
5115: {
5116:   PetscSection    clSection;
5117:   IS              clPoints;
5118:   PetscScalar    *array;
5119:   PetscInt       *points = NULL;
5120:   const PetscInt *clp, *clperm;
5121:   PetscInt        depth, numFields, numPoints, p;
5122:   PetscErrorCode  ierr;

5126:   if (!section) {DMGetLocalSection(dm, &section);}
5129:   DMPlexGetDepth(dm, &depth);
5130:   PetscSectionGetNumFields(section, &numFields);
5131:   if (depth == 1 && numFields < 2 && mode == ADD_VALUES) {
5132:     DMPlexVecSetClosure_Depth1_Static(dm, section, v, point, values, mode);
5133:     return(0);
5134:   }
5135:   /* Get points */
5136:   PetscSectionGetClosureInversePermutation_Internal(section, (PetscObject) dm, NULL, &clperm);
5137:   DMPlexGetCompressedClosure(dm,section,point,&numPoints,&points,&clSection,&clPoints,&clp);
5138:   /* Get array */
5139:   VecGetArray(v, &array);
5140:   /* Get values */
5141:   if (numFields > 0) {
5142:     PetscInt offset = 0, f;
5143:     for (f = 0; f < numFields; ++f) {
5144:       const PetscInt    **perms = NULL;
5145:       const PetscScalar **flips = NULL;

5147:       PetscSectionGetFieldPointSyms(section,f,numPoints,points,&perms,&flips);
5148:       switch (mode) {
5149:       case INSERT_VALUES:
5150:         for (p = 0; p < numPoints; p++) {
5151:           const PetscInt    point = points[2*p];
5152:           const PetscInt    *perm = perms ? perms[p] : NULL;
5153:           const PetscScalar *flip = flips ? flips[p] : NULL;
5154:           updatePointFields_private(section, point, perm, flip, f, insert, PETSC_FALSE, clperm, values, &offset, array);
5155:         } break;
5156:       case INSERT_ALL_VALUES:
5157:         for (p = 0; p < numPoints; p++) {
5158:           const PetscInt    point = points[2*p];
5159:           const PetscInt    *perm = perms ? perms[p] : NULL;
5160:           const PetscScalar *flip = flips ? flips[p] : NULL;
5161:           updatePointFields_private(section, point, perm, flip, f, insert, PETSC_TRUE, clperm, values, &offset, array);
5162:         } break;
5163:       case INSERT_BC_VALUES:
5164:         for (p = 0; p < numPoints; p++) {
5165:           const PetscInt    point = points[2*p];
5166:           const PetscInt    *perm = perms ? perms[p] : NULL;
5167:           const PetscScalar *flip = flips ? flips[p] : NULL;
5168:           updatePointFieldsBC_private(section, point, perm, flip, f, -1, NULL, insert, clperm, values, &offset, array);
5169:         } break;
5170:       case ADD_VALUES:
5171:         for (p = 0; p < numPoints; p++) {
5172:           const PetscInt    point = points[2*p];
5173:           const PetscInt    *perm = perms ? perms[p] : NULL;
5174:           const PetscScalar *flip = flips ? flips[p] : NULL;
5175:           updatePointFields_private(section, point, perm, flip, f, add, PETSC_FALSE, clperm, values, &offset, array);
5176:         } break;
5177:       case ADD_ALL_VALUES:
5178:         for (p = 0; p < numPoints; p++) {
5179:           const PetscInt    point = points[2*p];
5180:           const PetscInt    *perm = perms ? perms[p] : NULL;
5181:           const PetscScalar *flip = flips ? flips[p] : NULL;
5182:           updatePointFields_private(section, point, perm, flip, f, add, PETSC_TRUE, clperm, values, &offset, array);
5183:         } break;
5184:       case ADD_BC_VALUES:
5185:         for (p = 0; p < numPoints; p++) {
5186:           const PetscInt    point = points[2*p];
5187:           const PetscInt    *perm = perms ? perms[p] : NULL;
5188:           const PetscScalar *flip = flips ? flips[p] : NULL;
5189:           updatePointFieldsBC_private(section, point, perm, flip, f, -1, NULL, add, clperm, values, &offset, array);
5190:         } break;
5191:       default:
5192:         SETERRQ1(PetscObjectComm((PetscObject)dm), PETSC_ERR_ARG_OUTOFRANGE, "Invalid insert mode %d", mode);
5193:       }
5194:       PetscSectionRestoreFieldPointSyms(section,f,numPoints,points,&perms,&flips);
5195:     }
5196:   } else {
5197:     PetscInt dof, off;
5198:     const PetscInt    **perms = NULL;
5199:     const PetscScalar **flips = NULL;

5201:     PetscSectionGetPointSyms(section,numPoints,points,&perms,&flips);
5202:     switch (mode) {
5203:     case INSERT_VALUES:
5204:       for (p = 0, off = 0; p < numPoints; p++, off += dof) {
5205:         const PetscInt    point = points[2*p];
5206:         const PetscInt    *perm = perms ? perms[p] : NULL;
5207:         const PetscScalar *flip = flips ? flips[p] : NULL;
5208:         PetscSectionGetDof(section, point, &dof);
5209:         updatePoint_private(section, point, dof, insert, PETSC_FALSE, perm, flip, clperm, values, off, array);
5210:       } break;
5211:     case INSERT_ALL_VALUES:
5212:       for (p = 0, off = 0; p < numPoints; p++, off += dof) {
5213:         const PetscInt    point = points[2*p];
5214:         const PetscInt    *perm = perms ? perms[p] : NULL;
5215:         const PetscScalar *flip = flips ? flips[p] : NULL;
5216:         PetscSectionGetDof(section, point, &dof);
5217:         updatePoint_private(section, point, dof, insert, PETSC_TRUE,  perm, flip, clperm, values, off, array);
5218:       } break;
5219:     case INSERT_BC_VALUES:
5220:       for (p = 0, off = 0; p < numPoints; p++, off += dof) {
5221:         const PetscInt    point = points[2*p];
5222:         const PetscInt    *perm = perms ? perms[p] : NULL;
5223:         const PetscScalar *flip = flips ? flips[p] : NULL;
5224:         PetscSectionGetDof(section, point, &dof);
5225:         updatePointBC_private(section, point, dof, insert,  perm, flip, clperm, values, off, array);
5226:       } break;
5227:     case ADD_VALUES:
5228:       for (p = 0, off = 0; p < numPoints; p++, off += dof) {
5229:         const PetscInt    point = points[2*p];
5230:         const PetscInt    *perm = perms ? perms[p] : NULL;
5231:         const PetscScalar *flip = flips ? flips[p] : NULL;
5232:         PetscSectionGetDof(section, point, &dof);
5233:         updatePoint_private(section, point, dof, add,    PETSC_FALSE, perm, flip, clperm, values, off, array);
5234:       } break;
5235:     case ADD_ALL_VALUES:
5236:       for (p = 0, off = 0; p < numPoints; p++, off += dof) {
5237:         const PetscInt    point = points[2*p];
5238:         const PetscInt    *perm = perms ? perms[p] : NULL;
5239:         const PetscScalar *flip = flips ? flips[p] : NULL;
5240:         PetscSectionGetDof(section, point, &dof);
5241:         updatePoint_private(section, point, dof, add,    PETSC_TRUE,  perm, flip, clperm, values, off, array);
5242:       } break;
5243:     case ADD_BC_VALUES:
5244:       for (p = 0, off = 0; p < numPoints; p++, off += dof) {
5245:         const PetscInt    point = points[2*p];
5246:         const PetscInt    *perm = perms ? perms[p] : NULL;
5247:         const PetscScalar *flip = flips ? flips[p] : NULL;
5248:         PetscSectionGetDof(section, point, &dof);
5249:         updatePointBC_private(section, point, dof, add,  perm, flip, clperm, values, off, array);
5250:       } break;
5251:     default:
5252:       SETERRQ1(PetscObjectComm((PetscObject)dm), PETSC_ERR_ARG_OUTOFRANGE, "Invalid insert mode %d", mode);
5253:     }
5254:     PetscSectionRestorePointSyms(section,numPoints,points,&perms,&flips);
5255:   }
5256:   /* Cleanup points */
5257:   DMPlexRestoreCompressedClosure(dm,section,point,&numPoints,&points,&clSection,&clPoints,&clp);
5258:   /* Cleanup array */
5259:   VecRestoreArray(v, &array);
5260:   return(0);
5261: }

5263: /* Unlike DMPlexVecSetClosure(), this uses plex-native closure permutation, not a user-specified permutation such as DMPlexSetClosurePermutationTensor(). */
5264: PetscErrorCode DMPlexVecSetFieldClosure_Internal(DM dm, PetscSection section, Vec v, PetscBool fieldActive[], PetscInt point, PetscInt Ncc, const PetscInt comps[], const PetscScalar values[], InsertMode mode)
5265: {
5266:   PetscSection      clSection;
5267:   IS                clPoints;
5268:   PetscScalar       *array;
5269:   PetscInt          *points = NULL;
5270:   const PetscInt    *clp;
5271:   PetscInt          numFields, numPoints, p;
5272:   PetscInt          offset = 0, f;
5273:   PetscErrorCode    ierr;

5277:   if (!section) {DMGetLocalSection(dm, &section);}
5280:   PetscSectionGetNumFields(section, &numFields);
5281:   /* Get points */
5282:   DMPlexGetCompressedClosure(dm,section,point,&numPoints,&points,&clSection,&clPoints,&clp);
5283:   /* Get array */
5284:   VecGetArray(v, &array);
5285:   /* Get values */
5286:   for (f = 0; f < numFields; ++f) {
5287:     const PetscInt    **perms = NULL;
5288:     const PetscScalar **flips = NULL;

5290:     if (!fieldActive[f]) {
5291:       for (p = 0; p < numPoints*2; p += 2) {
5292:         PetscInt fdof;
5293:         PetscSectionGetFieldDof(section, points[p], f, &fdof);
5294:         offset += fdof;
5295:       }
5296:       continue;
5297:     }
5298:     PetscSectionGetFieldPointSyms(section,f,numPoints,points,&perms,&flips);
5299:     switch (mode) {
5300:     case INSERT_VALUES:
5301:       for (p = 0; p < numPoints; p++) {
5302:         const PetscInt    point = points[2*p];
5303:         const PetscInt    *perm = perms ? perms[p] : NULL;
5304:         const PetscScalar *flip = flips ? flips[p] : NULL;
5305:         updatePointFields_private(section, point, perm, flip, f, insert, PETSC_FALSE, NULL, values, &offset, array);
5306:       } break;
5307:     case INSERT_ALL_VALUES:
5308:       for (p = 0; p < numPoints; p++) {
5309:         const PetscInt    point = points[2*p];
5310:         const PetscInt    *perm = perms ? perms[p] : NULL;
5311:         const PetscScalar *flip = flips ? flips[p] : NULL;
5312:         updatePointFields_private(section, point, perm, flip, f, insert, PETSC_TRUE, NULL, values, &offset, array);
5313:         } break;
5314:     case INSERT_BC_VALUES:
5315:       for (p = 0; p < numPoints; p++) {
5316:         const PetscInt    point = points[2*p];
5317:         const PetscInt    *perm = perms ? perms[p] : NULL;
5318:         const PetscScalar *flip = flips ? flips[p] : NULL;
5319:         updatePointFieldsBC_private(section, point, perm, flip, f, Ncc, comps, insert, NULL, values, &offset, array);
5320:       } break;
5321:     case ADD_VALUES:
5322:       for (p = 0; p < numPoints; p++) {
5323:         const PetscInt    point = points[2*p];
5324:         const PetscInt    *perm = perms ? perms[p] : NULL;
5325:         const PetscScalar *flip = flips ? flips[p] : NULL;
5326:         updatePointFields_private(section, point, perm, flip, f, add, PETSC_FALSE, NULL, values, &offset, array);
5327:       } break;
5328:     case ADD_ALL_VALUES:
5329:       for (p = 0; p < numPoints; p++) {
5330:         const PetscInt    point = points[2*p];
5331:         const PetscInt    *perm = perms ? perms[p] : NULL;
5332:         const PetscScalar *flip = flips ? flips[p] : NULL;
5333:         updatePointFields_private(section, point, perm, flip, f, add, PETSC_TRUE, NULL, values, &offset, array);
5334:       } break;
5335:     default:
5336:       SETERRQ1(PetscObjectComm((PetscObject)dm), PETSC_ERR_ARG_OUTOFRANGE, "Invalid insert mode %d", mode);
5337:     }
5338:     PetscSectionRestoreFieldPointSyms(section,f,numPoints,points,&perms,&flips);
5339:   }
5340:   /* Cleanup points */
5341:   DMPlexRestoreCompressedClosure(dm,section,point,&numPoints,&points,&clSection,&clPoints,&clp);
5342:   /* Cleanup array */
5343:   VecRestoreArray(v, &array);
5344:   return(0);
5345: }

5347: static PetscErrorCode DMPlexPrintMatSetValues(PetscViewer viewer, Mat A, PetscInt point, PetscInt numRIndices, const PetscInt rindices[], PetscInt numCIndices, const PetscInt cindices[], const PetscScalar values[])
5348: {
5349:   PetscMPIInt    rank;
5350:   PetscInt       i, j;

5354:   MPI_Comm_rank(PetscObjectComm((PetscObject)A), &rank);
5355:   PetscViewerASCIIPrintf(viewer, "[%d]mat for point %D\n", rank, point);
5356:   for (i = 0; i < numRIndices; i++) {PetscViewerASCIIPrintf(viewer, "[%d]mat row indices[%D] = %D\n", rank, i, rindices[i]);}
5357:   for (i = 0; i < numCIndices; i++) {PetscViewerASCIIPrintf(viewer, "[%d]mat col indices[%D] = %D\n", rank, i, cindices[i]);}
5358:   numCIndices = numCIndices ? numCIndices : numRIndices;
5359:   for (i = 0; i < numRIndices; i++) {
5360:     PetscViewerASCIIPrintf(viewer, "[%d]", rank);
5361:     for (j = 0; j < numCIndices; j++) {
5362: #if defined(PETSC_USE_COMPLEX)
5363:       PetscViewerASCIIPrintf(viewer, " (%g,%g)", (double)PetscRealPart(values[i*numCIndices+j]), (double)PetscImaginaryPart(values[i*numCIndices+j]));
5364: #else
5365:       PetscViewerASCIIPrintf(viewer, " %g", (double)values[i*numCIndices+j]);
5366: #endif
5367:     }
5368:     PetscViewerASCIIPrintf(viewer, "\n");
5369:   }
5370:   return(0);
5371: }

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

5376:   Input Parameters:
5377: + section - The section for this data layout
5378: . islocal - Is the section (and thus indices being requested) local or global?
5379: . point   - The point contributing dofs with these indices
5380: . off     - The global offset of this point
5381: . loff    - The local offset of each field
5382: . setBC   - The flag determining whether to include indices of bounsary values
5383: . perm    - A permutation of the dofs on this point, or NULL
5384: - indperm - A permutation of the entire indices array, or NULL

5386:   Output Parameter:
5387: . indices - Indices for dofs on this point

5389:   Level: developer

5391:   Note: The indices could be local or global, depending on the value of 'off'.
5392: */
5393: PetscErrorCode DMPlexGetIndicesPoint_Internal(PetscSection section, PetscBool islocal,PetscInt point, PetscInt off, PetscInt *loff, PetscBool setBC, const PetscInt perm[], const PetscInt indperm[], PetscInt indices[])
5394: {
5395:   PetscInt        dof;   /* The number of unknowns on this point */
5396:   PetscInt        cdof;  /* The number of constraints on this point */
5397:   const PetscInt *cdofs; /* The indices of the constrained dofs on this point */
5398:   PetscInt        cind = 0, k;
5399:   PetscErrorCode  ierr;

5402:   if (!islocal && setBC) SETERRQ(PetscObjectComm((PetscObject)section),PETSC_ERR_ARG_INCOMP,"setBC incompatible with global indices; use a local section or disable setBC");
5403:   PetscSectionGetDof(section, point, &dof);
5404:   PetscSectionGetConstraintDof(section, point, &cdof);
5405:   if (!cdof || setBC) {
5406:     for (k = 0; k < dof; ++k) {
5407:       const PetscInt preind = perm ? *loff+perm[k] : *loff+k;
5408:       const PetscInt ind    = indperm ? indperm[preind] : preind;

5410:       indices[ind] = off + k;
5411:     }
5412:   } else {
5413:     PetscSectionGetConstraintIndices(section, point, &cdofs);
5414:     for (k = 0; k < dof; ++k) {
5415:       const PetscInt preind = perm ? *loff+perm[k] : *loff+k;
5416:       const PetscInt ind    = indperm ? indperm[preind] : preind;

5418:       if ((cind < cdof) && (k == cdofs[cind])) {
5419:         /* Insert check for returning constrained indices */
5420:         indices[ind] = -(off+k+1);
5421:         ++cind;
5422:       } else {
5423:         indices[ind] = off + k - (islocal ? 0 : cind);
5424:       }
5425:     }
5426:   }
5427:   *loff += dof;
5428:   return(0);
5429: }

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

5434:  Input Parameters:
5435: + section - a section (global or local)
5436: - islocal - PETSC_TRUE if requesting local indices (i.e., section is local); PETSC_FALSE for global
5437: . point - point within section
5438: . off - The offset of this point in the (local or global) indexed space - should match islocal and (usually) the section
5439: . foffs - array of length numFields containing the offset in canonical point ordering (the location in indices) of each field
5440: . setBC - identify constrained (boundary condition) points via involution.
5441: . perms - perms[f][permsoff][:] is a permutation of dofs within each field
5442: . permsoff - offset
5443: - indperm - index permutation

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

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

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

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

5462:  Example:
5463:  Suppose a point contains one field with three components, and for which the unconstrained indices are {10, 11, 12}.
5464:  When the middle component is constrained, we get the array {10, -12, 12} for (islocal=TRUE, setBC=FALSE).
5465:  Note that -12 is the involution of 11, so the user can involute negative indices to recover local indices.
5466:  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.

5468:  Level: developer
5469: */
5470: 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[])
5471: {
5472:   PetscInt       numFields, foff, f;

5476:   if (!islocal && setBC) SETERRQ(PetscObjectComm((PetscObject)section),PETSC_ERR_ARG_INCOMP,"setBC incompatible with global indices; use a local section or disable setBC");
5477:   PetscSectionGetNumFields(section, &numFields);
5478:   for (f = 0, foff = 0; f < numFields; ++f) {
5479:     PetscInt        fdof, cfdof;
5480:     const PetscInt *fcdofs; /* The indices of the constrained dofs for field f on this point */
5481:     PetscInt        cind = 0, b;
5482:     const PetscInt  *perm = (perms && perms[f]) ? perms[f][permsoff] : NULL;

5484:     PetscSectionGetFieldDof(section, point, f, &fdof);
5485:     PetscSectionGetFieldConstraintDof(section, point, f, &cfdof);
5486:     if (!cfdof || setBC) {
5487:       for (b = 0; b < fdof; ++b) {
5488:         const PetscInt preind = perm ? foffs[f]+perm[b] : foffs[f]+b;
5489:         const PetscInt ind    = indperm ? indperm[preind] : preind;

5491:         indices[ind] = off+foff+b;
5492:       }
5493:     } else {
5494:       PetscSectionGetFieldConstraintIndices(section, point, f, &fcdofs);
5495:       for (b = 0; b < fdof; ++b) {
5496:         const PetscInt preind = perm ? foffs[f]+perm[b] : foffs[f]+b;
5497:         const PetscInt ind    = indperm ? indperm[preind] : preind;

5499:         if ((cind < cfdof) && (b == fcdofs[cind])) {
5500:           indices[ind] = -(off+foff+b+1);
5501:           ++cind;
5502:         } else {
5503:           indices[ind] = off + foff + b - (islocal ? 0 : cind);
5504:         }
5505:       }
5506:     }
5507:     foff     += (setBC || islocal ? fdof : (fdof - cfdof));
5508:     foffs[f] += fdof;
5509:   }
5510:   return(0);
5511: }

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

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

5518:  Notes:
5519:  The semantics of this function relate to that of setBC=FALSE in DMPlexGetIndicesPointFields_Internal.
5520:  Since this function uses global indices, setBC=TRUE would be invalid, so no such argument exists.
5521: */
5522: static PetscErrorCode DMPlexGetIndicesPointFieldsSplit_Internal(PetscSection section, PetscSection globalSection, PetscInt point, PetscInt foffs[], const PetscInt ***perms, PetscInt permsoff, const PetscInt indperm[], PetscInt indices[])
5523: {
5524:   PetscInt       numFields, foff, f;

5528:   PetscSectionGetNumFields(section, &numFields);
5529:   for (f = 0; f < numFields; ++f) {
5530:     PetscInt        fdof, cfdof;
5531:     const PetscInt *fcdofs; /* The indices of the constrained dofs for field f on this point */
5532:     PetscInt        cind = 0, b;
5533:     const PetscInt  *perm = (perms && perms[f]) ? perms[f][permsoff] : NULL;

5535:     PetscSectionGetFieldDof(section, point, f, &fdof);
5536:     PetscSectionGetFieldConstraintDof(section, point, f, &cfdof);
5537:     PetscSectionGetFieldOffset(globalSection, point, f, &foff);
5538:     if (!cfdof) {
5539:       for (b = 0; b < fdof; ++b) {
5540:         const PetscInt preind = perm ? foffs[f]+perm[b] : foffs[f]+b;
5541:         const PetscInt ind    = indperm ? indperm[preind] : preind;

5543:         indices[ind] = foff+b;
5544:       }
5545:     } else {
5546:       PetscSectionGetFieldConstraintIndices(section, point, f, &fcdofs);
5547:       for (b = 0; b < fdof; ++b) {
5548:         const PetscInt preind = perm ? foffs[f]+perm[b] : foffs[f]+b;
5549:         const PetscInt ind    = indperm ? indperm[preind] : preind;

5551:         if ((cind < cfdof) && (b == fcdofs[cind])) {
5552:           indices[ind] = -(foff+b+1);
5553:           ++cind;
5554:         } else {
5555:           indices[ind] = foff+b-cind;
5556:         }
5557:       }
5558:     }
5559:     foffs[f] += fdof;
5560:   }
5561:   return(0);
5562: }

5564: 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)
5565: {
5566:   Mat             cMat;
5567:   PetscSection    aSec, cSec;
5568:   IS              aIS;
5569:   PetscInt        aStart = -1, aEnd = -1;
5570:   const PetscInt  *anchors;
5571:   PetscInt        numFields, f, p, q, newP = 0;
5572:   PetscInt        newNumPoints = 0, newNumIndices = 0;
5573:   PetscInt        *newPoints, *indices, *newIndices;
5574:   PetscInt        maxAnchor, maxDof;
5575:   PetscInt        newOffsets[32];
5576:   PetscInt        *pointMatOffsets[32];
5577:   PetscInt        *newPointOffsets[32];
5578:   PetscScalar     *pointMat[32];
5579:   PetscScalar     *newValues=NULL,*tmpValues;
5580:   PetscBool       anyConstrained = PETSC_FALSE;
5581:   PetscErrorCode  ierr;

5586:   PetscSectionGetNumFields(section, &numFields);

5588:   DMPlexGetAnchors(dm,&aSec,&aIS);
5589:   /* if there are point-to-point constraints */
5590:   if (aSec) {
5591:     PetscArrayzero(newOffsets, 32);
5592:     ISGetIndices(aIS,&anchors);
5593:     PetscSectionGetChart(aSec,&aStart,&aEnd);
5594:     /* figure out how many points are going to be in the new element matrix
5595:      * (we allow double counting, because it's all just going to be summed
5596:      * into the global matrix anyway) */
5597:     for (p = 0; p < 2*numPoints; p+=2) {
5598:       PetscInt b    = points[p];
5599:       PetscInt bDof = 0, bSecDof;

5601:       PetscSectionGetDof(section,b,&bSecDof);
5602:       if (!bSecDof) {
5603:         continue;
5604:       }
5605:       if (b >= aStart && b < aEnd) {
5606:         PetscSectionGetDof(aSec,b,&bDof);
5607:       }
5608:       if (bDof) {
5609:         /* this point is constrained */
5610:         /* it is going to be replaced by its anchors */
5611:         PetscInt bOff, q;

5613:         anyConstrained = PETSC_TRUE;
5614:         newNumPoints  += bDof;
5615:         PetscSectionGetOffset(aSec,b,&bOff);
5616:         for (q = 0; q < bDof; q++) {
5617:           PetscInt a = anchors[bOff + q];
5618:           PetscInt aDof;

5620:           PetscSectionGetDof(section,a,&aDof);
5621:           newNumIndices += aDof;
5622:           for (f = 0; f < numFields; ++f) {
5623:             PetscInt fDof;

5625:             PetscSectionGetFieldDof(section, a, f, &fDof);
5626:             newOffsets[f+1] += fDof;
5627:           }
5628:         }
5629:       }
5630:       else {
5631:         /* this point is not constrained */
5632:         newNumPoints++;
5633:         newNumIndices += bSecDof;
5634:         for (f = 0; f < numFields; ++f) {
5635:           PetscInt fDof;

5637:           PetscSectionGetFieldDof(section, b, f, &fDof);
5638:           newOffsets[f+1] += fDof;
5639:         }
5640:       }
5641:     }
5642:   }
5643:   if (!anyConstrained) {
5644:     if (outNumPoints)  *outNumPoints  = 0;
5645:     if (outNumIndices) *outNumIndices = 0;
5646:     if (outPoints)     *outPoints     = NULL;
5647:     if (outValues)     *outValues     = NULL;
5648:     if (aSec) {ISRestoreIndices(aIS,&anchors);}
5649:     return(0);
5650:   }

5652:   if (outNumPoints)  *outNumPoints  = newNumPoints;
5653:   if (outNumIndices) *outNumIndices = newNumIndices;

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

5657:   if (!outPoints && !outValues) {
5658:     if (offsets) {
5659:       for (f = 0; f <= numFields; f++) {
5660:         offsets[f] = newOffsets[f];
5661:       }
5662:     }
5663:     if (aSec) {ISRestoreIndices(aIS,&anchors);}
5664:     return(0);
5665:   }

5667:   if (numFields && newOffsets[numFields] != newNumIndices) SETERRQ2(PETSC_COMM_SELF, PETSC_ERR_PLIB, "Invalid size for closure %D should be %D", newOffsets[numFields], newNumIndices);

5669:   DMGetDefaultConstraints(dm, &cSec, &cMat);

5671:   /* workspaces */
5672:   if (numFields) {
5673:     for (f = 0; f < numFields; f++) {
5674:       DMGetWorkArray(dm,numPoints+1,MPIU_INT,&pointMatOffsets[f]);
5675:       DMGetWorkArray(dm,numPoints+1,MPIU_INT,&newPointOffsets[f]);
5676:     }
5677:   }
5678:   else {
5679:     DMGetWorkArray(dm,numPoints+1,MPIU_INT,&pointMatOffsets[0]);
5680:     DMGetWorkArray(dm,numPoints,MPIU_INT,&newPointOffsets[0]);
5681:   }

5683:   /* get workspaces for the point-to-point matrices */
5684:   if (numFields) {
5685:     PetscInt totalOffset, totalMatOffset;

5687:     for (p = 0; p < numPoints; p++) {
5688:       PetscInt b    = points[2*p];
5689:       PetscInt bDof = 0, bSecDof;

5691:       PetscSectionGetDof(section,b,&bSecDof);
5692:       if (!bSecDof) {
5693:         for (f = 0; f < numFields; f++) {
5694:           newPointOffsets[f][p + 1] = 0;
5695:           pointMatOffsets[f][p + 1] = 0;
5696:         }
5697:         continue;
5698:       }
5699:       if (b >= aStart && b < aEnd) {
5700:         PetscSectionGetDof(aSec, b, &bDof);
5701:       }
5702:       if (bDof) {
5703:         for (f = 0; f < numFields; f++) {
5704:           PetscInt fDof, q, bOff, allFDof = 0;

5706:           PetscSectionGetFieldDof(section, b, f, &fDof);
5707:           PetscSectionGetOffset(aSec, b, &bOff);
5708:           for (q = 0; q < bDof; q++) {
5709:             PetscInt a = anchors[bOff + q];
5710:             PetscInt aFDof;

5712:             PetscSectionGetFieldDof(section, a, f, &aFDof);
5713:             allFDof += aFDof;
5714:           }
5715:           newPointOffsets[f][p+1] = allFDof;
5716:           pointMatOffsets[f][p+1] = fDof * allFDof;
5717:         }
5718:       }
5719:       else {
5720:         for (f = 0; f < numFields; f++) {
5721:           PetscInt fDof;

5723:           PetscSectionGetFieldDof(section, b, f, &fDof);
5724:           newPointOffsets[f][p+1] = fDof;
5725:           pointMatOffsets[f][p+1] = 0;
5726:         }
5727:       }
5728:     }
5729:     for (f = 0, totalOffset = 0, totalMatOffset = 0; f < numFields; f++) {
5730:       newPointOffsets[f][0] = totalOffset;
5731:       pointMatOffsets[f][0] = totalMatOffset;
5732:       for (p = 0; p < numPoints; p++) {
5733:         newPointOffsets[f][p+1] += newPointOffsets[f][p];
5734:         pointMatOffsets[f][p+1] += pointMatOffsets[f][p];
5735:       }
5736:       totalOffset    = newPointOffsets[f][numPoints];
5737:       totalMatOffset = pointMatOffsets[f][numPoints];
5738:       DMGetWorkArray(dm,pointMatOffsets[f][numPoints],MPIU_SCALAR,&pointMat[f]);
5739:     }
5740:   }
5741:   else {
5742:     for (p = 0; p < numPoints; p++) {
5743:       PetscInt b    = points[2*p];
5744:       PetscInt bDof = 0, bSecDof;

5746:       PetscSectionGetDof(section,b,&bSecDof);
5747:       if (!bSecDof) {
5748:         newPointOffsets[0][p + 1] = 0;
5749:         pointMatOffsets[0][p + 1] = 0;
5750:         continue;
5751:       }
5752:       if (b >= aStart && b < aEnd) {
5753:         PetscSectionGetDof(aSec, b, &bDof);
5754:       }
5755:       if (bDof) {
5756:         PetscInt bOff, q, allDof = 0;

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

5762:           PetscSectionGetDof(section, a, &aDof);
5763:           allDof += aDof;
5764:         }
5765:         newPointOffsets[0][p+1] = allDof;
5766:         pointMatOffsets[0][p+1] = bSecDof * allDof;
5767:       }
5768:       else {
5769:         newPointOffsets[0][p+1] = bSecDof;
5770:         pointMatOffsets[0][p+1] = 0;
5771:       }
5772:     }
5773:     newPointOffsets[0][0] = 0;
5774:     pointMatOffsets[0][0] = 0;
5775:     for (p = 0; p < numPoints; p++) {
5776:       newPointOffsets[0][p+1] += newPointOffsets[0][p];
5777:       pointMatOffsets[0][p+1] += pointMatOffsets[0][p];
5778:     }
5779:     DMGetWorkArray(dm,pointMatOffsets[0][numPoints],MPIU_SCALAR,&pointMat[0]);
5780:   }

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

5785:   /* get the point-to-point matrices; construct newPoints */
5786:   PetscSectionGetMaxDof(aSec, &maxAnchor);
5787:   PetscSectionGetMaxDof(section, &maxDof);
5788:   DMGetWorkArray(dm,maxDof,MPIU_INT,&indices);
5789:   DMGetWorkArray(dm,maxAnchor*maxDof,MPIU_INT,&newIndices);
5790:   if (numFields) {
5791:     for (p = 0, newP = 0; p < numPoints; p++) {
5792:       PetscInt b    = points[2*p];
5793:       PetscInt o    = points[2*p+1];
5794:       PetscInt bDof = 0, bSecDof;

5796:       PetscSectionGetDof(section, b, &bSecDof);
5797:       if (!bSecDof) {
5798:         continue;
5799:       }
5800:       if (b >= aStart && b < aEnd) {
5801:         PetscSectionGetDof(aSec, b, &bDof);
5802:       }
5803:       if (bDof) {
5804:         PetscInt fStart[32], fEnd[32], fAnchorStart[32], fAnchorEnd[32], bOff, q;

5806:         fStart[0] = 0;
5807:         fEnd[0]   = 0;
5808:         for (f = 0; f < numFields; f++) {
5809:           PetscInt fDof;

5811:           PetscSectionGetFieldDof(cSec, b, f, &fDof);
5812:           fStart[f+1] = fStart[f] + fDof;
5813:           fEnd[f+1]   = fStart[f+1];
5814:         }
5815:         PetscSectionGetOffset(cSec, b, &bOff);
5816:         DMPlexGetIndicesPointFields_Internal(cSec, PETSC_TRUE, b, bOff, fEnd, PETSC_TRUE, perms, p, NULL, indices);

5818:         fAnchorStart[0] = 0;
5819:         fAnchorEnd[0]   = 0;
5820:         for (f = 0; f < numFields; f++) {
5821:           PetscInt fDof = newPointOffsets[f][p + 1] - newPointOffsets[f][p];

5823:           fAnchorStart[f+1] = fAnchorStart[f] + fDof;
5824:           fAnchorEnd[f+1]   = fAnchorStart[f + 1];
5825:         }
5826:         PetscSectionGetOffset(aSec, b, &bOff);
5827:         for (q = 0; q < bDof; q++) {
5828:           PetscInt a = anchors[bOff + q], aOff;

5830:           /* we take the orientation of ap into account in the order that we constructed the indices above: the newly added points have no orientation */
5831:           newPoints[2*(newP + q)]     = a;
5832:           newPoints[2*(newP + q) + 1] = 0;
5833:           PetscSectionGetOffset(section, a, &aOff);
5834:           DMPlexGetIndicesPointFields_Internal(section, PETSC_TRUE, a, aOff, fAnchorEnd, PETSC_TRUE, NULL, -1, NULL, newIndices);
5835:         }
5836:         newP += bDof;

5838:         if (outValues) {
5839:           /* get the point-to-point submatrix */
5840:           for (f = 0; f < numFields; f++) {
5841:             MatGetValues(cMat,fEnd[f]-fStart[f],indices + fStart[f],fAnchorEnd[f] - fAnchorStart[f],newIndices + fAnchorStart[f],pointMat[f] + pointMatOffsets[f][p]);
5842:           }
5843:         }
5844:       }
5845:       else {
5846:         newPoints[2 * newP]     = b;
5847:         newPoints[2 * newP + 1] = o;
5848:         newP++;
5849:       }
5850:     }
5851:   } else {
5852:     for (p = 0; p < numPoints; p++) {
5853:       PetscInt b    = points[2*p];
5854:       PetscInt o    = points[2*p+1];
5855:       PetscInt bDof = 0, bSecDof;

5857:       PetscSectionGetDof(section, b, &bSecDof);
5858:       if (!bSecDof) {
5859:         continue;
5860:       }
5861:       if (b >= aStart && b < aEnd) {
5862:         PetscSectionGetDof(aSec, b, &bDof);
5863:       }
5864:       if (bDof) {
5865:         PetscInt bEnd = 0, bAnchorEnd = 0, bOff;

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

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

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

5876:           newPoints[2*(newP + q)]     = a;
5877:           newPoints[2*(newP + q) + 1] = 0;
5878:           PetscSectionGetOffset(section, a, &aOff);
5879:           DMPlexGetIndicesPoint_Internal(section, PETSC_TRUE, a, aOff, &bAnchorEnd, PETSC_TRUE, NULL, NULL, newIndices);
5880:         }
5881:         newP += bDof;

5883:         /* get the point-to-point submatrix */
5884:         if (outValues) {
5885:           MatGetValues(cMat,bEnd,indices,bAnchorEnd,newIndices,pointMat[0] + pointMatOffsets[0][p]);
5886:         }
5887:       }
5888:       else {
5889:         newPoints[2 * newP]     = b;
5890:         newPoints[2 * newP + 1] = o;
5891:         newP++;
5892:       }
5893:     }
5894:   }

5896:   if (outValues) {
5897:     DMGetWorkArray(dm,newNumIndices*numIndices,MPIU_SCALAR,&tmpValues);
5898:     PetscArrayzero(tmpValues,newNumIndices*numIndices);
5899:     /* multiply constraints on the right */
5900:     if (numFields) {
5901:       for (f = 0; f < numFields; f++) {
5902:         PetscInt oldOff = offsets[f];

5904:         for (p = 0; p < numPoints; p++) {
5905:           PetscInt cStart = newPointOffsets[f][p];
5906:           PetscInt b      = points[2 * p];
5907:           PetscInt c, r, k;
5908:           PetscInt dof;

5910:           PetscSectionGetFieldDof(section,b,f,&dof);
5911:           if (!dof) {
5912:             continue;
5913:           }
5914:           if (pointMatOffsets[f][p] < pointMatOffsets[f][p + 1]) {
5915:             PetscInt nCols         = newPointOffsets[f][p+1]-cStart;
5916:             const PetscScalar *mat = pointMat[f] + pointMatOffsets[f][p];

5918:             for (r = 0; r < numIndices; r++) {
5919:               for (c = 0; c < nCols; c++) {
5920:                 for (k = 0; k < dof; k++) {
5921:                   tmpValues[r * newNumIndices + cStart + c] += values[r * numIndices + oldOff + k] * mat[k * nCols + c];
5922:                 }
5923:               }
5924:             }
5925:           }
5926:           else {
5927:             /* copy this column as is */
5928:             for (r = 0; r < numIndices; r++) {
5929:               for (c = 0; c < dof; c++) {
5930:                 tmpValues[r * newNumIndices + cStart + c] = values[r * numIndices + oldOff + c];
5931:               }
5932:             }
5933:           }
5934:           oldOff += dof;
5935:         }
5936:       }
5937:     }
5938:     else {
5939:       PetscInt oldOff = 0;
5940:       for (p = 0; p < numPoints; p++) {
5941:         PetscInt cStart = newPointOffsets[0][p];
5942:         PetscInt b      = points[2 * p];
5943:         PetscInt c, r, k;
5944:         PetscInt dof;

5946:         PetscSectionGetDof(section,b,&dof);
5947:         if (!dof) {
5948:           continue;
5949:         }
5950:         if (pointMatOffsets[0][p] < pointMatOffsets[0][p + 1]) {
5951:           PetscInt nCols         = newPointOffsets[0][p+1]-cStart;
5952:           const PetscScalar *mat = pointMat[0] + pointMatOffsets[0][p];

5954:           for (r = 0; r < numIndices; r++) {
5955:             for (c = 0; c < nCols; c++) {
5956:               for (k = 0; k < dof; k++) {
5957:                 tmpValues[r * newNumIndices + cStart + c] += mat[k * nCols + c] * values[r * numIndices + oldOff + k];
5958:               }
5959:             }
5960:           }
5961:         }
5962:         else {
5963:           /* copy this column as is */
5964:           for (r = 0; r < numIndices; r++) {
5965:             for (c = 0; c < dof; c++) {
5966:               tmpValues[r * newNumIndices + cStart + c] = values[r * numIndices + oldOff + c];
5967:             }
5968:           }
5969:         }
5970:         oldOff += dof;
5971:       }
5972:     }

5974:     if (multiplyLeft) {
5975:       DMGetWorkArray(dm,newNumIndices*newNumIndices,MPIU_SCALAR,&newValues);
5976:       PetscArrayzero(newValues,newNumIndices*newNumIndices);
5977:       /* multiply constraints transpose on the left */
5978:       if (numFields) {
5979:         for (f = 0; f < numFields; f++) {
5980:           PetscInt oldOff = offsets[f];

5982:           for (p = 0; p < numPoints; p++) {
5983:             PetscInt rStart = newPointOffsets[f][p];
5984:             PetscInt b      = points[2 * p];
5985:             PetscInt c, r, k;
5986:             PetscInt dof;

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

5993:               for (r = 0; r < nRows; r++) {
5994:                 for (c = 0; c < newNumIndices; c++) {
5995:                   for (k = 0; k < dof; k++) {
5996:                     newValues[(rStart + r) * newNumIndices + c] += mat[k * nRows + r] * tmpValues[(oldOff + k) * newNumIndices + c];
5997:                   }
5998:                 }
5999:               }
6000:             }
6001:             else {
6002:               /* copy this row as is */
6003:               for (r = 0; r < dof; r++) {
6004:                 for (c = 0; c < newNumIndices; c++) {
6005:                   newValues[(rStart + r) * newNumIndices + c] = tmpValues[(oldOff + r) * newNumIndices + c];
6006:                 }
6007:               }
6008:             }
6009:             oldOff += dof;
6010:           }
6011:         }
6012:       }
6013:       else {
6014:         PetscInt oldOff = 0;

6016:         for (p = 0; p < numPoints; p++) {
6017:           PetscInt rStart = newPointOffsets[0][p];
6018:           PetscInt b      = points[2 * p];
6019:           PetscInt c, r, k;
6020:           PetscInt dof;

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

6027:             for (r = 0; r < nRows; r++) {
6028:               for (c = 0; c < newNumIndices; c++) {
6029:                 for (k = 0; k < dof; k++) {
6030:                   newValues[(rStart + r) * newNumIndices + c] += mat[k * nRows + r] * tmpValues[(oldOff + k) * newNumIndices + c];
6031:                 }
6032:               }
6033:             }
6034:           }
6035:           else {
6036:             /* copy this row as is */
6037:             for (r = 0; r < dof; r++) {
6038:               for (c = 0; c < newNumIndices; c++) {
6039:                 newValues[(rStart + r) * newNumIndices + c] = tmpValues[(oldOff + r) * newNumIndices + c];
6040:               }
6041:             }
6042:           }
6043:           oldOff += dof;
6044:         }
6045:       }

6047:       DMRestoreWorkArray(dm,newNumIndices*numIndices,MPIU_SCALAR,&tmpValues);
6048:     }
6049:     else {
6050:       newValues = tmpValues;
6051:     }
6052:   }

6054:   /* clean up */
6055:   DMRestoreWorkArray(dm,maxDof,MPIU_INT,&indices);
6056:   DMRestoreWorkArray(dm,maxAnchor*maxDof,MPIU_INT,&newIndices);

6058:   if (numFields) {
6059:     for (f = 0; f < numFields; f++) {
6060:       DMRestoreWorkArray(dm,pointMatOffsets[f][numPoints],MPIU_SCALAR,&pointMat[f]);
6061:       DMRestoreWorkArray(dm,numPoints+1,MPIU_INT,&pointMatOffsets[f]);
6062:       DMRestoreWorkArray(dm,numPoints+1,MPIU_INT,&newPointOffsets[f]);
6063:     }
6064:   }
6065:   else {
6066:     DMRestoreWorkArray(dm,pointMatOffsets[0][numPoints],MPIU_SCALAR,&pointMat[0]);
6067:     DMRestoreWorkArray(dm,numPoints+1,MPIU_INT,&pointMatOffsets[0]);
6068:     DMRestoreWorkArray(dm,numPoints+1,MPIU_INT,&newPointOffsets[0]);
6069:   }
6070:   ISRestoreIndices(aIS,&anchors);

6072:   /* output */
6073:   if (outPoints) {
6074:     *outPoints = newPoints;
6075:   }
6076:   else {
6077:     DMRestoreWorkArray(dm,2*newNumPoints,MPIU_INT,&newPoints);
6078:   }
6079:   if (outValues) {
6080:     *outValues = newValues;
6081:   }
6082:   for (f = 0; f <= numFields; f++) {
6083:     offsets[f] = newOffsets[f];
6084:   }
6085:   return(0);
6086: }

6088: /*@C
6089:   DMPlexGetClosureIndices - Get the global indices for all local points in the closure of the given point

6091:   Not collective

6093:   Input Parameters:
6094: + dm - The DM
6095: . section - The section describing the points (a local section)
6096: . idxSection - The section on which to obtain indices (may be local or global)
6097: - point - The mesh point

6099:   Output parameters:
6100: + numIndices - The number of indices
6101: . indices - The indices
6102: - outOffsets - Field offset if not NULL

6104:   Notes:
6105:   Must call DMPlexRestoreClosureIndices() to free allocated memory

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

6113:   Level: advanced

6115: .seealso DMPlexRestoreClosureIndices(), DMPlexVecGetClosure(), DMPlexMatSetClosure(), DMGetLocalSection(), DMGetGlobalSection()
6116: @*/
6117: PetscErrorCode DMPlexGetClosureIndices(DM dm, PetscSection section, PetscSection idxSection, PetscInt point, PetscInt *numIndices, PetscInt **indices, PetscInt *outOffsets)
6118: {
6119:   PetscBool       isLocal = (PetscBool)(section == idxSection);
6120:   PetscSection    clSection;
6121:   IS              clPoints;
6122:   const PetscInt *clp, *clperm;
6123:   const PetscInt  **perms[32] = {NULL};
6124:   PetscInt       *points = NULL, *pointsNew;
6125:   PetscInt        numPoints, numPointsNew;
6126:   PetscInt        offsets[32];
6127:   PetscInt        Nf, Nind, NindNew, off, idxOff, f, p;
6128:   PetscErrorCode  ierr;

6136:   PetscSectionGetNumFields(section, &Nf);
6137:   if (Nf > 31) SETERRQ1(PetscObjectComm((PetscObject)dm), PETSC_ERR_ARG_OUTOFRANGE, "Number of fields %D limited to 31", Nf);
6138:   PetscArrayzero(offsets, 32);
6139:   /* Get points in closure */
6140:   DMPlexGetCompressedClosure(dm,section,point,&numPoints,&points,&clSection,&clPoints,&clp);
6141:   PetscSectionGetClosureInversePermutation_Internal(section, (PetscObject) dm, NULL, &clperm);
6142:   /* Get number of indices and indices per field */
6143:   for (p = 0, Nind = 0; p < numPoints*2; p += 2) {
6144:     PetscInt dof, fdof;

6146:     PetscSectionGetDof(section, points[p], &dof);
6147:     for (f = 0; f < Nf; ++f) {
6148:       PetscSectionGetFieldDof(section, points[p], f, &fdof);
6149:       offsets[f+1] += fdof;
6150:     }
6151:     Nind += dof;
6152:   }
6153:   for (f = 1; f < Nf; ++f) offsets[f+1] += offsets[f];
6154:   if (Nf && offsets[Nf] != Nind) SETERRQ2(PetscObjectComm((PetscObject) dm), PETSC_ERR_PLIB, "Invalid size for closure %D should be %D", offsets[Nf], Nind);
6155:   if (!Nf) offsets[1] = Nind;
6156:   /* Get dual space symmetries */
6157:   for (f = 0; f < PetscMax(1,Nf); f++) {
6158:     if (Nf) {PetscSectionGetFieldPointSyms(section,f,numPoints,points,&perms[f],NULL);}
6159:     else    {PetscSectionGetPointSyms(section,numPoints,points,&perms[f],NULL);}
6160:   }
6161:   /* Correct for hanging node constraints */
6162:   {
6163:     DMPlexAnchorsModifyMat(dm, section, numPoints, Nind, points, perms, NULL, &numPointsNew, &NindNew, &pointsNew, NULL, offsets, PETSC_TRUE);
6164:     if (numPointsNew) {
6165:       for (f = 0; f < PetscMax(1,Nf); f++) {
6166:         if (Nf) {PetscSectionRestoreFieldPointSyms(section,f,numPoints,points,&perms[f],NULL);}
6167:         else    {PetscSectionRestorePointSyms(section,numPoints,points,&perms[f],NULL);}
6168:       }
6169:       for (f = 0; f < PetscMax(1,Nf); f++) {
6170:         if (Nf) {PetscSectionGetFieldPointSyms(section,f,numPointsNew,pointsNew,&perms[f],NULL);}
6171:         else    {PetscSectionGetPointSyms(section,numPointsNew,pointsNew,&perms[f],NULL);}
6172:       }
6173:       DMPlexRestoreCompressedClosure(dm,section,point,&numPoints,&points,&clSection,&clPoints,&clp);
6174:       numPoints = numPointsNew;
6175:       Nind      = NindNew;
6176:       points    = pointsNew;
6177:     }
6178:   }
6179:   /* Calculate indices */
6180:   DMGetWorkArray(dm, Nind, MPIU_INT, indices);
6181:   if (Nf) {
6182:     if (outOffsets) {
6183:       PetscInt f;

6185:       for (f = 0; f <= Nf; f++) {
6186:         outOffsets[f] = offsets[f];
6187:       }
6188:     }
6189:     for (p = 0; p < numPoints; p++) {
6190:       PetscSectionGetOffset(idxSection, points[2*p], &idxOff);
6191:       DMPlexGetIndicesPointFields_Internal(section, isLocal, points[2*p], idxOff < 0 ? -(idxOff+1) : idxOff, offsets, PETSC_FALSE, perms, p, clperm, *indices);
6192:     }
6193:   } else {
6194:     for (p = 0, off = 0; p < numPoints; p++) {
6195:       const PetscInt *perm = perms[0] ? perms[0][p] : NULL;

6197:       PetscSectionGetOffset(idxSection, points[2*p], &idxOff);
6198:       DMPlexGetIndicesPoint_Internal(section, isLocal, points[2*p], idxOff < 0 ? -(idxOff+1) : idxOff, &off, PETSC_FALSE, perm, clperm, *indices);
6199:     }
6200:   }
6201:   /* Cleanup points */
6202:   for (f = 0; f < PetscMax(1,Nf); f++) {
6203:     if (Nf) {PetscSectionRestoreFieldPointSyms(section,f,numPoints,points,&perms[f],NULL);}
6204:     else    {PetscSectionRestorePointSyms(section,numPoints,points,&perms[f],NULL);}
6205:   }
6206:   if (numPointsNew) {
6207:     DMRestoreWorkArray(dm, 2*numPointsNew, MPIU_INT, &pointsNew);
6208:   } else {
6209:     DMPlexRestoreCompressedClosure(dm,section,point,&numPoints,&points,&clSection,&clPoints,&clp);
6210:   }
6211:   if (numIndices) *numIndices = Nind;
6212:   return(0);
6213: }

6215: /*@C
6216:   DMPlexRestoreClosureIndices - Restore the indices in a vector v for all points in the closure of the given point

6218:   Not collective

6220:   Input Parameters:
6221: + dm - The DM
6222: . section - The section describing the layout in v, or NULL to use the default section
6223: . globalSection - The section describing the parallel layout in v, or NULL to use the default section
6224: . point - The mesh point
6225: . numIndices - The number of indices
6226: . indices - The indices
6227: - outOffsets - Field offset if not NULL

6229:   Level: advanced

6231: .seealso DMPlexGetClosureIndices(), DMPlexVecGetClosure(), DMPlexMatSetClosure()
6232: @*/
6233: PetscErrorCode DMPlexRestoreClosureIndices(DM dm, PetscSection section, PetscSection globalSection, PetscInt point, PetscInt *numIndices, PetscInt **indices,PetscInt *outOffsets)
6234: {

6240:   DMRestoreWorkArray(dm, 0, MPIU_INT, indices);
6241:   return(0);
6242: }

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

6247:   Not collective

6249:   Input Parameters:
6250: + dm - The DM
6251: . section - The section describing the layout in v, or NULL to use the default section
6252: . globalSection - The section describing the layout in v, or NULL to use the default global section
6253: . A - The matrix
6254: . point - The point in the DM
6255: . values - The array of values
6256: - mode - The insert mode, where INSERT_ALL_VALUES and ADD_ALL_VALUES also overwrite boundary conditions

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

6261:   Level: intermediate

6263: .seealso DMPlexVecGetClosure(), DMPlexVecSetClosure()
6264: @*/
6265: PetscErrorCode DMPlexMatSetClosure(DM dm, PetscSection section, PetscSection globalSection, Mat A, PetscInt point, const PetscScalar values[], InsertMode mode)
6266: {
6267:   DM_Plex            *mesh   = (DM_Plex*) dm->data;
6268:   PetscSection        clSection;
6269:   IS                  clPoints;
6270:   PetscInt           *points = NULL, *newPoints;
6271:   const PetscInt     *clp, *clperm;
6272:   PetscInt           *indices;
6273:   PetscInt            offsets[32];
6274:   const PetscInt    **perms[32] = {NULL};
6275:   const PetscScalar **flips[32] = {NULL};
6276:   PetscInt            numFields, numPoints, newNumPoints, numIndices, newNumIndices, dof, off, globalOff, p, f;
6277:   PetscScalar        *valCopy = NULL;
6278:   PetscScalar        *newValues;
6279:   PetscErrorCode      ierr;

6283:   if (!section) {DMGetLocalSection(dm, &section);}
6285:   if (!globalSection) {DMGetGlobalSection(dm, &globalSection);}
6288:   PetscSectionGetNumFields(section, &numFields);
6289:   if (numFields > 31) SETERRQ1(PetscObjectComm((PetscObject)dm), PETSC_ERR_ARG_OUTOFRANGE, "Number of fields %D limited to 31", numFields);
6290:   PetscArrayzero(offsets, 32);
6291:   PetscSectionGetClosureInversePermutation_Internal(section, (PetscObject) dm, NULL, &clperm);
6292:   DMPlexGetCompressedClosure(dm,section,point,&numPoints,&points,&clSection,&clPoints,&clp);
6293:   for (p = 0, numIndices = 0; p < numPoints*2; p += 2) {
6294:     PetscInt fdof;

6296:     PetscSectionGetDof(section, points[p], &dof);
6297:     for (f = 0; f < numFields; ++f) {
6298:       PetscSectionGetFieldDof(section, points[p], f, &fdof);
6299:       offsets[f+1] += fdof;
6300:     }
6301:     numIndices += dof;
6302:   }
6303:   for (f = 1; f < numFields; ++f) offsets[f+1] += offsets[f];

6305:   if (numFields && offsets[numFields] != numIndices) SETERRQ2(PetscObjectComm((PetscObject)dm), PETSC_ERR_PLIB, "Invalid size for closure %D should be %D", offsets[numFields], numIndices);
6306:   /* Get symmetries */
6307:   for (f = 0; f < PetscMax(1,numFields); f++) {
6308:     if (numFields) {PetscSectionGetFieldPointSyms(section,f,numPoints,points,&perms[f],&flips[f]);}
6309:     else           {PetscSectionGetPointSyms(section,numPoints,points,&perms[f],&flips[f]);}
6310:     if (values && flips[f]) { /* may need to apply sign changes to the element matrix */
6311:       PetscInt foffset = offsets[f];

6313:       for (p = 0; p < numPoints; p++) {
6314:         PetscInt point          = points[2*p], fdof;
6315:         const PetscScalar *flip = flips[f] ? flips[f][p] : NULL;

6317:         if (!numFields) {
6318:           PetscSectionGetDof(section,point,&fdof);
6319:         } else {
6320:           PetscSectionGetFieldDof(section,point,f,&fdof);
6321:         }
6322:         if (flip) {
6323:           PetscInt i, j, k;

6325:           if (!valCopy) {
6326:             DMGetWorkArray(dm,numIndices*numIndices,MPIU_SCALAR,&valCopy);
6327:             for (j = 0; j < numIndices * numIndices; j++) valCopy[j] = values[j];
6328:             values = valCopy;
6329:           }
6330:           for (i = 0; i < fdof; i++) {
6331:             PetscScalar fval = flip[i];

6333:             for (k = 0; k < numIndices; k++) {
6334:               valCopy[numIndices * (foffset + i) + k] *= fval;
6335:               valCopy[numIndices * k + (foffset + i)] *= fval;
6336:             }
6337:           }
6338:         }
6339:         foffset += fdof;
6340:       }
6341:     }
6342:   }
6343:   DMPlexAnchorsModifyMat(dm,section,numPoints,numIndices,points,perms,values,&newNumPoints,&newNumIndices,&newPoints,&newValues,offsets,PETSC_TRUE);
6344:   if (newNumPoints) {
6345:     if (valCopy) {
6346:       DMRestoreWorkArray(dm,numIndices*numIndices,MPIU_SCALAR,&valCopy);
6347:     }
6348:     for (f = 0; f < PetscMax(1,numFields); f++) {
6349:       if (numFields) {PetscSectionRestoreFieldPointSyms(section,f,numPoints,points,&perms[f],&flips[f]);}
6350:       else           {PetscSectionRestorePointSyms(section,numPoints,points,&perms[f],&flips[f]);}
6351:     }
6352:     for (f = 0; f < PetscMax(1,numFields); f++) {
6353:       if (numFields) {PetscSectionGetFieldPointSyms(section,f,newNumPoints,newPoints,&perms[f],&flips[f]);}
6354:       else           {PetscSectionGetPointSyms(section,newNumPoints,newPoints,&perms[f],&flips[f]);}
6355:     }
6356:     DMPlexRestoreCompressedClosure(dm,section,point,&numPoints,&points,&clSection,&clPoints,&clp);
6357:     numPoints  = newNumPoints;
6358:     numIndices = newNumIndices;
6359:     points     = newPoints;
6360:     values     = newValues;
6361:   }
6362:   DMGetWorkArray(dm, numIndices, MPIU_INT, &indices);
6363:   if (numFields) {
6364:     PetscBool useFieldOffsets;

6366:     PetscSectionGetUseFieldOffsets(globalSection, &useFieldOffsets);
6367:     if (useFieldOffsets) {
6368:       for (p = 0; p < numPoints; p++) {
6369:         DMPlexGetIndicesPointFieldsSplit_Internal(section, globalSection, points[2*p], offsets, perms, p, clperm, indices);
6370:       }
6371:     } else {
6372:       for (p = 0; p < numPoints; p++) {
6373:         PetscSectionGetOffset(globalSection, points[2*p], &globalOff);
6374:         /* Note that we pass a local section even though we're using global offsets.  This is because global sections do
6375:          * not (at the time of this writing) have fields set. They probably should, in which case we would pass the
6376:          * global section. */
6377:         DMPlexGetIndicesPointFields_Internal(section, PETSC_FALSE, points[2*p], globalOff < 0 ? -(globalOff+1) : globalOff, offsets, PETSC_FALSE, perms, p, clperm, indices);
6378:       }
6379:     }
6380:   } else {
6381:     for (p = 0, off = 0; p < numPoints; p++) {
6382:       const PetscInt *perm = perms[0] ? perms[0][p] : NULL;
6383:       PetscSectionGetOffset(globalSection, points[2*p], &globalOff);
6384:       /* Note that we pass a local section even though we're using global offsets.  This is because global sections do
6385:        * not (at the time of this writing) have fields set. They probably should, in which case we would pass the
6386:        * global section. */
6387:       DMPlexGetIndicesPoint_Internal(section, PETSC_FALSE, points[2*p], globalOff < 0 ? -(globalOff+1) : globalOff, &off, PETSC_FALSE, perm, clperm, indices);
6388:     }
6389:   }
6390:   if (mesh->printSetValues) {DMPlexPrintMatSetValues(PETSC_VIEWER_STDOUT_SELF, A, point, numIndices, indices, 0, NULL, values);}
6391:   MatSetValues(A, numIndices, indices, numIndices, indices, values, mode);
6392:   if (mesh->printFEM > 1) {
6393:     PetscInt i;
6394:     PetscPrintf(PETSC_COMM_SELF, "  Indices:");
6395:     for (i = 0; i < numIndices; ++i) {PetscPrintf(PETSC_COMM_SELF, " %D", indices[i]);}
6396:     PetscPrintf(PETSC_COMM_SELF, "\n");
6397:   }
6398:   if (ierr) {
6399:     PetscMPIInt    rank;
6400:     PetscErrorCode ierr2;

6402:     ierr2 = MPI_Comm_rank(PetscObjectComm((PetscObject)A), &rank);CHKERRQ(ierr2);
6403:     ierr2 = (*PetscErrorPrintf)("[%d]ERROR in DMPlexMatSetClosure\n", rank);CHKERRQ(ierr2);
6404:     ierr2 = DMPlexPrintMatSetValues(PETSC_VIEWER_STDERR_SELF, A, point, numIndices, indices, 0, NULL, values);CHKERRQ(ierr2);
6405:     ierr2 = DMRestoreWorkArray(dm, numIndices, MPIU_INT, &indices);CHKERRQ(ierr2);
6406:     
6407:   }
6408:   for (f = 0; f < PetscMax(1,numFields); f++) {
6409:     if (numFields) {PetscSectionRestoreFieldPointSyms(section,f,numPoints,points,&perms[f],&flips[f]);}
6410:     else           {PetscSectionRestorePointSyms(section,numPoints,points,&perms[f],&flips[f]);}
6411:   }
6412:   if (newNumPoints) {
6413:     DMRestoreWorkArray(dm,newNumIndices*newNumIndices,MPIU_SCALAR,&newValues);
6414:     DMRestoreWorkArray(dm,2*newNumPoints,MPIU_INT,&newPoints);
6415:   }
6416:   else {
6417:     if (valCopy) {
6418:       DMRestoreWorkArray(dm,numIndices*numIndices,MPIU_SCALAR,&valCopy);
6419:     }
6420:     DMPlexRestoreCompressedClosure(dm,section,point,&numPoints,&points,&clSection,&clPoints,&clp);
6421:   }
6422:   DMRestoreWorkArray(dm, numIndices, MPIU_INT, &indices);
6423:   return(0);
6424: }

6426: PetscErrorCode DMPlexMatSetClosureRefined(DM dmf, PetscSection fsection, PetscSection globalFSection, DM dmc, PetscSection csection, PetscSection globalCSection, Mat A, PetscInt point, const PetscScalar values[], InsertMode mode)
6427: {
6428:   DM_Plex        *mesh   = (DM_Plex*) dmf->data;
6429:   PetscInt       *fpoints = NULL, *ftotpoints = NULL;
6430:   PetscInt       *cpoints = NULL;
6431:   PetscInt       *findices, *cindices;
6432:   const PetscInt *fclperm = NULL, *cclperm = NULL; /* Closure permutations cannot work here */
6433:   PetscInt        foffsets[32], coffsets[32];
6434:   DMPolytopeType  ct;
6435:   PetscInt        numFields, numSubcells, maxFPoints, numFPoints, numCPoints, numFIndices, numCIndices, dof, off, globalOff, pStart, pEnd, p, q, r, s, f;
6436:   PetscErrorCode  ierr;

6441:   if (!fsection) {DMGetLocalSection(dmf, &fsection);}
6443:   if (!csection) {DMGetLocalSection(dmc, &csection);}
6445:   if (!globalFSection) {DMGetGlobalSection(dmf, &globalFSection);}
6447:   if (!globalCSection) {DMGetGlobalSection(dmc, &globalCSection);}
6450:   PetscSectionGetNumFields(fsection, &numFields);
6451:   if (numFields > 31) SETERRQ1(PetscObjectComm((PetscObject)dmf), PETSC_ERR_ARG_OUTOFRANGE, "Number of fields %D limited to 31", numFields);
6452:   PetscArrayzero(foffsets, 32);
6453:   PetscArrayzero(coffsets, 32);
6454:   /* Column indices */
6455:   DMPlexGetTransitiveClosure(dmc, point, PETSC_TRUE, &numCPoints, &cpoints);
6456:   maxFPoints = numCPoints;
6457:   /* Compress out points not in the section */
6458:   /*   TODO: Squeeze out points with 0 dof as well */
6459:   PetscSectionGetChart(csection, &pStart, &pEnd);
6460:   for (p = 0, q = 0; p < numCPoints*2; p += 2) {
6461:     if ((cpoints[p] >= pStart) && (cpoints[p] < pEnd)) {
6462:       cpoints[q*2]   = cpoints[p];
6463:       cpoints[q*2+1] = cpoints[p+1];
6464:       ++q;
6465:     }
6466:   }
6467:   numCPoints = q;
6468:   for (p = 0, numCIndices = 0; p < numCPoints*2; p += 2) {
6469:     PetscInt fdof;

6471:     PetscSectionGetDof(csection, cpoints[p], &dof);
6472:     if (!dof) continue;
6473:     for (f = 0; f < numFields; ++f) {
6474:       PetscSectionGetFieldDof(csection, cpoints[p], f, &fdof);
6475:       coffsets[f+1] += fdof;
6476:     }
6477:     numCIndices += dof;
6478:   }
6479:   for (f = 1; f < numFields; ++f) coffsets[f+1] += coffsets[f];
6480:   /* Row indices */
6481:   DMPlexGetCellType(dmc, point, &ct);
6482:   {
6483:     DMPlexCellRefiner cr;
6484:     DMPlexCellRefinerCreate(dmc, &cr);
6485:     DMPlexCellRefinerGetAffineTransforms(cr, ct, &numSubcells, NULL, NULL, NULL);
6486:     DMPlexCellRefinerDestroy(&cr);
6487:   }
6488:   DMGetWorkArray(dmf, maxFPoints*2*numSubcells, MPIU_INT, &ftotpoints);
6489:   for (r = 0, q = 0; r < numSubcells; ++r) {
6490:     /* TODO Map from coarse to fine cells */
6491:     DMPlexGetTransitiveClosure(dmf, point*numSubcells + r, PETSC_TRUE, &numFPoints, &fpoints);
6492:     /* Compress out points not in the section */
6493:     PetscSectionGetChart(fsection, &pStart, &pEnd);
6494:     for (p = 0; p < numFPoints*2; p += 2) {
6495:       if ((fpoints[p] >= pStart) && (fpoints[p] < pEnd)) {
6496:         PetscSectionGetDof(fsection, fpoints[p], &dof);
6497:         if (!dof) continue;
6498:         for (s = 0; s < q; ++s) if (fpoints[p] == ftotpoints[s*2]) break;
6499:         if (s < q) continue;
6500:         ftotpoints[q*2]   = fpoints[p];
6501:         ftotpoints[q*2+1] = fpoints[p+1];
6502:         ++q;
6503:       }
6504:     }
6505:     DMPlexRestoreTransitiveClosure(dmf, point, PETSC_TRUE, &numFPoints, &fpoints);
6506:   }
6507:   numFPoints = q;
6508:   for (p = 0, numFIndices = 0; p < numFPoints*2; p += 2) {
6509:     PetscInt fdof;

6511:     PetscSectionGetDof(fsection, ftotpoints[p], &dof);
6512:     if (!dof) continue;
6513:     for (f = 0; f < numFields; ++f) {
6514:       PetscSectionGetFieldDof(fsection, ftotpoints[p], f, &fdof);
6515:       foffsets[f+1] += fdof;
6516:     }
6517:     numFIndices += dof;
6518:   }
6519:   for (f = 1; f < numFields; ++f) foffsets[f+1] += foffsets[f];

6521:   if (numFields && foffsets[numFields] != numFIndices) SETERRQ2(PetscObjectComm((PetscObject)dmf), PETSC_ERR_PLIB, "Invalid size for closure %D should be %D", foffsets[numFields], numFIndices);
6522:   if (numFields && coffsets[numFields] != numCIndices) SETERRQ2(PetscObjectComm((PetscObject)dmc), PETSC_ERR_PLIB, "Invalid size for closure %D should be %D", coffsets[numFields], numCIndices);
6523:   DMGetWorkArray(dmf, numFIndices, MPIU_INT, &findices);
6524:   DMGetWorkArray(dmc, numCIndices, MPIU_INT, &cindices);
6525:   if (numFields) {
6526:     const PetscInt **permsF[32] = {NULL};
6527:     const PetscInt **permsC[32] = {NULL};

6529:     for (f = 0; f < numFields; f++) {
6530:       PetscSectionGetFieldPointSyms(fsection,f,numFPoints,ftotpoints,&permsF[f],NULL);
6531:       PetscSectionGetFieldPointSyms(csection,f,numCPoints,cpoints,&permsC[f],NULL);
6532:     }
6533:     for (p = 0; p < numFPoints; p++) {
6534:       PetscSectionGetOffset(globalFSection, ftotpoints[2*p], &globalOff);
6535:       DMPlexGetIndicesPointFields_Internal(fsection, PETSC_FALSE, ftotpoints[2*p], globalOff < 0 ? -(globalOff+1) : globalOff, foffsets, PETSC_FALSE, permsF, p, fclperm, findices);
6536:     }
6537:     for (p = 0; p < numCPoints; p++) {
6538:       PetscSectionGetOffset(globalCSection, cpoints[2*p], &globalOff);
6539:       DMPlexGetIndicesPointFields_Internal(csection, PETSC_FALSE, cpoints[2*p], globalOff < 0 ? -(globalOff+1) : globalOff, coffsets, PETSC_FALSE, permsC, p, cclperm, cindices);
6540:     }
6541:     for (f = 0; f < numFields; f++) {
6542:       PetscSectionRestoreFieldPointSyms(fsection,f,numFPoints,ftotpoints,&permsF[f],NULL);
6543:       PetscSectionRestoreFieldPointSyms(csection,f,numCPoints,cpoints,&permsC[f],NULL);
6544:     }
6545:   } else {
6546:     const PetscInt **permsF = NULL;
6547:     const PetscInt **permsC = NULL;

6549:     PetscSectionGetPointSyms(fsection,numFPoints,ftotpoints,&permsF,NULL);
6550:     PetscSectionGetPointSyms(csection,numCPoints,cpoints,&permsC,NULL);
6551:     for (p = 0, off = 0; p < numFPoints; p++) {
6552:       const PetscInt *perm = permsF ? permsF[p] : NULL;

6554:       PetscSectionGetOffset(globalFSection, ftotpoints[2*p], &globalOff);
6555:       DMPlexGetIndicesPoint_Internal(fsection, PETSC_FALSE, ftotpoints[2*p], globalOff < 0 ? -(globalOff+1) : globalOff, &off, PETSC_FALSE, perm, fclperm, findices);
6556:     }
6557:     for (p = 0, off = 0; p < numCPoints; p++) {
6558:       const PetscInt *perm = permsC ? permsC[p] : NULL;

6560:       PetscSectionGetOffset(globalCSection, cpoints[2*p], &globalOff);
6561:       DMPlexGetIndicesPoint_Internal(csection, PETSC_FALSE, cpoints[2*p], globalOff < 0 ? -(globalOff+1) : globalOff, &off, PETSC_FALSE, perm, cclperm, cindices);
6562:     }
6563:     PetscSectionRestorePointSyms(fsection,numFPoints,ftotpoints,&permsF,NULL);
6564:     PetscSectionRestorePointSyms(csection,numCPoints,cpoints,&permsC,NULL);
6565:   }
6566:   if (mesh->printSetValues) {DMPlexPrintMatSetValues(PETSC_VIEWER_STDOUT_SELF, A, point, numFIndices, findices, numCIndices, cindices, values);}
6567:   /* TODO: flips */
6568:   MatSetValues(A, numFIndices, findices, numCIndices, cindices, values, mode);
6569:   if (ierr) {
6570:     PetscMPIInt    rank;
6571:     PetscErrorCode ierr2;

6573:     ierr2 = MPI_Comm_rank(PetscObjectComm((PetscObject)A), &rank);CHKERRQ(ierr2);
6574:     ierr2 = (*PetscErrorPrintf)("[%d]ERROR in DMPlexMatSetClosure\n", rank);CHKERRQ(ierr2);
6575:     ierr2 = DMPlexPrintMatSetValues(PETSC_VIEWER_STDERR_SELF, A, point, numFIndices, findices, numCIndices, cindices, values);CHKERRQ(ierr2);
6576:     ierr2 = DMRestoreWorkArray(dmf, numFIndices, MPIU_INT, &findices);CHKERRQ(ierr2);
6577:     ierr2 = DMRestoreWorkArray(dmc, numCIndices, MPIU_INT, &cindices);CHKERRQ(ierr2);
6578:     
6579:   }
6580:   DMRestoreWorkArray(dmf, numCPoints*2*4, MPIU_INT, &ftotpoints);
6581:   DMPlexRestoreTransitiveClosure(dmc, point, PETSC_TRUE, &numCPoints, &cpoints);
6582:   DMRestoreWorkArray(dmf, numFIndices, MPIU_INT, &findices);
6583:   DMRestoreWorkArray(dmc, numCIndices, MPIU_INT, &cindices);
6584:   return(0);
6585: }

6587: PetscErrorCode DMPlexMatGetClosureIndicesRefined(DM dmf, PetscSection fsection, PetscSection globalFSection, DM dmc, PetscSection csection, PetscSection globalCSection, PetscInt point, PetscInt cindices[], PetscInt findices[])
6588: {
6589:   PetscInt      *fpoints = NULL, *ftotpoints = NULL;
6590:   PetscInt      *cpoints = NULL;
6591:   PetscInt       foffsets[32], coffsets[32];
6592:   const PetscInt *fclperm = NULL, *cclperm = NULL; /* Closure permutations cannot work here */
6593:   DMPolytopeType ct;
6594:   PetscInt       numFields, numSubcells, maxFPoints, numFPoints, numCPoints, numFIndices, numCIndices, dof, off, globalOff, pStart, pEnd, p, q, r, s, f;

6600:   if (!fsection) {DMGetLocalSection(dmf, &fsection);}
6602:   if (!csection) {DMGetLocalSection(dmc, &csection);}
6604:   if (!globalFSection) {DMGetGlobalSection(dmf, &globalFSection);}
6606:   if (!globalCSection) {DMGetGlobalSection(dmc, &globalCSection);}
6608:   PetscSectionGetNumFields(fsection, &numFields);
6609:   if (numFields > 31) SETERRQ1(PetscObjectComm((PetscObject)dmf), PETSC_ERR_ARG_OUTOFRANGE, "Number of fields %D limited to 31", numFields);
6610:   PetscArrayzero(foffsets, 32);
6611:   PetscArrayzero(coffsets, 32);
6612:   /* Column indices */
6613:   DMPlexGetTransitiveClosure(dmc, point, PETSC_TRUE, &numCPoints, &cpoints);
6614:   maxFPoints = numCPoints;
6615:   /* Compress out points not in the section */
6616:   /*   TODO: Squeeze out points with 0 dof as well */
6617:   PetscSectionGetChart(csection, &pStart, &pEnd);
6618:   for (p = 0, q = 0; p < numCPoints*2; p += 2) {
6619:     if ((cpoints[p] >= pStart) && (cpoints[p] < pEnd)) {
6620:       cpoints[q*2]   = cpoints[p];
6621:       cpoints[q*2+1] = cpoints[p+1];
6622:       ++q;
6623:     }
6624:   }
6625:   numCPoints = q;
6626:   for (p = 0, numCIndices = 0; p < numCPoints*2; p += 2) {
6627:     PetscInt fdof;

6629:     PetscSectionGetDof(csection, cpoints[p], &dof);
6630:     if (!dof) continue;
6631:     for (f = 0; f < numFields; ++f) {
6632:       PetscSectionGetFieldDof(csection, cpoints[p], f, &fdof);
6633:       coffsets[f+1] += fdof;
6634:     }
6635:     numCIndices += dof;
6636:   }
6637:   for (f = 1; f < numFields; ++f) coffsets[f+1] += coffsets[f];
6638:   /* Row indices */
6639:   DMPlexGetCellType(dmc, point, &ct);
6640:   {
6641:     DMPlexCellRefiner cr;
6642:     DMPlexCellRefinerCreate(dmc, &cr);
6643:     DMPlexCellRefinerGetAffineTransforms(cr, ct, &numSubcells, NULL, NULL, NULL);
6644:     DMPlexCellRefinerDestroy(&cr);
6645:   }
6646:   DMGetWorkArray(dmf, maxFPoints*2*numSubcells, MPIU_INT, &ftotpoints);
6647:   for (r = 0, q = 0; r < numSubcells; ++r) {
6648:     /* TODO Map from coarse to fine cells */
6649:     DMPlexGetTransitiveClosure(dmf, point*numSubcells + r, PETSC_TRUE, &numFPoints, &fpoints);
6650:     /* Compress out points not in the section */
6651:     PetscSectionGetChart(fsection, &pStart, &pEnd);
6652:     for (p = 0; p < numFPoints*2; p += 2) {
6653:       if ((fpoints[p] >= pStart) && (fpoints[p] < pEnd)) {
6654:         PetscSectionGetDof(fsection, fpoints[p], &dof);
6655:         if (!dof) continue;
6656:         for (s = 0; s < q; ++s) if (fpoints[p] == ftotpoints[s*2]) break;
6657:         if (s < q) continue;
6658:         ftotpoints[q*2]   = fpoints[p];
6659:         ftotpoints[q*2+1] = fpoints[p+1];
6660:         ++q;
6661:       }
6662:     }
6663:     DMPlexRestoreTransitiveClosure(dmf, point, PETSC_TRUE, &numFPoints, &fpoints);
6664:   }
6665:   numFPoints = q;
6666:   for (p = 0, numFIndices = 0; p < numFPoints*2; p += 2) {
6667:     PetscInt fdof;

6669:     PetscSectionGetDof(fsection, ftotpoints[p], &dof);
6670:     if (!dof) continue;
6671:     for (f = 0; f < numFields; ++f) {
6672:       PetscSectionGetFieldDof(fsection, ftotpoints[p], f, &fdof);
6673:       foffsets[f+1] += fdof;
6674:     }
6675:     numFIndices += dof;
6676:   }
6677:   for (f = 1; f < numFields; ++f) foffsets[f+1] += foffsets[f];

6679:   if (numFields && foffsets[numFields] != numFIndices) SETERRQ2(PetscObjectComm((PetscObject)dmf), PETSC_ERR_PLIB, "Invalid size for closure %D should be %D", foffsets[numFields], numFIndices);
6680:   if (numFields && coffsets[numFields] != numCIndices) SETERRQ2(PetscObjectComm((PetscObject)dmc), PETSC_ERR_PLIB, "Invalid size for closure %D should be %D", coffsets[numFields], numCIndices);
6681:   if (numFields) {
6682:     const PetscInt **permsF[32] = {NULL};
6683:     const PetscInt **permsC[32] = {NULL};

6685:     for (f = 0; f < numFields; f++) {
6686:       PetscSectionGetFieldPointSyms(fsection,f,numFPoints,ftotpoints,&permsF[f],NULL);
6687:       PetscSectionGetFieldPointSyms(csection,f,numCPoints,cpoints,&permsC[f],NULL);
6688:     }
6689:     for (p = 0; p < numFPoints; p++) {
6690:       PetscSectionGetOffset(globalFSection, ftotpoints[2*p], &globalOff);
6691:       DMPlexGetIndicesPointFields_Internal(fsection, PETSC_FALSE, ftotpoints[2*p], globalOff < 0 ? -(globalOff+1) : globalOff, foffsets, PETSC_FALSE, permsF, p, fclperm, findices);
6692:     }
6693:     for (p = 0; p < numCPoints; p++) {
6694:       PetscSectionGetOffset(globalCSection, cpoints[2*p], &globalOff);
6695:       DMPlexGetIndicesPointFields_Internal(csection, PETSC_FALSE, cpoints[2*p], globalOff < 0 ? -(globalOff+1) : globalOff, coffsets, PETSC_FALSE, permsC, p, cclperm, cindices);
6696:     }
6697:     for (f = 0; f < numFields; f++) {
6698:       PetscSectionRestoreFieldPointSyms(fsection,f,numFPoints,ftotpoints,&permsF[f],NULL);
6699:       PetscSectionRestoreFieldPointSyms(csection,f,numCPoints,cpoints,&permsC[f],NULL);
6700:     }
6701:   } else {
6702:     const PetscInt **permsF = NULL;
6703:     const PetscInt **permsC = NULL;

6705:     PetscSectionGetPointSyms(fsection,numFPoints,ftotpoints,&permsF,NULL);
6706:     PetscSectionGetPointSyms(csection,numCPoints,cpoints,&permsC,NULL);
6707:     for (p = 0, off = 0; p < numFPoints; p++) {
6708:       const PetscInt *perm = permsF ? permsF[p] : NULL;

6710:       PetscSectionGetOffset(globalFSection, ftotpoints[2*p], &globalOff);
6711:       DMPlexGetIndicesPoint_Internal(fsection, PETSC_FALSE, ftotpoints[2*p], globalOff < 0 ? -(globalOff+1) : globalOff, &off, PETSC_FALSE, perm, fclperm, findices);
6712:     }
6713:     for (p = 0, off = 0; p < numCPoints; p++) {
6714:       const PetscInt *perm = permsC ? permsC[p] : NULL;

6716:       PetscSectionGetOffset(globalCSection, cpoints[2*p], &globalOff);
6717:       DMPlexGetIndicesPoint_Internal(csection, PETSC_FALSE, cpoints[2*p], globalOff < 0 ? -(globalOff+1) : globalOff, &off, PETSC_FALSE, perm, cclperm, cindices);
6718:     }
6719:     PetscSectionRestorePointSyms(fsection,numFPoints,ftotpoints,&permsF,NULL);
6720:     PetscSectionRestorePointSyms(csection,numCPoints,cpoints,&permsC,NULL);
6721:   }
6722:   DMRestoreWorkArray(dmf, numCPoints*2*4, MPIU_INT, &ftotpoints);
6723:   DMPlexRestoreTransitiveClosure(dmc, point, PETSC_TRUE, &numCPoints, &cpoints);
6724:   return(0);
6725: }

6727: /*@C
6728:   DMPlexGetVTKCellHeight - Returns the height in the DAG used to determine which points are cells (normally 0)

6730:   Input Parameter:
6731: . dm   - The DMPlex object

6733:   Output Parameter:
6734: . cellHeight - The height of a cell

6736:   Level: developer

6738: .seealso DMPlexSetVTKCellHeight()
6739: @*/
6740: PetscErrorCode DMPlexGetVTKCellHeight(DM dm, PetscInt *cellHeight)
6741: {
6742:   DM_Plex *mesh = (DM_Plex*) dm->data;

6747:   *cellHeight = mesh->vtkCellHeight;
6748:   return(0);
6749: }

6751: /*@C
6752:   DMPlexSetVTKCellHeight - Sets the height in the DAG used to determine which points are cells (normally 0)

6754:   Input Parameters:
6755: + dm   - The DMPlex object
6756: - cellHeight - The height of a cell

6758:   Level: developer

6760: .seealso DMPlexGetVTKCellHeight()
6761: @*/
6762: PetscErrorCode DMPlexSetVTKCellHeight(DM dm, PetscInt cellHeight)
6763: {
6764:   DM_Plex *mesh = (DM_Plex*) dm->data;

6768:   mesh->vtkCellHeight = cellHeight;
6769:   return(0);
6770: }

6772: /*@
6773:   DMPlexGetGhostCellStratum - Get the range of cells which are used to enforce FV boundary conditions

6775:   Input Parameter:
6776: . dm - The DMPlex object

6778:   Output Parameters:
6779: + gcStart - The first ghost cell, or NULL
6780: - gcEnd   - The upper bound on ghost cells, or NULL

6782:   Level: advanced

6784: .seealso DMPlexConstructGhostCells(), DMPlexSetGhostCellStratum()
6785: @*/
6786: PetscErrorCode DMPlexGetGhostCellStratum(DM dm, PetscInt *gcStart, PetscInt *gcEnd)
6787: {
6788:   DMLabel        ctLabel;

6793:   DMPlexGetCellTypeLabel(dm, &ctLabel);
6794:   DMLabelGetStratumBounds(ctLabel, DM_POLYTOPE_FV_GHOST, gcStart, gcEnd);
6795:   return(0);
6796: }

6798: /* We can easily have a form that takes an IS instead */
6799: PetscErrorCode DMPlexCreateNumbering_Plex(DM dm, PetscInt pStart, PetscInt pEnd, PetscInt shift, PetscInt *globalSize, PetscSF sf, IS *numbering)
6800: {
6801:   PetscSection   section, globalSection;
6802:   PetscInt      *numbers, p;

6806:   PetscSectionCreate(PetscObjectComm((PetscObject)dm), &section);
6807:   PetscSectionSetChart(section, pStart, pEnd);
6808:   for (p = pStart; p < pEnd; ++p) {
6809:     PetscSectionSetDof(section, p, 1);
6810:   }
6811:   PetscSectionSetUp(section);
6812:   PetscSectionCreateGlobalSection(section, sf, PETSC_FALSE, PETSC_FALSE, &globalSection);
6813:   PetscMalloc1(pEnd - pStart, &numbers);
6814:   for (p = pStart; p < pEnd; ++p) {
6815:     PetscSectionGetOffset(globalSection, p, &numbers[p-pStart]);
6816:     if (numbers[p-pStart] < 0) numbers[p-pStart] -= shift;
6817:     else                       numbers[p-pStart] += shift;
6818:   }
6819:   ISCreateGeneral(PetscObjectComm((PetscObject) dm), pEnd - pStart, numbers, PETSC_OWN_POINTER, numbering);
6820:   if (globalSize) {
6821:     PetscLayout layout;
6822:     PetscSectionGetPointLayout(PetscObjectComm((PetscObject) dm), globalSection, &layout);
6823:     PetscLayoutGetSize(layout, globalSize);
6824:     PetscLayoutDestroy(&layout);
6825:   }
6826:   PetscSectionDestroy(&section);
6827:   PetscSectionDestroy(&globalSection);
6828:   return(0);
6829: }

6831: PetscErrorCode DMPlexCreateCellNumbering_Internal(DM dm, PetscBool includeHybrid, IS *globalCellNumbers)
6832: {
6833:   PetscInt       cellHeight, cStart, cEnd;

6837:   DMPlexGetVTKCellHeight(dm, &cellHeight);
6838:   if (includeHybrid) {DMPlexGetHeightStratum(dm, cellHeight, &cStart, &cEnd);}
6839:   else               {DMPlexGetSimplexOrBoxCells(dm, cellHeight, &cStart, &cEnd);}
6840:   DMPlexCreateNumbering_Plex(dm, cStart, cEnd, 0, NULL, dm->sf, globalCellNumbers);
6841:   return(0);
6842: }

6844: /*@
6845:   DMPlexGetCellNumbering - Get a global cell numbering for all cells on this process

6847:   Input Parameter:
6848: . dm   - The DMPlex object

6850:   Output Parameter:
6851: . globalCellNumbers - Global cell numbers for all cells on this process

6853:   Level: developer

6855: .seealso DMPlexGetVertexNumbering()
6856: @*/
6857: PetscErrorCode DMPlexGetCellNumbering(DM dm, IS *globalCellNumbers)
6858: {
6859:   DM_Plex       *mesh = (DM_Plex*) dm->data;

6864:   if (!mesh->globalCellNumbers) {DMPlexCreateCellNumbering_Internal(dm, PETSC_FALSE, &mesh->globalCellNumbers);}
6865:   *globalCellNumbers = mesh->globalCellNumbers;
6866:   return(0);
6867: }

6869: PetscErrorCode DMPlexCreateVertexNumbering_Internal(DM dm, PetscBool includeHybrid, IS *globalVertexNumbers)
6870: {
6871:   PetscInt       vStart, vEnd;

6876:   DMPlexGetDepthStratum(dm, 0, &vStart, &vEnd);
6877:   DMPlexCreateNumbering_Plex(dm, vStart, vEnd, 0, NULL, dm->sf, globalVertexNumbers);
6878:   return(0);
6879: }

6881: /*@
6882:   DMPlexGetVertexNumbering - Get a global vertex numbering for all vertices on this process

6884:   Input Parameter:
6885: . dm   - The DMPlex object

6887:   Output Parameter:
6888: . globalVertexNumbers - Global vertex numbers for all vertices on this process

6890:   Level: developer

6892: .seealso DMPlexGetCellNumbering()
6893: @*/
6894: PetscErrorCode DMPlexGetVertexNumbering(DM dm, IS *globalVertexNumbers)
6895: {
6896:   DM_Plex       *mesh = (DM_Plex*) dm->data;

6901:   if (!mesh->globalVertexNumbers) {DMPlexCreateVertexNumbering_Internal(dm, PETSC_FALSE, &mesh->globalVertexNumbers);}
6902:   *globalVertexNumbers = mesh->globalVertexNumbers;
6903:   return(0);
6904: }

6906: /*@
6907:   DMPlexCreatePointNumbering - Create a global numbering for all points on this process

6909:   Input Parameter:
6910: . dm   - The DMPlex object

6912:   Output Parameter:
6913: . globalPointNumbers - Global numbers for all points on this process

6915:   Level: developer

6917: .seealso DMPlexGetCellNumbering()
6918: @*/
6919: PetscErrorCode DMPlexCreatePointNumbering(DM dm, IS *globalPointNumbers)
6920: {
6921:   IS             nums[4];
6922:   PetscInt       depths[4], gdepths[4], starts[4];
6923:   PetscInt       depth, d, shift = 0;

6928:   DMPlexGetDepth(dm, &depth);
6929:   /* For unstratified meshes use dim instead of depth */
6930:   if (depth < 0) {DMGetDimension(dm, &depth);}
6931:   for (d = 0; d <= depth; ++d) {
6932:     PetscInt end;

6934:     depths[d] = depth-d;
6935:     DMPlexGetDepthStratum(dm, depths[d], &starts[d], &end);
6936:     if (!(starts[d]-end)) { starts[d] = depths[d] = -1; }
6937:   }
6938:   PetscSortIntWithArray(depth+1, starts, depths);
6939:   MPIU_Allreduce(depths, gdepths, depth+1, MPIU_INT, MPI_MAX, PetscObjectComm((PetscObject) dm));
6940:   for (d = 0; d <= depth; ++d) {
6941:     if (starts[d] >= 0 && depths[d] != gdepths[d]) SETERRQ2(PETSC_COMM_SELF,PETSC_ERR_PLIB,"Expected depth %D, found %D",depths[d],gdepths[d]);
6942:   }
6943:   for (d = 0; d <= depth; ++d) {
6944:     PetscInt pStart, pEnd, gsize;

6946:     DMPlexGetDepthStratum(dm, gdepths[d], &pStart, &pEnd);
6947:     DMPlexCreateNumbering_Plex(dm, pStart, pEnd, shift, &gsize, dm->sf, &nums[d]);
6948:     shift += gsize;
6949:   }
6950:   ISConcatenate(PetscObjectComm((PetscObject) dm), depth+1, nums, globalPointNumbers);
6951:   for (d = 0; d <= depth; ++d) {ISDestroy(&nums[d]);}
6952:   return(0);
6953: }


6956: /*@
6957:   DMPlexCreateRankField - Create a cell field whose value is the rank of the owner

6959:   Input Parameter:
6960: . dm - The DMPlex object

6962:   Output Parameter:
6963: . ranks - The rank field

6965:   Options Database Keys:
6966: . -dm_partition_view - Adds the rank field into the DM output from -dm_view using the same viewer

6968:   Level: intermediate

6970: .seealso: DMView()
6971: @*/
6972: PetscErrorCode DMPlexCreateRankField(DM dm, Vec *ranks)
6973: {
6974:   DM             rdm;
6975:   PetscFE        fe;
6976:   PetscScalar   *r;
6977:   PetscMPIInt    rank;
6978:   PetscInt       dim, cStart, cEnd, c;

6984:   MPI_Comm_rank(PetscObjectComm((PetscObject) dm), &rank);
6985:   DMClone(dm, &rdm);
6986:   DMGetDimension(rdm, &dim);
6987:   PetscFECreateDefault(PetscObjectComm((PetscObject) rdm), dim, 1, PETSC_TRUE, "PETSc___rank_", -1, &fe);
6988:   PetscObjectSetName((PetscObject) fe, "rank");
6989:   DMSetField(rdm, 0, NULL, (PetscObject) fe);
6990:   PetscFEDestroy(&fe);
6991:   DMCreateDS(rdm);
6992:   DMPlexGetHeightStratum(rdm, 0, &cStart, &cEnd);
6993:   DMCreateGlobalVector(rdm, ranks);
6994:   PetscObjectSetName((PetscObject) *ranks, "partition");
6995:   VecGetArray(*ranks, &r);
6996:   for (c = cStart; c < cEnd; ++c) {
6997:     PetscScalar *lr;

6999:     DMPlexPointGlobalRef(rdm, c, r, &lr);
7000:     if (lr) *lr = rank;
7001:   }
7002:   VecRestoreArray(*ranks, &r);
7003:   DMDestroy(&rdm);
7004:   return(0);
7005: }

7007: /*@
7008:   DMPlexCreateLabelField - Create a cell field whose value is the label value for that cell

7010:   Input Parameters:
7011: + dm    - The DMPlex
7012: - label - The DMLabel

7014:   Output Parameter:
7015: . val - The label value field

7017:   Options Database Keys:
7018: . -dm_label_view - Adds the label value field into the DM output from -dm_view using the same viewer

7020:   Level: intermediate

7022: .seealso: DMView()
7023: @*/
7024: PetscErrorCode DMPlexCreateLabelField(DM dm, DMLabel label, Vec *val)
7025: {
7026:   DM             rdm;
7027:   PetscFE        fe;
7028:   PetscScalar   *v;
7029:   PetscInt       dim, cStart, cEnd, c;

7036:   DMClone(dm, &rdm);
7037:   DMGetDimension(rdm, &dim);
7038:   PetscFECreateDefault(PetscObjectComm((PetscObject) rdm), dim, 1, PETSC_TRUE, "PETSc___label_value_", -1, &fe);
7039:   PetscObjectSetName((PetscObject) fe, "label_value");
7040:   DMSetField(rdm, 0, NULL, (PetscObject) fe);
7041:   PetscFEDestroy(&fe);
7042:   DMCreateDS(rdm);
7043:   DMPlexGetHeightStratum(rdm, 0, &cStart, &cEnd);
7044:   DMCreateGlobalVector(rdm, val);
7045:   PetscObjectSetName((PetscObject) *val, "label_value");
7046:   VecGetArray(*val, &v);
7047:   for (c = cStart; c < cEnd; ++c) {
7048:     PetscScalar *lv;
7049:     PetscInt     cval;

7051:     DMPlexPointGlobalRef(rdm, c, v, &lv);
7052:     DMLabelGetValue(label, c, &cval);
7053:     *lv = cval;
7054:   }
7055:   VecRestoreArray(*val, &v);
7056:   DMDestroy(&rdm);
7057:   return(0);
7058: }

7060: /*@
7061:   DMPlexCheckSymmetry - Check that the adjacency information in the mesh is symmetric.

7063:   Input Parameter:
7064: . dm - The DMPlex object

7066:   Notes:
7067:   This is a useful diagnostic when creating meshes programmatically.

7069:   For the complete list of DMPlexCheck* functions, see DMSetFromOptions().

7071:   Level: developer

7073: .seealso: DMCreate(), DMSetFromOptions()
7074: @*/
7075: PetscErrorCode DMPlexCheckSymmetry(DM dm)
7076: {
7077:   PetscSection    coneSection, supportSection;
7078:   const PetscInt *cone, *support;
7079:   PetscInt        coneSize, c, supportSize, s;
7080:   PetscInt        pStart, pEnd, p, pp, csize, ssize;
7081:   PetscBool       storagecheck = PETSC_TRUE;
7082:   PetscErrorCode  ierr;

7086:   DMViewFromOptions(dm, NULL, "-sym_dm_view");
7087:   DMPlexGetConeSection(dm, &coneSection);
7088:   DMPlexGetSupportSection(dm, &supportSection);
7089:   /* Check that point p is found in the support of its cone points, and vice versa */
7090:   DMPlexGetChart(dm, &pStart, &pEnd);
7091:   for (p = pStart; p < pEnd; ++p) {
7092:     DMPlexGetConeSize(dm, p, &coneSize);
7093:     DMPlexGetCone(dm, p, &cone);
7094:     for (c = 0; c < coneSize; ++c) {
7095:       PetscBool dup = PETSC_FALSE;
7096:       PetscInt  d;
7097:       for (d = c-1; d >= 0; --d) {
7098:         if (cone[c] == cone[d]) {dup = PETSC_TRUE; break;}
7099:       }
7100:       DMPlexGetSupportSize(dm, cone[c], &supportSize);
7101:       DMPlexGetSupport(dm, cone[c], &support);
7102:       for (s = 0; s < supportSize; ++s) {
7103:         if (support[s] == p) break;
7104:       }
7105:       if ((s >= supportSize) || (dup && (support[s+1] != p))) {
7106:         PetscPrintf(PETSC_COMM_SELF, "p: %D cone: ", p);
7107:         for (s = 0; s < coneSize; ++s) {
7108:           PetscPrintf(PETSC_COMM_SELF, "%D, ", cone[s]);
7109:         }
7110:         PetscPrintf(PETSC_COMM_SELF, "\n");
7111:         PetscPrintf(PETSC_COMM_SELF, "p: %D support: ", cone[c]);
7112:         for (s = 0; s < supportSize; ++s) {
7113:           PetscPrintf(PETSC_COMM_SELF, "%D, ", support[s]);
7114:         }
7115:         PetscPrintf(PETSC_COMM_SELF, "\n");
7116:         if (dup) SETERRQ2(PETSC_COMM_SELF, PETSC_ERR_PLIB, "Point %D not repeatedly found in support of repeated cone point %D", p, cone[c]);
7117:         else SETERRQ2(PETSC_COMM_SELF, PETSC_ERR_PLIB, "Point %D not found in support of cone point %D", p, cone[c]);
7118:       }
7119:     }
7120:     DMPlexGetTreeParent(dm, p, &pp, NULL);
7121:     if (p != pp) { storagecheck = PETSC_FALSE; continue; }
7122:     DMPlexGetSupportSize(dm, p, &supportSize);
7123:     DMPlexGetSupport(dm, p, &support);
7124:     for (s = 0; s < supportSize; ++s) {
7125:       DMPlexGetConeSize(dm, support[s], &coneSize);
7126:       DMPlexGetCone(dm, support[s], &cone);
7127:       for (c = 0; c < coneSize; ++c) {
7128:         DMPlexGetTreeParent(dm, cone[c], &pp, NULL);
7129:         if (cone[c] != pp) { c = 0; break; }
7130:         if (cone[c] == p) break;
7131:       }
7132:       if (c >= coneSize) {
7133:         PetscPrintf(PETSC_COMM_SELF, "p: %D support: ", p);
7134:         for (c = 0; c < supportSize; ++c) {
7135:           PetscPrintf(PETSC_COMM_SELF, "%D, ", support[c]);
7136:         }
7137:         PetscPrintf(PETSC_COMM_SELF, "\n");
7138:         PetscPrintf(PETSC_COMM_SELF, "p: %D cone: ", support[s]);
7139:         for (c = 0; c < coneSize; ++c) {
7140:           PetscPrintf(PETSC_COMM_SELF, "%D, ", cone[c]);
7141:         }
7142:         PetscPrintf(PETSC_COMM_SELF, "\n");
7143:         SETERRQ2(PETSC_COMM_SELF, PETSC_ERR_PLIB, "Point %D not found in cone of support point %D", p, support[s]);
7144:       }
7145:     }
7146:   }
7147:   if (storagecheck) {
7148:     PetscSectionGetStorageSize(coneSection, &csize);
7149:     PetscSectionGetStorageSize(supportSection, &ssize);
7150:     if (csize != ssize) SETERRQ2(PETSC_COMM_SELF, PETSC_ERR_ARG_SIZ, "Total cone size %D != Total support size %D", csize, ssize);
7151:   }
7152:   return(0);
7153: }

7155: /*
7156:   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.
7157: */
7158: static PetscErrorCode DMPlexCellUnsplitVertices_Private(DM dm, PetscInt c, DMPolytopeType ct, PetscInt *unsplit)
7159: {
7160:   DMPolytopeType  cct;
7161:   PetscInt        ptpoints[4];
7162:   const PetscInt *cone, *ccone, *ptcone;
7163:   PetscInt        coneSize, cp, cconeSize, ccp, npt = 0, pt;
7164:   PetscErrorCode  ierr;

7167:   *unsplit = 0;
7168:   switch (ct) {
7169:     case DM_POLYTOPE_SEG_PRISM_TENSOR:
7170:       DMPlexGetCone(dm, c, &cone);
7171:       DMPlexGetConeSize(dm, c, &coneSize);
7172:       for (cp = 0; cp < coneSize; ++cp) {
7173:         DMPlexGetCellType(dm, cone[cp], &cct);
7174:         if (cct == DM_POLYTOPE_POINT_PRISM_TENSOR) ptpoints[npt++] = cone[cp];
7175:       }
7176:       break;
7177:     case DM_POLYTOPE_TRI_PRISM_TENSOR:
7178:     case DM_POLYTOPE_QUAD_PRISM_TENSOR:
7179:       DMPlexGetCone(dm, c, &cone);
7180:       DMPlexGetConeSize(dm, c, &coneSize);
7181:       for (cp = 0; cp < coneSize; ++cp) {
7182:         DMPlexGetCone(dm, cone[cp], &ccone);
7183:         DMPlexGetConeSize(dm, cone[cp], &cconeSize);
7184:         for (ccp = 0; ccp < cconeSize; ++ccp) {
7185:           DMPlexGetCellType(dm, ccone[ccp], &cct);
7186:           if (cct == DM_POLYTOPE_POINT_PRISM_TENSOR) {
7187:             PetscInt p;
7188:             for (p = 0; p < npt; ++p) if (ptpoints[p] == ccone[ccp]) break;
7189:             if (p == npt) ptpoints[npt++] = ccone[ccp];
7190:           }
7191:         }
7192:       }
7193:       break;
7194:     default: break;
7195:   }
7196:   for (pt = 0; pt < npt; ++pt) {
7197:     DMPlexGetCone(dm, ptpoints[pt], &ptcone);
7198:     if (ptcone[0] == ptcone[1]) ++(*unsplit);
7199:   }
7200:   return(0);
7201: }

7203: /*@
7204:   DMPlexCheckSkeleton - Check that each cell has the correct number of vertices

7206:   Input Parameters:
7207: + dm - The DMPlex object
7208: - cellHeight - Normally 0

7210:   Notes:
7211:   This is a useful diagnostic when creating meshes programmatically.
7212:   Currently applicable only to homogeneous simplex or tensor meshes.

7214:   For the complete list of DMPlexCheck* functions, see DMSetFromOptions().

7216:   Level: developer

7218: .seealso: DMCreate(), DMSetFromOptions()
7219: @*/
7220: PetscErrorCode DMPlexCheckSkeleton(DM dm, PetscInt cellHeight)
7221: {
7222:   DMPlexInterpolatedFlag interp;
7223:   DMPolytopeType         ct;
7224:   PetscInt               vStart, vEnd, cStart, cEnd, c;
7225:   PetscErrorCode         ierr;

7229:   DMPlexIsInterpolated(dm, &interp);
7230:   DMPlexGetHeightStratum(dm, cellHeight, &cStart, &cEnd);
7231:   DMPlexGetDepthStratum(dm, 0, &vStart, &vEnd);
7232:   for (c = cStart; c < cEnd; ++c) {
7233:     PetscInt *closure = NULL;
7234:     PetscInt  coneSize, closureSize, cl, Nv = 0;

7236:     DMPlexGetCellType(dm, c, &ct);
7237:     if ((PetscInt) ct < 0) SETERRQ1(PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Cell %D has no cell type", c);
7238:     if (ct == DM_POLYTOPE_UNKNOWN) continue;
7239:     if (interp == DMPLEX_INTERPOLATED_FULL) {
7240:       DMPlexGetConeSize(dm, c, &coneSize);
7241:       if (coneSize != DMPolytopeTypeGetConeSize(ct)) SETERRQ3(PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Cell %D has cone size %D != %D", c, coneSize, DMPolytopeTypeGetConeSize(ct));
7242:     }
7243:     DMPlexGetTransitiveClosure(dm, c, PETSC_TRUE, &closureSize, &closure);
7244:     for (cl = 0; cl < closureSize*2; cl += 2) {
7245:       const PetscInt p = closure[cl];
7246:       if ((p >= vStart) && (p < vEnd)) ++Nv;
7247:     }
7248:     DMPlexRestoreTransitiveClosure(dm, c, PETSC_TRUE, &closureSize, &closure);
7249:     /* Special Case: Tensor faces with identified vertices */
7250:     if (Nv < DMPolytopeTypeGetNumVertices(ct)) {
7251:       PetscInt unsplit;

7253:       DMPlexCellUnsplitVertices_Private(dm, c, ct, &unsplit);
7254:       if (Nv + unsplit == DMPolytopeTypeGetNumVertices(ct)) continue;
7255:     }
7256:     if (Nv != DMPolytopeTypeGetNumVertices(ct)) SETERRQ3(PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Cell %D has %D vertices != %D", c, Nv, DMPolytopeTypeGetNumVertices(ct));
7257:   }
7258:   return(0);
7259: }

7261: /*@
7262:   DMPlexCheckFaces - Check that the faces of each cell give a vertex order this is consistent with what we expect from the cell type

7264:   Not Collective

7266:   Input Parameters:
7267: + dm - The DMPlex object
7268: - cellHeight - Normally 0

7270:   Notes:
7271:   This is a useful diagnostic when creating meshes programmatically.
7272:   This routine is only relevant for meshes that are fully interpolated across all ranks.
7273:   It will error out if a partially interpolated mesh is given on some rank.
7274:   It will do nothing for locally uninterpolated mesh (as there is nothing to check).

7276:   For the complete list of DMPlexCheck* functions, see DMSetFromOptions().

7278:   Level: developer

7280: .seealso: DMCreate(), DMPlexGetVTKCellHeight(), DMSetFromOptions()
7281: @*/
7282: PetscErrorCode DMPlexCheckFaces(DM dm, PetscInt cellHeight)
7283: {
7284:   PetscInt       dim, depth, vStart, vEnd, cStart, cEnd, c, h;
7286:   DMPlexInterpolatedFlag interpEnum;

7290:   DMPlexIsInterpolated(dm, &interpEnum);
7291:   if (interpEnum == DMPLEX_INTERPOLATED_NONE) return(0);
7292:   if (interpEnum == DMPLEX_INTERPOLATED_PARTIAL) {
7293:     PetscMPIInt        rank;
7294:     MPI_Comm        comm;

7296:     PetscObjectGetComm((PetscObject) dm, &comm);
7297:     MPI_Comm_rank(comm, &rank);
7298:     SETERRQ1(PETSC_COMM_SELF, PETSC_ERR_SUP, "Mesh is only partially interpolated on rank %d, this is currently not supported", rank);
7299:   }

7301:   DMGetDimension(dm, &dim);
7302:   DMPlexGetDepth(dm, &depth);
7303:   DMPlexGetDepthStratum(dm, 0, &vStart, &vEnd);
7304:   for (h = cellHeight; h < PetscMin(depth, dim); ++h) {
7305:     DMPlexGetHeightStratum(dm, h, &cStart, &cEnd);
7306:     for (c = cStart; c < cEnd; ++c) {
7307:       const PetscInt      *cone, *ornt, *faceSizes, *faces;
7308:       const DMPolytopeType *faceTypes;
7309:       DMPolytopeType        ct;
7310:       PetscInt              numFaces, coneSize, f;
7311:       PetscInt             *closure = NULL, closureSize, cl, numCorners = 0, fOff = 0, unsplit;

7313:       DMPlexGetCellType(dm, c, &ct);
7314:       DMPlexCellUnsplitVertices_Private(dm, c, ct, &unsplit);
7315:       if (unsplit) continue;
7316:       DMPlexGetConeSize(dm, c, &coneSize);
7317:       DMPlexGetCone(dm, c, &cone);
7318:       DMPlexGetConeOrientation(dm, c, &ornt);
7319:       DMPlexGetTransitiveClosure(dm, c, PETSC_TRUE, &closureSize, &closure);
7320:       for (cl = 0; cl < closureSize*2; cl += 2) {
7321:         const PetscInt p = closure[cl];
7322:         if ((p >= vStart) && (p < vEnd)) closure[numCorners++] = p;
7323:       }
7324:       DMPlexGetRawFaces_Internal(dm, ct, closure, &numFaces, &faceTypes, &faceSizes, &faces);
7325:       if (coneSize != numFaces) SETERRQ3(PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Cell %D has %D faces but should have %D", c, coneSize, numFaces);
7326:       for (f = 0; f < numFaces; ++f) {
7327:         PetscInt *fclosure = NULL, fclosureSize, cl, fnumCorners = 0, v;

7329:         DMPlexGetTransitiveClosure_Internal(dm, cone[f], ornt[f], PETSC_TRUE, &fclosureSize, &fclosure);
7330:         for (cl = 0; cl < fclosureSize*2; cl += 2) {
7331:           const PetscInt p = fclosure[cl];
7332:           if ((p >= vStart) && (p < vEnd)) fclosure[fnumCorners++] = p;
7333:         }
7334:         if (fnumCorners != faceSizes[f]) SETERRQ5(PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Face %D (%D) of cell %D has %D vertices but should have %D", cone[f], f, c, fnumCorners, faceSizes[f]);
7335:         for (v = 0; v < fnumCorners; ++v) {
7336:           if (fclosure[v] != faces[fOff+v]) SETERRQ6(PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Face %D (%d) of cell %D vertex %D, %D != %D", cone[f], f, c, v, fclosure[v], faces[fOff+v]);
7337:         }
7338:         DMPlexRestoreTransitiveClosure(dm, cone[f], PETSC_TRUE, &fclosureSize, &fclosure);
7339:         fOff += faceSizes[f];
7340:       }
7341:       DMPlexRestoreRawFaces_Internal(dm, ct, closure, &numFaces, &faceTypes, &faceSizes, &faces);
7342:       DMPlexRestoreTransitiveClosure(dm, c, PETSC_TRUE, &closureSize, &closure);
7343:     }
7344:   }
7345:   return(0);
7346: }

7348: /*@
7349:   DMPlexCheckGeometry - Check the geometry of mesh cells

7351:   Input Parameter:
7352: . dm - The DMPlex object

7354:   Notes:
7355:   This is a useful diagnostic when creating meshes programmatically.

7357:   For the complete list of DMPlexCheck* functions, see DMSetFromOptions().

7359:   Level: developer

7361: .seealso: DMCreate(), DMSetFromOptions()
7362: @*/
7363: PetscErrorCode DMPlexCheckGeometry(DM dm)
7364: {
7365:   PetscReal      detJ, J[9], refVol = 1.0;
7366:   PetscReal      vol;
7367:   PetscBool      periodic;
7368:   PetscInt       dim, depth, d, cStart, cEnd, c;

7372:   DMGetDimension(dm, &dim);
7373:   DMPlexGetDepth(dm, &depth);
7374:   DMGetPeriodicity(dm, &periodic, NULL, NULL, NULL);
7375:   for (d = 0; d < dim; ++d) refVol *= 2.0;
7376:   DMPlexGetHeightStratum(dm, 0, &cStart, &cEnd);
7377:   for (c = cStart; c < cEnd; ++c) {
7378:     DMPolytopeType ct;
7379:     PetscInt       unsplit;
7380:     PetscBool      ignoreZeroVol = PETSC_FALSE;

7382:     DMPlexGetCellType(dm, c, &ct);
7383:     switch (ct) {
7384:       case DM_POLYTOPE_SEG_PRISM_TENSOR:
7385:       case DM_POLYTOPE_TRI_PRISM_TENSOR:
7386:       case DM_POLYTOPE_QUAD_PRISM_TENSOR:
7387:         ignoreZeroVol = PETSC_TRUE; break;
7388:       default: break;
7389:     }
7390:     switch (ct) {
7391:       case DM_POLYTOPE_TRI_PRISM:
7392:       case DM_POLYTOPE_TRI_PRISM_TENSOR:
7393:       case DM_POLYTOPE_QUAD_PRISM_TENSOR:
7394:         continue;
7395:       default: break;
7396:     }
7397:     DMPlexCellUnsplitVertices_Private(dm, c, ct, &unsplit);
7398:     if (unsplit) continue;
7399:     DMPlexComputeCellGeometryFEM(dm, c, NULL, NULL, J, NULL, &detJ);
7400:     if (detJ < -PETSC_SMALL || (detJ <= 0.0 && !ignoreZeroVol)) SETERRQ2(PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Mesh cell %D is inverted, |J| = %g", c, (double) detJ);
7401:     PetscInfo2(dm, "Cell %D FEM Volume %g\n", c, (double) detJ*refVol);
7402:     if (depth > 1 && !periodic) {
7403:       DMPlexComputeCellGeometryFVM(dm, c, &vol, NULL, NULL);
7404:       if (vol < -PETSC_SMALL || (vol <= 0.0 && !ignoreZeroVol)) SETERRQ2(PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Mesh cell %d is inverted, vol = %g", c, (double) vol);
7405:       PetscInfo2(dm, "Cell %D FVM Volume %g\n", c, (double) vol);
7406:     }
7407:   }
7408:   return(0);
7409: }

7411: /*@
7412:   DMPlexCheckPointSF - Check that several necessary conditions are met for the point SF of this plex.

7414:   Input Parameters:
7415: . dm - The DMPlex object

7417:   Notes:
7418:   This is mainly intended for debugging/testing purposes.
7419:   It currently checks only meshes with no partition overlapping.

7421:   For the complete list of DMPlexCheck* functions, see DMSetFromOptions().

7423:   Level: developer

7425: .seealso: DMGetPointSF(), DMSetFromOptions()
7426: @*/
7427: PetscErrorCode DMPlexCheckPointSF(DM dm)
7428: {
7429:   PetscSF         pointSF;
7430:   PetscInt        cellHeight, cStart, cEnd, l, nleaves, nroots, overlap;
7431:   const PetscInt *locals, *rootdegree;
7432:   PetscBool       distributed;
7433:   PetscErrorCode  ierr;

7437:   DMGetPointSF(dm, &pointSF);
7438:   DMPlexIsDistributed(dm, &distributed);
7439:   if (!distributed) return(0);
7440:   DMPlexGetOverlap(dm, &overlap);
7441:   if (overlap) {
7442:     PetscPrintf(PetscObjectComm((PetscObject)dm), "Warning: DMPlexCheckPointSF() is currently not implemented for meshes with partition overlapping");
7443:     return(0);
7444:   }
7445:   if (!pointSF) SETERRQ(PetscObjectComm((PetscObject)dm), PETSC_ERR_ARG_WRONGSTATE, "This DMPlex is distributed but does not have PointSF attached");
7446:   PetscSFGetGraph(pointSF, &nroots, &nleaves, &locals, NULL);
7447:   if (nroots < 0) SETERRQ(PetscObjectComm((PetscObject)dm), PETSC_ERR_ARG_WRONGSTATE, "This DMPlex is distributed but its PointSF has no graph set");
7448:   PetscSFComputeDegreeBegin(pointSF, &rootdegree);
7449:   PetscSFComputeDegreeEnd(pointSF, &rootdegree);

7451:   /* 1) check there are no faces in 2D, cells in 3D, in interface */
7452:   DMPlexGetVTKCellHeight(dm, &cellHeight);
7453:   DMPlexGetHeightStratum(dm, cellHeight, &cStart, &cEnd);
7454:   for (l = 0; l < nleaves; ++l) {
7455:     const PetscInt point = locals[l];

7457:     if (point >= cStart && point < cEnd) SETERRQ1(PETSC_COMM_SELF, PETSC_ERR_PLIB, "Point SF contains %D which is a cell", point);
7458:   }

7460:   /* 2) if some point is in interface, then all its cone points must be also in interface (either as leaves or roots) */
7461:   for (l = 0; l < nleaves; ++l) {
7462:     const PetscInt  point = locals[l];
7463:     const PetscInt *cone;
7464:     PetscInt        coneSize, c, idx;

7466:     DMPlexGetConeSize(dm, point, &coneSize);
7467:     DMPlexGetCone(dm, point, &cone);
7468:     for (c = 0; c < coneSize; ++c) {
7469:       if (!rootdegree[cone[c]]) {
7470:         PetscFindInt(cone[c], nleaves, locals, &idx);
7471:         if (idx < 0) SETERRQ2(PETSC_COMM_SELF, PETSC_ERR_PLIB, "Point SF contains %D but not %D from its cone", point, cone[c]);
7472:       }
7473:     }
7474:   }
7475:   return(0);
7476: }

7478: typedef struct cell_stats
7479: {
7480:   PetscReal min, max, sum, squaresum;
7481:   PetscInt  count;
7482: } cell_stats_t;

7484: static void MPIAPI cell_stats_reduce(void *a, void *b, int * len, MPI_Datatype *datatype)
7485: {
7486:   PetscInt i, N = *len;

7488:   for (i = 0; i < N; i++) {
7489:     cell_stats_t *A = (cell_stats_t *) a;
7490:     cell_stats_t *B = (cell_stats_t *) b;

7492:     B->min = PetscMin(A->min,B->min);
7493:     B->max = PetscMax(A->max,B->max);
7494:     B->sum += A->sum;
7495:     B->squaresum += A->squaresum;
7496:     B->count += A->count;
7497:   }
7498: }

7500: /*@
7501:   DMPlexCheckCellShape - Checks the Jacobian of the mapping from reference to real cells and computes some minimal statistics.

7503:   Collective on dm

7505:   Input Parameters:
7506: + dm        - The DMPlex object
7507: . output    - If true, statistics will be displayed on stdout
7508: - condLimit - Display all cells above this condition number, or PETSC_DETERMINE for no cell output

7510:   Notes:
7511:   This is mainly intended for debugging/testing purposes.

7513:   For the complete list of DMPlexCheck* functions, see DMSetFromOptions().

7515:   Level: developer

7517: .seealso: DMSetFromOptions()
7518: @*/
7519: PetscErrorCode DMPlexCheckCellShape(DM dm, PetscBool output, PetscReal condLimit)
7520: {
7521:   DM             dmCoarse;
7522:   cell_stats_t   stats, globalStats;
7523:   MPI_Comm       comm = PetscObjectComm((PetscObject)dm);
7524:   PetscReal      *J, *invJ, min = 0, max = 0, mean = 0, stdev = 0;
7525:   PetscReal      limit = condLimit > 0 ? condLimit : PETSC_MAX_REAL;
7526:   PetscInt       cdim, cStart, cEnd, c, eStart, eEnd, count = 0;
7527:   PetscMPIInt    rank,size;

7532:   stats.min   = PETSC_MAX_REAL;
7533:   stats.max   = PETSC_MIN_REAL;
7534:   stats.sum   = stats.squaresum = 0.;
7535:   stats.count = 0;

7537:   MPI_Comm_size(comm, &size);
7538:   MPI_Comm_rank(comm, &rank);
7539:   DMGetCoordinateDim(dm,&cdim);
7540:   PetscMalloc2(PetscSqr(cdim), &J, PetscSqr(cdim), &invJ);
7541:   DMPlexGetSimplexOrBoxCells(dm,0,&cStart,&cEnd);
7542:   DMPlexGetDepthStratum(dm,1,&eStart,&eEnd);
7543:   for (c = cStart; c < cEnd; c++) {
7544:     PetscInt  i;
7545:     PetscReal frobJ = 0., frobInvJ = 0., cond2, cond, detJ;

7547:     DMPlexComputeCellGeometryAffineFEM(dm,c,NULL,J,invJ,&detJ);
7548:     if (detJ < 0.0) SETERRQ1(PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Mesh cell %D is inverted", c);
7549:     for (i = 0; i < PetscSqr(cdim); ++i) {
7550:       frobJ    += J[i] * J[i];
7551:       frobInvJ += invJ[i] * invJ[i];
7552:     }
7553:     cond2 = frobJ * frobInvJ;
7554:     cond  = PetscSqrtReal(cond2);

7556:     stats.min        = PetscMin(stats.min,cond);
7557:     stats.max        = PetscMax(stats.max,cond);
7558:     stats.sum       += cond;
7559:     stats.squaresum += cond2;
7560:     stats.count++;
7561:     if (output && cond > limit) {
7562:       PetscSection coordSection;
7563:       Vec          coordsLocal;
7564:       PetscScalar *coords = NULL;
7565:       PetscInt     Nv, d, clSize, cl, *closure = NULL;

7567:       DMGetCoordinatesLocal(dm, &coordsLocal);
7568:       DMGetCoordinateSection(dm, &coordSection);
7569:       DMPlexVecGetClosure(dm, coordSection, coordsLocal, c, &Nv, &coords);
7570:       PetscSynchronizedPrintf(comm, "[%d] Cell %D cond %g\n", rank, c, (double) cond);
7571:       for (i = 0; i < Nv/cdim; ++i) {
7572:         PetscSynchronizedPrintf(comm, "  Vertex %D: (", i);
7573:         for (d = 0; d < cdim; ++d) {
7574:           if (d > 0) {PetscSynchronizedPrintf(comm, ", ");}
7575:           PetscSynchronizedPrintf(comm, "%g", (double) PetscRealPart(coords[i*cdim+d]));
7576:         }
7577:         PetscSynchronizedPrintf(comm, ")\n");
7578:       }
7579:       DMPlexGetTransitiveClosure(dm, c, PETSC_TRUE, &clSize, &closure);
7580:       for (cl = 0; cl < clSize*2; cl += 2) {
7581:         const PetscInt edge = closure[cl];

7583:         if ((edge >= eStart) && (edge < eEnd)) {
7584:           PetscReal len;

7586:           DMPlexComputeCellGeometryFVM(dm, edge, &len, NULL, NULL);
7587:           PetscSynchronizedPrintf(comm, "  Edge %D: length %g\n", edge, (double) len);
7588:         }
7589:       }
7590:       DMPlexRestoreTransitiveClosure(dm, c, PETSC_TRUE, &clSize, &closure);
7591:       DMPlexVecRestoreClosure(dm, coordSection, coordsLocal, c, &Nv, &coords);
7592:     }
7593:   }
7594:   if (output) {PetscSynchronizedFlush(comm, NULL);}

7596:   if (size > 1) {
7597:     PetscMPIInt   blockLengths[2] = {4,1};
7598:     MPI_Aint      blockOffsets[2] = {offsetof(cell_stats_t,min),offsetof(cell_stats_t,count)};
7599:     MPI_Datatype  blockTypes[2]   = {MPIU_REAL,MPIU_INT}, statType;
7600:     MPI_Op        statReduce;

7602:     MPI_Type_create_struct(2,blockLengths,blockOffsets,blockTypes,&statType);
7603:     MPI_Type_commit(&statType);
7604:     MPI_Op_create(cell_stats_reduce, PETSC_TRUE, &statReduce);
7605:     MPI_Reduce(&stats,&globalStats,1,statType,statReduce,0,comm);
7606:     MPI_Op_free(&statReduce);
7607:     MPI_Type_free(&statType);
7608:   } else {
7609:     PetscArraycpy(&globalStats,&stats,1);
7610:   }
7611:   if (!rank) {
7612:     count = globalStats.count;
7613:     min   = globalStats.min;
7614:     max   = globalStats.max;
7615:     mean  = globalStats.sum / globalStats.count;
7616:     stdev = globalStats.count > 1 ? PetscSqrtReal(PetscMax((globalStats.squaresum - globalStats.count * mean * mean) / (globalStats.count - 1),0)) : 0.0;
7617:   }

7619:   if (output) {
7620:     PetscPrintf(comm,"Mesh with %D cells, shape condition numbers: min = %g, max = %g, mean = %g, stddev = %g\n", count, (double) min, (double) max, (double) mean, (double) stdev);
7621:   }
7622:   PetscFree2(J,invJ);

7624:   DMGetCoarseDM(dm,&dmCoarse);
7625:   if (dmCoarse) {
7626:     PetscBool isplex;

7628:     PetscObjectTypeCompare((PetscObject)dmCoarse,DMPLEX,&isplex);
7629:     if (isplex) {
7630:       DMPlexCheckCellShape(dmCoarse,output,condLimit);
7631:     }
7632:   }
7633:   return(0);
7634: }

7636: /* Pointwise interpolation
7637:      Just code FEM for now
7638:      u^f = I u^c
7639:      sum_k u^f_k phi^f_k = I sum_j u^c_j phi^c_j
7640:      u^f_i = sum_j psi^f_i I phi^c_j u^c_j
7641:      I_{ij} = psi^f_i phi^c_j
7642: */
7643: PetscErrorCode DMCreateInterpolation_Plex(DM dmCoarse, DM dmFine, Mat *interpolation, Vec *scaling)
7644: {
7645:   PetscSection   gsc, gsf;
7646:   PetscInt       m, n;
7647:   void          *ctx;
7648:   DM             cdm;
7649:   PetscBool      regular, ismatis;

7653:   DMGetGlobalSection(dmFine, &gsf);
7654:   PetscSectionGetConstrainedStorageSize(gsf, &m);
7655:   DMGetGlobalSection(dmCoarse, &gsc);
7656:   PetscSectionGetConstrainedStorageSize(gsc, &n);

7658:   PetscStrcmp(dmCoarse->mattype, MATIS, &ismatis);
7659:   MatCreate(PetscObjectComm((PetscObject) dmCoarse), interpolation);
7660:   MatSetSizes(*interpolation, m, n, PETSC_DETERMINE, PETSC_DETERMINE);
7661:   MatSetType(*interpolation, ismatis ? MATAIJ : dmCoarse->mattype);
7662:   DMGetApplicationContext(dmFine, &ctx);

7664:   DMGetCoarseDM(dmFine, &cdm);
7665:   DMPlexGetRegularRefinement(dmFine, &regular);
7666:   if (regular && cdm == dmCoarse) {DMPlexComputeInterpolatorNested(dmCoarse, dmFine, *interpolation, ctx);}
7667:   else                            {DMPlexComputeInterpolatorGeneral(dmCoarse, dmFine, *interpolation, ctx);}
7668:   MatViewFromOptions(*interpolation, NULL, "-interp_mat_view");
7669:   if (scaling) {
7670:     /* Use naive scaling */
7671:     DMCreateInterpolationScale(dmCoarse, dmFine, *interpolation, scaling);
7672:   }
7673:   return(0);
7674: }

7676: PetscErrorCode DMCreateInjection_Plex(DM dmCoarse, DM dmFine, Mat *mat)
7677: {
7679:   VecScatter     ctx;

7682:   DMPlexComputeInjectorFEM(dmCoarse, dmFine, &ctx, NULL);
7683:   MatCreateScatter(PetscObjectComm((PetscObject)ctx), ctx, mat);
7684:   VecScatterDestroy(&ctx);
7685:   return(0);
7686: }

7688: PetscErrorCode DMCreateMassMatrix_Plex(DM dmCoarse, DM dmFine, Mat *mass)
7689: {
7690:   PetscSection   gsc, gsf;
7691:   PetscInt       m, n;
7692:   void          *ctx;
7693:   DM             cdm;
7694:   PetscBool      regular;

7698:   DMGetGlobalSection(dmFine, &gsf);
7699:   PetscSectionGetConstrainedStorageSize(gsf, &m);
7700:   DMGetGlobalSection(dmCoarse, &gsc);
7701:   PetscSectionGetConstrainedStorageSize(gsc, &n);

7703:   MatCreate(PetscObjectComm((PetscObject) dmCoarse), mass);
7704:   MatSetSizes(*mass, m, n, PETSC_DETERMINE, PETSC_DETERMINE);
7705:   MatSetType(*mass, dmCoarse->mattype);
7706:   DMGetApplicationContext(dmFine, &ctx);

7708:   DMGetCoarseDM(dmFine, &cdm);
7709:   DMPlexGetRegularRefinement(dmFine, &regular);
7710:   if (regular && cdm == dmCoarse) {DMPlexComputeMassMatrixNested(dmCoarse, dmFine, *mass, ctx);}
7711:   else                            {DMPlexComputeMassMatrixGeneral(dmCoarse, dmFine, *mass, ctx);}
7712:   MatViewFromOptions(*mass, NULL, "-mass_mat_view");
7713:   return(0);
7714: }

7716: /*@
7717:   DMPlexGetRegularRefinement - Get the flag indicating that this mesh was obtained by regular refinement from its coarse mesh

7719:   Input Parameter:
7720: . dm - The DMPlex object

7722:   Output Parameter:
7723: . regular - The flag

7725:   Level: intermediate

7727: .seealso: DMPlexSetRegularRefinement()
7728: @*/
7729: PetscErrorCode DMPlexGetRegularRefinement(DM dm, PetscBool *regular)
7730: {
7734:   *regular = ((DM_Plex *) dm->data)->regularRefinement;
7735:   return(0);
7736: }

7738: /*@
7739:   DMPlexSetRegularRefinement - Set the flag indicating that this mesh was obtained by regular refinement from its coarse mesh

7741:   Input Parameters:
7742: + dm - The DMPlex object
7743: - regular - The flag

7745:   Level: intermediate

7747: .seealso: DMPlexGetRegularRefinement()
7748: @*/
7749: PetscErrorCode DMPlexSetRegularRefinement(DM dm, PetscBool regular)
7750: {
7753:   ((DM_Plex *) dm->data)->regularRefinement = regular;
7754:   return(0);
7755: }

7757: /*@
7758:   DMPlexGetCellRefinerType - Get the strategy for refining a cell

7760:   Input Parameter:
7761: . dm - The DMPlex object

7763:   Output Parameter:
7764: . cr - The strategy number

7766:   Level: intermediate

7768: .seealso: DMPlexSetCellRefinerType(), DMPlexSetRegularRefinement()
7769: @*/
7770: PetscErrorCode DMPlexGetCellRefinerType(DM dm, DMPlexCellRefinerType *cr)
7771: {
7775:   *cr = ((DM_Plex *) dm->data)->cellRefiner;
7776:   return(0);
7777: }

7779: /*@
7780:   DMPlexSetCellRefinerType - Set the strategy for refining a cell

7782:   Input Parameters:
7783: + dm - The DMPlex object
7784: - cr - The strategy number

7786:   Level: intermediate

7788: .seealso: DMPlexGetCellRefinerType(), DMPlexGetRegularRefinement()
7789: @*/
7790: PetscErrorCode DMPlexSetCellRefinerType(DM dm, DMPlexCellRefinerType cr)
7791: {
7794:   ((DM_Plex *) dm->data)->cellRefiner = cr;
7795:   return(0);
7796: }

7798: /* anchors */
7799: /*@
7800:   DMPlexGetAnchors - Get the layout of the anchor (point-to-point) constraints.  Typically, the user will not have to
7801:   call DMPlexGetAnchors() directly: if there are anchors, then DMPlexGetAnchors() is called during DMGetConstraints().

7803:   not collective

7805:   Input Parameters:
7806: . dm - The DMPlex object

7808:   Output Parameters:
7809: + anchorSection - If not NULL, set to the section describing which points anchor the constrained points.
7810: - anchorIS - If not NULL, set to the list of anchors indexed by anchorSection


7813:   Level: intermediate

7815: .seealso: DMPlexSetAnchors(), DMGetConstraints(), DMSetConstraints()
7816: @*/
7817: PetscErrorCode DMPlexGetAnchors(DM dm, PetscSection *anchorSection, IS *anchorIS)
7818: {
7819:   DM_Plex *plex = (DM_Plex *)dm->data;

7824:   if (!plex->anchorSection && !plex->anchorIS && plex->createanchors) {(*plex->createanchors)(dm);}
7825:   if (anchorSection) *anchorSection = plex->anchorSection;
7826:   if (anchorIS) *anchorIS = plex->anchorIS;
7827:   return(0);
7828: }

7830: /*@
7831:   DMPlexSetAnchors - Set the layout of the local anchor (point-to-point) constraints.  Unlike boundary conditions,
7832:   when a point's degrees of freedom in a section are constrained to an outside value, the anchor constraints set a
7833:   point's degrees of freedom to be a linear combination of other points' degrees of freedom.

7835:   After specifying the layout of constraints with DMPlexSetAnchors(), one specifies the constraints by calling
7836:   DMGetConstraints() and filling in the entries in the constraint matrix.

7838:   collective on dm

7840:   Input Parameters:
7841: + dm - The DMPlex object
7842: . anchorSection - The section that describes the mapping from constrained points to the anchor points listed in anchorIS.  Must have a local communicator (PETSC_COMM_SELF or derivative).
7843: - anchorIS - The list of all anchor points.  Must have a local communicator (PETSC_COMM_SELF or derivative).

7845:   The reference counts of anchorSection and anchorIS are incremented.

7847:   Level: intermediate

7849: .seealso: DMPlexGetAnchors(), DMGetConstraints(), DMSetConstraints()
7850: @*/
7851: PetscErrorCode DMPlexSetAnchors(DM dm, PetscSection anchorSection, IS anchorIS)
7852: {
7853:   DM_Plex        *plex = (DM_Plex *)dm->data;
7854:   PetscMPIInt    result;

7859:   if (anchorSection) {
7861:     MPI_Comm_compare(PETSC_COMM_SELF,PetscObjectComm((PetscObject)anchorSection),&result);
7862:     if (result != MPI_CONGRUENT && result != MPI_IDENT) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_NOTSAMECOMM,"anchor section must have local communicator");
7863:   }
7864:   if (anchorIS) {
7866:     MPI_Comm_compare(PETSC_COMM_SELF,PetscObjectComm((PetscObject)anchorIS),&result);
7867:     if (result != MPI_CONGRUENT && result != MPI_IDENT) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_NOTSAMECOMM,"anchor IS must have local communicator");
7868:   }

7870:   PetscObjectReference((PetscObject)anchorSection);
7871:   PetscSectionDestroy(&plex->anchorSection);
7872:   plex->anchorSection = anchorSection;

7874:   PetscObjectReference((PetscObject)anchorIS);
7875:   ISDestroy(&plex->anchorIS);
7876:   plex->anchorIS = anchorIS;

7878: #if defined(PETSC_USE_DEBUG)
7879:   if (anchorIS && anchorSection) {
7880:     PetscInt size, a, pStart, pEnd;
7881:     const PetscInt *anchors;

7883:     PetscSectionGetChart(anchorSection,&pStart,&pEnd);
7884:     ISGetLocalSize(anchorIS,&size);
7885:     ISGetIndices(anchorIS,&anchors);
7886:     for (a = 0; a < size; a++) {
7887:       PetscInt p;

7889:       p = anchors[a];
7890:       if (p >= pStart && p < pEnd) {
7891:         PetscInt dof;

7893:         PetscSectionGetDof(anchorSection,p,&dof);
7894:         if (dof) {
7895:           PetscErrorCode ierr2;

7897:           ierr2 = ISRestoreIndices(anchorIS,&anchors);CHKERRQ(ierr2);
7898:           SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_ARG_INCOMP,"Point %D cannot be constrained and an anchor",p);
7899:         }
7900:       }
7901:     }
7902:     ISRestoreIndices(anchorIS,&anchors);
7903:   }
7904: #endif
7905:   /* reset the generic constraints */
7906:   DMSetDefaultConstraints(dm,NULL,NULL);
7907:   return(0);
7908: }

7910: static PetscErrorCode DMPlexCreateConstraintSection_Anchors(DM dm, PetscSection section, PetscSection *cSec)
7911: {
7912:   PetscSection anchorSection;
7913:   PetscInt pStart, pEnd, sStart, sEnd, p, dof, numFields, f;

7918:   DMPlexGetAnchors(dm,&anchorSection,NULL);
7919:   PetscSectionCreate(PETSC_COMM_SELF,cSec);
7920:   PetscSectionGetNumFields(section,&numFields);
7921:   if (numFields) {
7922:     PetscInt f;
7923:     PetscSectionSetNumFields(*cSec,numFields);

7925:     for (f = 0; f < numFields; f++) {
7926:       PetscInt numComp;

7928:       PetscSectionGetFieldComponents(section,f,&numComp);
7929:       PetscSectionSetFieldComponents(*cSec,f,numComp);
7930:     }
7931:   }
7932:   PetscSectionGetChart(anchorSection,&pStart,&pEnd);
7933:   PetscSectionGetChart(section,&sStart,&sEnd);
7934:   pStart = PetscMax(pStart,sStart);
7935:   pEnd   = PetscMin(pEnd,sEnd);
7936:   pEnd   = PetscMax(pStart,pEnd);
7937:   PetscSectionSetChart(*cSec,pStart,pEnd);
7938:   for (p = pStart; p < pEnd; p++) {
7939:     PetscSectionGetDof(anchorSection,p,&dof);
7940:     if (dof) {
7941:       PetscSectionGetDof(section,p,&dof);
7942:       PetscSectionSetDof(*cSec,p,dof);
7943:       for (f = 0; f < numFields; f++) {
7944:         PetscSectionGetFieldDof(section,p,f,&dof);
7945:         PetscSectionSetFieldDof(*cSec,p,f,dof);
7946:       }
7947:     }
7948:   }
7949:   PetscSectionSetUp(*cSec);
7950:   return(0);
7951: }

7953: static PetscErrorCode DMPlexCreateConstraintMatrix_Anchors(DM dm, PetscSection section, PetscSection cSec, Mat *cMat)
7954: {
7955:   PetscSection aSec;
7956:   PetscInt pStart, pEnd, p, dof, aDof, aOff, off, nnz, annz, m, n, q, a, offset, *i, *j;
7957:   const PetscInt *anchors;
7958:   PetscInt numFields, f;
7959:   IS aIS;

7964:   PetscSectionGetStorageSize(cSec, &m);
7965:   PetscSectionGetStorageSize(section, &n);
7966:   MatCreate(PETSC_COMM_SELF,cMat);
7967:   MatSetSizes(*cMat,m,n,m,n);
7968:   MatSetType(*cMat,MATSEQAIJ);
7969:   DMPlexGetAnchors(dm,&aSec,&aIS);
7970:   ISGetIndices(aIS,&anchors);
7971:   /* cSec will be a subset of aSec and section */
7972:   PetscSectionGetChart(cSec,&pStart,&pEnd);
7973:   PetscMalloc1(m+1,&i);
7974:   i[0] = 0;
7975:   PetscSectionGetNumFields(section,&numFields);
7976:   for (p = pStart; p < pEnd; p++) {
7977:     PetscInt rDof, rOff, r;

7979:     PetscSectionGetDof(aSec,p,&rDof);
7980:     if (!rDof) continue;
7981:     PetscSectionGetOffset(aSec,p,&rOff);
7982:     if (numFields) {
7983:       for (f = 0; f < numFields; f++) {
7984:         annz = 0;
7985:         for (r = 0; r < rDof; r++) {
7986:           a = anchors[rOff + r];
7987:           PetscSectionGetFieldDof(section,a,f,&aDof);
7988:           annz += aDof;
7989:         }
7990:         PetscSectionGetFieldDof(cSec,p,f,&dof);
7991:         PetscSectionGetFieldOffset(cSec,p,f,&off);
7992:         for (q = 0; q < dof; q++) {
7993:           i[off + q + 1] = i[off + q] + annz;
7994:         }
7995:       }
7996:     }
7997:     else {
7998:       annz = 0;
7999:       for (q = 0; q < dof; q++) {
8000:         a = anchors[off + q];
8001:         PetscSectionGetDof(section,a,&aDof);
8002:         annz += aDof;
8003:       }
8004:       PetscSectionGetDof(cSec,p,&dof);
8005:       PetscSectionGetOffset(cSec,p,&off);
8006:       for (q = 0; q < dof; q++) {
8007:         i[off + q + 1] = i[off + q] + annz;
8008:       }
8009:     }
8010:   }
8011:   nnz = i[m];
8012:   PetscMalloc1(nnz,&j);
8013:   offset = 0;
8014:   for (p = pStart; p < pEnd; p++) {
8015:     if (numFields) {
8016:       for (f = 0; f < numFields; f++) {
8017:         PetscSectionGetFieldDof(cSec,p,f,&dof);
8018:         for (q = 0; q < dof; q++) {
8019:           PetscInt rDof, rOff, r;
8020:           PetscSectionGetDof(aSec,p,&rDof);
8021:           PetscSectionGetOffset(aSec,p,&rOff);
8022:           for (r = 0; r < rDof; r++) {
8023:             PetscInt s;

8025:             a = anchors[rOff + r];
8026:             PetscSectionGetFieldDof(section,a,f,&aDof);
8027:             PetscSectionGetFieldOffset(section,a,f,&aOff);
8028:             for (s = 0; s < aDof; s++) {
8029:               j[offset++] = aOff + s;
8030:             }
8031:           }
8032:         }
8033:       }
8034:     }
8035:     else {
8036:       PetscSectionGetDof(cSec,p,&dof);
8037:       for (q = 0; q < dof; q++) {
8038:         PetscInt rDof, rOff, r;
8039:         PetscSectionGetDof(aSec,p,&rDof);
8040:         PetscSectionGetOffset(aSec,p,&rOff);
8041:         for (r = 0; r < rDof; r++) {
8042:           PetscInt s;

8044:           a = anchors[rOff + r];
8045:           PetscSectionGetDof(section,a,&aDof);
8046:           PetscSectionGetOffset(section,a,&aOff);
8047:           for (s = 0; s < aDof; s++) {
8048:             j[offset++] = aOff + s;
8049:           }
8050:         }
8051:       }
8052:     }
8053:   }
8054:   MatSeqAIJSetPreallocationCSR(*cMat,i,j,NULL);
8055:   PetscFree(i);
8056:   PetscFree(j);
8057:   ISRestoreIndices(aIS,&anchors);
8058:   return(0);
8059: }

8061: PetscErrorCode DMCreateDefaultConstraints_Plex(DM dm)
8062: {
8063:   DM_Plex        *plex = (DM_Plex *)dm->data;
8064:   PetscSection   anchorSection, section, cSec;
8065:   Mat            cMat;

8070:   DMPlexGetAnchors(dm,&anchorSection,NULL);
8071:   if (anchorSection) {
8072:     PetscInt Nf;

8074:     DMGetLocalSection(dm,&section);
8075:     DMPlexCreateConstraintSection_Anchors(dm,section,&cSec);
8076:     DMPlexCreateConstraintMatrix_Anchors(dm,section,cSec,&cMat);
8077:     DMGetNumFields(dm,&Nf);
8078:     if (Nf && plex->computeanchormatrix) {(*plex->computeanchormatrix)(dm,section,cSec,cMat);}
8079:     DMSetDefaultConstraints(dm,cSec,cMat);
8080:     PetscSectionDestroy(&cSec);
8081:     MatDestroy(&cMat);
8082:   }
8083:   return(0);
8084: }

8086: PetscErrorCode DMCreateSubDomainDM_Plex(DM dm, DMLabel label, PetscInt value, IS *is, DM *subdm)
8087: {
8088:   IS             subis;
8089:   PetscSection   section, subsection;

8093:   DMGetLocalSection(dm, &section);
8094:   if (!section) SETERRQ(PetscObjectComm((PetscObject) dm), PETSC_ERR_ARG_WRONG, "Must set default section for DM before splitting subdomain");
8095:   if (!subdm)   SETERRQ(PetscObjectComm((PetscObject) dm), PETSC_ERR_ARG_WRONG, "Must set output subDM for splitting subdomain");
8096:   /* Create subdomain */
8097:   DMPlexFilter(dm, label, value, subdm);
8098:   /* Create submodel */
8099:   DMPlexCreateSubpointIS(*subdm, &subis);
8100:   PetscSectionCreateSubmeshSection(section, subis, &subsection);
8101:   ISDestroy(&subis);
8102:   DMSetLocalSection(*subdm, subsection);
8103:   PetscSectionDestroy(&subsection);
8104:   DMCopyDisc(dm, *subdm);
8105:   /* Create map from submodel to global model */
8106:   if (is) {
8107:     PetscSection    sectionGlobal, subsectionGlobal;
8108:     IS              spIS;
8109:     const PetscInt *spmap;
8110:     PetscInt       *subIndices;
8111:     PetscInt        subSize = 0, subOff = 0, pStart, pEnd, p;
8112:     PetscInt        Nf, f, bs = -1, bsLocal[2], bsMinMax[2];

8114:     DMPlexCreateSubpointIS(*subdm, &spIS);
8115:     ISGetIndices(spIS, &spmap);
8116:     PetscSectionGetNumFields(section, &Nf);
8117:     DMGetGlobalSection(dm, &sectionGlobal);
8118:     DMGetGlobalSection(*subdm, &subsectionGlobal);
8119:     PetscSectionGetChart(subsection, &pStart, &pEnd);
8120:     for (p = pStart; p < pEnd; ++p) {
8121:       PetscInt gdof, pSubSize  = 0;

8123:       PetscSectionGetDof(sectionGlobal, p, &gdof);
8124:       if (gdof > 0) {
8125:         for (f = 0; f < Nf; ++f) {
8126:           PetscInt fdof, fcdof;

8128:           PetscSectionGetFieldDof(subsection, p, f, &fdof);
8129:           PetscSectionGetFieldConstraintDof(subsection, p, f, &fcdof);
8130:           pSubSize += fdof-fcdof;
8131:         }
8132:         subSize += pSubSize;
8133:         if (pSubSize) {
8134:           if (bs < 0) {
8135:             bs = pSubSize;
8136:           } else if (bs != pSubSize) {
8137:             /* Layout does not admit a pointwise block size */
8138:             bs = 1;
8139:           }
8140:         }
8141:       }
8142:     }
8143:     /* Must have same blocksize on all procs (some might have no points) */
8144:     bsLocal[0] = bs < 0 ? PETSC_MAX_INT : bs; bsLocal[1] = bs;
8145:     PetscGlobalMinMaxInt(PetscObjectComm((PetscObject) dm), bsLocal, bsMinMax);
8146:     if (bsMinMax[0] != bsMinMax[1]) {bs = 1;}
8147:     else                            {bs = bsMinMax[0];}
8148:     PetscMalloc1(subSize, &subIndices);
8149:     for (p = pStart; p < pEnd; ++p) {
8150:       PetscInt gdof, goff;

8152:       PetscSectionGetDof(subsectionGlobal, p, &gdof);
8153:       if (gdof > 0) {
8154:         const PetscInt point = spmap[p];

8156:         PetscSectionGetOffset(sectionGlobal, point, &goff);
8157:         for (f = 0; f < Nf; ++f) {
8158:           PetscInt fdof, fcdof, fc, f2, poff = 0;

8160:           /* Can get rid of this loop by storing field information in the global section */
8161:           for (f2 = 0; f2 < f; ++f2) {
8162:             PetscSectionGetFieldDof(section, p, f2, &fdof);
8163:             PetscSectionGetFieldConstraintDof(section, p, f2, &fcdof);
8164:             poff += fdof-fcdof;
8165:           }
8166:           PetscSectionGetFieldDof(section, p, f, &fdof);
8167:           PetscSectionGetFieldConstraintDof(section, p, f, &fcdof);
8168:           for (fc = 0; fc < fdof-fcdof; ++fc, ++subOff) {
8169:             subIndices[subOff] = goff+poff+fc;
8170:           }
8171:         }
8172:       }
8173:     }
8174:     ISRestoreIndices(spIS, &spmap);
8175:     ISDestroy(&spIS);
8176:     ISCreateGeneral(PetscObjectComm((PetscObject)dm), subSize, subIndices, PETSC_OWN_POINTER, is);
8177:     if (bs > 1) {
8178:       /* We need to check that the block size does not come from non-contiguous fields */
8179:       PetscInt i, j, set = 1;
8180:       for (i = 0; i < subSize; i += bs) {
8181:         for (j = 0; j < bs; ++j) {
8182:           if (subIndices[i+j] != subIndices[i]+j) {set = 0; break;}
8183:         }
8184:       }
8185:       if (set) {ISSetBlockSize(*is, bs);}
8186:     }
8187:     /* Attach nullspace */
8188:     for (f = 0; f < Nf; ++f) {
8189:       (*subdm)->nullspaceConstructors[f] = dm->nullspaceConstructors[f];
8190:       if ((*subdm)->nullspaceConstructors[f]) break;
8191:     }
8192:     if (f < Nf) {
8193:       MatNullSpace nullSpace;

8195:       (*(*subdm)->nullspaceConstructors[f])(*subdm, f, &nullSpace);
8196:       PetscObjectCompose((PetscObject) *is, "nullspace", (PetscObject) nullSpace);
8197:       MatNullSpaceDestroy(&nullSpace);
8198:     }
8199:   }
8200:   return(0);
8201: }

8203: /*@
8204:   DMPlexMonitorThroughput - Report the cell throughput of FE integration

8206:   Input Parameter:
8207: - dm - The DM

8209:   Level: developer

8211:   Options Database Keys:
8212: . -dm_plex_monitor_throughput - Activate the monitor

8214: .seealso: DMSetFromOptions(), DMPlexCreate()
8215: @*/
8216: PetscErrorCode DMPlexMonitorThroughput(DM dm, void *dummy)
8217: {
8218: #if defined(PETSC_USE_LOG)
8219:   PetscStageLog      stageLog;
8220:   PetscLogEvent      event;
8221:   PetscLogStage      stage;
8222:   PetscEventPerfInfo eventInfo;
8223:   PetscReal          cellRate, flopRate;
8224:   PetscInt           cStart, cEnd, Nf, N;
8225:   const char        *name;
8226:   PetscErrorCode     ierr;
8227: #endif

8231: #if defined(PETSC_USE_LOG)
8232:   PetscObjectGetName((PetscObject) dm, &name);
8233:   DMPlexGetHeightStratum(dm, 0, &cStart, &cEnd);
8234:   DMGetNumFields(dm, &Nf);
8235:   PetscLogGetStageLog(&stageLog);
8236:   PetscStageLogGetCurrent(stageLog, &stage);
8237:   PetscLogEventGetId("DMPlexResidualFE", &event);
8238:   PetscLogEventGetPerfInfo(stage, event, &eventInfo);
8239:   N        = (cEnd - cStart)*Nf*eventInfo.count;
8240:   flopRate = eventInfo.flops/eventInfo.time;
8241:   cellRate = N/eventInfo.time;
8242:   PetscPrintf(PetscObjectComm((PetscObject) dm), "DM (%s) FE Residual Integration: %D integrals %D reps\n  Cell rate: %.2g/s flop rate: %.2g MF/s\n", name ? name : "unknown", N, eventInfo.count, (double) cellRate, (double) (flopRate/1.e6));
8243: #else
8244:   SETERRQ(PetscObjectComm((PetscObject) dm), PETSC_ERR_SUP, "Plex Throughput Monitor is not supported if logging is turned off. Reconfigure using --with-log.");
8245: #endif
8246:   return(0);
8247: }