Actual source code: plex.c

petsc-3.14.6 2021-03-30
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,DMPLEX_LocatePoints;

 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(), DMPlexGetGhostCellStratum()
 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, sizeof(lname), &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 DMPlexDrawCell(DM dm, PetscDraw draw, PetscInt cell, const PetscScalar coords[])
1138: {
1139:   DMPolytopeType ct;
1140:   PetscMPIInt    rank;

1144:   MPI_Comm_rank(PetscObjectComm((PetscObject) dm), &rank);
1145:   DMPlexGetCellType(dm, cell, &ct);
1146:   switch (ct) {
1147:   case DM_POLYTOPE_TRIANGLE:
1148:     PetscDrawTriangle(draw, PetscRealPart(coords[0]), PetscRealPart(coords[1]), PetscRealPart(coords[2]), PetscRealPart(coords[3]), PetscRealPart(coords[4]), PetscRealPart(coords[5]),
1149:                              PETSC_DRAW_WHITE + rank % (PETSC_DRAW_BASIC_COLORS-2) + 2,
1150:                              PETSC_DRAW_WHITE + rank % (PETSC_DRAW_BASIC_COLORS-2) + 2,
1151:                              PETSC_DRAW_WHITE + rank % (PETSC_DRAW_BASIC_COLORS-2) + 2);
1152:     PetscDrawLine(draw, PetscRealPart(coords[0]), PetscRealPart(coords[1]), PetscRealPart(coords[2]), PetscRealPart(coords[3]), PETSC_DRAW_BLACK);
1153:     PetscDrawLine(draw, PetscRealPart(coords[2]), PetscRealPart(coords[3]), PetscRealPart(coords[4]), PetscRealPart(coords[5]), PETSC_DRAW_BLACK);
1154:     PetscDrawLine(draw, PetscRealPart(coords[4]), PetscRealPart(coords[5]), PetscRealPart(coords[0]), PetscRealPart(coords[1]), PETSC_DRAW_BLACK);
1155:     break;
1156:   case DM_POLYTOPE_QUADRILATERAL:
1157:     PetscDrawTriangle(draw, PetscRealPart(coords[0]), PetscRealPart(coords[1]), PetscRealPart(coords[2]), PetscRealPart(coords[3]), PetscRealPart(coords[4]), PetscRealPart(coords[5]),
1158:                               PETSC_DRAW_WHITE + rank % (PETSC_DRAW_BASIC_COLORS-2) + 2,
1159:                               PETSC_DRAW_WHITE + rank % (PETSC_DRAW_BASIC_COLORS-2) + 2,
1160:                               PETSC_DRAW_WHITE + rank % (PETSC_DRAW_BASIC_COLORS-2) + 2);
1161:     PetscDrawTriangle(draw, PetscRealPart(coords[0]), PetscRealPart(coords[1]), PetscRealPart(coords[4]), PetscRealPart(coords[5]), PetscRealPart(coords[6]), PetscRealPart(coords[7]),
1162:                               PETSC_DRAW_WHITE + rank % (PETSC_DRAW_BASIC_COLORS-2) + 2,
1163:                               PETSC_DRAW_WHITE + rank % (PETSC_DRAW_BASIC_COLORS-2) + 2,
1164:                               PETSC_DRAW_WHITE + rank % (PETSC_DRAW_BASIC_COLORS-2) + 2);
1165:     PetscDrawLine(draw, PetscRealPart(coords[0]), PetscRealPart(coords[1]), PetscRealPart(coords[2]), PetscRealPart(coords[3]), PETSC_DRAW_BLACK);
1166:     PetscDrawLine(draw, PetscRealPart(coords[2]), PetscRealPart(coords[3]), PetscRealPart(coords[4]), PetscRealPart(coords[5]), PETSC_DRAW_BLACK);
1167:     PetscDrawLine(draw, PetscRealPart(coords[4]), PetscRealPart(coords[5]), PetscRealPart(coords[6]), PetscRealPart(coords[7]), PETSC_DRAW_BLACK);
1168:     PetscDrawLine(draw, PetscRealPart(coords[6]), PetscRealPart(coords[7]), PetscRealPart(coords[0]), PetscRealPart(coords[1]), PETSC_DRAW_BLACK);
1169:     break;
1170:   default: SETERRQ1(PETSC_COMM_SELF, PETSC_ERR_SUP, "Cannot draw cells of type %s", DMPolytopeTypes[ct]);
1171:   }
1172:   return(0);
1173: }

1175: static PetscErrorCode DMPlexDrawCellHighOrder(DM dm, PetscDraw draw, PetscInt cell, const PetscScalar coords[], PetscInt edgeDiv, PetscReal refCoords[], PetscReal edgeCoords[])
1176: {
1177:   DMPolytopeType ct;
1178:   PetscReal      centroid[2] = {0., 0.};
1179:   PetscMPIInt    rank;
1180:   PetscInt       fillColor, v, e, d;

1184:   MPI_Comm_rank(PetscObjectComm((PetscObject) dm), &rank);
1185:   DMPlexGetCellType(dm, cell, &ct);
1186:   fillColor = PETSC_DRAW_WHITE + rank % (PETSC_DRAW_BASIC_COLORS-2) + 2;
1187:   switch (ct) {
1188:   case DM_POLYTOPE_TRIANGLE:
1189:     {
1190:       PetscReal refVertices[6] = {-1., -1., 1., -1., -1., 1.};

1192:       for (v = 0; v < 3; ++v) {centroid[0] += PetscRealPart(coords[v*2+0])/3.;centroid[1] += PetscRealPart(coords[v*2+1])/3.;}
1193:       for (e = 0; e < 3; ++e) {
1194:         refCoords[0] = refVertices[e*2+0];
1195:         refCoords[1] = refVertices[e*2+1];
1196:         for (d = 1; d <= edgeDiv; ++d) {
1197:           refCoords[d*2+0] = refCoords[0] + (refVertices[(e+1)%3 * 2 + 0] - refCoords[0])*d/edgeDiv;
1198:           refCoords[d*2+1] = refCoords[1] + (refVertices[(e+1)%3 * 2 + 1] - refCoords[1])*d/edgeDiv;
1199:         }
1200:         DMPlexReferenceToCoordinates(dm, cell, edgeDiv+1, refCoords, edgeCoords);
1201:         for (d = 0; d < edgeDiv; ++d) {
1202:           PetscDrawTriangle(draw, centroid[0], centroid[1], edgeCoords[d*2+0], edgeCoords[d*2+1], edgeCoords[(d+1)*2+0], edgeCoords[(d+1)*2+1], fillColor, fillColor, fillColor);
1203:           PetscDrawLine(draw, edgeCoords[d*2+0], edgeCoords[d*2+1], edgeCoords[(d+1)*2+0], edgeCoords[(d+1)*2+1], PETSC_DRAW_BLACK);
1204:         }
1205:       }
1206:     }
1207:     break;
1208:   default: SETERRQ1(PETSC_COMM_SELF, PETSC_ERR_SUP, "Cannot draw cells of type %s", DMPolytopeTypes[ct]);
1209:   }
1210:   return(0);
1211: }

1213: static PetscErrorCode DMPlexView_Draw(DM dm, PetscViewer viewer)
1214: {
1215:   PetscDraw          draw;
1216:   DM                 cdm;
1217:   PetscSection       coordSection;
1218:   Vec                coordinates;
1219:   const PetscScalar *coords;
1220:   PetscReal          xyl[2],xyr[2],bound[4] = {PETSC_MAX_REAL, PETSC_MAX_REAL, PETSC_MIN_REAL, PETSC_MIN_REAL};
1221:   PetscReal         *refCoords, *edgeCoords;
1222:   PetscBool          isnull, drawAffine = PETSC_TRUE;
1223:   PetscInt           dim, vStart, vEnd, cStart, cEnd, c, N, edgeDiv = 4;
1224:   PetscErrorCode     ierr;

1227:   DMGetCoordinateDim(dm, &dim);
1228:   if (dim != 2) SETERRQ1(PetscObjectComm((PetscObject) dm), PETSC_ERR_SUP, "Cannot draw meshes of dimension %D", dim);
1229:   PetscOptionsGetBool(((PetscObject) dm)->options, ((PetscObject) dm)->prefix, "-dm_view_draw_affine", &drawAffine, NULL);
1230:   if (!drawAffine) {PetscMalloc2((edgeDiv+1)*dim, &refCoords, (edgeDiv+1)*dim, &edgeCoords);}
1231:   DMGetCoordinateDM(dm, &cdm);
1232:   DMGetLocalSection(cdm, &coordSection);
1233:   DMGetCoordinatesLocal(dm, &coordinates);
1234:   DMPlexGetDepthStratum(dm, 0, &vStart, &vEnd);
1235:   DMPlexGetHeightStratum(dm, 0, &cStart, &cEnd);

1237:   PetscViewerDrawGetDraw(viewer, 0, &draw);
1238:   PetscDrawIsNull(draw, &isnull);
1239:   if (isnull) return(0);
1240:   PetscDrawSetTitle(draw, "Mesh");

1242:   VecGetLocalSize(coordinates, &N);
1243:   VecGetArrayRead(coordinates, &coords);
1244:   for (c = 0; c < N; c += dim) {
1245:     bound[0] = PetscMin(bound[0], PetscRealPart(coords[c]));   bound[2] = PetscMax(bound[2], PetscRealPart(coords[c]));
1246:     bound[1] = PetscMin(bound[1], PetscRealPart(coords[c+1])); bound[3] = PetscMax(bound[3], PetscRealPart(coords[c+1]));
1247:   }
1248:   VecRestoreArrayRead(coordinates, &coords);
1249:   MPIU_Allreduce(&bound[0],xyl,2,MPIU_REAL,MPIU_MIN,PetscObjectComm((PetscObject)dm));
1250:   MPIU_Allreduce(&bound[2],xyr,2,MPIU_REAL,MPIU_MAX,PetscObjectComm((PetscObject)dm));
1251:   PetscDrawSetCoordinates(draw, xyl[0], xyl[1], xyr[0], xyr[1]);
1252:   PetscDrawClear(draw);

1254:   for (c = cStart; c < cEnd; ++c) {
1255:     PetscScalar *coords = NULL;
1256:     PetscInt     numCoords;

1258:     DMPlexVecGetClosureAtDepth_Internal(dm, coordSection, coordinates, c, 0, &numCoords, &coords);
1259:     if (drawAffine) {
1260:       DMPlexDrawCell(dm, draw, c, coords);
1261:     } else {
1262:       DMPlexDrawCellHighOrder(dm, draw, c, coords, edgeDiv, refCoords, edgeCoords);
1263:     }
1264:     DMPlexVecRestoreClosure(dm, coordSection, coordinates, c, &numCoords, &coords);
1265:   }
1266:   if (!drawAffine) {PetscFree2(refCoords, edgeCoords);}
1267:   PetscDrawFlush(draw);
1268:   PetscDrawPause(draw);
1269:   PetscDrawSave(draw);
1270:   return(0);
1271: }

1273: #if defined(PETSC_HAVE_EXODUSII)
1274: #include <exodusII.h>
1275: #endif

1277: PetscErrorCode DMView_Plex(DM dm, PetscViewer viewer)
1278: {
1279:   PetscBool      iascii, ishdf5, isvtk, isdraw, flg, isglvis, isexodus;
1280:   char           name[PETSC_MAX_PATH_LEN];

1286:   PetscObjectTypeCompare((PetscObject) viewer, PETSCVIEWERASCII,    &iascii);
1287:   PetscObjectTypeCompare((PetscObject) viewer, PETSCVIEWERVTK,      &isvtk);
1288:   PetscObjectTypeCompare((PetscObject) viewer, PETSCVIEWERHDF5,     &ishdf5);
1289:   PetscObjectTypeCompare((PetscObject) viewer, PETSCVIEWERDRAW,     &isdraw);
1290:   PetscObjectTypeCompare((PetscObject) viewer, PETSCVIEWERGLVIS,    &isglvis);
1291:   PetscObjectTypeCompare((PetscObject) viewer, PETSCVIEWEREXODUSII, &isexodus);
1292:   if (iascii) {
1293:     PetscViewerFormat format;
1294:     PetscViewerGetFormat(viewer, &format);
1295:     if (format == PETSC_VIEWER_ASCII_GLVIS) {
1296:       DMPlexView_GLVis(dm, viewer);
1297:     } else {
1298:       DMPlexView_Ascii(dm, viewer);
1299:     }
1300:   } else if (ishdf5) {
1301: #if defined(PETSC_HAVE_HDF5)
1302:     DMPlexView_HDF5_Internal(dm, viewer);
1303: #else
1304:     SETERRQ(PetscObjectComm((PetscObject) dm), PETSC_ERR_SUP, "HDF5 not supported in this build.\nPlease reconfigure using --download-hdf5");
1305: #endif
1306:   } else if (isvtk) {
1307:     DMPlexVTKWriteAll((PetscObject) dm,viewer);
1308:   } else if (isdraw) {
1309:     DMPlexView_Draw(dm, viewer);
1310:   } else if (isglvis) {
1311:     DMPlexView_GLVis(dm, viewer);
1312: #if defined(PETSC_HAVE_EXODUSII)
1313:   } else if (isexodus) {
1314:     int exoid;
1315:     PetscInt cStart, cEnd, c;

1317:     DMCreateLabel(dm, "Cell Sets");
1318:     DMPlexGetHeightStratum(dm, 0, &cStart, &cEnd);
1319:     for (c = cStart; c < cEnd; ++c) {DMSetLabelValue(dm, "Cell Sets", c, 1);}
1320:     PetscViewerExodusIIGetId(viewer, &exoid);
1321:     DMPlexView_ExodusII_Internal(dm, exoid, 1);
1322: #endif
1323:   } else {
1324:     SETERRQ1(PetscObjectComm((PetscObject) dm), PETSC_ERR_SUP, "Viewer type %s not yet supported for DMPlex writing", ((PetscObject)viewer)->type_name);
1325:   }
1326:   /* Optionally view the partition */
1327:   PetscOptionsHasName(((PetscObject) dm)->options, ((PetscObject) dm)->prefix, "-dm_partition_view", &flg);
1328:   if (flg) {
1329:     Vec ranks;
1330:     DMPlexCreateRankField(dm, &ranks);
1331:     VecView(ranks, viewer);
1332:     VecDestroy(&ranks);
1333:   }
1334:   /* Optionally view a label */
1335:   PetscOptionsGetString(((PetscObject) dm)->options, ((PetscObject) dm)->prefix, "-dm_label_view", name, sizeof(name), &flg);
1336:   if (flg) {
1337:     DMLabel label;
1338:     Vec     val;

1340:     DMGetLabel(dm, name, &label);
1341:     if (!label) SETERRQ1(PetscObjectComm((PetscObject) dm), PETSC_ERR_ARG_WRONG, "Label %s provided to -dm_label_view does not exist in this DM", name);
1342:     DMPlexCreateLabelField(dm, label, &val);
1343:     VecView(val, viewer);
1344:     VecDestroy(&val);
1345:   }
1346:   return(0);
1347: }

1349: PetscErrorCode DMLoad_Plex(DM dm, PetscViewer viewer)
1350: {
1351:   PetscBool      ishdf5;

1357:   PetscObjectTypeCompare((PetscObject) viewer, PETSCVIEWERHDF5,   &ishdf5);
1358:   if (ishdf5) {
1359: #if defined(PETSC_HAVE_HDF5)
1360:     PetscViewerFormat format;
1361:     PetscViewerGetFormat(viewer, &format);
1362:     if (format == PETSC_VIEWER_HDF5_XDMF || format == PETSC_VIEWER_HDF5_VIZ) {
1363:       DMPlexLoad_HDF5_Xdmf_Internal(dm, viewer);
1364:     } else if (format == PETSC_VIEWER_HDF5_PETSC || format == PETSC_VIEWER_DEFAULT || format == PETSC_VIEWER_NATIVE) {
1365:       DMPlexLoad_HDF5_Internal(dm, viewer);
1366:     } else SETERRQ1(PetscObjectComm((PetscObject)dm), PETSC_ERR_SUP, "PetscViewerFormat %s not supported for HDF5 input.", PetscViewerFormats[format]);
1367:     return(0);
1368: #else
1369:     SETERRQ(PetscObjectComm((PetscObject) dm), PETSC_ERR_SUP, "HDF5 not supported in this build.\nPlease reconfigure using --download-hdf5");
1370: #endif
1371:   } else SETERRQ1(PetscObjectComm((PetscObject) dm), PETSC_ERR_SUP, "Viewer type %s not yet supported for DMPlex loading", ((PetscObject)viewer)->type_name);
1372: }

1374: PetscErrorCode DMDestroy_Plex(DM dm)
1375: {
1376:   DM_Plex       *mesh = (DM_Plex*) dm->data;

1380:   PetscObjectComposeFunction((PetscObject)dm,"DMSetUpGLVisViewer_C",NULL);
1381:   PetscObjectComposeFunction((PetscObject)dm,"DMPlexInsertBoundaryValues_C", NULL);
1382:   PetscObjectComposeFunction((PetscObject)dm,"DMCreateNeumannOverlap_C", NULL);
1383:   if (--mesh->refct > 0) return(0);
1384:   PetscSectionDestroy(&mesh->coneSection);
1385:   PetscFree(mesh->cones);
1386:   PetscFree(mesh->coneOrientations);
1387:   PetscSectionDestroy(&mesh->supportSection);
1388:   PetscSectionDestroy(&mesh->subdomainSection);
1389:   PetscFree(mesh->supports);
1390:   PetscFree(mesh->facesTmp);
1391:   PetscFree(mesh->tetgenOpts);
1392:   PetscFree(mesh->triangleOpts);
1393:   PetscPartitionerDestroy(&mesh->partitioner);
1394:   DMLabelDestroy(&mesh->subpointMap);
1395:   ISDestroy(&mesh->subpointIS);
1396:   ISDestroy(&mesh->globalVertexNumbers);
1397:   ISDestroy(&mesh->globalCellNumbers);
1398:   PetscSectionDestroy(&mesh->anchorSection);
1399:   ISDestroy(&mesh->anchorIS);
1400:   PetscSectionDestroy(&mesh->parentSection);
1401:   PetscFree(mesh->parents);
1402:   PetscFree(mesh->childIDs);
1403:   PetscSectionDestroy(&mesh->childSection);
1404:   PetscFree(mesh->children);
1405:   DMDestroy(&mesh->referenceTree);
1406:   PetscGridHashDestroy(&mesh->lbox);
1407:   PetscFree(mesh->neighbors);
1408:   /* This was originally freed in DMDestroy(), but that prevents reference counting of backend objects */
1409:   PetscFree(mesh);
1410:   return(0);
1411: }

1413: PetscErrorCode DMCreateMatrix_Plex(DM dm, Mat *J)
1414: {
1415:   PetscSection           sectionGlobal;
1416:   PetscInt               bs = -1, mbs;
1417:   PetscInt               localSize;
1418:   PetscBool              isShell, isBlock, isSeqBlock, isMPIBlock, isSymBlock, isSymSeqBlock, isSymMPIBlock, isMatIS;
1419:   PetscErrorCode         ierr;
1420:   MatType                mtype;
1421:   ISLocalToGlobalMapping ltog;

1424:   MatInitializePackage();
1425:   mtype = dm->mattype;
1426:   DMGetGlobalSection(dm, &sectionGlobal);
1427:   /* PetscSectionGetStorageSize(sectionGlobal, &localSize); */
1428:   PetscSectionGetConstrainedStorageSize(sectionGlobal, &localSize);
1429:   MatCreate(PetscObjectComm((PetscObject)dm), J);
1430:   MatSetSizes(*J, localSize, localSize, PETSC_DETERMINE, PETSC_DETERMINE);
1431:   MatSetType(*J, mtype);
1432:   MatSetFromOptions(*J);
1433:   MatGetBlockSize(*J, &mbs);
1434:   if (mbs > 1) bs = mbs;
1435:   PetscStrcmp(mtype, MATSHELL, &isShell);
1436:   PetscStrcmp(mtype, MATBAIJ, &isBlock);
1437:   PetscStrcmp(mtype, MATSEQBAIJ, &isSeqBlock);
1438:   PetscStrcmp(mtype, MATMPIBAIJ, &isMPIBlock);
1439:   PetscStrcmp(mtype, MATSBAIJ, &isSymBlock);
1440:   PetscStrcmp(mtype, MATSEQSBAIJ, &isSymSeqBlock);
1441:   PetscStrcmp(mtype, MATMPISBAIJ, &isSymMPIBlock);
1442:   PetscStrcmp(mtype, MATIS, &isMatIS);
1443:   if (!isShell) {
1444:     PetscSection subSection;
1445:     PetscBool    fillMatrix = (PetscBool)(!dm->prealloc_only && !isMatIS);
1446:     PetscInt    *dnz, *onz, *dnzu, *onzu, bsLocal[2], bsMinMax[2], *ltogidx, lsize;
1447:     PetscInt     pStart, pEnd, p, dof, cdof;

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

1454:       DMGetLocalSection(dm, &section);
1455:       PetscSectionGetStorageSize(section, &size);
1456:       PetscMalloc1(size,&ltogidx);
1457:       DMPlexGetSubdomainSection(dm, &subSection);
1458:     } else {
1459:       DMGetLocalToGlobalMapping(dm,&ltog);
1460:     }
1461:     PetscSectionGetChart(sectionGlobal, &pStart, &pEnd);
1462:     for (p = pStart, lsize = 0; p < pEnd; ++p) {
1463:       PetscInt bdof;

1465:       PetscSectionGetDof(sectionGlobal, p, &dof);
1466:       PetscSectionGetConstraintDof(sectionGlobal, p, &cdof);
1467:       dof  = dof < 0 ? -(dof+1) : dof;
1468:       bdof = cdof && (dof-cdof) ? 1 : dof;
1469:       if (dof) {
1470:         if (bs < 0)          {bs = bdof;}
1471:         else if (bs != bdof) {bs = 1; if (!isMatIS) break;}
1472:       }
1473:       if (isMatIS) {
1474:         PetscInt loff,c,off;
1475:         PetscSectionGetOffset(subSection, p, &loff);
1476:         PetscSectionGetOffset(sectionGlobal, p, &off);
1477:         for (c = 0; c < dof-cdof; ++c, ++lsize) ltogidx[loff+c] = off > -1 ? off+c : -(off+1)+c;
1478:       }
1479:     }
1480:     /* Must have same blocksize on all procs (some might have no points) */
1481:     bsLocal[0] = bs < 0 ? PETSC_MAX_INT : bs; bsLocal[1] = bs;
1482:     PetscGlobalMinMaxInt(PetscObjectComm((PetscObject) dm), bsLocal, bsMinMax);
1483:     if (bsMinMax[0] != bsMinMax[1]) {bs = 1;}
1484:     else                            {bs = bsMinMax[0];}
1485:     bs = PetscMax(1,bs);
1486:     if (isMatIS) { /* Must reduce indices by blocksize */
1487:       PetscInt l;

1489:       lsize = lsize/bs;
1490:       if (bs > 1) for (l = 0; l < lsize; ++l) ltogidx[l] = ltogidx[l*bs]/bs;
1491:       ISLocalToGlobalMappingCreate(PetscObjectComm((PetscObject)dm), bs, lsize, ltogidx, PETSC_OWN_POINTER, &ltog);
1492:     }
1493:     MatSetLocalToGlobalMapping(*J,ltog,ltog);
1494:     if (isMatIS) {
1495:       ISLocalToGlobalMappingDestroy(&ltog);
1496:     }
1497:     PetscCalloc4(localSize/bs, &dnz, localSize/bs, &onz, localSize/bs, &dnzu, localSize/bs, &onzu);
1498:     DMPlexPreallocateOperator(dm, bs, dnz, onz, dnzu, onzu, *J, fillMatrix);
1499:     PetscFree4(dnz, onz, dnzu, onzu);
1500:   }
1501:   MatSetDM(*J, dm);
1502:   return(0);
1503: }

1505: /*@
1506:   DMPlexGetSubdomainSection - Returns the section associated with the subdomain

1508:   Not collective

1510:   Input Parameter:
1511: . mesh - The DMPlex

1513:   Output Parameters:
1514: . subsection - The subdomain section

1516:   Level: developer

1518: .seealso:
1519: @*/
1520: PetscErrorCode DMPlexGetSubdomainSection(DM dm, PetscSection *subsection)
1521: {
1522:   DM_Plex       *mesh = (DM_Plex*) dm->data;

1527:   if (!mesh->subdomainSection) {
1528:     PetscSection section;
1529:     PetscSF      sf;

1531:     PetscSFCreate(PETSC_COMM_SELF,&sf);
1532:     DMGetLocalSection(dm,&section);
1533:     PetscSectionCreateGlobalSection(section,sf,PETSC_FALSE,PETSC_TRUE,&mesh->subdomainSection);
1534:     PetscSFDestroy(&sf);
1535:   }
1536:   *subsection = mesh->subdomainSection;
1537:   return(0);
1538: }

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

1543:   Not collective

1545:   Input Parameter:
1546: . mesh - The DMPlex

1548:   Output Parameters:
1549: + pStart - The first mesh point
1550: - pEnd   - The upper bound for mesh points

1552:   Level: beginner

1554: .seealso: DMPlexCreate(), DMPlexSetChart()
1555: @*/
1556: PetscErrorCode DMPlexGetChart(DM dm, PetscInt *pStart, PetscInt *pEnd)
1557: {
1558:   DM_Plex       *mesh = (DM_Plex*) dm->data;

1563:   PetscSectionGetChart(mesh->coneSection, pStart, pEnd);
1564:   return(0);
1565: }

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

1570:   Not collective

1572:   Input Parameters:
1573: + mesh - The DMPlex
1574: . pStart - The first mesh point
1575: - pEnd   - The upper bound for mesh points

1577:   Output Parameters:

1579:   Level: beginner

1581: .seealso: DMPlexCreate(), DMPlexGetChart()
1582: @*/
1583: PetscErrorCode DMPlexSetChart(DM dm, PetscInt pStart, PetscInt pEnd)
1584: {
1585:   DM_Plex       *mesh = (DM_Plex*) dm->data;

1590:   PetscSectionSetChart(mesh->coneSection, pStart, pEnd);
1591:   PetscSectionSetChart(mesh->supportSection, pStart, pEnd);
1592:   return(0);
1593: }

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

1598:   Not collective

1600:   Input Parameters:
1601: + mesh - The DMPlex
1602: - p - The point, which must lie in the chart set with DMPlexSetChart()

1604:   Output Parameter:
1605: . size - The cone size for point p

1607:   Level: beginner

1609: .seealso: DMPlexCreate(), DMPlexSetConeSize(), DMPlexSetChart()
1610: @*/
1611: PetscErrorCode DMPlexGetConeSize(DM dm, PetscInt p, PetscInt *size)
1612: {
1613:   DM_Plex       *mesh = (DM_Plex*) dm->data;

1619:   PetscSectionGetDof(mesh->coneSection, p, size);
1620:   return(0);
1621: }

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

1626:   Not collective

1628:   Input Parameters:
1629: + mesh - The DMPlex
1630: . p - The point, which must lie in the chart set with DMPlexSetChart()
1631: - size - The cone size for point p

1633:   Output Parameter:

1635:   Note:
1636:   This should be called after DMPlexSetChart().

1638:   Level: beginner

1640: .seealso: DMPlexCreate(), DMPlexGetConeSize(), DMPlexSetChart()
1641: @*/
1642: PetscErrorCode DMPlexSetConeSize(DM dm, PetscInt p, PetscInt size)
1643: {
1644:   DM_Plex       *mesh = (DM_Plex*) dm->data;

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

1651:   mesh->maxConeSize = PetscMax(mesh->maxConeSize, size);
1652:   return(0);
1653: }

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

1658:   Not collective

1660:   Input Parameters:
1661: + mesh - The DMPlex
1662: . p - The point, which must lie in the chart set with DMPlexSetChart()
1663: - size - The additional cone size for point p

1665:   Output Parameter:

1667:   Note:
1668:   This should be called after DMPlexSetChart().

1670:   Level: beginner

1672: .seealso: DMPlexCreate(), DMPlexSetConeSize(), DMPlexGetConeSize(), DMPlexSetChart()
1673: @*/
1674: PetscErrorCode DMPlexAddConeSize(DM dm, PetscInt p, PetscInt size)
1675: {
1676:   DM_Plex       *mesh = (DM_Plex*) dm->data;
1677:   PetscInt       csize;

1682:   PetscSectionAddDof(mesh->coneSection, p, size);
1683:   PetscSectionGetDof(mesh->coneSection, p, &csize);

1685:   mesh->maxConeSize = PetscMax(mesh->maxConeSize, csize);
1686:   return(0);
1687: }

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

1692:   Not collective

1694:   Input Parameters:
1695: + dm - The DMPlex
1696: - p - The point, which must lie in the chart set with DMPlexSetChart()

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

1701:   Level: beginner

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

1709: .seealso: DMPlexGetConeSize(), DMPlexSetCone(), DMPlexGetConeTuple(), DMPlexSetChart()
1710: @*/
1711: PetscErrorCode DMPlexGetCone(DM dm, PetscInt p, const PetscInt *cone[])
1712: {
1713:   DM_Plex       *mesh = (DM_Plex*) dm->data;
1714:   PetscInt       off;

1720:   PetscSectionGetOffset(mesh->coneSection, p, &off);
1721:   *cone = &mesh->cones[off];
1722:   return(0);
1723: }

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

1728:   Not collective

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

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

1738:   Level: intermediate

1740: .seealso: DMPlexCreate(), DMPlexGetCone(), DMPlexGetConeRecursive(), DMPlexSetChart()
1741: @*/
1742: PetscErrorCode DMPlexGetConeTuple(DM dm, IS p, PetscSection *pConesSection, IS *pCones)
1743: {
1744:   PetscSection        cs, newcs;
1745:   PetscInt            *cones;
1746:   PetscInt            *newarr=NULL;
1747:   PetscInt            n;
1748:   PetscErrorCode      ierr;

1751:   DMPlexGetCones(dm, &cones);
1752:   DMPlexGetConeSection(dm, &cs);
1753:   PetscSectionExtractDofsFromArray(cs, MPIU_INT, cones, p, &newcs, pCones ? ((void**)&newarr) : NULL);
1754:   if (pConesSection) *pConesSection = newcs;
1755:   if (pCones) {
1756:     PetscSectionGetStorageSize(newcs, &n);
1757:     ISCreateGeneral(PetscObjectComm((PetscObject)p), n, newarr, PETSC_OWN_POINTER, pCones);
1758:   }
1759:   return(0);
1760: }

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

1765:   Not collective

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

1771:   Output Parameter:
1772: . expandedPoints - An array of vertices recursively expanded from input points

1774:   Level: advanced

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

1780: .seealso: DMPlexCreate(), DMPlexGetCone(), DMPlexGetConeTuple(), DMPlexGetConeRecursive(), DMPlexRestoreConeRecursive(), DMPlexGetDepth()
1781: @*/
1782: PetscErrorCode DMPlexGetConeRecursiveVertices(DM dm, IS points, IS *expandedPoints)
1783: {
1784:   IS                  *expandedPointsAll;
1785:   PetscInt            depth;
1786:   PetscErrorCode      ierr;

1792:   DMPlexGetConeRecursive(dm, points, &depth, &expandedPointsAll, NULL);
1793:   *expandedPoints = expandedPointsAll[0];
1794:   PetscObjectReference((PetscObject)expandedPointsAll[0]);
1795:   DMPlexRestoreConeRecursive(dm, points, &depth, &expandedPointsAll, NULL);
1796:   return(0);
1797: }

1799: /*@
1800:   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).

1802:   Not collective

1804:   Input Parameters:
1805: + dm - The DMPlex
1806: - points - The IS of points, which must lie in the chart set with DMPlexSetChart()

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

1813:   Level: advanced

1815:   Notes:
1816:   Like DMPlexGetConeTuple() but recursive.

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

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

1825: .seealso: DMPlexCreate(), DMPlexGetCone(), DMPlexGetConeTuple(), DMPlexRestoreConeRecursive(), DMPlexGetConeRecursiveVertices(), DMPlexGetDepth()
1826: @*/
1827: PetscErrorCode DMPlexGetConeRecursive(DM dm, IS points, PetscInt *depth, IS *expandedPoints[], PetscSection *sections[])
1828: {
1829:   const PetscInt      *arr0=NULL, *cone=NULL;
1830:   PetscInt            *arr=NULL, *newarr=NULL;
1831:   PetscInt            d, depth_, i, n, newn, cn, co, start, end;
1832:   IS                  *expandedPoints_;
1833:   PetscSection        *sections_;
1834:   PetscErrorCode      ierr;

1842:   ISGetLocalSize(points, &n);
1843:   ISGetIndices(points, &arr0);
1844:   DMPlexGetDepth(dm, &depth_);
1845:   PetscCalloc1(depth_, &expandedPoints_);
1846:   PetscCalloc1(depth_, &sections_);
1847:   arr = (PetscInt*) arr0; /* this is ok because first generation of arr is not modified */
1848:   for (d=depth_-1; d>=0; d--) {
1849:     PetscSectionCreate(PETSC_COMM_SELF, &sections_[d]);
1850:     PetscSectionSetChart(sections_[d], 0, n);
1851:     for (i=0; i<n; i++) {
1852:       DMPlexGetDepthStratum(dm, d+1, &start, &end);
1853:       if (arr[i] >= start && arr[i] < end) {
1854:         DMPlexGetConeSize(dm, arr[i], &cn);
1855:         PetscSectionSetDof(sections_[d], i, cn);
1856:       } else {
1857:         PetscSectionSetDof(sections_[d], i, 1);
1858:       }
1859:     }
1860:     PetscSectionSetUp(sections_[d]);
1861:     PetscSectionGetStorageSize(sections_[d], &newn);
1862:     PetscMalloc1(newn, &newarr);
1863:     for (i=0; i<n; i++) {
1864:       PetscSectionGetDof(sections_[d], i, &cn);
1865:       PetscSectionGetOffset(sections_[d], i, &co);
1866:       if (cn > 1) {
1867:         DMPlexGetCone(dm, arr[i], &cone);
1868:         PetscMemcpy(&newarr[co], cone, cn*sizeof(PetscInt));
1869:       } else {
1870:         newarr[co] = arr[i];
1871:       }
1872:     }
1873:     ISCreateGeneral(PETSC_COMM_SELF, newn, newarr, PETSC_OWN_POINTER, &expandedPoints_[d]);
1874:     arr = newarr;
1875:     n = newn;
1876:   }
1877:   ISRestoreIndices(points, &arr0);
1878:   *depth = depth_;
1879:   if (expandedPoints) *expandedPoints = expandedPoints_;
1880:   else {
1881:     for (d=0; d<depth_; d++) {ISDestroy(&expandedPoints_[d]);}
1882:     PetscFree(expandedPoints_);
1883:   }
1884:   if (sections) *sections = sections_;
1885:   else {
1886:     for (d=0; d<depth_; d++) {PetscSectionDestroy(&sections_[d]);}
1887:     PetscFree(sections_);
1888:   }
1889:   return(0);
1890: }

1892: /*@
1893:   DMPlexRestoreConeRecursive - Deallocates arrays created by DMPlexGetConeRecursive

1895:   Not collective

1897:   Input Parameters:
1898: + dm - The DMPlex
1899: - points - The IS of points, which must lie in the chart set with DMPlexSetChart()

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

1906:   Level: advanced

1908:   Notes:
1909:   See DMPlexGetConeRecursive() for details.

1911: .seealso: DMPlexCreate(), DMPlexGetCone(), DMPlexGetConeTuple(), DMPlexGetConeRecursive(), DMPlexGetConeRecursiveVertices(), DMPlexGetDepth()
1912: @*/
1913: PetscErrorCode DMPlexRestoreConeRecursive(DM dm, IS points, PetscInt *depth, IS *expandedPoints[], PetscSection *sections[])
1914: {
1915:   PetscInt            d, depth_;
1916:   PetscErrorCode      ierr;

1919:   DMPlexGetDepth(dm, &depth_);
1920:   if (depth && *depth != depth_) SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "depth changed since last call to DMPlexGetConeRecursive");
1921:   if (depth) *depth = 0;
1922:   if (expandedPoints) {
1923:     for (d=0; d<depth_; d++) {ISDestroy(&((*expandedPoints)[d]));}
1924:     PetscFree(*expandedPoints);
1925:   }
1926:   if (sections)  {
1927:     for (d=0; d<depth_; d++) {PetscSectionDestroy(&((*sections)[d]));}
1928:     PetscFree(*sections);
1929:   }
1930:   return(0);
1931: }

1933: /*@
1934:   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

1936:   Not collective

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

1943:   Output Parameter:

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

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

1950:   Level: beginner

1952: .seealso: DMPlexCreate(), DMPlexGetCone(), DMPlexSetChart(), DMPlexSetConeSize(), DMSetUp(), DMPlexSetSupport(), DMPlexSetSupportSize()
1953: @*/
1954: PetscErrorCode DMPlexSetCone(DM dm, PetscInt p, const PetscInt cone[])
1955: {
1956:   DM_Plex       *mesh = (DM_Plex*) dm->data;
1957:   PetscInt       pStart, pEnd;
1958:   PetscInt       dof, off, c;

1963:   PetscSectionGetChart(mesh->coneSection, &pStart, &pEnd);
1964:   PetscSectionGetDof(mesh->coneSection, p, &dof);
1966:   PetscSectionGetOffset(mesh->coneSection, p, &off);
1967:   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);
1968:   for (c = 0; c < dof; ++c) {
1969:     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);
1970:     mesh->cones[off+c] = cone[c];
1971:   }
1972:   return(0);
1973: }

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

1978:   Not collective

1980:   Input Parameters:
1981: + mesh - The DMPlex
1982: - p - The point, which must lie in the chart set with DMPlexSetChart()

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

1990:   Level: beginner

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

1998: .seealso: DMPlexCreate(), DMPlexGetCone(), DMPlexSetCone(), DMPlexSetChart()
1999: @*/
2000: PetscErrorCode DMPlexGetConeOrientation(DM dm, PetscInt p, const PetscInt *coneOrientation[])
2001: {
2002:   DM_Plex       *mesh = (DM_Plex*) dm->data;
2003:   PetscInt       off;

2008:   if (PetscDefined(USE_DEBUG)) {
2009:     PetscInt dof;
2010:     PetscSectionGetDof(mesh->coneSection, p, &dof);
2012:   }
2013:   PetscSectionGetOffset(mesh->coneSection, p, &off);

2015:   *coneOrientation = &mesh->coneOrientations[off];
2016:   return(0);
2017: }

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

2022:   Not collective

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

2032:   Output Parameter:

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

2037:   Level: beginner

2039: .seealso: DMPlexCreate(), DMPlexGetConeOrientation(), DMPlexSetCone(), DMPlexSetChart(), DMPlexSetConeSize(), DMSetUp()
2040: @*/
2041: PetscErrorCode DMPlexSetConeOrientation(DM dm, PetscInt p, const PetscInt coneOrientation[])
2042: {
2043:   DM_Plex       *mesh = (DM_Plex*) dm->data;
2044:   PetscInt       pStart, pEnd;
2045:   PetscInt       dof, off, c;

2050:   PetscSectionGetChart(mesh->coneSection, &pStart, &pEnd);
2051:   PetscSectionGetDof(mesh->coneSection, p, &dof);
2053:   PetscSectionGetOffset(mesh->coneSection, p, &off);
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:   for (c = 0; c < dof; ++c) {
2056:     PetscInt cdof, o = coneOrientation[c];

2058:     PetscSectionGetDof(mesh->coneSection, mesh->cones[off+c], &cdof);
2059:     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);
2060:     mesh->coneOrientations[off+c] = o;
2061:   }
2062:   return(0);
2063: }

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

2068:   Not collective

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

2076:   Level: beginner

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

2089:   PetscSectionGetChart(mesh->coneSection, &pStart, &pEnd);
2090:   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);
2091:   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);
2092:   PetscSectionGetDof(mesh->coneSection, p, &dof);
2093:   PetscSectionGetOffset(mesh->coneSection, p, &off);
2094:   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);
2095:   mesh->cones[off+conePos] = conePoint;
2096:   return(0);
2097: }

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

2102:   Not collective

2104:   Input Parameters:
2105: + mesh - The DMPlex
2106: . p - The point, which must lie in the chart set with DMPlexSetChart()
2107: . conePos - The local index in the cone where the point should be put
2108: - coneOrientation - The point orientation to insert

2110:   Level: beginner

2112: .seealso: DMPlexCreate(), DMPlexGetCone(), DMPlexSetChart(), DMPlexSetConeSize(), DMSetUp()
2113: @*/
2114: PetscErrorCode DMPlexInsertConeOrientation(DM dm, PetscInt p, PetscInt conePos, PetscInt coneOrientation)
2115: {
2116:   DM_Plex       *mesh = (DM_Plex*) dm->data;
2117:   PetscInt       pStart, pEnd;
2118:   PetscInt       dof, off;

2123:   PetscSectionGetChart(mesh->coneSection, &pStart, &pEnd);
2124:   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);
2125:   PetscSectionGetDof(mesh->coneSection, p, &dof);
2126:   PetscSectionGetOffset(mesh->coneSection, p, &off);
2127:   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);
2128:   mesh->coneOrientations[off+conePos] = coneOrientation;
2129:   return(0);
2130: }

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

2135:   Not collective

2137:   Input Parameters:
2138: + mesh - The DMPlex
2139: - p - The point, which must lie in the chart set with DMPlexSetChart()

2141:   Output Parameter:
2142: . size - The support size for point p

2144:   Level: beginner

2146: .seealso: DMPlexCreate(), DMPlexSetConeSize(), DMPlexSetChart(), DMPlexGetConeSize()
2147: @*/
2148: PetscErrorCode DMPlexGetSupportSize(DM dm, PetscInt p, PetscInt *size)
2149: {
2150:   DM_Plex       *mesh = (DM_Plex*) dm->data;

2156:   PetscSectionGetDof(mesh->supportSection, p, size);
2157:   return(0);
2158: }

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

2163:   Not collective

2165:   Input Parameters:
2166: + mesh - The DMPlex
2167: . p - The point, which must lie in the chart set with DMPlexSetChart()
2168: - size - The support size for point p

2170:   Output Parameter:

2172:   Note:
2173:   This should be called after DMPlexSetChart().

2175:   Level: beginner

2177: .seealso: DMPlexCreate(), DMPlexGetSupportSize(), DMPlexSetChart()
2178: @*/
2179: PetscErrorCode DMPlexSetSupportSize(DM dm, PetscInt p, PetscInt size)
2180: {
2181:   DM_Plex       *mesh = (DM_Plex*) dm->data;

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

2188:   mesh->maxSupportSize = PetscMax(mesh->maxSupportSize, size);
2189:   return(0);
2190: }

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

2195:   Not collective

2197:   Input Parameters:
2198: + mesh - The DMPlex
2199: - p - The point, which must lie in the chart set with DMPlexSetChart()

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

2204:   Level: beginner

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

2212: .seealso: DMPlexGetSupportSize(), DMPlexSetSupport(), DMPlexGetCone(), DMPlexSetChart()
2213: @*/
2214: PetscErrorCode DMPlexGetSupport(DM dm, PetscInt p, const PetscInt *support[])
2215: {
2216:   DM_Plex       *mesh = (DM_Plex*) dm->data;
2217:   PetscInt       off;

2223:   PetscSectionGetOffset(mesh->supportSection, p, &off);
2224:   *support = &mesh->supports[off];
2225:   return(0);
2226: }

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

2231:   Not collective

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

2238:   Output Parameter:

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

2243:   Level: beginner

2245: .seealso: DMPlexSetCone(), DMPlexSetConeSize(), DMPlexCreate(), DMPlexGetSupport(), DMPlexSetChart(), DMPlexSetSupportSize(), DMSetUp()
2246: @*/
2247: PetscErrorCode DMPlexSetSupport(DM dm, PetscInt p, const PetscInt support[])
2248: {
2249:   DM_Plex       *mesh = (DM_Plex*) dm->data;
2250:   PetscInt       pStart, pEnd;
2251:   PetscInt       dof, off, c;

2256:   PetscSectionGetChart(mesh->supportSection, &pStart, &pEnd);
2257:   PetscSectionGetDof(mesh->supportSection, p, &dof);
2259:   PetscSectionGetOffset(mesh->supportSection, p, &off);
2260:   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);
2261:   for (c = 0; c < dof; ++c) {
2262:     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);
2263:     mesh->supports[off+c] = support[c];
2264:   }
2265:   return(0);
2266: }

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

2271:   Not collective

2273:   Input Parameters:
2274: + mesh - The DMPlex
2275: . p - The point, which must lie in the chart set with DMPlexSetChart()
2276: . supportPos - The local index in the cone where the point should be put
2277: - supportPoint - The mesh point to insert

2279:   Level: beginner

2281: .seealso: DMPlexCreate(), DMPlexGetCone(), DMPlexSetChart(), DMPlexSetConeSize(), DMSetUp()
2282: @*/
2283: PetscErrorCode DMPlexInsertSupport(DM dm, PetscInt p, PetscInt supportPos, PetscInt supportPoint)
2284: {
2285:   DM_Plex       *mesh = (DM_Plex*) dm->data;
2286:   PetscInt       pStart, pEnd;
2287:   PetscInt       dof, off;

2292:   PetscSectionGetChart(mesh->supportSection, &pStart, &pEnd);
2293:   PetscSectionGetDof(mesh->supportSection, p, &dof);
2294:   PetscSectionGetOffset(mesh->supportSection, p, &off);
2295:   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);
2296:   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);
2297:   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);
2298:   mesh->supports[off+supportPos] = supportPoint;
2299:   return(0);
2300: }

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

2305:   Not collective

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

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

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

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

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

2326:   Level: beginner

2328: .seealso: DMPlexRestoreTransitiveClosure(), DMPlexCreate(), DMPlexSetCone(), DMPlexSetChart(), DMPlexGetCone()
2329: @*/
2330: PetscErrorCode DMPlexGetTransitiveClosure(DM dm, PetscInt p, PetscBool useCone, PetscInt *numPoints, PetscInt *points[])
2331: {
2332:   DM_Plex        *mesh = (DM_Plex*) dm->data;
2333:   PetscInt       *closure, *fifo;
2334:   const PetscInt *tmp = NULL, *tmpO = NULL;
2335:   PetscInt        tmpSize, t;
2336:   PetscInt        depth       = 0, maxSize;
2337:   PetscInt        closureSize = 2, fifoSize = 0, fifoStart = 0;
2338:   PetscErrorCode  ierr;

2342:   DMPlexGetDepth(dm, &depth);
2343:   /* This is only 1-level */
2344:   if (useCone) {
2345:     DMPlexGetConeSize(dm, p, &tmpSize);
2346:     DMPlexGetCone(dm, p, &tmp);
2347:     DMPlexGetConeOrientation(dm, p, &tmpO);
2348:   } else {
2349:     DMPlexGetSupportSize(dm, p, &tmpSize);
2350:     DMPlexGetSupport(dm, p, &tmp);
2351:   }
2352:   if (depth == 1) {
2353:     if (*points) {
2354:       closure = *points;
2355:     } else {
2356:       maxSize = 2*(PetscMax(mesh->maxConeSize, mesh->maxSupportSize)+1);
2357:       DMGetWorkArray(dm, maxSize, MPIU_INT, &closure);
2358:     }
2359:     closure[0] = p; closure[1] = 0;
2360:     for (t = 0; t < tmpSize; ++t, closureSize += 2) {
2361:       closure[closureSize]   = tmp[t];
2362:       closure[closureSize+1] = tmpO ? tmpO[t] : 0;
2363:     }
2364:     if (numPoints) *numPoints = closureSize/2;
2365:     if (points)    *points    = closure;
2366:     return(0);
2367:   }
2368:   {
2369:     PetscInt c, coneSeries, s,supportSeries;

2371:     c = mesh->maxConeSize;
2372:     coneSeries = (c > 1) ? ((PetscPowInt(c,depth+1)-1)/(c-1)) : depth+1;
2373:     s = mesh->maxSupportSize;
2374:     supportSeries = (s > 1) ? ((PetscPowInt(s,depth+1)-1)/(s-1)) : depth+1;
2375:     maxSize = 2*PetscMax(coneSeries,supportSeries);
2376:   }
2377:   DMGetWorkArray(dm, maxSize, MPIU_INT, &fifo);
2378:   if (*points) {
2379:     closure = *points;
2380:   } else {
2381:     DMGetWorkArray(dm, maxSize, MPIU_INT, &closure);
2382:   }
2383:   closure[0] = p; closure[1] = 0;
2384:   for (t = 0; t < tmpSize; ++t, closureSize += 2, fifoSize += 2) {
2385:     const PetscInt cp = tmp[t];
2386:     const PetscInt co = tmpO ? tmpO[t] : 0;

2388:     closure[closureSize]   = cp;
2389:     closure[closureSize+1] = co;
2390:     fifo[fifoSize]         = cp;
2391:     fifo[fifoSize+1]       = co;
2392:   }
2393:   /* Should kick out early when depth is reached, rather than checking all vertices for empty cones */
2394:   while (fifoSize - fifoStart) {
2395:     const PetscInt q   = fifo[fifoStart];
2396:     const PetscInt o   = fifo[fifoStart+1];
2397:     const PetscInt rev = o >= 0 ? 0 : 1;
2398:     const PetscInt off = rev ? -(o+1) : o;

2400:     if (useCone) {
2401:       DMPlexGetConeSize(dm, q, &tmpSize);
2402:       DMPlexGetCone(dm, q, &tmp);
2403:       DMPlexGetConeOrientation(dm, q, &tmpO);
2404:     } else {
2405:       DMPlexGetSupportSize(dm, q, &tmpSize);
2406:       DMPlexGetSupport(dm, q, &tmp);
2407:       tmpO = NULL;
2408:     }
2409:     for (t = 0; t < tmpSize; ++t) {
2410:       const PetscInt i  = ((rev ? tmpSize-t : t) + off)%tmpSize;
2411:       const PetscInt cp = tmp[i];
2412:       /* Must propogate orientation: When we reverse orientation, we both reverse the direction of iteration and start at the other end of the chain. */
2413:       /* HACK: It is worse to get the size here, than to change the interpretation of -(*+1)
2414:        const PetscInt co = tmpO ? (rev ? -(tmpO[i]+1) : tmpO[i]) : 0; */
2415:       PetscInt       co = tmpO ? tmpO[i] : 0;
2416:       PetscInt       c;

2418:       if (rev) {
2419:         PetscInt childSize, coff;
2420:         DMPlexGetConeSize(dm, cp, &childSize);
2421:         coff = tmpO[i] < 0 ? -(tmpO[i]+1) : tmpO[i];
2422:         co   = childSize ? -(((coff+childSize-1)%childSize)+1) : 0;
2423:       }
2424:       /* Check for duplicate */
2425:       for (c = 0; c < closureSize; c += 2) {
2426:         if (closure[c] == cp) break;
2427:       }
2428:       if (c == closureSize) {
2429:         closure[closureSize]   = cp;
2430:         closure[closureSize+1] = co;
2431:         fifo[fifoSize]         = cp;
2432:         fifo[fifoSize+1]       = co;
2433:         closureSize           += 2;
2434:         fifoSize              += 2;
2435:       }
2436:     }
2437:     fifoStart += 2;
2438:   }
2439:   if (numPoints) *numPoints = closureSize/2;
2440:   if (points)    *points    = closure;
2441:   DMRestoreWorkArray(dm, maxSize, MPIU_INT, &fifo);
2442:   return(0);
2443: }

2445: /*@C
2446:   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

2448:   Not collective

2450:   Input Parameters:
2451: + mesh - The DMPlex
2452: . p - The point, which must lie in the chart set with DMPlexSetChart()
2453: . orientation - The orientation of the point
2454: . useCone - PETSC_TRUE for in-edges,  otherwise use out-edges
2455: - points - If points is NULL on input, internal storage will be returned, otherwise the provided array is used

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

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

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

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

2470:   Level: beginner

2472: .seealso: DMPlexRestoreTransitiveClosure(), DMPlexCreate(), DMPlexSetCone(), DMPlexSetChart(), DMPlexGetCone()
2473: @*/
2474: PetscErrorCode DMPlexGetTransitiveClosure_Internal(DM dm, PetscInt p, PetscInt ornt, PetscBool useCone, PetscInt *numPoints, PetscInt *points[])
2475: {
2476:   DM_Plex        *mesh = (DM_Plex*) dm->data;
2477:   PetscInt       *closure, *fifo;
2478:   const PetscInt *tmp = NULL, *tmpO = NULL;
2479:   PetscInt        tmpSize, t;
2480:   PetscInt        depth       = 0, maxSize;
2481:   PetscInt        closureSize = 2, fifoSize = 0, fifoStart = 0;
2482:   PetscErrorCode  ierr;

2486:   DMPlexGetDepth(dm, &depth);
2487:   /* This is only 1-level */
2488:   if (useCone) {
2489:     DMPlexGetConeSize(dm, p, &tmpSize);
2490:     DMPlexGetCone(dm, p, &tmp);
2491:     DMPlexGetConeOrientation(dm, p, &tmpO);
2492:   } else {
2493:     DMPlexGetSupportSize(dm, p, &tmpSize);
2494:     DMPlexGetSupport(dm, p, &tmp);
2495:   }
2496:   if (depth == 1) {
2497:     if (*points) {
2498:       closure = *points;
2499:     } else {
2500:       maxSize = 2*(PetscMax(mesh->maxConeSize, mesh->maxSupportSize)+1);
2501:       DMGetWorkArray(dm, maxSize, MPIU_INT, &closure);
2502:     }
2503:     closure[0] = p; closure[1] = ornt;
2504:     for (t = 0; t < tmpSize; ++t, closureSize += 2) {
2505:       const PetscInt i = ornt >= 0 ? (t+ornt)%tmpSize : (-(ornt+1) + tmpSize-t)%tmpSize;
2506:       closure[closureSize]   = tmp[i];
2507:       closure[closureSize+1] = tmpO ? tmpO[i] : 0;
2508:     }
2509:     if (numPoints) *numPoints = closureSize/2;
2510:     if (points)    *points    = closure;
2511:     return(0);
2512:   }
2513:   {
2514:     PetscInt c, coneSeries, s,supportSeries;

2516:     c = mesh->maxConeSize;
2517:     coneSeries = (c > 1) ? ((PetscPowInt(c,depth+1)-1)/(c-1)) : depth+1;
2518:     s = mesh->maxSupportSize;
2519:     supportSeries = (s > 1) ? ((PetscPowInt(s,depth+1)-1)/(s-1)) : depth+1;
2520:     maxSize = 2*PetscMax(coneSeries,supportSeries);
2521:   }
2522:   DMGetWorkArray(dm, maxSize, MPIU_INT, &fifo);
2523:   if (*points) {
2524:     closure = *points;
2525:   } else {
2526:     DMGetWorkArray(dm, maxSize, MPIU_INT, &closure);
2527:   }
2528:   closure[0] = p; closure[1] = ornt;
2529:   for (t = 0; t < tmpSize; ++t, closureSize += 2, fifoSize += 2) {
2530:     const PetscInt i  = ornt >= 0 ? (t+ornt)%tmpSize : (-(ornt+1) + tmpSize-t)%tmpSize;
2531:     const PetscInt cp = tmp[i];
2532:     PetscInt       co = tmpO ? tmpO[i] : 0;

2534:     if (ornt < 0) {
2535:       PetscInt childSize, coff;
2536:       DMPlexGetConeSize(dm, cp, &childSize);
2537:       coff = co < 0 ? -(tmpO[i]+1) : tmpO[i];
2538:       co   = childSize ? -(((coff+childSize-1)%childSize)+1) : 0;
2539:     }
2540:     closure[closureSize]   = cp;
2541:     closure[closureSize+1] = co;
2542:     fifo[fifoSize]         = cp;
2543:     fifo[fifoSize+1]       = co;
2544:   }
2545:   /* Should kick out early when depth is reached, rather than checking all vertices for empty cones */
2546:   while (fifoSize - fifoStart) {
2547:     const PetscInt q   = fifo[fifoStart];
2548:     const PetscInt o   = fifo[fifoStart+1];
2549:     const PetscInt rev = o >= 0 ? 0 : 1;
2550:     const PetscInt off = rev ? -(o+1) : o;

2552:     if (useCone) {
2553:       DMPlexGetConeSize(dm, q, &tmpSize);
2554:       DMPlexGetCone(dm, q, &tmp);
2555:       DMPlexGetConeOrientation(dm, q, &tmpO);
2556:     } else {
2557:       DMPlexGetSupportSize(dm, q, &tmpSize);
2558:       DMPlexGetSupport(dm, q, &tmp);
2559:       tmpO = NULL;
2560:     }
2561:     for (t = 0; t < tmpSize; ++t) {
2562:       const PetscInt i  = ((rev ? tmpSize-t : t) + off)%tmpSize;
2563:       const PetscInt cp = tmp[i];
2564:       /* Must propogate orientation: When we reverse orientation, we both reverse the direction of iteration and start at the other end of the chain. */
2565:       /* HACK: It is worse to get the size here, than to change the interpretation of -(*+1)
2566:        const PetscInt co = tmpO ? (rev ? -(tmpO[i]+1) : tmpO[i]) : 0; */
2567:       PetscInt       co = tmpO ? tmpO[i] : 0;
2568:       PetscInt       c;

2570:       if (rev) {
2571:         PetscInt childSize, coff;
2572:         DMPlexGetConeSize(dm, cp, &childSize);
2573:         coff = tmpO[i] < 0 ? -(tmpO[i]+1) : tmpO[i];
2574:         co   = childSize ? -(((coff+childSize-1)%childSize)+1) : 0;
2575:       }
2576:       /* Check for duplicate */
2577:       for (c = 0; c < closureSize; c += 2) {
2578:         if (closure[c] == cp) break;
2579:       }
2580:       if (c == closureSize) {
2581:         closure[closureSize]   = cp;
2582:         closure[closureSize+1] = co;
2583:         fifo[fifoSize]         = cp;
2584:         fifo[fifoSize+1]       = co;
2585:         closureSize           += 2;
2586:         fifoSize              += 2;
2587:       }
2588:     }
2589:     fifoStart += 2;
2590:   }
2591:   if (numPoints) *numPoints = closureSize/2;
2592:   if (points)    *points    = closure;
2593:   DMRestoreWorkArray(dm, maxSize, MPIU_INT, &fifo);
2594:   return(0);
2595: }

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

2600:   Not collective

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

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

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

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

2618:   Level: beginner

2620: .seealso: DMPlexGetTransitiveClosure(), DMPlexCreate(), DMPlexSetCone(), DMPlexSetChart(), DMPlexGetCone()
2621: @*/
2622: PetscErrorCode DMPlexRestoreTransitiveClosure(DM dm, PetscInt p, PetscBool useCone, PetscInt *numPoints, PetscInt *points[])
2623: {

2630:   DMRestoreWorkArray(dm, 0, MPIU_INT, points);
2631:   if (numPoints) *numPoints = 0;
2632:   return(0);
2633: }

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

2638:   Not collective

2640:   Input Parameter:
2641: . mesh - The DMPlex

2643:   Output Parameters:
2644: + maxConeSize - The maximum number of in-edges
2645: - maxSupportSize - The maximum number of out-edges

2647:   Level: beginner

2649: .seealso: DMPlexCreate(), DMPlexSetConeSize(), DMPlexSetChart()
2650: @*/
2651: PetscErrorCode DMPlexGetMaxSizes(DM dm, PetscInt *maxConeSize, PetscInt *maxSupportSize)
2652: {
2653:   DM_Plex *mesh = (DM_Plex*) dm->data;

2657:   if (maxConeSize)    *maxConeSize    = mesh->maxConeSize;
2658:   if (maxSupportSize) *maxSupportSize = mesh->maxSupportSize;
2659:   return(0);
2660: }

2662: PetscErrorCode DMSetUp_Plex(DM dm)
2663: {
2664:   DM_Plex       *mesh = (DM_Plex*) dm->data;
2665:   PetscInt       size;

2670:   PetscSectionSetUp(mesh->coneSection);
2671:   PetscSectionGetStorageSize(mesh->coneSection, &size);
2672:   PetscMalloc1(size, &mesh->cones);
2673:   PetscCalloc1(size, &mesh->coneOrientations);
2674:   PetscLogObjectMemory((PetscObject) dm, size*2*sizeof(PetscInt));
2675:   if (mesh->maxSupportSize) {
2676:     PetscSectionSetUp(mesh->supportSection);
2677:     PetscSectionGetStorageSize(mesh->supportSection, &size);
2678:     PetscMalloc1(size, &mesh->supports);
2679:     PetscLogObjectMemory((PetscObject) dm, size*sizeof(PetscInt));
2680:   }
2681:   return(0);
2682: }

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

2689:   if (subdm) {DMClone(dm, subdm);}
2690:   DMCreateSectionSubDM(dm, numFields, fields, is, subdm);
2691:   if (subdm) {(*subdm)->useNatural = dm->useNatural;}
2692:   if (dm->useNatural && dm->sfMigration) {
2693:     PetscSF        sfMigrationInv,sfNatural;
2694:     PetscSection   section, sectionSeq;

2696:     (*subdm)->sfMigration = dm->sfMigration;
2697:     PetscObjectReference((PetscObject) dm->sfMigration);
2698:     DMGetLocalSection((*subdm), &section);
2699:     PetscSFCreateInverseSF((*subdm)->sfMigration, &sfMigrationInv);
2700:     PetscSectionCreate(PetscObjectComm((PetscObject) (*subdm)), &sectionSeq);
2701:     PetscSFDistributeSection(sfMigrationInv, section, NULL, sectionSeq);

2703:     DMPlexCreateGlobalToNaturalSF(*subdm, sectionSeq, (*subdm)->sfMigration, &sfNatural);
2704:     (*subdm)->sfNatural = sfNatural;
2705:     PetscSectionDestroy(&sectionSeq);
2706:     PetscSFDestroy(&sfMigrationInv);
2707:   }
2708:   return(0);
2709: }

2711: PetscErrorCode DMCreateSuperDM_Plex(DM dms[], PetscInt len, IS **is, DM *superdm)
2712: {
2714:   PetscInt       i = 0;

2717:   DMClone(dms[0], superdm);
2718:   DMCreateSectionSuperDM(dms, len, is, superdm);
2719:   (*superdm)->useNatural = PETSC_FALSE;
2720:   for (i = 0; i < len; i++){
2721:     if (dms[i]->useNatural && dms[i]->sfMigration) {
2722:       PetscSF        sfMigrationInv,sfNatural;
2723:       PetscSection   section, sectionSeq;

2725:       (*superdm)->sfMigration = dms[i]->sfMigration;
2726:       PetscObjectReference((PetscObject) dms[i]->sfMigration);
2727:       (*superdm)->useNatural = PETSC_TRUE;
2728:       DMGetLocalSection((*superdm), &section);
2729:       PetscSFCreateInverseSF((*superdm)->sfMigration, &sfMigrationInv);
2730:       PetscSectionCreate(PetscObjectComm((PetscObject) (*superdm)), &sectionSeq);
2731:       PetscSFDistributeSection(sfMigrationInv, section, NULL, sectionSeq);

2733:       DMPlexCreateGlobalToNaturalSF(*superdm, sectionSeq, (*superdm)->sfMigration, &sfNatural);
2734:       (*superdm)->sfNatural = sfNatural;
2735:       PetscSectionDestroy(&sectionSeq);
2736:       PetscSFDestroy(&sfMigrationInv);
2737:       break;
2738:     }
2739:   }
2740:   return(0);
2741: }

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

2746:   Not collective

2748:   Input Parameter:
2749: . mesh - The DMPlex

2751:   Output Parameter:

2753:   Note:
2754:   This should be called after all calls to DMPlexSetCone()

2756:   Level: beginner

2758: .seealso: DMPlexCreate(), DMPlexSetChart(), DMPlexSetConeSize(), DMPlexSetCone()
2759: @*/
2760: PetscErrorCode DMPlexSymmetrize(DM dm)
2761: {
2762:   DM_Plex       *mesh = (DM_Plex*) dm->data;
2763:   PetscInt      *offsets;
2764:   PetscInt       supportSize;
2765:   PetscInt       pStart, pEnd, p;

2770:   if (mesh->supports) SETERRQ(PetscObjectComm((PetscObject)dm), PETSC_ERR_ARG_WRONGSTATE, "Supports were already setup in this DMPlex");
2771:   PetscLogEventBegin(DMPLEX_Symmetrize,dm,0,0,0);
2772:   /* Calculate support sizes */
2773:   DMPlexGetChart(dm, &pStart, &pEnd);
2774:   for (p = pStart; p < pEnd; ++p) {
2775:     PetscInt dof, off, c;

2777:     PetscSectionGetDof(mesh->coneSection, p, &dof);
2778:     PetscSectionGetOffset(mesh->coneSection, p, &off);
2779:     for (c = off; c < off+dof; ++c) {
2780:       PetscSectionAddDof(mesh->supportSection, mesh->cones[c], 1);
2781:     }
2782:   }
2783:   for (p = pStart; p < pEnd; ++p) {
2784:     PetscInt dof;

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

2788:     mesh->maxSupportSize = PetscMax(mesh->maxSupportSize, dof);
2789:   }
2790:   PetscSectionSetUp(mesh->supportSection);
2791:   /* Calculate supports */
2792:   PetscSectionGetStorageSize(mesh->supportSection, &supportSize);
2793:   PetscMalloc1(supportSize, &mesh->supports);
2794:   PetscCalloc1(pEnd - pStart, &offsets);
2795:   for (p = pStart; p < pEnd; ++p) {
2796:     PetscInt dof, off, c;

2798:     PetscSectionGetDof(mesh->coneSection, p, &dof);
2799:     PetscSectionGetOffset(mesh->coneSection, p, &off);
2800:     for (c = off; c < off+dof; ++c) {
2801:       const PetscInt q = mesh->cones[c];
2802:       PetscInt       offS;

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

2806:       mesh->supports[offS+offsets[q]] = p;
2807:       ++offsets[q];
2808:     }
2809:   }
2810:   PetscFree(offsets);
2811:   PetscLogEventEnd(DMPLEX_Symmetrize,dm,0,0,0);
2812:   return(0);
2813: }

2815: static PetscErrorCode DMPlexCreateDepthStratum(DM dm, DMLabel label, PetscInt depth, PetscInt pStart, PetscInt pEnd)
2816: {
2817:   IS             stratumIS;

2821:   if (pStart >= pEnd) return(0);
2822:   if (PetscDefined(USE_DEBUG)) {
2823:     PetscInt  qStart, qEnd, numLevels, level;
2824:     PetscBool overlap = PETSC_FALSE;
2825:     DMLabelGetNumValues(label, &numLevels);
2826:     for (level = 0; level < numLevels; level++) {
2827:       DMLabelGetStratumBounds(label, level, &qStart, &qEnd);
2828:       if ((pStart >= qStart && pStart < qEnd) || (pEnd > qStart && pEnd <= qEnd)) {overlap = PETSC_TRUE; break;}
2829:     }
2830:     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);
2831:   }
2832:   ISCreateStride(PETSC_COMM_SELF, pEnd-pStart, pStart, 1, &stratumIS);
2833:   DMLabelSetStratumIS(label, depth, stratumIS);
2834:   ISDestroy(&stratumIS);
2835:   return(0);
2836: }

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

2844:   Collective on dm

2846:   Input Parameter:
2847: . mesh - The DMPlex

2849:   Output Parameter:

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

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

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

2871:   Level: beginner

2873: .seealso: DMPlexCreate(), DMPlexSymmetrize(), DMPlexComputeCellTypes()
2874: @*/
2875: PetscErrorCode DMPlexStratify(DM dm)
2876: {
2877:   DM_Plex       *mesh = (DM_Plex*) dm->data;
2878:   DMLabel        label;
2879:   PetscInt       pStart, pEnd, p;
2880:   PetscInt       numRoots = 0, numLeaves = 0;

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

2887:   /* Create depth label */
2888:   DMPlexGetChart(dm, &pStart, &pEnd);
2889:   DMCreateLabel(dm, "depth");
2890:   DMPlexGetDepthLabel(dm, &label);

2892:   {
2893:     /* Initialize roots and count leaves */
2894:     PetscInt sMin = PETSC_MAX_INT;
2895:     PetscInt sMax = PETSC_MIN_INT;
2896:     PetscInt coneSize, supportSize;

2898:     for (p = pStart; p < pEnd; ++p) {
2899:       DMPlexGetConeSize(dm, p, &coneSize);
2900:       DMPlexGetSupportSize(dm, p, &supportSize);
2901:       if (!coneSize && supportSize) {
2902:         sMin = PetscMin(p, sMin);
2903:         sMax = PetscMax(p, sMax);
2904:         ++numRoots;
2905:       } else if (!supportSize && coneSize) {
2906:         ++numLeaves;
2907:       } else if (!supportSize && !coneSize) {
2908:         /* Isolated points */
2909:         sMin = PetscMin(p, sMin);
2910:         sMax = PetscMax(p, sMax);
2911:       }
2912:     }
2913:     DMPlexCreateDepthStratum(dm, label, 0, sMin, sMax+1);
2914:   }

2916:   if (numRoots + numLeaves == (pEnd - pStart)) {
2917:     PetscInt sMin = PETSC_MAX_INT;
2918:     PetscInt sMax = PETSC_MIN_INT;
2919:     PetscInt coneSize, supportSize;

2921:     for (p = pStart; p < pEnd; ++p) {
2922:       DMPlexGetConeSize(dm, p, &coneSize);
2923:       DMPlexGetSupportSize(dm, p, &supportSize);
2924:       if (!supportSize && coneSize) {
2925:         sMin = PetscMin(p, sMin);
2926:         sMax = PetscMax(p, sMax);
2927:       }
2928:     }
2929:     DMPlexCreateDepthStratum(dm, label, 1, sMin, sMax+1);
2930:   } else {
2931:     PetscInt level = 0;
2932:     PetscInt qStart, qEnd, q;

2934:     DMLabelGetStratumBounds(label, level, &qStart, &qEnd);
2935:     while (qEnd > qStart) {
2936:       PetscInt sMin = PETSC_MAX_INT;
2937:       PetscInt sMax = PETSC_MIN_INT;

2939:       for (q = qStart; q < qEnd; ++q) {
2940:         const PetscInt *support;
2941:         PetscInt        supportSize, s;

2943:         DMPlexGetSupportSize(dm, q, &supportSize);
2944:         DMPlexGetSupport(dm, q, &support);
2945:         for (s = 0; s < supportSize; ++s) {
2946:           sMin = PetscMin(support[s], sMin);
2947:           sMax = PetscMax(support[s], sMax);
2948:         }
2949:       }
2950:       DMLabelGetNumValues(label, &level);
2951:       DMPlexCreateDepthStratum(dm, label, level, sMin, sMax+1);
2952:       DMLabelGetStratumBounds(label, level, &qStart, &qEnd);
2953:     }
2954:   }
2955:   { /* just in case there is an empty process */
2956:     PetscInt numValues, maxValues = 0, v;

2958:     DMLabelGetNumValues(label, &numValues);
2959:     MPI_Allreduce(&numValues,&maxValues,1,MPIU_INT,MPI_MAX,PetscObjectComm((PetscObject)dm));
2960:     for (v = numValues; v < maxValues; v++) {
2961:       DMLabelAddStratum(label, v);
2962:     }
2963:   }
2964:   PetscObjectStateGet((PetscObject) label, &mesh->depthState);
2965:   PetscLogEventEnd(DMPLEX_Stratify,dm,0,0,0);
2966:   return(0);
2967: }

2969: PetscErrorCode DMPlexComputeCellType_Internal(DM dm, PetscInt p, PetscInt pdepth, DMPolytopeType *pt)
2970: {
2971:   DMPolytopeType ct = DM_POLYTOPE_UNKNOWN;
2972:   PetscInt       dim, depth, pheight, coneSize;

2976:   DMGetDimension(dm, &dim);
2977:   DMPlexGetDepth(dm, &depth);
2978:   DMPlexGetConeSize(dm, p, &coneSize);
2979:   pheight = depth - pdepth;
2980:   if (depth <= 1) {
2981:     switch (pdepth) {
2982:       case 0: ct = DM_POLYTOPE_POINT;break;
2983:       case 1:
2984:         switch (coneSize) {
2985:           case 2: ct = DM_POLYTOPE_SEGMENT;break;
2986:           case 3: ct = DM_POLYTOPE_TRIANGLE;break;
2987:           case 4:
2988:           switch (dim) {
2989:             case 2: ct = DM_POLYTOPE_QUADRILATERAL;break;
2990:             case 3: ct = DM_POLYTOPE_TETRAHEDRON;break;
2991:             default: break;
2992:           }
2993:           break;
2994:         case 6: ct = DM_POLYTOPE_TRI_PRISM_TENSOR;break;
2995:         case 8: ct = DM_POLYTOPE_HEXAHEDRON;break;
2996:         default: break;
2997:       }
2998:     }
2999:   } else {
3000:     if (pdepth == 0) {
3001:       ct = DM_POLYTOPE_POINT;
3002:     } else if (pheight == 0) {
3003:       switch (dim) {
3004:         case 1:
3005:           switch (coneSize) {
3006:             case 2: ct = DM_POLYTOPE_SEGMENT;break;
3007:             default: break;
3008:           }
3009:           break;
3010:         case 2:
3011:           switch (coneSize) {
3012:             case 3: ct = DM_POLYTOPE_TRIANGLE;break;
3013:             case 4: ct = DM_POLYTOPE_QUADRILATERAL;break;
3014:             default: break;
3015:           }
3016:           break;
3017:         case 3:
3018:           switch (coneSize) {
3019:             case 4: ct = DM_POLYTOPE_TETRAHEDRON;break;
3020:             case 5: ct = DM_POLYTOPE_TRI_PRISM_TENSOR;break;
3021:             case 6: ct = DM_POLYTOPE_HEXAHEDRON;break;
3022:             default: break;
3023:           }
3024:           break;
3025:         default: break;
3026:       }
3027:     } else if (pheight > 0) {
3028:       switch (coneSize) {
3029:         case 2: ct = DM_POLYTOPE_SEGMENT;break;
3030:         case 3: ct = DM_POLYTOPE_TRIANGLE;break;
3031:         case 4: ct = DM_POLYTOPE_QUADRILATERAL;break;
3032:         default: break;
3033:       }
3034:     }
3035:   }
3036:   *pt = ct;
3037:   return(0);
3038: }

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

3043:   Collective on dm

3045:   Input Parameter:
3046: . mesh - The DMPlex

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

3050:   Level: developer

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

3056: .seealso: DMPlexCreate(), DMPlexSymmetrize(), DMPlexStratify(), DMGetLabel(), DMCreateLabel()
3057: @*/
3058: PetscErrorCode DMPlexComputeCellTypes(DM dm)
3059: {
3060:   DM_Plex       *mesh;
3061:   DMLabel        ctLabel;
3062:   PetscInt       pStart, pEnd, p;

3067:   mesh = (DM_Plex *) dm->data;
3068:   DMCreateLabel(dm, "celltype");
3069:   DMPlexGetCellTypeLabel(dm, &ctLabel);
3070:   DMPlexGetChart(dm, &pStart, &pEnd);
3071:   for (p = pStart; p < pEnd; ++p) {
3072:     DMPolytopeType ct = DM_POLYTOPE_UNKNOWN;
3073:     PetscInt       pdepth;

3075:     DMPlexGetPointDepth(dm, p, &pdepth);
3076:     DMPlexComputeCellType_Internal(dm, p, pdepth, &ct);
3077:     if (ct == DM_POLYTOPE_UNKNOWN) SETERRQ1(PETSC_COMM_SELF, PETSC_ERR_SUP, "Point %D is screwed up", p);
3078:     DMLabelSetValue(ctLabel, p, ct);
3079:   }
3080:   PetscObjectStateGet((PetscObject) ctLabel, &mesh->celltypeState);
3081:   PetscObjectViewFromOptions((PetscObject) ctLabel, NULL, "-dm_plex_celltypes_view");
3082:   return(0);
3083: }

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

3088:   Not Collective

3090:   Input Parameters:
3091: + dm - The DMPlex object
3092: . numPoints - The number of input points for the join
3093: - points - The input points

3095:   Output Parameters:
3096: + numCoveredPoints - The number of points in the join
3097: - coveredPoints - The points in the join

3099:   Level: intermediate

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

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

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

3109: .seealso: DMPlexRestoreJoin(), DMPlexGetMeet()
3110: @*/
3111: PetscErrorCode DMPlexGetJoin(DM dm, PetscInt numPoints, const PetscInt points[], PetscInt *numCoveredPoints, const PetscInt **coveredPoints)
3112: {
3113:   DM_Plex       *mesh = (DM_Plex*) dm->data;
3114:   PetscInt      *join[2];
3115:   PetscInt       joinSize, i = 0;
3116:   PetscInt       dof, off, p, c, m;

3124:   DMGetWorkArray(dm, mesh->maxSupportSize, MPIU_INT, &join[0]);
3125:   DMGetWorkArray(dm, mesh->maxSupportSize, MPIU_INT, &join[1]);
3126:   /* Copy in support of first point */
3127:   PetscSectionGetDof(mesh->supportSection, points[0], &dof);
3128:   PetscSectionGetOffset(mesh->supportSection, points[0], &off);
3129:   for (joinSize = 0; joinSize < dof; ++joinSize) {
3130:     join[i][joinSize] = mesh->supports[off+joinSize];
3131:   }
3132:   /* Check each successive support */
3133:   for (p = 1; p < numPoints; ++p) {
3134:     PetscInt newJoinSize = 0;

3136:     PetscSectionGetDof(mesh->supportSection, points[p], &dof);
3137:     PetscSectionGetOffset(mesh->supportSection, points[p], &off);
3138:     for (c = 0; c < dof; ++c) {
3139:       const PetscInt point = mesh->supports[off+c];

3141:       for (m = 0; m < joinSize; ++m) {
3142:         if (point == join[i][m]) {
3143:           join[1-i][newJoinSize++] = point;
3144:           break;
3145:         }
3146:       }
3147:     }
3148:     joinSize = newJoinSize;
3149:     i        = 1-i;
3150:   }
3151:   *numCoveredPoints = joinSize;
3152:   *coveredPoints    = join[i];
3153:   DMRestoreWorkArray(dm, mesh->maxSupportSize, MPIU_INT, &join[1-i]);
3154:   return(0);
3155: }

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

3160:   Not Collective

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

3167:   Output Parameters:
3168: + numCoveredPoints - The number of points in the join
3169: - coveredPoints - The points in the join

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

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

3177:   Level: intermediate

3179: .seealso: DMPlexGetJoin(), DMPlexGetFullJoin(), DMPlexGetMeet()
3180: @*/
3181: PetscErrorCode DMPlexRestoreJoin(DM dm, PetscInt numPoints, const PetscInt points[], PetscInt *numCoveredPoints, const PetscInt **coveredPoints)
3182: {

3190:   DMRestoreWorkArray(dm, 0, MPIU_INT, (void*) coveredPoints);
3191:   if (numCoveredPoints) *numCoveredPoints = 0;
3192:   return(0);
3193: }

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

3198:   Not Collective

3200:   Input Parameters:
3201: + dm - The DMPlex object
3202: . numPoints - The number of input points for the join
3203: - points - The input points

3205:   Output Parameters:
3206: + numCoveredPoints - The number of points in the join
3207: - coveredPoints - The points in the join

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

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

3215:   Level: intermediate

3217: .seealso: DMPlexGetJoin(), DMPlexRestoreJoin(), DMPlexGetMeet()
3218: @*/
3219: PetscErrorCode DMPlexGetFullJoin(DM dm, PetscInt numPoints, const PetscInt points[], PetscInt *numCoveredPoints, const PetscInt **coveredPoints)
3220: {
3221:   DM_Plex       *mesh = (DM_Plex*) dm->data;
3222:   PetscInt      *offsets, **closures;
3223:   PetscInt      *join[2];
3224:   PetscInt       depth = 0, maxSize, joinSize = 0, i = 0;
3225:   PetscInt       p, d, c, m, ms;


3234:   DMPlexGetDepth(dm, &depth);
3235:   PetscCalloc1(numPoints, &closures);
3236:   DMGetWorkArray(dm, numPoints*(depth+2), MPIU_INT, &offsets);
3237:   ms      = mesh->maxSupportSize;
3238:   maxSize = (ms > 1) ? ((PetscPowInt(ms,depth+1)-1)/(ms-1)) : depth + 1;
3239:   DMGetWorkArray(dm, maxSize, MPIU_INT, &join[0]);
3240:   DMGetWorkArray(dm, maxSize, MPIU_INT, &join[1]);

3242:   for (p = 0; p < numPoints; ++p) {
3243:     PetscInt closureSize;

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

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

3251:       DMPlexGetDepthStratum(dm, d, &pStart, &pEnd);
3252:       for (i = offsets[p*(depth+2)+d]; i < closureSize; ++i) {
3253:         if ((pStart > closures[p][i*2]) || (pEnd <= closures[p][i*2])) {
3254:           offsets[p*(depth+2)+d+1] = i;
3255:           break;
3256:         }
3257:       }
3258:       if (i == closureSize) offsets[p*(depth+2)+d+1] = i;
3259:     }
3260:     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);
3261:   }
3262:   for (d = 0; d < depth+1; ++d) {
3263:     PetscInt dof;

3265:     /* Copy in support of first point */
3266:     dof = offsets[d+1] - offsets[d];
3267:     for (joinSize = 0; joinSize < dof; ++joinSize) {
3268:       join[i][joinSize] = closures[0][(offsets[d]+joinSize)*2];
3269:     }
3270:     /* Check each successive cone */
3271:     for (p = 1; p < numPoints && joinSize; ++p) {
3272:       PetscInt newJoinSize = 0;

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

3278:         for (m = 0; m < joinSize; ++m) {
3279:           if (point == join[i][m]) {
3280:             join[1-i][newJoinSize++] = point;
3281:             break;
3282:           }
3283:         }
3284:       }
3285:       joinSize = newJoinSize;
3286:       i        = 1-i;
3287:     }
3288:     if (joinSize) break;
3289:   }
3290:   *numCoveredPoints = joinSize;
3291:   *coveredPoints    = join[i];
3292:   for (p = 0; p < numPoints; ++p) {
3293:     DMPlexRestoreTransitiveClosure(dm, points[p], PETSC_FALSE, NULL, &closures[p]);
3294:   }
3295:   PetscFree(closures);
3296:   DMRestoreWorkArray(dm, numPoints*(depth+2), MPIU_INT, &offsets);
3297:   DMRestoreWorkArray(dm, mesh->maxSupportSize, MPIU_INT, &join[1-i]);
3298:   return(0);
3299: }

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

3304:   Not Collective

3306:   Input Parameters:
3307: + dm - The DMPlex object
3308: . numPoints - The number of input points for the meet
3309: - points - The input points

3311:   Output Parameters:
3312: + numCoveredPoints - The number of points in the meet
3313: - coveredPoints - The points in the meet

3315:   Level: intermediate

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

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

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

3325: .seealso: DMPlexRestoreMeet(), DMPlexGetJoin()
3326: @*/
3327: PetscErrorCode DMPlexGetMeet(DM dm, PetscInt numPoints, const PetscInt points[], PetscInt *numCoveringPoints, const PetscInt **coveringPoints)
3328: {
3329:   DM_Plex       *mesh = (DM_Plex*) dm->data;
3330:   PetscInt      *meet[2];
3331:   PetscInt       meetSize, i = 0;
3332:   PetscInt       dof, off, p, c, m;

3340:   DMGetWorkArray(dm, mesh->maxConeSize, MPIU_INT, &meet[0]);
3341:   DMGetWorkArray(dm, mesh->maxConeSize, MPIU_INT, &meet[1]);
3342:   /* Copy in cone of first point */
3343:   PetscSectionGetDof(mesh->coneSection, points[0], &dof);
3344:   PetscSectionGetOffset(mesh->coneSection, points[0], &off);
3345:   for (meetSize = 0; meetSize < dof; ++meetSize) {
3346:     meet[i][meetSize] = mesh->cones[off+meetSize];
3347:   }
3348:   /* Check each successive cone */
3349:   for (p = 1; p < numPoints; ++p) {
3350:     PetscInt newMeetSize = 0;

3352:     PetscSectionGetDof(mesh->coneSection, points[p], &dof);
3353:     PetscSectionGetOffset(mesh->coneSection, points[p], &off);
3354:     for (c = 0; c < dof; ++c) {
3355:       const PetscInt point = mesh->cones[off+c];

3357:       for (m = 0; m < meetSize; ++m) {
3358:         if (point == meet[i][m]) {
3359:           meet[1-i][newMeetSize++] = point;
3360:           break;
3361:         }
3362:       }
3363:     }
3364:     meetSize = newMeetSize;
3365:     i        = 1-i;
3366:   }
3367:   *numCoveringPoints = meetSize;
3368:   *coveringPoints    = meet[i];
3369:   DMRestoreWorkArray(dm, mesh->maxConeSize, MPIU_INT, &meet[1-i]);
3370:   return(0);
3371: }

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

3376:   Not Collective

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

3383:   Output Parameters:
3384: + numCoveredPoints - The number of points in the meet
3385: - coveredPoints - The points in the meet

3387:   Level: intermediate

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

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

3395: .seealso: DMPlexGetMeet(), DMPlexGetFullMeet(), DMPlexGetJoin()
3396: @*/
3397: PetscErrorCode DMPlexRestoreMeet(DM dm, PetscInt numPoints, const PetscInt points[], PetscInt *numCoveredPoints, const PetscInt **coveredPoints)
3398: {

3406:   DMRestoreWorkArray(dm, 0, MPIU_INT, (void*) coveredPoints);
3407:   if (numCoveredPoints) *numCoveredPoints = 0;
3408:   return(0);
3409: }

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

3414:   Not Collective

3416:   Input Parameters:
3417: + dm - The DMPlex object
3418: . numPoints - The number of input points for the meet
3419: - points - The input points

3421:   Output Parameters:
3422: + numCoveredPoints - The number of points in the meet
3423: - coveredPoints - The points in the meet

3425:   Level: intermediate

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

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

3433: .seealso: DMPlexGetMeet(), DMPlexRestoreMeet(), DMPlexGetJoin()
3434: @*/
3435: PetscErrorCode DMPlexGetFullMeet(DM dm, PetscInt numPoints, const PetscInt points[], PetscInt *numCoveredPoints, const PetscInt **coveredPoints)
3436: {
3437:   DM_Plex       *mesh = (DM_Plex*) dm->data;
3438:   PetscInt      *offsets, **closures;
3439:   PetscInt      *meet[2];
3440:   PetscInt       height = 0, maxSize, meetSize = 0, i = 0;
3441:   PetscInt       p, h, c, m, mc;


3450:   DMPlexGetDepth(dm, &height);
3451:   PetscMalloc1(numPoints, &closures);
3452:   DMGetWorkArray(dm, numPoints*(height+2), MPIU_INT, &offsets);
3453:   mc      = mesh->maxConeSize;
3454:   maxSize = (mc > 1) ? ((PetscPowInt(mc,height+1)-1)/(mc-1)) : height + 1;
3455:   DMGetWorkArray(dm, maxSize, MPIU_INT, &meet[0]);
3456:   DMGetWorkArray(dm, maxSize, MPIU_INT, &meet[1]);

3458:   for (p = 0; p < numPoints; ++p) {
3459:     PetscInt closureSize;

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

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

3467:       DMPlexGetHeightStratum(dm, h, &pStart, &pEnd);
3468:       for (i = offsets[p*(height+2)+h]; i < closureSize; ++i) {
3469:         if ((pStart > closures[p][i*2]) || (pEnd <= closures[p][i*2])) {
3470:           offsets[p*(height+2)+h+1] = i;
3471:           break;
3472:         }
3473:       }
3474:       if (i == closureSize) offsets[p*(height+2)+h+1] = i;
3475:     }
3476:     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);
3477:   }
3478:   for (h = 0; h < height+1; ++h) {
3479:     PetscInt dof;

3481:     /* Copy in cone of first point */
3482:     dof = offsets[h+1] - offsets[h];
3483:     for (meetSize = 0; meetSize < dof; ++meetSize) {
3484:       meet[i][meetSize] = closures[0][(offsets[h]+meetSize)*2];
3485:     }
3486:     /* Check each successive cone */
3487:     for (p = 1; p < numPoints && meetSize; ++p) {
3488:       PetscInt newMeetSize = 0;

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

3494:         for (m = 0; m < meetSize; ++m) {
3495:           if (point == meet[i][m]) {
3496:             meet[1-i][newMeetSize++] = point;
3497:             break;
3498:           }
3499:         }
3500:       }
3501:       meetSize = newMeetSize;
3502:       i        = 1-i;
3503:     }
3504:     if (meetSize) break;
3505:   }
3506:   *numCoveredPoints = meetSize;
3507:   *coveredPoints    = meet[i];
3508:   for (p = 0; p < numPoints; ++p) {
3509:     DMPlexRestoreTransitiveClosure(dm, points[p], PETSC_TRUE, NULL, &closures[p]);
3510:   }
3511:   PetscFree(closures);
3512:   DMRestoreWorkArray(dm, numPoints*(height+2), MPIU_INT, &offsets);
3513:   DMRestoreWorkArray(dm, mesh->maxConeSize, MPIU_INT, &meet[1-i]);
3514:   return(0);
3515: }

3517: /*@C
3518:   DMPlexEqual - Determine if two DMs have the same topology

3520:   Not Collective

3522:   Input Parameters:
3523: + dmA - A DMPlex object
3524: - dmB - A DMPlex object

3526:   Output Parameters:
3527: . equal - PETSC_TRUE if the topologies are identical

3529:   Level: intermediate

3531:   Notes:
3532:   We are not solving graph isomorphism, so we do not permutation.

3534: .seealso: DMPlexGetCone()
3535: @*/
3536: PetscErrorCode DMPlexEqual(DM dmA, DM dmB, PetscBool *equal)
3537: {
3538:   PetscInt       depth, depthB, pStart, pEnd, pStartB, pEndB, p;


3546:   *equal = PETSC_FALSE;
3547:   DMPlexGetDepth(dmA, &depth);
3548:   DMPlexGetDepth(dmB, &depthB);
3549:   if (depth != depthB) return(0);
3550:   DMPlexGetChart(dmA, &pStart,  &pEnd);
3551:   DMPlexGetChart(dmB, &pStartB, &pEndB);
3552:   if ((pStart != pStartB) || (pEnd != pEndB)) return(0);
3553:   for (p = pStart; p < pEnd; ++p) {
3554:     const PetscInt *cone, *coneB, *ornt, *orntB, *support, *supportB;
3555:     PetscInt        coneSize, coneSizeB, c, supportSize, supportSizeB, s;

3557:     DMPlexGetConeSize(dmA, p, &coneSize);
3558:     DMPlexGetCone(dmA, p, &cone);
3559:     DMPlexGetConeOrientation(dmA, p, &ornt);
3560:     DMPlexGetConeSize(dmB, p, &coneSizeB);
3561:     DMPlexGetCone(dmB, p, &coneB);
3562:     DMPlexGetConeOrientation(dmB, p, &orntB);
3563:     if (coneSize != coneSizeB) return(0);
3564:     for (c = 0; c < coneSize; ++c) {
3565:       if (cone[c] != coneB[c]) return(0);
3566:       if (ornt[c] != orntB[c]) return(0);
3567:     }
3568:     DMPlexGetSupportSize(dmA, p, &supportSize);
3569:     DMPlexGetSupport(dmA, p, &support);
3570:     DMPlexGetSupportSize(dmB, p, &supportSizeB);
3571:     DMPlexGetSupport(dmB, p, &supportB);
3572:     if (supportSize != supportSizeB) return(0);
3573:     for (s = 0; s < supportSize; ++s) {
3574:       if (support[s] != supportB[s]) return(0);
3575:     }
3576:   }
3577:   *equal = PETSC_TRUE;
3578:   return(0);
3579: }

3581: /*@C
3582:   DMPlexGetNumFaceVertices - Returns the number of vertices on a face

3584:   Not Collective

3586:   Input Parameters:
3587: + dm         - The DMPlex
3588: . cellDim    - The cell dimension
3589: - numCorners - The number of vertices on a cell

3591:   Output Parameters:
3592: . numFaceVertices - The number of vertices on a face

3594:   Level: developer

3596:   Notes:
3597:   Of course this can only work for a restricted set of symmetric shapes

3599: .seealso: DMPlexGetCone()
3600: @*/
3601: PetscErrorCode DMPlexGetNumFaceVertices(DM dm, PetscInt cellDim, PetscInt numCorners, PetscInt *numFaceVertices)
3602: {
3603:   MPI_Comm       comm;

3607:   PetscObjectGetComm((PetscObject)dm,&comm);
3609:   switch (cellDim) {
3610:   case 0:
3611:     *numFaceVertices = 0;
3612:     break;
3613:   case 1:
3614:     *numFaceVertices = 1;
3615:     break;
3616:   case 2:
3617:     switch (numCorners) {
3618:     case 3: /* triangle */
3619:       *numFaceVertices = 2; /* Edge has 2 vertices */
3620:       break;
3621:     case 4: /* quadrilateral */
3622:       *numFaceVertices = 2; /* Edge has 2 vertices */
3623:       break;
3624:     case 6: /* quadratic triangle, tri and quad cohesive Lagrange cells */
3625:       *numFaceVertices = 3; /* Edge has 3 vertices */
3626:       break;
3627:     case 9: /* quadratic quadrilateral, quadratic quad cohesive Lagrange cells */
3628:       *numFaceVertices = 3; /* Edge has 3 vertices */
3629:       break;
3630:     default:
3631:       SETERRQ2(comm, PETSC_ERR_ARG_OUTOFRANGE, "Invalid number of face corners %D for dimension %D", numCorners, cellDim);
3632:     }
3633:     break;
3634:   case 3:
3635:     switch (numCorners) {
3636:     case 4: /* tetradehdron */
3637:       *numFaceVertices = 3; /* Face has 3 vertices */
3638:       break;
3639:     case 6: /* tet cohesive cells */
3640:       *numFaceVertices = 4; /* Face has 4 vertices */
3641:       break;
3642:     case 8: /* hexahedron */
3643:       *numFaceVertices = 4; /* Face has 4 vertices */
3644:       break;
3645:     case 9: /* tet cohesive Lagrange cells */
3646:       *numFaceVertices = 6; /* Face has 6 vertices */
3647:       break;
3648:     case 10: /* quadratic tetrahedron */
3649:       *numFaceVertices = 6; /* Face has 6 vertices */
3650:       break;
3651:     case 12: /* hex cohesive Lagrange cells */
3652:       *numFaceVertices = 6; /* Face has 6 vertices */
3653:       break;
3654:     case 18: /* quadratic tet cohesive Lagrange cells */
3655:       *numFaceVertices = 6; /* Face has 6 vertices */
3656:       break;
3657:     case 27: /* quadratic hexahedron, quadratic hex cohesive Lagrange cells */
3658:       *numFaceVertices = 9; /* Face has 9 vertices */
3659:       break;
3660:     default:
3661:       SETERRQ2(comm, PETSC_ERR_ARG_OUTOFRANGE, "Invalid number of face corners %D for dimension %D", numCorners, cellDim);
3662:     }
3663:     break;
3664:   default:
3665:     SETERRQ1(comm, PETSC_ERR_ARG_OUTOFRANGE, "Invalid cell dimension %D", cellDim);
3666:   }
3667:   return(0);
3668: }

3670: /*@
3671:   DMPlexGetDepthLabel - Get the DMLabel recording the depth of each point

3673:   Not Collective

3675:   Input Parameter:
3676: . dm    - The DMPlex object

3678:   Output Parameter:
3679: . depthLabel - The DMLabel recording point depth

3681:   Level: developer

3683: .seealso: DMPlexGetDepth(), DMPlexGetHeightStratum(), DMPlexGetDepthStratum(), DMPlexGetPointDepth(),
3684: @*/
3685: PetscErrorCode DMPlexGetDepthLabel(DM dm, DMLabel *depthLabel)
3686: {
3690:   *depthLabel = dm->depthLabel;
3691:   return(0);
3692: }

3694: /*@
3695:   DMPlexGetDepth - Get the depth of the DAG representing this mesh

3697:   Not Collective

3699:   Input Parameter:
3700: . dm    - The DMPlex object

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

3705:   Level: developer

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

3712: .seealso: DMPlexGetDepthLabel(), DMPlexGetDepthStratum(), DMPlexGetPointDepth(), DMPlexSymmetrize()
3713: @*/
3714: PetscErrorCode DMPlexGetDepth(DM dm, PetscInt *depth)
3715: {
3716:   DMLabel        label;
3717:   PetscInt       d = 0;

3723:   DMPlexGetDepthLabel(dm, &label);
3724:   if (label) {DMLabelGetNumValues(label, &d);}
3725:   *depth = d-1;
3726:   return(0);
3727: }

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

3732:   Not Collective

3734:   Input Parameters:
3735: + dm           - The DMPlex object
3736: - stratumValue - The requested depth

3738:   Output Parameters:
3739: + start - The first point at this depth
3740: - end   - One beyond the last point at this depth

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

3747:   Level: developer

3749: .seealso: DMPlexGetHeightStratum(), DMPlexGetDepth(), DMPlexGetDepthLabel(), DMPlexGetPointDepth(), DMPlexSymmetrize(), DMPlexInterpolate()
3750: @*/
3751: PetscErrorCode DMPlexGetDepthStratum(DM dm, PetscInt stratumValue, PetscInt *start, PetscInt *end)
3752: {
3753:   DMLabel        label;
3754:   PetscInt       pStart, pEnd;

3761:   DMPlexGetChart(dm, &pStart, &pEnd);
3762:   if (pStart == pEnd) return(0);
3763:   if (stratumValue < 0) {
3764:     if (start) *start = pStart;
3765:     if (end)   *end   = pEnd;
3766:     return(0);
3767:   }
3768:   DMPlexGetDepthLabel(dm, &label);
3769:   if (!label) SETERRQ(PetscObjectComm((PetscObject) dm), PETSC_ERR_ARG_WRONG, "No label named depth was found");
3770:   DMLabelGetStratumBounds(label, stratumValue, start, end);
3771:   return(0);
3772: }

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

3777:   Not Collective

3779:   Input Parameters:
3780: + dm           - The DMPlex object
3781: - stratumValue - The requested height

3783:   Output Parameters:
3784: + start - The first point at this height
3785: - end   - One beyond the last point at this height

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

3792:   Level: developer

3794: .seealso: DMPlexGetDepthStratum(), DMPlexGetDepth(), DMPlexGetPointHeight()
3795: @*/
3796: PetscErrorCode DMPlexGetHeightStratum(DM dm, PetscInt stratumValue, PetscInt *start, PetscInt *end)
3797: {
3798:   DMLabel        label;
3799:   PetscInt       depth, pStart, pEnd;

3806:   DMPlexGetChart(dm, &pStart, &pEnd);
3807:   if (pStart == pEnd) return(0);
3808:   if (stratumValue < 0) {
3809:     if (start) *start = pStart;
3810:     if (end)   *end   = pEnd;
3811:     return(0);
3812:   }
3813:   DMPlexGetDepthLabel(dm, &label);
3814:   if (!label) SETERRQ(PetscObjectComm((PetscObject) dm), PETSC_ERR_ARG_WRONG, "No label named depth was found");
3815:   DMLabelGetNumValues(label, &depth);
3816:   DMLabelGetStratumBounds(label, depth-1-stratumValue, start, end);
3817:   return(0);
3818: }

3820: /*@
3821:   DMPlexGetPointDepth - Get the depth of a given point

3823:   Not Collective

3825:   Input Parameter:
3826: + dm    - The DMPlex object
3827: - point - The point

3829:   Output Parameter:
3830: . depth - The depth of the point

3832:   Level: intermediate

3834: .seealso: DMPlexGetCellType(), DMPlexGetDepthLabel(), DMPlexGetDepth(), DMPlexGetPointHeight()
3835: @*/
3836: PetscErrorCode DMPlexGetPointDepth(DM dm, PetscInt point, PetscInt *depth)
3837: {

3843:   DMLabelGetValue(dm->depthLabel, point, depth);
3844:   return(0);
3845: }

3847: /*@
3848:   DMPlexGetPointHeight - Get the height of a given point

3850:   Not Collective

3852:   Input Parameter:
3853: + dm    - The DMPlex object
3854: - point - The point

3856:   Output Parameter:
3857: . height - The height of the point

3859:   Level: intermediate

3861: .seealso: DMPlexGetCellType(), DMPlexGetDepthLabel(), DMPlexGetDepth(), DMPlexGetPointDepth()
3862: @*/
3863: PetscErrorCode DMPlexGetPointHeight(DM dm, PetscInt point, PetscInt *height)
3864: {
3865:   PetscInt       n, pDepth;

3871:   DMLabelGetNumValues(dm->depthLabel, &n);
3872:   DMLabelGetValue(dm->depthLabel, point, &pDepth);
3873:   *height = n - 1 - pDepth;  /* DAG depth is n-1 */
3874:   return(0);
3875: }

3877: /*@
3878:   DMPlexGetCellTypeLabel - Get the DMLabel recording the polytope type of each cell

3880:   Not Collective

3882:   Input Parameter:
3883: . dm - The DMPlex object

3885:   Output Parameter:
3886: . celltypeLabel - The DMLabel recording cell polytope type

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

3891:   Level: developer

3893: .seealso: DMPlexGetCellType(), DMPlexGetDepthLabel(), DMCreateLabel()
3894: @*/
3895: PetscErrorCode DMPlexGetCellTypeLabel(DM dm, DMLabel *celltypeLabel)
3896: {

3902:   if (!dm->celltypeLabel) {DMPlexComputeCellTypes(dm);}
3903:   *celltypeLabel = dm->celltypeLabel;
3904:   return(0);
3905: }

3907: /*@
3908:   DMPlexGetCellType - Get the polytope type of a given cell

3910:   Not Collective

3912:   Input Parameter:
3913: + dm   - The DMPlex object
3914: - cell - The cell

3916:   Output Parameter:
3917: . celltype - The polytope type of the cell

3919:   Level: intermediate

3921: .seealso: DMPlexGetCellTypeLabel(), DMPlexGetDepthLabel(), DMPlexGetDepth()
3922: @*/
3923: PetscErrorCode DMPlexGetCellType(DM dm, PetscInt cell, DMPolytopeType *celltype)
3924: {
3925:   DMLabel        label;
3926:   PetscInt       ct;

3932:   DMPlexGetCellTypeLabel(dm, &label);
3933:   DMLabelGetValue(label, cell, &ct);
3934:   *celltype = (DMPolytopeType) ct;
3935:   return(0);
3936: }

3938: /*@
3939:   DMPlexSetCellType - Set the polytope type of a given cell

3941:   Not Collective

3943:   Input Parameters:
3944: + dm   - The DMPlex object
3945: . cell - The cell
3946: - celltype - The polytope type of the cell

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

3953:   Level: advanced

3955: .seealso: DMPlexGetCellTypeLabel(), DMPlexGetDepthLabel(), DMPlexGetDepth(), DMPlexComputeCellTypes(), DMCreateLabel()
3956: @*/
3957: PetscErrorCode DMPlexSetCellType(DM dm, PetscInt cell, DMPolytopeType celltype)
3958: {
3959:   DMLabel        label;

3964:   DMPlexGetCellTypeLabel(dm, &label);
3965:   DMLabelSetValue(label, cell, celltype);
3966:   return(0);
3967: }

3969: PetscErrorCode DMCreateCoordinateDM_Plex(DM dm, DM *cdm)
3970: {
3971:   PetscSection   section, s;
3972:   Mat            m;
3973:   PetscInt       maxHeight;

3977:   DMClone(dm, cdm);
3978:   DMPlexGetMaxProjectionHeight(dm, &maxHeight);
3979:   DMPlexSetMaxProjectionHeight(*cdm, maxHeight);
3980:   PetscSectionCreate(PetscObjectComm((PetscObject)dm), &section);
3981:   DMSetLocalSection(*cdm, section);
3982:   PetscSectionDestroy(&section);
3983:   PetscSectionCreate(PETSC_COMM_SELF, &s);
3984:   MatCreate(PETSC_COMM_SELF, &m);
3985:   DMSetDefaultConstraints(*cdm, s, m);
3986:   PetscSectionDestroy(&s);
3987:   MatDestroy(&m);

3989:   DMSetNumFields(*cdm, 1);
3990:   DMCreateDS(*cdm);
3991:   return(0);
3992: }

3994: PetscErrorCode DMCreateCoordinateField_Plex(DM dm, DMField *field)
3995: {
3996:   Vec            coordsLocal;
3997:   DM             coordsDM;

4001:   *field = NULL;
4002:   DMGetCoordinatesLocal(dm,&coordsLocal);
4003:   DMGetCoordinateDM(dm,&coordsDM);
4004:   if (coordsLocal && coordsDM) {
4005:     DMFieldCreateDS(coordsDM, 0, coordsLocal, field);
4006:   }
4007:   return(0);
4008: }

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

4013:   Not Collective

4015:   Input Parameters:
4016: . dm        - The DMPlex object

4018:   Output Parameter:
4019: . section - The PetscSection object

4021:   Level: developer

4023: .seealso: DMPlexGetSupportSection(), DMPlexGetCones(), DMPlexGetConeOrientations()
4024: @*/
4025: PetscErrorCode DMPlexGetConeSection(DM dm, PetscSection *section)
4026: {
4027:   DM_Plex *mesh = (DM_Plex*) dm->data;

4031:   if (section) *section = mesh->coneSection;
4032:   return(0);
4033: }

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

4038:   Not Collective

4040:   Input Parameters:
4041: . dm        - The DMPlex object

4043:   Output Parameter:
4044: . section - The PetscSection object

4046:   Level: developer

4048: .seealso: DMPlexGetConeSection()
4049: @*/
4050: PetscErrorCode DMPlexGetSupportSection(DM dm, PetscSection *section)
4051: {
4052:   DM_Plex *mesh = (DM_Plex*) dm->data;

4056:   if (section) *section = mesh->supportSection;
4057:   return(0);
4058: }

4060: /*@C
4061:   DMPlexGetCones - Return cone data

4063:   Not Collective

4065:   Input Parameters:
4066: . dm        - The DMPlex object

4068:   Output Parameter:
4069: . cones - The cone for each point

4071:   Level: developer

4073: .seealso: DMPlexGetConeSection()
4074: @*/
4075: PetscErrorCode DMPlexGetCones(DM dm, PetscInt *cones[])
4076: {
4077:   DM_Plex *mesh = (DM_Plex*) dm->data;

4081:   if (cones) *cones = mesh->cones;
4082:   return(0);
4083: }

4085: /*@C
4086:   DMPlexGetConeOrientations - Return cone orientation data

4088:   Not Collective

4090:   Input Parameters:
4091: . dm        - The DMPlex object

4093:   Output Parameter:
4094: . coneOrientations - The cone orientation for each point

4096:   Level: developer

4098: .seealso: DMPlexGetConeSection()
4099: @*/
4100: PetscErrorCode DMPlexGetConeOrientations(DM dm, PetscInt *coneOrientations[])
4101: {
4102:   DM_Plex *mesh = (DM_Plex*) dm->data;

4106:   if (coneOrientations) *coneOrientations = mesh->coneOrientations;
4107:   return(0);
4108: }

4110: /******************************** FEM Support **********************************/

4112: /*
4113:  Returns number of components and tensor degree for the field.  For interpolated meshes, line should be a point
4114:  representing a line in the section.
4115: */
4116: static PetscErrorCode PetscSectionFieldGetTensorDegree_Private(PetscSection section,PetscInt field,PetscInt line,PetscBool vertexchart,PetscInt *Nc,PetscInt *k)
4117: {

4121:   PetscSectionGetFieldComponents(section, field, Nc);
4122:   if (line < 0) {
4123:     *k = 0;
4124:     *Nc = 0;
4125:   } else if (vertexchart) {            /* If we only have a vertex chart, we must have degree k=1 */
4126:     *k = 1;
4127:   } else {                      /* Assume the full interpolated mesh is in the chart; lines in particular */
4128:     /* An order k SEM disc has k-1 dofs on an edge */
4129:     PetscSectionGetFieldDof(section, line, field, k);
4130:     *k = *k / *Nc + 1;
4131:   }
4132:   return(0);
4133: }

4135: /*@

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

4141:   Input Parameters:
4142: + dm      - The DM
4143: . point   - Either a cell (highest dim point) or an edge (dim 1 point), or PETSC_DETERMINE
4144: - section - The PetscSection to reorder, or NULL for the default section

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

4149:   Example:
4150:   A typical interpolated single-quad mesh might order points as
4151: .vb
4152:   [c0, v1, v2, v3, v4, e5, e6, e7, e8]

4154:   v4 -- e6 -- v3
4155:   |           |
4156:   e7    c0    e8
4157:   |           |
4158:   v1 -- e5 -- v2
4159: .ve

4161:   (There is no significance to the ordering described here.)  The default section for a Q3 quad might typically assign
4162:   dofs in the order of points, e.g.,
4163: .vb
4164:     c0 -> [0,1,2,3]
4165:     v1 -> [4]
4166:     ...
4167:     e5 -> [8, 9]
4168: .ve

4170:   which corresponds to the dofs
4171: .vb
4172:     6   10  11  7
4173:     13  2   3   15
4174:     12  0   1   14
4175:     4   8   9   5
4176: .ve

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

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

4188:   Level: developer

4190: .seealso: DMGetLocalSection(), PetscSectionSetClosurePermutation(), DMSetGlobalSection()
4191: @*/
4192: PetscErrorCode DMPlexSetClosurePermutationTensor(DM dm, PetscInt point, PetscSection section)
4193: {
4194:   DMLabel        label;
4195:   PetscInt       dim, depth = -1, eStart = -1, Nf;
4196:   PetscBool      vertexchart;

4200:   DMGetDimension(dm, &dim);
4201:   if (dim < 1) return(0);
4202:   if (point < 0) {
4203:     PetscInt sStart,sEnd;

4205:     DMPlexGetDepthStratum(dm, 1, &sStart, &sEnd);
4206:     point = sEnd-sStart ? sStart : point;
4207:   }
4208:   DMPlexGetDepthLabel(dm, &label);
4209:   if (point >= 0) { DMLabelGetValue(label, point, &depth); }
4210:   if (!section) {DMGetLocalSection(dm, &section);}
4211:   if (depth == 1) {eStart = point;}
4212:   else if  (depth == dim) {
4213:     const PetscInt *cone;

4215:     DMPlexGetCone(dm, point, &cone);
4216:     if (dim == 2) eStart = cone[0];
4217:     else if (dim == 3) {
4218:       const PetscInt *cone2;
4219:       DMPlexGetCone(dm, cone[0], &cone2);
4220:       eStart = cone2[0];
4221:     } 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);
4222:   } 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);
4223:   {                             /* Determine whether the chart covers all points or just vertices. */
4224:     PetscInt pStart,pEnd,cStart,cEnd;
4225:     DMPlexGetDepthStratum(dm,0,&pStart,&pEnd);
4226:     PetscSectionGetChart(section,&cStart,&cEnd);
4227:     if (pStart == cStart && pEnd == cEnd) vertexchart = PETSC_TRUE; /* Just vertices */
4228:     else vertexchart = PETSC_FALSE;                                 /* Assume all interpolated points are in chart */
4229:   }
4230:   PetscSectionGetNumFields(section, &Nf);
4231:   for (PetscInt d=1; d<=dim; d++) {
4232:     PetscInt k, f, Nc, c, i, j, size = 0, offset = 0, foffset = 0;
4233:     PetscInt *perm;

4235:     for (f = 0; f < Nf; ++f) {
4236:       PetscSectionFieldGetTensorDegree_Private(section,f,eStart,vertexchart,&Nc,&k);
4237:       size += PetscPowInt(k+1, d)*Nc;
4238:     }
4239:     PetscMalloc1(size, &perm);
4240:     for (f = 0; f < Nf; ++f) {
4241:       switch (d) {
4242:       case 1:
4243:         PetscSectionFieldGetTensorDegree_Private(section,f,eStart,vertexchart,&Nc,&k);
4244:         /*
4245:          Original ordering is [ edge of length k-1; vtx0; vtx1 ]
4246:          We want              [ vtx0; edge of length k-1; vtx1 ]
4247:          */
4248:         for (c=0; c<Nc; c++,offset++) perm[offset] = (k-1)*Nc + c + foffset;
4249:         for (i=0; i<k-1; i++) for (c=0; c<Nc; c++,offset++) perm[offset] = i*Nc + c + foffset;
4250:         for (c=0; c<Nc; c++,offset++) perm[offset] = k*Nc + c + foffset;
4251:         foffset = offset;
4252:         break;
4253:       case 2:
4254:         /* The original quad closure is oriented clockwise, {f, e_b, e_r, e_t, e_l, v_lb, v_rb, v_tr, v_tl} */
4255:         PetscSectionFieldGetTensorDegree_Private(section,f,eStart,vertexchart,&Nc,&k);
4256:         /* The SEM order is

4258:          v_lb, {e_b}, v_rb,
4259:          e^{(k-1)-i}_l, {f^{i*(k-1)}}, e^i_r,
4260:          v_lt, reverse {e_t}, v_rt
4261:          */
4262:         {
4263:           const PetscInt of   = 0;
4264:           const PetscInt oeb  = of   + PetscSqr(k-1);
4265:           const PetscInt oer  = oeb  + (k-1);
4266:           const PetscInt oet  = oer  + (k-1);
4267:           const PetscInt oel  = oet  + (k-1);
4268:           const PetscInt ovlb = oel  + (k-1);
4269:           const PetscInt ovrb = ovlb + 1;
4270:           const PetscInt ovrt = ovrb + 1;
4271:           const PetscInt ovlt = ovrt + 1;
4272:           PetscInt       o;

4274:           /* bottom */
4275:           for (c = 0; c < Nc; ++c, ++offset) perm[offset] = ovlb*Nc + c + foffset;
4276:           for (o = oeb; o < oer; ++o) for (c = 0; c < Nc; ++c, ++offset) perm[offset] = o*Nc + c + foffset;
4277:           for (c = 0; c < Nc; ++c, ++offset) perm[offset] = ovrb*Nc + c + foffset;
4278:           /* middle */
4279:           for (i = 0; i < k-1; ++i) {
4280:             for (c = 0; c < Nc; ++c, ++offset) perm[offset] = (oel+(k-2)-i)*Nc + c + foffset;
4281:             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;
4282:             for (c = 0; c < Nc; ++c, ++offset) perm[offset] = (oer+i)*Nc + c + foffset;
4283:           }
4284:           /* top */
4285:           for (c = 0; c < Nc; ++c, ++offset) perm[offset] = ovlt*Nc + c + foffset;
4286:           for (o = oel-1; o >= oet; --o) for (c = 0; c < Nc; ++c, ++offset) perm[offset] = o*Nc + c + foffset;
4287:           for (c = 0; c < Nc; ++c, ++offset) perm[offset] = ovrt*Nc + c + foffset;
4288:           foffset = offset;
4289:         }
4290:         break;
4291:       case 3:
4292:         /* The original hex closure is

4294:          {c,
4295:          f_b, f_t, f_f, f_b, f_r, f_l,
4296:          e_bl, e_bb, e_br, e_bf,  e_tf, e_tr, e_tb, e_tl,  e_rf, e_lf, e_lb, e_rb,
4297:          v_blf, v_blb, v_brb, v_brf, v_tlf, v_trf, v_trb, v_tlb}
4298:          */
4299:         PetscSectionFieldGetTensorDegree_Private(section,f,eStart,vertexchart,&Nc,&k);
4300:         /* The SEM order is
4301:          Bottom Slice
4302:          v_blf, {e^{(k-1)-n}_bf}, v_brf,
4303:          e^{i}_bl, f^{n*(k-1)+(k-1)-i}_b, e^{(k-1)-i}_br,
4304:          v_blb, {e_bb}, v_brb,

4306:          Middle Slice (j)
4307:          {e^{(k-1)-j}_lf}, {f^{j*(k-1)+n}_f}, e^j_rf,
4308:          f^{i*(k-1)+j}_l, {c^{(j*(k-1) + i)*(k-1)+n}_t}, f^{j*(k-1)+i}_r,
4309:          e^j_lb, {f^{j*(k-1)+(k-1)-n}_b}, e^{(k-1)-j}_rb,

4311:          Top Slice
4312:          v_tlf, {e_tf}, v_trf,
4313:          e^{(k-1)-i}_tl, {f^{i*(k-1)}_t}, e^{i}_tr,
4314:          v_tlb, {e^{(k-1)-n}_tb}, v_trb,
4315:          */
4316:         {
4317:           const PetscInt oc    = 0;
4318:           const PetscInt ofb   = oc    + PetscSqr(k-1)*(k-1);
4319:           const PetscInt oft   = ofb   + PetscSqr(k-1);
4320:           const PetscInt off   = oft   + PetscSqr(k-1);
4321:           const PetscInt ofk   = off   + PetscSqr(k-1);
4322:           const PetscInt ofr   = ofk   + PetscSqr(k-1);
4323:           const PetscInt ofl   = ofr   + PetscSqr(k-1);
4324:           const PetscInt oebl  = ofl   + PetscSqr(k-1);
4325:           const PetscInt oebb  = oebl  + (k-1);
4326:           const PetscInt oebr  = oebb  + (k-1);
4327:           const PetscInt oebf  = oebr  + (k-1);
4328:           const PetscInt oetf  = oebf  + (k-1);
4329:           const PetscInt oetr  = oetf  + (k-1);
4330:           const PetscInt oetb  = oetr  + (k-1);
4331:           const PetscInt oetl  = oetb  + (k-1);
4332:           const PetscInt oerf  = oetl  + (k-1);
4333:           const PetscInt oelf  = oerf  + (k-1);
4334:           const PetscInt oelb  = oelf  + (k-1);
4335:           const PetscInt oerb  = oelb  + (k-1);
4336:           const PetscInt ovblf = oerb  + (k-1);
4337:           const PetscInt ovblb = ovblf + 1;
4338:           const PetscInt ovbrb = ovblb + 1;
4339:           const PetscInt ovbrf = ovbrb + 1;
4340:           const PetscInt ovtlf = ovbrf + 1;
4341:           const PetscInt ovtrf = ovtlf + 1;
4342:           const PetscInt ovtrb = ovtrf + 1;
4343:           const PetscInt ovtlb = ovtrb + 1;
4344:           PetscInt       o, n;

4346:           /* Bottom Slice */
4347:           /*   bottom */
4348:           for (c = 0; c < Nc; ++c, ++offset) perm[offset] = ovblf*Nc + c + foffset;
4349:           for (o = oetf-1; o >= oebf; --o) for (c = 0; c < Nc; ++c, ++offset) perm[offset] = o*Nc + c + foffset;
4350:           for (c = 0; c < Nc; ++c, ++offset) perm[offset] = ovbrf*Nc + c + foffset;
4351:           /*   middle */
4352:           for (i = 0; i < k-1; ++i) {
4353:             for (c = 0; c < Nc; ++c, ++offset) perm[offset] = (oebl+i)*Nc + c + foffset;
4354:             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;}
4355:             for (c = 0; c < Nc; ++c, ++offset) perm[offset] = (oebr+(k-2)-i)*Nc + c + foffset;
4356:           }
4357:           /*   top */
4358:           for (c = 0; c < Nc; ++c, ++offset) perm[offset] = ovblb*Nc + c + foffset;
4359:           for (o = oebb; o < oebr; ++o) for (c = 0; c < Nc; ++c, ++offset) perm[offset] = o*Nc + c + foffset;
4360:           for (c = 0; c < Nc; ++c, ++offset) perm[offset] = ovbrb*Nc + c + foffset;

4362:           /* Middle Slice */
4363:           for (j = 0; j < k-1; ++j) {
4364:             /*   bottom */
4365:             for (c = 0; c < Nc; ++c, ++offset) perm[offset] = (oelf+(k-2)-j)*Nc + c + foffset;
4366:             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;
4367:             for (c = 0; c < Nc; ++c, ++offset) perm[offset] = (oerf+j)*Nc + c + foffset;
4368:             /*   middle */
4369:             for (i = 0; i < k-1; ++i) {
4370:               for (c = 0; c < Nc; ++c, ++offset) perm[offset] = (ofl+i*(k-1)+j)*Nc + c + foffset;
4371:               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;
4372:               for (c = 0; c < Nc; ++c, ++offset) perm[offset] = (ofr+j*(k-1)+i)*Nc + c + foffset;
4373:             }
4374:             /*   top */
4375:             for (c = 0; c < Nc; ++c, ++offset) perm[offset] = (oelb+j)*Nc + c + foffset;
4376:             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;
4377:             for (c = 0; c < Nc; ++c, ++offset) perm[offset] = (oerb+(k-2)-j)*Nc + c + foffset;
4378:           }

4380:           /* Top Slice */
4381:           /*   bottom */
4382:           for (c = 0; c < Nc; ++c, ++offset) perm[offset] = ovtlf*Nc + c + foffset;
4383:           for (o = oetf; o < oetr; ++o) for (c = 0; c < Nc; ++c, ++offset) perm[offset] = o*Nc + c + foffset;
4384:           for (c = 0; c < Nc; ++c, ++offset) perm[offset] = ovtrf*Nc + c + foffset;
4385:           /*   middle */
4386:           for (i = 0; i < k-1; ++i) {
4387:             for (c = 0; c < Nc; ++c, ++offset) perm[offset] = (oetl+(k-2)-i)*Nc + c + foffset;
4388:             for (n = 0; n < k-1; ++n) for (c = 0; c < Nc; ++c, ++offset) perm[offset] = (oft+i*(k-1)+n)*Nc + c + foffset;
4389:             for (c = 0; c < Nc; ++c, ++offset) perm[offset] = (oetr+i)*Nc + c + foffset;
4390:           }
4391:           /*   top */
4392:           for (c = 0; c < Nc; ++c, ++offset) perm[offset] = ovtlb*Nc + c + foffset;
4393:           for (o = oetl-1; o >= oetb; --o) for (c = 0; c < Nc; ++c, ++offset) perm[offset] = o*Nc + c + foffset;
4394:           for (c = 0; c < Nc; ++c, ++offset) perm[offset] = ovtrb*Nc + c + foffset;

4396:           foffset = offset;
4397:         }
4398:         break;
4399:       default: SETERRQ1(PetscObjectComm((PetscObject) dm), PETSC_ERR_ARG_OUTOFRANGE, "No spectral ordering for dimension %D", d);
4400:       }
4401:     }
4402:     if (offset != size) SETERRQ2(PetscObjectComm((PetscObject) dm), PETSC_ERR_PLIB, "Number of permutation entries %D != %D", offset, size);
4403:     /* Check permutation */
4404:     {
4405:       PetscInt *check;

4407:       PetscMalloc1(size, &check);
4408:       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]);}
4409:       for (i = 0; i < size; ++i) check[perm[i]] = i;
4410:       for (i = 0; i < size; ++i) {if (check[i] < 0) SETERRQ1(PetscObjectComm((PetscObject) dm), PETSC_ERR_PLIB, "Missing permutation index %D", i);}
4411:       PetscFree(check);
4412:     }
4413:     PetscSectionSetClosurePermutation_Internal(section, (PetscObject) dm, d, size, PETSC_OWN_POINTER, perm);
4414:   }
4415:   return(0);
4416: }

4418: PetscErrorCode DMPlexGetPointDualSpaceFEM(DM dm, PetscInt point, PetscInt field, PetscDualSpace *dspace)
4419: {
4420:   PetscDS        prob;
4421:   PetscInt       depth, Nf, h;
4422:   DMLabel        label;

4426:   DMGetDS(dm, &prob);
4427:   Nf      = prob->Nf;
4428:   label   = dm->depthLabel;
4429:   *dspace = NULL;
4430:   if (field < Nf) {
4431:     PetscObject disc = prob->disc[field];

4433:     if (disc->classid == PETSCFE_CLASSID) {
4434:       PetscDualSpace dsp;

4436:       PetscFEGetDualSpace((PetscFE)disc,&dsp);
4437:       DMLabelGetNumValues(label,&depth);
4438:       DMLabelGetValue(label,point,&h);
4439:       h    = depth - 1 - h;
4440:       if (h) {
4441:         PetscDualSpaceGetHeightSubspace(dsp,h,dspace);
4442:       } else {
4443:         *dspace = dsp;
4444:       }
4445:     }
4446:   }
4447:   return(0);
4448: }


4451: PETSC_STATIC_INLINE PetscErrorCode DMPlexVecGetClosure_Depth1_Static(DM dm, PetscSection section, Vec v, PetscInt point, PetscInt *csize, PetscScalar *values[])
4452: {
4453:   PetscScalar    *array, *vArray;
4454:   const PetscInt *cone, *coneO;
4455:   PetscInt        pStart, pEnd, p, numPoints, size = 0, offset = 0;
4456:   PetscErrorCode  ierr;

4459:   PetscSectionGetChart(section, &pStart, &pEnd);
4460:   DMPlexGetConeSize(dm, point, &numPoints);
4461:   DMPlexGetCone(dm, point, &cone);
4462:   DMPlexGetConeOrientation(dm, point, &coneO);
4463:   if (!values || !*values) {
4464:     if ((point >= pStart) && (point < pEnd)) {
4465:       PetscInt dof;

4467:       PetscSectionGetDof(section, point, &dof);
4468:       size += dof;
4469:     }
4470:     for (p = 0; p < numPoints; ++p) {
4471:       const PetscInt cp = cone[p];
4472:       PetscInt       dof;

4474:       if ((cp < pStart) || (cp >= pEnd)) continue;
4475:       PetscSectionGetDof(section, cp, &dof);
4476:       size += dof;
4477:     }
4478:     if (!values) {
4479:       if (csize) *csize = size;
4480:       return(0);
4481:     }
4482:     DMGetWorkArray(dm, size, MPIU_SCALAR, &array);
4483:   } else {
4484:     array = *values;
4485:   }
4486:   size = 0;
4487:   VecGetArray(v, &vArray);
4488:   if ((point >= pStart) && (point < pEnd)) {
4489:     PetscInt     dof, off, d;
4490:     PetscScalar *varr;

4492:     PetscSectionGetDof(section, point, &dof);
4493:     PetscSectionGetOffset(section, point, &off);
4494:     varr = &vArray[off];
4495:     for (d = 0; d < dof; ++d, ++offset) {
4496:       array[offset] = varr[d];
4497:     }
4498:     size += dof;
4499:   }
4500:   for (p = 0; p < numPoints; ++p) {
4501:     const PetscInt cp = cone[p];
4502:     PetscInt       o  = coneO[p];
4503:     PetscInt       dof, off, d;
4504:     PetscScalar   *varr;

4506:     if ((cp < pStart) || (cp >= pEnd)) continue;
4507:     PetscSectionGetDof(section, cp, &dof);
4508:     PetscSectionGetOffset(section, cp, &off);
4509:     varr = &vArray[off];
4510:     if (o >= 0) {
4511:       for (d = 0; d < dof; ++d, ++offset) {
4512:         array[offset] = varr[d];
4513:       }
4514:     } else {
4515:       for (d = dof-1; d >= 0; --d, ++offset) {
4516:         array[offset] = varr[d];
4517:       }
4518:     }
4519:     size += dof;
4520:   }
4521:   VecRestoreArray(v, &vArray);
4522:   if (!*values) {
4523:     if (csize) *csize = size;
4524:     *values = array;
4525:   } else {
4526:     if (size > *csize) SETERRQ2(PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Size of input array %D < actual size %D", *csize, size);
4527:     *csize = size;
4528:   }
4529:   return(0);
4530: }

4532: /* Compress out points not in the section */
4533: PETSC_STATIC_INLINE PetscErrorCode CompressPoints_Private(PetscSection section, PetscInt *numPoints, PetscInt points[])
4534: {
4535:   const PetscInt np = *numPoints;
4536:   PetscInt       pStart, pEnd, p, q;

4539:   PetscSectionGetChart(section, &pStart, &pEnd);
4540:   for (p = 0, q = 0; p < np; ++p) {
4541:     const PetscInt r = points[p*2];
4542:     if ((r >= pStart) && (r < pEnd)) {
4543:       points[q*2]   = r;
4544:       points[q*2+1] = points[p*2+1];
4545:       ++q;
4546:     }
4547:   }
4548:   *numPoints = q;
4549:   return 0;
4550: }

4552: static PetscErrorCode DMPlexTransitiveClosure_Hybrid_Internal(DM dm, PetscInt point, PetscInt np, PetscInt *numPoints, PetscInt **points)
4553: {
4554:   const PetscInt *cone, *ornt;
4555:   PetscInt       *pts,  *closure = NULL;
4556:   PetscInt        dim, coneSize, c, d, clSize, cl;
4557:   PetscErrorCode  ierr;

4560:   DMGetDimension(dm, &dim);
4561:   DMPlexGetConeSize(dm, point, &coneSize);
4562:   DMPlexGetCone(dm, point, &cone);
4563:   DMPlexGetConeOrientation(dm, point, &ornt);
4564:   DMPlexGetTransitiveClosure(dm, cone[0], PETSC_TRUE, &clSize, &closure);
4565:   DMGetWorkArray(dm, np*2, MPIU_INT, &pts);
4566:   c    = 0;
4567:   pts[c*2+0] = point;
4568:   pts[c*2+1] = 0;
4569:   ++c;
4570:   for (cl = 0; cl < clSize*2; cl += 2, ++c) {pts[c*2+0] = closure[cl]; pts[c*2+1] = closure[cl+1];}
4571:   DMPlexGetTransitiveClosure(dm, cone[1], PETSC_TRUE, &clSize, &closure);
4572:   for (cl = 0; cl < clSize*2; cl += 2, ++c) {pts[c*2+0] = closure[cl]; pts[c*2+1] = closure[cl+1];}
4573:   DMPlexRestoreTransitiveClosure(dm, cone[0], PETSC_TRUE, &clSize, &closure);
4574:   if (dim >= 2) {
4575:     for (d = 2; d < coneSize; ++d, ++c) {pts[c*2+0] = cone[d]; pts[c*2+1] = ornt[d];}
4576:   }
4577:   if (dim >= 3) {
4578:     for (d = 2; d < coneSize; ++d) {
4579:       const PetscInt  fpoint = cone[d];
4580:       const PetscInt *fcone;
4581:       PetscInt        fconeSize, fc, i;

4583:       DMPlexGetConeSize(dm, fpoint, &fconeSize);
4584:       DMPlexGetCone(dm, fpoint, &fcone);
4585:       for (fc = 0; fc < fconeSize; ++fc) {
4586:         for (i = 0; i < c; ++i) if (pts[i*2] == fcone[fc]) break;
4587:         if (i == c) {pts[c*2+0] = fcone[fc]; pts[c*2+1] = 0; ++c;}
4588:       }
4589:     }
4590:   }
4591:   if (c != np) SETERRQ3(PETSC_COMM_SELF, PETSC_ERR_PLIB, "Invalid closure for hybrid point %D, size %D != %D", point, c, np);
4592:   *numPoints = np;
4593:   *points    = pts;
4594:   return(0);
4595: }

4597: /* Compressed closure does not apply closure permutation */
4598: PetscErrorCode DMPlexGetCompressedClosure(DM dm, PetscSection section, PetscInt point, PetscInt *numPoints, PetscInt **points, PetscSection *clSec, IS *clPoints, const PetscInt **clp)
4599: {
4600:   const PetscInt *cla = NULL;
4601:   PetscInt       np, *pts = NULL;

4605:   PetscSectionGetClosureIndex(section, (PetscObject) dm, clSec, clPoints);
4606:   if (*clPoints) {
4607:     PetscInt dof, off;

4609:     PetscSectionGetDof(*clSec, point, &dof);
4610:     PetscSectionGetOffset(*clSec, point, &off);
4611:     ISGetIndices(*clPoints, &cla);
4612:     np   = dof/2;
4613:     pts  = (PetscInt *) &cla[off];
4614:   } else {
4615:     DMPolytopeType ct;

4617:     /* Do not make the label if it does not exist */
4618:     if (!dm->celltypeLabel) {ct = DM_POLYTOPE_POINT;}
4619:     else                    {DMPlexGetCellType(dm, point, &ct);}
4620:     switch (ct) {
4621:       case DM_POLYTOPE_SEG_PRISM_TENSOR:
4622:         DMPlexTransitiveClosure_Hybrid_Internal(dm, point, 9, &np, &pts);
4623:         break;
4624:       case DM_POLYTOPE_TRI_PRISM_TENSOR:
4625:         DMPlexTransitiveClosure_Hybrid_Internal(dm, point, 21, &np, &pts);
4626:         break;
4627:       case DM_POLYTOPE_QUAD_PRISM_TENSOR:
4628:         DMPlexTransitiveClosure_Hybrid_Internal(dm, point, 27, &np, &pts);
4629:         break;
4630:       default:
4631:         DMPlexGetTransitiveClosure(dm, point, PETSC_TRUE, &np, &pts);
4632:     }
4633:     CompressPoints_Private(section, &np, pts);
4634:   }
4635:   *numPoints = np;
4636:   *points    = pts;
4637:   *clp       = cla;
4638:   return(0);
4639: }

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

4646:   if (!*clPoints) {
4647:     DMPlexRestoreTransitiveClosure(dm, point, PETSC_TRUE, numPoints, points);
4648:   } else {
4649:     ISRestoreIndices(*clPoints, clp);
4650:   }
4651:   *numPoints = 0;
4652:   *points    = NULL;
4653:   *clSec     = NULL;
4654:   *clPoints  = NULL;
4655:   *clp       = NULL;
4656:   return(0);
4657: }

4659: 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[])
4660: {
4661:   PetscInt          offset = 0, p;
4662:   const PetscInt    **perms = NULL;
4663:   const PetscScalar **flips = NULL;
4664:   PetscErrorCode    ierr;

4667:   *size = 0;
4668:   PetscSectionGetPointSyms(section,numPoints,points,&perms,&flips);
4669:   for (p = 0; p < numPoints; p++) {
4670:     const PetscInt    point = points[2*p];
4671:     const PetscInt    *perm = perms ? perms[p] : NULL;
4672:     const PetscScalar *flip = flips ? flips[p] : NULL;
4673:     PetscInt          dof, off, d;
4674:     const PetscScalar *varr;

4676:     PetscSectionGetDof(section, point, &dof);
4677:     PetscSectionGetOffset(section, point, &off);
4678:     varr = &vArray[off];
4679:     if (clperm) {
4680:       if (perm) {
4681:         for (d = 0; d < dof; d++) array[clperm[offset + perm[d]]]  = varr[d];
4682:       } else {
4683:         for (d = 0; d < dof; d++) array[clperm[offset +      d ]]  = varr[d];
4684:       }
4685:       if (flip) {
4686:         for (d = 0; d < dof; d++) array[clperm[offset +      d ]] *= flip[d];
4687:       }
4688:     } else {
4689:       if (perm) {
4690:         for (d = 0; d < dof; d++) array[offset + perm[d]]  = varr[d];
4691:       } else {
4692:         for (d = 0; d < dof; d++) array[offset +      d ]  = varr[d];
4693:       }
4694:       if (flip) {
4695:         for (d = 0; d < dof; d++) array[offset +      d ] *= flip[d];
4696:       }
4697:     }
4698:     offset += dof;
4699:   }
4700:   PetscSectionRestorePointSyms(section,numPoints,points,&perms,&flips);
4701:   *size = offset;
4702:   return(0);
4703: }

4705: 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[])
4706: {
4707:   PetscInt          offset = 0, f;
4708:   PetscErrorCode    ierr;

4711:   *size = 0;
4712:   for (f = 0; f < numFields; ++f) {
4713:     PetscInt          p;
4714:     const PetscInt    **perms = NULL;
4715:     const PetscScalar **flips = NULL;

4717:     PetscSectionGetFieldPointSyms(section,f,numPoints,points,&perms,&flips);
4718:     for (p = 0; p < numPoints; p++) {
4719:       const PetscInt    point = points[2*p];
4720:       PetscInt          fdof, foff, b;
4721:       const PetscScalar *varr;
4722:       const PetscInt    *perm = perms ? perms[p] : NULL;
4723:       const PetscScalar *flip = flips ? flips[p] : NULL;

4725:       PetscSectionGetFieldDof(section, point, f, &fdof);
4726:       PetscSectionGetFieldOffset(section, point, f, &foff);
4727:       varr = &vArray[foff];
4728:       if (clperm) {
4729:         if (perm) {for (b = 0; b < fdof; b++) {array[clperm[offset + perm[b]]]  = varr[b];}}
4730:         else      {for (b = 0; b < fdof; b++) {array[clperm[offset +      b ]]  = varr[b];}}
4731:         if (flip) {for (b = 0; b < fdof; b++) {array[clperm[offset +      b ]] *= flip[b];}}
4732:       } else {
4733:         if (perm) {for (b = 0; b < fdof; b++) {array[offset + perm[b]]  = varr[b];}}
4734:         else      {for (b = 0; b < fdof; b++) {array[offset +      b ]  = varr[b];}}
4735:         if (flip) {for (b = 0; b < fdof; b++) {array[offset +      b ] *= flip[b];}}
4736:       }
4737:       offset += fdof;
4738:     }
4739:     PetscSectionRestoreFieldPointSyms(section,f,numPoints,points,&perms,&flips);
4740:   }
4741:   *size = offset;
4742:   return(0);
4743: }

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

4748:   Not collective

4750:   Input Parameters:
4751: + dm - The DM
4752: . section - The section describing the layout in v, or NULL to use the default section
4753: . v - The local vector
4754: . point - The point in the DM
4755: . csize - The size of the input values array, or NULL
4756: - values - An array to use for the values, or NULL to have it allocated automatically

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

4762: $ Note that DMPlexVecGetClosure/DMPlexVecRestoreClosure only allocates the values array if it set to NULL in the
4763: $ calling function. This is because DMPlexVecGetClosure() is typically called in the inner loop of a Vec or Mat
4764: $ assembly function, and a user may already have allocated storage for this operation.
4765: $
4766: $ A typical use could be
4767: $
4768: $  values = NULL;
4769: $  DMPlexVecGetClosure(dm, NULL, v, p, &clSize, &values);
4770: $  for (cl = 0; cl < clSize; ++cl) {
4771: $    <Compute on closure>
4772: $  }
4773: $  DMPlexVecRestoreClosure(dm, NULL, v, p, &clSize, &values);
4774: $
4775: $ or
4776: $
4777: $  PetscMalloc1(clMaxSize, &values);
4778: $  for (p = pStart; p < pEnd; ++p) {
4779: $    clSize = clMaxSize;
4780: $    DMPlexVecGetClosure(dm, NULL, v, p, &clSize, &values);
4781: $    for (cl = 0; cl < clSize; ++cl) {
4782: $      <Compute on closure>
4783: $    }
4784: $  }
4785: $  PetscFree(values);

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

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

4793:   Level: intermediate

4795: .seealso DMPlexVecRestoreClosure(), DMPlexVecSetClosure(), DMPlexMatSetClosure()
4796: @*/
4797: PetscErrorCode DMPlexVecGetClosure(DM dm, PetscSection section, Vec v, PetscInt point, PetscInt *csize, PetscScalar *values[])
4798: {
4799:   PetscSection       clSection;
4800:   IS                 clPoints;
4801:   PetscInt          *points = NULL;
4802:   const PetscInt    *clp, *perm;
4803:   PetscInt           depth, numFields, numPoints, asize;
4804:   PetscErrorCode     ierr;

4808:   if (!section) {DMGetLocalSection(dm, &section);}
4811:   DMPlexGetDepth(dm, &depth);
4812:   PetscSectionGetNumFields(section, &numFields);
4813:   if (depth == 1 && numFields < 2) {
4814:     DMPlexVecGetClosure_Depth1_Static(dm, section, v, point, csize, values);
4815:     return(0);
4816:   }
4817:   /* Get points */
4818:   DMPlexGetCompressedClosure(dm,section,point,&numPoints,&points,&clSection,&clPoints,&clp);
4819:   /* Get sizes */
4820:   asize = 0;
4821:   for (PetscInt p = 0; p < numPoints*2; p += 2) {
4822:     PetscInt dof;
4823:     PetscSectionGetDof(section, points[p], &dof);
4824:     asize += dof;
4825:   }
4826:   if (values) {
4827:     const PetscScalar *vArray;
4828:     PetscInt          size;

4830:     if (*values) {
4831:       if (PetscUnlikely(*csize < asize)) SETERRQ2(PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Provided array size %D not sufficient to hold closure size %D", *csize, asize);
4832:     } else {DMGetWorkArray(dm, asize, MPIU_SCALAR, values);}
4833:     PetscSectionGetClosureInversePermutation_Internal(section, (PetscObject) dm, depth, asize, &perm);
4834:     VecGetArrayRead(v, &vArray);
4835:     /* Get values */
4836:     if (numFields > 0) {DMPlexVecGetClosure_Fields_Static(dm, section, numPoints, points, numFields, perm, vArray, &size, *values);}
4837:     else               {DMPlexVecGetClosure_Static(dm, section, numPoints, points, perm, vArray, &size, *values);}
4838:     if (PetscUnlikely(asize != size)) SETERRQ2(PETSC_COMM_SELF, PETSC_ERR_PLIB, "Section size %D does not match Vec closure size %D", asize, size);
4839:     /* Cleanup array */
4840:     VecRestoreArrayRead(v, &vArray);
4841:   }
4842:   if (csize) *csize = asize;
4843:   /* Cleanup points */
4844:   DMPlexRestoreCompressedClosure(dm,section,point,&numPoints,&points,&clSection,&clPoints,&clp);
4845:   return(0);
4846: }

4848: PetscErrorCode DMPlexVecGetClosureAtDepth_Internal(DM dm, PetscSection section, Vec v, PetscInt point, PetscInt depth, PetscInt *csize, PetscScalar *values[])
4849: {
4850:   DMLabel            depthLabel;
4851:   PetscSection       clSection;
4852:   IS                 clPoints;
4853:   PetscScalar       *array;
4854:   const PetscScalar *vArray;
4855:   PetscInt          *points = NULL;
4856:   const PetscInt    *clp, *perm = NULL;
4857:   PetscInt           mdepth, numFields, numPoints, Np = 0, p, clsize, size;
4858:   PetscErrorCode     ierr;

4862:   if (!section) {DMGetLocalSection(dm, &section);}
4865:   DMPlexGetDepth(dm, &mdepth);
4866:   DMPlexGetDepthLabel(dm, &depthLabel);
4867:   PetscSectionGetNumFields(section, &numFields);
4868:   if (mdepth == 1 && numFields < 2) {
4869:     DMPlexVecGetClosure_Depth1_Static(dm, section, v, point, csize, values);
4870:     return(0);
4871:   }
4872:   /* Get points */
4873:   DMPlexGetCompressedClosure(dm,section,point,&numPoints,&points,&clSection,&clPoints,&clp);
4874:   for (clsize=0,p=0; p<Np; p++) {
4875:     PetscInt dof;
4876:     PetscSectionGetDof(section, points[2*p], &dof);
4877:     clsize += dof;
4878:   }
4879:   PetscSectionGetClosureInversePermutation_Internal(section, (PetscObject) dm, depth, clsize, &perm);
4880:   /* Filter points */
4881:   for (p = 0; p < numPoints*2; p += 2) {
4882:     PetscInt dep;

4884:     DMLabelGetValue(depthLabel, points[p], &dep);
4885:     if (dep != depth) continue;
4886:     points[Np*2+0] = points[p];
4887:     points[Np*2+1] = points[p+1];
4888:     ++Np;
4889:   }
4890:   /* Get array */
4891:   if (!values || !*values) {
4892:     PetscInt asize = 0, dof;

4894:     for (p = 0; p < Np*2; p += 2) {
4895:       PetscSectionGetDof(section, points[p], &dof);
4896:       asize += dof;
4897:     }
4898:     if (!values) {
4899:       DMPlexRestoreCompressedClosure(dm,section,point,&numPoints,&points,&clSection,&clPoints,&clp);
4900:       if (csize) *csize = asize;
4901:       return(0);
4902:     }
4903:     DMGetWorkArray(dm, asize, MPIU_SCALAR, &array);
4904:   } else {
4905:     array = *values;
4906:   }
4907:   VecGetArrayRead(v, &vArray);
4908:   /* Get values */
4909:   if (numFields > 0) {DMPlexVecGetClosure_Fields_Static(dm, section, Np, points, numFields, perm, vArray, &size, array);}
4910:   else               {DMPlexVecGetClosure_Static(dm, section, Np, points, perm, vArray, &size, array);}
4911:   /* Cleanup points */
4912:   DMPlexRestoreCompressedClosure(dm,section,point,&numPoints,&points,&clSection,&clPoints,&clp);
4913:   /* Cleanup array */
4914:   VecRestoreArrayRead(v, &vArray);
4915:   if (!*values) {
4916:     if (csize) *csize = size;
4917:     *values = array;
4918:   } else {
4919:     if (size > *csize) SETERRQ2(PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Size of input array %D < actual size %D", *csize, size);
4920:     *csize = size;
4921:   }
4922:   return(0);
4923: }

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

4928:   Not collective

4930:   Input Parameters:
4931: + dm - The DM
4932: . section - The section describing the layout in v, or NULL to use the default section
4933: . v - The local vector
4934: . point - The point in the DM
4935: . csize - The number of values in the closure, or NULL
4936: - values - The array of values, which is a borrowed array and should not be freed

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

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

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

4946:   Level: intermediate

4948: .seealso DMPlexVecGetClosure(), DMPlexVecSetClosure(), DMPlexMatSetClosure()
4949: @*/
4950: PetscErrorCode DMPlexVecRestoreClosure(DM dm, PetscSection section, Vec v, PetscInt point, PetscInt *csize, PetscScalar *values[])
4951: {
4952:   PetscInt       size = 0;

4956:   /* Should work without recalculating size */
4957:   DMRestoreWorkArray(dm, size, MPIU_SCALAR, (void*) values);
4958:   *values = NULL;
4959:   return(0);
4960: }

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

4965: 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[])
4966: {
4967:   PetscInt        cdof;   /* The number of constraints on this point */
4968:   const PetscInt *cdofs; /* The indices of the constrained dofs on this point */
4969:   PetscScalar    *a;
4970:   PetscInt        off, cind = 0, k;
4971:   PetscErrorCode  ierr;

4974:   PetscSectionGetConstraintDof(section, point, &cdof);
4975:   PetscSectionGetOffset(section, point, &off);
4976:   a    = &array[off];
4977:   if (!cdof || setBC) {
4978:     if (clperm) {
4979:       if (perm) {for (k = 0; k < dof; ++k) {fuse(&a[k], values[clperm[offset+perm[k]]] * (flip ? flip[perm[k]] : 1.));}}
4980:       else      {for (k = 0; k < dof; ++k) {fuse(&a[k], values[clperm[offset+     k ]] * (flip ? flip[     k ] : 1.));}}
4981:     } else {
4982:       if (perm) {for (k = 0; k < dof; ++k) {fuse(&a[k], values[offset+perm[k]] * (flip ? flip[perm[k]] : 1.));}}
4983:       else      {for (k = 0; k < dof; ++k) {fuse(&a[k], values[offset+     k ] * (flip ? flip[     k ] : 1.));}}
4984:     }
4985:   } else {
4986:     PetscSectionGetConstraintIndices(section, point, &cdofs);
4987:     if (clperm) {
4988:       if (perm) {for (k = 0; k < dof; ++k) {
4989:           if ((cind < cdof) && (k == cdofs[cind])) {++cind; continue;}
4990:           fuse(&a[k], values[clperm[offset+perm[k]]] * (flip ? flip[perm[k]] : 1.));
4991:         }
4992:       } else {
4993:         for (k = 0; k < dof; ++k) {
4994:           if ((cind < cdof) && (k == cdofs[cind])) {++cind; continue;}
4995:           fuse(&a[k], values[clperm[offset+     k ]] * (flip ? flip[     k ] : 1.));
4996:         }
4997:       }
4998:     } else {
4999:       if (perm) {
5000:         for (k = 0; k < dof; ++k) {
5001:           if ((cind < cdof) && (k == cdofs[cind])) {++cind; continue;}
5002:           fuse(&a[k], values[offset+perm[k]] * (flip ? flip[perm[k]] : 1.));
5003:         }
5004:       } else {
5005:         for (k = 0; k < dof; ++k) {
5006:           if ((cind < cdof) && (k == cdofs[cind])) {++cind; continue;}
5007:           fuse(&a[k], values[offset+     k ] * (flip ? flip[     k ] : 1.));
5008:         }
5009:       }
5010:     }
5011:   }
5012:   return(0);
5013: }

5015: 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[])
5016: {
5017:   PetscInt        cdof;   /* The number of constraints on this point */
5018:   const PetscInt *cdofs; /* The indices of the constrained dofs on this point */
5019:   PetscScalar    *a;
5020:   PetscInt        off, cind = 0, k;
5021:   PetscErrorCode  ierr;

5024:   PetscSectionGetConstraintDof(section, point, &cdof);
5025:   PetscSectionGetOffset(section, point, &off);
5026:   a    = &array[off];
5027:   if (cdof) {
5028:     PetscSectionGetConstraintIndices(section, point, &cdofs);
5029:     if (clperm) {
5030:       if (perm) {
5031:         for (k = 0; k < dof; ++k) {
5032:           if ((cind < cdof) && (k == cdofs[cind])) {
5033:             fuse(&a[k], values[clperm[offset+perm[k]]] * (flip ? flip[perm[k]] : 1.));
5034:             cind++;
5035:           }
5036:         }
5037:       } else {
5038:         for (k = 0; k < dof; ++k) {
5039:           if ((cind < cdof) && (k == cdofs[cind])) {
5040:             fuse(&a[k], values[clperm[offset+     k ]] * (flip ? flip[     k ] : 1.));
5041:             cind++;
5042:           }
5043:         }
5044:       }
5045:     } else {
5046:       if (perm) {
5047:         for (k = 0; k < dof; ++k) {
5048:           if ((cind < cdof) && (k == cdofs[cind])) {
5049:             fuse(&a[k], values[offset+perm[k]] * (flip ? flip[perm[k]] : 1.));
5050:             cind++;
5051:           }
5052:         }
5053:       } else {
5054:         for (k = 0; k < dof; ++k) {
5055:           if ((cind < cdof) && (k == cdofs[cind])) {
5056:             fuse(&a[k], values[offset+     k ] * (flip ? flip[     k ] : 1.));
5057:             cind++;
5058:           }
5059:         }
5060:       }
5061:     }
5062:   }
5063:   return(0);
5064: }

5066: 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[])
5067: {
5068:   PetscScalar    *a;
5069:   PetscInt        fdof, foff, fcdof, foffset = *offset;
5070:   const PetscInt *fcdofs; /* The indices of the constrained dofs for field f on this point */
5071:   PetscInt        cind = 0, b;
5072:   PetscErrorCode  ierr;

5075:   PetscSectionGetFieldDof(section, point, f, &fdof);
5076:   PetscSectionGetFieldConstraintDof(section, point, f, &fcdof);
5077:   PetscSectionGetFieldOffset(section, point, f, &foff);
5078:   a    = &array[foff];
5079:   if (!fcdof || setBC) {
5080:     if (clperm) {
5081:       if (perm) {for (b = 0; b < fdof; b++) {fuse(&a[b], values[clperm[foffset+perm[b]]] * (flip ? flip[perm[b]] : 1.));}}
5082:       else      {for (b = 0; b < fdof; b++) {fuse(&a[b], values[clperm[foffset+     b ]] * (flip ? flip[     b ] : 1.));}}
5083:     } else {
5084:       if (perm) {for (b = 0; b < fdof; b++) {fuse(&a[b], values[foffset+perm[b]] * (flip ? flip[perm[b]] : 1.));}}
5085:       else      {for (b = 0; b < fdof; b++) {fuse(&a[b], values[foffset+     b ] * (flip ? flip[     b ] : 1.));}}
5086:     }
5087:   } else {
5088:     PetscSectionGetFieldConstraintIndices(section, point, f, &fcdofs);
5089:     if (clperm) {
5090:       if (perm) {
5091:         for (b = 0; b < fdof; b++) {
5092:           if ((cind < fcdof) && (b == fcdofs[cind])) {++cind; continue;}
5093:           fuse(&a[b], values[clperm[foffset+perm[b]]] * (flip ? flip[perm[b]] : 1.));
5094:         }
5095:       } else {
5096:         for (b = 0; b < fdof; b++) {
5097:           if ((cind < fcdof) && (b == fcdofs[cind])) {++cind; continue;}
5098:           fuse(&a[b], values[clperm[foffset+     b ]] * (flip ? flip[     b ] : 1.));
5099:         }
5100:       }
5101:     } else {
5102:       if (perm) {
5103:         for (b = 0; b < fdof; b++) {
5104:           if ((cind < fcdof) && (b == fcdofs[cind])) {++cind; continue;}
5105:           fuse(&a[b], values[foffset+perm[b]] * (flip ? flip[perm[b]] : 1.));
5106:         }
5107:       } else {
5108:         for (b = 0; b < fdof; b++) {
5109:           if ((cind < fcdof) && (b == fcdofs[cind])) {++cind; continue;}
5110:           fuse(&a[b], values[foffset+     b ] * (flip ? flip[     b ] : 1.));
5111:         }
5112:       }
5113:     }
5114:   }
5115:   *offset += fdof;
5116:   return(0);
5117: }

5119: 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[])
5120: {
5121:   PetscScalar    *a;
5122:   PetscInt        fdof, foff, fcdof, foffset = *offset;
5123:   const PetscInt *fcdofs; /* The indices of the constrained dofs for field f on this point */
5124:   PetscInt        Nc, cind = 0, ncind = 0, b;
5125:   PetscBool       ncSet, fcSet;
5126:   PetscErrorCode  ierr;

5129:   PetscSectionGetFieldComponents(section, f, &Nc);
5130:   PetscSectionGetFieldDof(section, point, f, &fdof);
5131:   PetscSectionGetFieldConstraintDof(section, point, f, &fcdof);
5132:   PetscSectionGetFieldOffset(section, point, f, &foff);
5133:   a    = &array[foff];
5134:   if (fcdof) {
5135:     /* We just override fcdof and fcdofs with Ncc and comps */
5136:     PetscSectionGetFieldConstraintIndices(section, point, f, &fcdofs);
5137:     if (clperm) {
5138:       if (perm) {
5139:         if (comps) {
5140:           for (b = 0; b < fdof; b++) {
5141:             ncSet = fcSet = PETSC_FALSE;
5142:             if (b%Nc == comps[ncind]) {ncind = (ncind+1)%Ncc; ncSet = PETSC_TRUE;}
5143:             if ((cind < fcdof) && (b == fcdofs[cind])) {++cind;  fcSet = PETSC_TRUE;}
5144:             if (ncSet && fcSet) {fuse(&a[b], values[clperm[foffset+perm[b]]] * (flip ? flip[perm[b]] : 1.));}
5145:           }
5146:         } else {
5147:           for (b = 0; b < fdof; b++) {
5148:             if ((cind < fcdof) && (b == fcdofs[cind])) {
5149:               fuse(&a[b], values[clperm[foffset+perm[b]]] * (flip ? flip[perm[b]] : 1.));
5150:               ++cind;
5151:             }
5152:           }
5153:         }
5154:       } else {
5155:         if (comps) {
5156:           for (b = 0; b < fdof; b++) {
5157:             ncSet = fcSet = PETSC_FALSE;
5158:             if (b%Nc == comps[ncind]) {ncind = (ncind+1)%Ncc; ncSet = PETSC_TRUE;}
5159:             if ((cind < fcdof) && (b == fcdofs[cind])) {++cind;  fcSet = PETSC_TRUE;}
5160:             if (ncSet && fcSet) {fuse(&a[b], values[clperm[foffset+     b ]] * (flip ? flip[     b ] : 1.));}
5161:           }
5162:         } else {
5163:           for (b = 0; b < fdof; b++) {
5164:             if ((cind < fcdof) && (b == fcdofs[cind])) {
5165:               fuse(&a[b], values[clperm[foffset+     b ]] * (flip ? flip[     b ] : 1.));
5166:               ++cind;
5167:             }
5168:           }
5169:         }
5170:       }
5171:     } else {
5172:       if (perm) {
5173:         if (comps) {
5174:           for (b = 0; b < fdof; b++) {
5175:             ncSet = fcSet = PETSC_FALSE;
5176:             if (b%Nc == comps[ncind]) {ncind = (ncind+1)%Ncc; ncSet = PETSC_TRUE;}
5177:             if ((cind < fcdof) && (b == fcdofs[cind])) {++cind;  fcSet = PETSC_TRUE;}
5178:             if (ncSet && fcSet) {fuse(&a[b], values[foffset+perm[b]] * (flip ? flip[perm[b]] : 1.));}
5179:           }
5180:         } else {
5181:           for (b = 0; b < fdof; b++) {
5182:             if ((cind < fcdof) && (b == fcdofs[cind])) {
5183:               fuse(&a[b], values[foffset+perm[b]] * (flip ? flip[perm[b]] : 1.));
5184:               ++cind;
5185:             }
5186:           }
5187:         }
5188:       } else {
5189:         if (comps) {
5190:           for (b = 0; b < fdof; b++) {
5191:             ncSet = fcSet = PETSC_FALSE;
5192:             if (b%Nc == comps[ncind]) {ncind = (ncind+1)%Ncc; ncSet = PETSC_TRUE;}
5193:             if ((cind < fcdof) && (b == fcdofs[cind])) {++cind;  fcSet = PETSC_TRUE;}
5194:             if (ncSet && fcSet) {fuse(&a[b], values[foffset+     b ] * (flip ? flip[     b ] : 1.));}
5195:           }
5196:         } else {
5197:           for (b = 0; b < fdof; b++) {
5198:             if ((cind < fcdof) && (b == fcdofs[cind])) {
5199:               fuse(&a[b], values[foffset+     b ] * (flip ? flip[     b ] : 1.));
5200:               ++cind;
5201:             }
5202:           }
5203:         }
5204:       }
5205:     }
5206:   }
5207:   *offset += fdof;
5208:   return(0);
5209: }

5211: PETSC_STATIC_INLINE PetscErrorCode DMPlexVecSetClosure_Depth1_Static(DM dm, PetscSection section, Vec v, PetscInt point, const PetscScalar values[], InsertMode mode)
5212: {
5213:   PetscScalar    *array;
5214:   const PetscInt *cone, *coneO;
5215:   PetscInt        pStart, pEnd, p, numPoints, off, dof;
5216:   PetscErrorCode  ierr;

5219:   PetscSectionGetChart(section, &pStart, &pEnd);
5220:   DMPlexGetConeSize(dm, point, &numPoints);
5221:   DMPlexGetCone(dm, point, &cone);
5222:   DMPlexGetConeOrientation(dm, point, &coneO);
5223:   VecGetArray(v, &array);
5224:   for (p = 0, off = 0; p <= numPoints; ++p, off += dof) {
5225:     const PetscInt cp = !p ? point : cone[p-1];
5226:     const PetscInt o  = !p ? 0     : coneO[p-1];

5228:     if ((cp < pStart) || (cp >= pEnd)) {dof = 0; continue;}
5229:     PetscSectionGetDof(section, cp, &dof);
5230:     /* ADD_VALUES */
5231:     {
5232:       const PetscInt *cdofs; /* The indices of the constrained dofs on this point */
5233:       PetscScalar    *a;
5234:       PetscInt        cdof, coff, cind = 0, k;

5236:       PetscSectionGetConstraintDof(section, cp, &cdof);
5237:       PetscSectionGetOffset(section, cp, &coff);
5238:       a    = &array[coff];
5239:       if (!cdof) {
5240:         if (o >= 0) {
5241:           for (k = 0; k < dof; ++k) {
5242:             a[k] += values[off+k];
5243:           }
5244:         } else {
5245:           for (k = 0; k < dof; ++k) {
5246:             a[k] += values[off+dof-k-1];
5247:           }
5248:         }
5249:       } else {
5250:         PetscSectionGetConstraintIndices(section, cp, &cdofs);
5251:         if (o >= 0) {
5252:           for (k = 0; k < dof; ++k) {
5253:             if ((cind < cdof) && (k == cdofs[cind])) {++cind; continue;}
5254:             a[k] += values[off+k];
5255:           }
5256:         } else {
5257:           for (k = 0; k < dof; ++k) {
5258:             if ((cind < cdof) && (k == cdofs[cind])) {++cind; continue;}
5259:             a[k] += values[off+dof-k-1];
5260:           }
5261:         }
5262:       }
5263:     }
5264:   }
5265:   VecRestoreArray(v, &array);
5266:   return(0);
5267: }

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

5272:   Not collective

5274:   Input Parameters:
5275: + dm - The DM
5276: . section - The section describing the layout in v, or NULL to use the default section
5277: . v - The local vector
5278: . point - The point in the DM
5279: . values - The array of values
5280: - mode - The insert mode. One of INSERT_ALL_VALUES, ADD_ALL_VALUES, INSERT_VALUES, ADD_VALUES, INSERT_BC_VALUES, and ADD_BC_VALUES,
5281:          where INSERT_ALL_VALUES and ADD_ALL_VALUES also overwrite boundary conditions.

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

5286:   Level: intermediate

5288: .seealso DMPlexVecGetClosure(), DMPlexMatSetClosure()
5289: @*/
5290: PetscErrorCode DMPlexVecSetClosure(DM dm, PetscSection section, Vec v, PetscInt point, const PetscScalar values[], InsertMode mode)
5291: {
5292:   PetscSection    clSection;
5293:   IS              clPoints;
5294:   PetscScalar    *array;
5295:   PetscInt       *points = NULL;
5296:   const PetscInt *clp, *clperm = NULL;
5297:   PetscInt        depth, numFields, numPoints, p, clsize;
5298:   PetscErrorCode  ierr;

5302:   if (!section) {DMGetLocalSection(dm, &section);}
5305:   DMPlexGetDepth(dm, &depth);
5306:   PetscSectionGetNumFields(section, &numFields);
5307:   if (depth == 1 && numFields < 2 && mode == ADD_VALUES) {
5308:     DMPlexVecSetClosure_Depth1_Static(dm, section, v, point, values, mode);
5309:     return(0);
5310:   }
5311:   /* Get points */
5312:   DMPlexGetCompressedClosure(dm,section,point,&numPoints,&points,&clSection,&clPoints,&clp);
5313:   for (clsize=0,p=0; p<numPoints; p++) {
5314:     PetscInt dof;
5315:     PetscSectionGetDof(section, points[2*p], &dof);
5316:     clsize += dof;
5317:   }
5318:   PetscSectionGetClosureInversePermutation_Internal(section, (PetscObject) dm, depth, clsize, &clperm);
5319:   /* Get array */
5320:   VecGetArray(v, &array);
5321:   /* Get values */
5322:   if (numFields > 0) {
5323:     PetscInt offset = 0, f;
5324:     for (f = 0; f < numFields; ++f) {
5325:       const PetscInt    **perms = NULL;
5326:       const PetscScalar **flips = NULL;

5328:       PetscSectionGetFieldPointSyms(section,f,numPoints,points,&perms,&flips);
5329:       switch (mode) {
5330:       case INSERT_VALUES:
5331:         for (p = 0; p < numPoints; p++) {
5332:           const PetscInt    point = points[2*p];
5333:           const PetscInt    *perm = perms ? perms[p] : NULL;
5334:           const PetscScalar *flip = flips ? flips[p] : NULL;
5335:           updatePointFields_private(section, point, perm, flip, f, insert, PETSC_FALSE, clperm, values, &offset, array);
5336:         } break;
5337:       case INSERT_ALL_VALUES:
5338:         for (p = 0; p < numPoints; p++) {
5339:           const PetscInt    point = points[2*p];
5340:           const PetscInt    *perm = perms ? perms[p] : NULL;
5341:           const PetscScalar *flip = flips ? flips[p] : NULL;
5342:           updatePointFields_private(section, point, perm, flip, f, insert, PETSC_TRUE, clperm, values, &offset, array);
5343:         } break;
5344:       case INSERT_BC_VALUES:
5345:         for (p = 0; p < numPoints; p++) {
5346:           const PetscInt    point = points[2*p];
5347:           const PetscInt    *perm = perms ? perms[p] : NULL;
5348:           const PetscScalar *flip = flips ? flips[p] : NULL;
5349:           updatePointFieldsBC_private(section, point, perm, flip, f, -1, NULL, insert, clperm, values, &offset, array);
5350:         } break;
5351:       case ADD_VALUES:
5352:         for (p = 0; p < numPoints; p++) {
5353:           const PetscInt    point = points[2*p];
5354:           const PetscInt    *perm = perms ? perms[p] : NULL;
5355:           const PetscScalar *flip = flips ? flips[p] : NULL;
5356:           updatePointFields_private(section, point, perm, flip, f, add, PETSC_FALSE, clperm, values, &offset, array);
5357:         } break;
5358:       case ADD_ALL_VALUES:
5359:         for (p = 0; p < numPoints; p++) {
5360:           const PetscInt    point = points[2*p];
5361:           const PetscInt    *perm = perms ? perms[p] : NULL;
5362:           const PetscScalar *flip = flips ? flips[p] : NULL;
5363:           updatePointFields_private(section, point, perm, flip, f, add, PETSC_TRUE, clperm, values, &offset, array);
5364:         } break;
5365:       case ADD_BC_VALUES:
5366:         for (p = 0; p < numPoints; p++) {
5367:           const PetscInt    point = points[2*p];
5368:           const PetscInt    *perm = perms ? perms[p] : NULL;
5369:           const PetscScalar *flip = flips ? flips[p] : NULL;
5370:           updatePointFieldsBC_private(section, point, perm, flip, f, -1, NULL, add, clperm, values, &offset, array);
5371:         } break;
5372:       default:
5373:         SETERRQ1(PetscObjectComm((PetscObject)dm), PETSC_ERR_ARG_OUTOFRANGE, "Invalid insert mode %d", mode);
5374:       }
5375:       PetscSectionRestoreFieldPointSyms(section,f,numPoints,points,&perms,&flips);
5376:     }
5377:   } else {
5378:     PetscInt dof, off;
5379:     const PetscInt    **perms = NULL;
5380:     const PetscScalar **flips = NULL;

5382:     PetscSectionGetPointSyms(section,numPoints,points,&perms,&flips);
5383:     switch (mode) {
5384:     case INSERT_VALUES:
5385:       for (p = 0, off = 0; p < numPoints; p++, off += dof) {
5386:         const PetscInt    point = points[2*p];
5387:         const PetscInt    *perm = perms ? perms[p] : NULL;
5388:         const PetscScalar *flip = flips ? flips[p] : NULL;
5389:         PetscSectionGetDof(section, point, &dof);
5390:         updatePoint_private(section, point, dof, insert, PETSC_FALSE, perm, flip, clperm, values, off, array);
5391:       } break;
5392:     case INSERT_ALL_VALUES:
5393:       for (p = 0, off = 0; p < numPoints; p++, off += dof) {
5394:         const PetscInt    point = points[2*p];
5395:         const PetscInt    *perm = perms ? perms[p] : NULL;
5396:         const PetscScalar *flip = flips ? flips[p] : NULL;
5397:         PetscSectionGetDof(section, point, &dof);
5398:         updatePoint_private(section, point, dof, insert, PETSC_TRUE,  perm, flip, clperm, values, off, array);
5399:       } break;
5400:     case INSERT_BC_VALUES:
5401:       for (p = 0, off = 0; p < numPoints; p++, off += dof) {
5402:         const PetscInt    point = points[2*p];
5403:         const PetscInt    *perm = perms ? perms[p] : NULL;
5404:         const PetscScalar *flip = flips ? flips[p] : NULL;
5405:         PetscSectionGetDof(section, point, &dof);
5406:         updatePointBC_private(section, point, dof, insert,  perm, flip, clperm, values, off, array);
5407:       } break;
5408:     case ADD_VALUES:
5409:       for (p = 0, off = 0; p < numPoints; p++, off += dof) {
5410:         const PetscInt    point = points[2*p];
5411:         const PetscInt    *perm = perms ? perms[p] : NULL;
5412:         const PetscScalar *flip = flips ? flips[p] : NULL;
5413:         PetscSectionGetDof(section, point, &dof);
5414:         updatePoint_private(section, point, dof, add,    PETSC_FALSE, perm, flip, clperm, values, off, array);
5415:       } break;
5416:     case ADD_ALL_VALUES:
5417:       for (p = 0, off = 0; p < numPoints; p++, off += dof) {
5418:         const PetscInt    point = points[2*p];
5419:         const PetscInt    *perm = perms ? perms[p] : NULL;
5420:         const PetscScalar *flip = flips ? flips[p] : NULL;
5421:         PetscSectionGetDof(section, point, &dof);
5422:         updatePoint_private(section, point, dof, add,    PETSC_TRUE,  perm, flip, clperm, values, off, array);
5423:       } break;
5424:     case ADD_BC_VALUES:
5425:       for (p = 0, off = 0; p < numPoints; p++, off += dof) {
5426:         const PetscInt    point = points[2*p];
5427:         const PetscInt    *perm = perms ? perms[p] : NULL;
5428:         const PetscScalar *flip = flips ? flips[p] : NULL;
5429:         PetscSectionGetDof(section, point, &dof);
5430:         updatePointBC_private(section, point, dof, add,  perm, flip, clperm, values, off, array);
5431:       } break;
5432:     default:
5433:       SETERRQ1(PetscObjectComm((PetscObject)dm), PETSC_ERR_ARG_OUTOFRANGE, "Invalid insert mode %d", mode);
5434:     }
5435:     PetscSectionRestorePointSyms(section,numPoints,points,&perms,&flips);
5436:   }
5437:   /* Cleanup points */
5438:   DMPlexRestoreCompressedClosure(dm,section,point,&numPoints,&points,&clSection,&clPoints,&clp);
5439:   /* Cleanup array */
5440:   VecRestoreArray(v, &array);
5441:   return(0);
5442: }

5444: /* Check whether the given point is in the label. If not, update the offset to skip this point */
5445: PETSC_STATIC_INLINE PetscErrorCode CheckPoint_Private(DMLabel label, PetscInt labelId, PetscSection section, PetscInt point, PetscInt f, PetscInt *offset)
5446: {
5448:   if (label) {
5449:     PetscInt       val, fdof;

5452:     /* There is a problem with this:
5453:          Suppose we have two label values, defining surfaces, interecting along a line in 3D. When we add cells to the label, the cells that
5454:        touch both surfaces must pick a label value. Thus we miss setting values for the surface with that other value intersecting that cell.
5455:        Thus I am only going to check val != -1, not val != labelId
5456:     */
5457:     DMLabelGetValue(label, point, &val);
5458:     if (val < 0) {
5459:       PetscSectionGetFieldDof(section, point, f, &fdof);
5460:       *offset += fdof;
5461:       PetscFunctionReturn(1);
5462:     }
5463:   }
5464:   return(0);
5465: }

5467: /* Unlike DMPlexVecSetClosure(), this uses plex-native closure permutation, not a user-specified permutation such as DMPlexSetClosurePermutationTensor(). */
5468: PetscErrorCode DMPlexVecSetFieldClosure_Internal(DM dm, PetscSection section, Vec v, PetscBool fieldActive[], PetscInt point, PetscInt Ncc, const PetscInt comps[], DMLabel label, PetscInt labelId, const PetscScalar values[], InsertMode mode)
5469: {
5470:   PetscSection      clSection;
5471:   IS                clPoints;
5472:   PetscScalar       *array;
5473:   PetscInt          *points = NULL;
5474:   const PetscInt    *clp;
5475:   PetscInt          numFields, numPoints, p;
5476:   PetscInt          offset = 0, f;
5477:   PetscErrorCode    ierr;

5481:   if (!section) {DMGetLocalSection(dm, &section);}
5484:   PetscSectionGetNumFields(section, &numFields);
5485:   /* Get points */
5486:   DMPlexGetCompressedClosure(dm,section,point,&numPoints,&points,&clSection,&clPoints,&clp);
5487:   /* Get array */
5488:   VecGetArray(v, &array);
5489:   /* Get values */
5490:   for (f = 0; f < numFields; ++f) {
5491:     const PetscInt    **perms = NULL;
5492:     const PetscScalar **flips = NULL;

5494:     if (!fieldActive[f]) {
5495:       for (p = 0; p < numPoints*2; p += 2) {
5496:         PetscInt fdof;
5497:         PetscSectionGetFieldDof(section, points[p], f, &fdof);
5498:         offset += fdof;
5499:       }
5500:       continue;
5501:     }
5502:     PetscSectionGetFieldPointSyms(section,f,numPoints,points,&perms,&flips);
5503:     switch (mode) {
5504:     case INSERT_VALUES:
5505:       for (p = 0; p < numPoints; p++) {
5506:         const PetscInt    point = points[2*p];
5507:         const PetscInt    *perm = perms ? perms[p] : NULL;
5508:         const PetscScalar *flip = flips ? flips[p] : NULL;
5509:         CheckPoint_Private(label, labelId, section, point, f, &offset); if (ierr) continue;
5510:         updatePointFields_private(section, point, perm, flip, f, insert, PETSC_FALSE, NULL, values, &offset, array);
5511:       } break;
5512:     case INSERT_ALL_VALUES:
5513:       for (p = 0; p < numPoints; p++) {
5514:         const PetscInt    point = points[2*p];
5515:         const PetscInt    *perm = perms ? perms[p] : NULL;
5516:         const PetscScalar *flip = flips ? flips[p] : NULL;
5517:         CheckPoint_Private(label, labelId, section, point, f, &offset); if (ierr) continue;
5518:         updatePointFields_private(section, point, perm, flip, f, insert, PETSC_TRUE, NULL, values, &offset, array);
5519:       } break;
5520:     case INSERT_BC_VALUES:
5521:       for (p = 0; p < numPoints; p++) {
5522:         const PetscInt    point = points[2*p];
5523:         const PetscInt    *perm = perms ? perms[p] : NULL;
5524:         const PetscScalar *flip = flips ? flips[p] : NULL;
5525:         CheckPoint_Private(label, labelId, section, point, f, &offset); if (ierr) continue;
5526:         updatePointFieldsBC_private(section, point, perm, flip, f, Ncc, comps, insert, NULL, values, &offset, array);
5527:       } break;
5528:     case ADD_VALUES:
5529:       for (p = 0; p < numPoints; p++) {
5530:         const PetscInt    point = points[2*p];
5531:         const PetscInt    *perm = perms ? perms[p] : NULL;
5532:         const PetscScalar *flip = flips ? flips[p] : NULL;
5533:         CheckPoint_Private(label, labelId, section, point, f, &offset); if (ierr) continue;
5534:         updatePointFields_private(section, point, perm, flip, f, add, PETSC_FALSE, NULL, values, &offset, array);
5535:       } break;
5536:     case ADD_ALL_VALUES:
5537:       for (p = 0; p < numPoints; p++) {
5538:         const PetscInt    point = points[2*p];
5539:         const PetscInt    *perm = perms ? perms[p] : NULL;
5540:         const PetscScalar *flip = flips ? flips[p] : NULL;
5541:         CheckPoint_Private(label, labelId, section, point, f, &offset); if (ierr) continue;
5542:         updatePointFields_private(section, point, perm, flip, f, add, PETSC_TRUE, NULL, values, &offset, array);
5543:       } break;
5544:     default:
5545:       SETERRQ1(PetscObjectComm((PetscObject)dm), PETSC_ERR_ARG_OUTOFRANGE, "Invalid insert mode %d", mode);
5546:     }
5547:     PetscSectionRestoreFieldPointSyms(section,f,numPoints,points,&perms,&flips);
5548:   }
5549:   /* Cleanup points */
5550:   DMPlexRestoreCompressedClosure(dm,section,point,&numPoints,&points,&clSection,&clPoints,&clp);
5551:   /* Cleanup array */
5552:   VecRestoreArray(v, &array);
5553:   return(0);
5554: }

5556: static PetscErrorCode DMPlexPrintMatSetValues(PetscViewer viewer, Mat A, PetscInt point, PetscInt numRIndices, const PetscInt rindices[], PetscInt numCIndices, const PetscInt cindices[], const PetscScalar values[])
5557: {
5558:   PetscMPIInt    rank;
5559:   PetscInt       i, j;

5563:   MPI_Comm_rank(PetscObjectComm((PetscObject)A), &rank);
5564:   PetscViewerASCIIPrintf(viewer, "[%d]mat for point %D\n", rank, point);
5565:   for (i = 0; i < numRIndices; i++) {PetscViewerASCIIPrintf(viewer, "[%d]mat row indices[%D] = %D\n", rank, i, rindices[i]);}
5566:   for (i = 0; i < numCIndices; i++) {PetscViewerASCIIPrintf(viewer, "[%d]mat col indices[%D] = %D\n", rank, i, cindices[i]);}
5567:   numCIndices = numCIndices ? numCIndices : numRIndices;
5568:   if (!values) return(0);
5569:   for (i = 0; i < numRIndices; i++) {
5570:     PetscViewerASCIIPrintf(viewer, "[%d]", rank);
5571:     for (j = 0; j < numCIndices; j++) {
5572: #if defined(PETSC_USE_COMPLEX)
5573:       PetscViewerASCIIPrintf(viewer, " (%g,%g)", (double)PetscRealPart(values[i*numCIndices+j]), (double)PetscImaginaryPart(values[i*numCIndices+j]));
5574: #else
5575:       PetscViewerASCIIPrintf(viewer, " %g", (double)values[i*numCIndices+j]);
5576: #endif
5577:     }
5578:     PetscViewerASCIIPrintf(viewer, "\n");
5579:   }
5580:   return(0);
5581: }

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

5586:   Input Parameters:
5587: + section - The section for this data layout
5588: . islocal - Is the section (and thus indices being requested) local or global?
5589: . point   - The point contributing dofs with these indices
5590: . off     - The global offset of this point
5591: . loff    - The local offset of each field
5592: . setBC   - The flag determining whether to include indices of bounsary values
5593: . perm    - A permutation of the dofs on this point, or NULL
5594: - indperm - A permutation of the entire indices array, or NULL

5596:   Output Parameter:
5597: . indices - Indices for dofs on this point

5599:   Level: developer

5601:   Note: The indices could be local or global, depending on the value of 'off'.
5602: */
5603: PetscErrorCode DMPlexGetIndicesPoint_Internal(PetscSection section, PetscBool islocal,PetscInt point, PetscInt off, PetscInt *loff, PetscBool setBC, const PetscInt perm[], const PetscInt indperm[], PetscInt indices[])
5604: {
5605:   PetscInt        dof;   /* The number of unknowns on this point */
5606:   PetscInt        cdof;  /* The number of constraints on this point */
5607:   const PetscInt *cdofs; /* The indices of the constrained dofs on this point */
5608:   PetscInt        cind = 0, k;
5609:   PetscErrorCode  ierr;

5612:   if (!islocal && setBC) SETERRQ(PetscObjectComm((PetscObject)section),PETSC_ERR_ARG_INCOMP,"setBC incompatible with global indices; use a local section or disable setBC");
5613:   PetscSectionGetDof(section, point, &dof);
5614:   PetscSectionGetConstraintDof(section, point, &cdof);
5615:   if (!cdof || setBC) {
5616:     for (k = 0; k < dof; ++k) {
5617:       const PetscInt preind = perm ? *loff+perm[k] : *loff+k;
5618:       const PetscInt ind    = indperm ? indperm[preind] : preind;

5620:       indices[ind] = off + k;
5621:     }
5622:   } else {
5623:     PetscSectionGetConstraintIndices(section, point, &cdofs);
5624:     for (k = 0; k < dof; ++k) {
5625:       const PetscInt preind = perm ? *loff+perm[k] : *loff+k;
5626:       const PetscInt ind    = indperm ? indperm[preind] : preind;

5628:       if ((cind < cdof) && (k == cdofs[cind])) {
5629:         /* Insert check for returning constrained indices */
5630:         indices[ind] = -(off+k+1);
5631:         ++cind;
5632:       } else {
5633:         indices[ind] = off + k - (islocal ? 0 : cind);
5634:       }
5635:     }
5636:   }
5637:   *loff += dof;
5638:   return(0);
5639: }

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

5644:  Input Parameters:
5645: + section - a section (global or local)
5646: - islocal - PETSC_TRUE if requesting local indices (i.e., section is local); PETSC_FALSE for global
5647: . point - point within section
5648: . off - The offset of this point in the (local or global) indexed space - should match islocal and (usually) the section
5649: . foffs - array of length numFields containing the offset in canonical point ordering (the location in indices) of each field
5650: . setBC - identify constrained (boundary condition) points via involution.
5651: . perms - perms[f][permsoff][:] is a permutation of dofs within each field
5652: . permsoff - offset
5653: - indperm - index permutation

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

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

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

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

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

5678:  Level: developer
5679: */
5680: 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[])
5681: {
5682:   PetscInt       numFields, foff, f;

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

5694:     PetscSectionGetFieldDof(section, point, f, &fdof);
5695:     PetscSectionGetFieldConstraintDof(section, point, f, &cfdof);
5696:     if (!cfdof || setBC) {
5697:       for (b = 0; b < fdof; ++b) {
5698:         const PetscInt preind = perm ? foffs[f]+perm[b] : foffs[f]+b;
5699:         const PetscInt ind    = indperm ? indperm[preind] : preind;

5701:         indices[ind] = off+foff+b;
5702:       }
5703:     } else {
5704:       PetscSectionGetFieldConstraintIndices(section, point, f, &fcdofs);
5705:       for (b = 0; b < fdof; ++b) {
5706:         const PetscInt preind = perm ? foffs[f]+perm[b] : foffs[f]+b;
5707:         const PetscInt ind    = indperm ? indperm[preind] : preind;

5709:         if ((cind < cfdof) && (b == fcdofs[cind])) {
5710:           indices[ind] = -(off+foff+b+1);
5711:           ++cind;
5712:         } else {
5713:           indices[ind] = off + foff + b - (islocal ? 0 : cind);
5714:         }
5715:       }
5716:     }
5717:     foff     += (setBC || islocal ? fdof : (fdof - cfdof));
5718:     foffs[f] += fdof;
5719:   }
5720:   return(0);
5721: }

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

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

5728:  Notes:
5729:  The semantics of this function relate to that of setBC=FALSE in DMPlexGetIndicesPointFields_Internal.
5730:  Since this function uses global indices, setBC=TRUE would be invalid, so no such argument exists.
5731: */
5732: static PetscErrorCode DMPlexGetIndicesPointFieldsSplit_Internal(PetscSection section, PetscSection globalSection, PetscInt point, PetscInt foffs[], const PetscInt ***perms, PetscInt permsoff, const PetscInt indperm[], PetscInt indices[])
5733: {
5734:   PetscInt       numFields, foff, f;

5738:   PetscSectionGetNumFields(section, &numFields);
5739:   for (f = 0; f < numFields; ++f) {
5740:     PetscInt        fdof, cfdof;
5741:     const PetscInt *fcdofs; /* The indices of the constrained dofs for field f on this point */
5742:     PetscInt        cind = 0, b;
5743:     const PetscInt  *perm = (perms && perms[f]) ? perms[f][permsoff] : NULL;

5745:     PetscSectionGetFieldDof(section, point, f, &fdof);
5746:     PetscSectionGetFieldConstraintDof(section, point, f, &cfdof);
5747:     PetscSectionGetFieldOffset(globalSection, point, f, &foff);
5748:     if (!cfdof) {
5749:       for (b = 0; b < fdof; ++b) {
5750:         const PetscInt preind = perm ? foffs[f]+perm[b] : foffs[f]+b;
5751:         const PetscInt ind    = indperm ? indperm[preind] : preind;

5753:         indices[ind] = foff+b;
5754:       }
5755:     } else {
5756:       PetscSectionGetFieldConstraintIndices(section, point, f, &fcdofs);
5757:       for (b = 0; b < fdof; ++b) {
5758:         const PetscInt preind = perm ? foffs[f]+perm[b] : foffs[f]+b;
5759:         const PetscInt ind    = indperm ? indperm[preind] : preind;

5761:         if ((cind < cfdof) && (b == fcdofs[cind])) {
5762:           indices[ind] = -(foff+b+1);
5763:           ++cind;
5764:         } else {
5765:           indices[ind] = foff+b-cind;
5766:         }
5767:       }
5768:     }
5769:     foffs[f] += fdof;
5770:   }
5771:   return(0);
5772: }

5774: 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)
5775: {
5776:   Mat             cMat;
5777:   PetscSection    aSec, cSec;
5778:   IS              aIS;
5779:   PetscInt        aStart = -1, aEnd = -1;
5780:   const PetscInt  *anchors;
5781:   PetscInt        numFields, f, p, q, newP = 0;
5782:   PetscInt        newNumPoints = 0, newNumIndices = 0;
5783:   PetscInt        *newPoints, *indices, *newIndices;
5784:   PetscInt        maxAnchor, maxDof;
5785:   PetscInt        newOffsets[32];
5786:   PetscInt        *pointMatOffsets[32];
5787:   PetscInt        *newPointOffsets[32];
5788:   PetscScalar     *pointMat[32];
5789:   PetscScalar     *newValues=NULL,*tmpValues;
5790:   PetscBool       anyConstrained = PETSC_FALSE;
5791:   PetscErrorCode  ierr;

5796:   PetscSectionGetNumFields(section, &numFields);

5798:   DMPlexGetAnchors(dm,&aSec,&aIS);
5799:   /* if there are point-to-point constraints */
5800:   if (aSec) {
5801:     PetscArrayzero(newOffsets, 32);
5802:     ISGetIndices(aIS,&anchors);
5803:     PetscSectionGetChart(aSec,&aStart,&aEnd);
5804:     /* figure out how many points are going to be in the new element matrix
5805:      * (we allow double counting, because it's all just going to be summed
5806:      * into the global matrix anyway) */
5807:     for (p = 0; p < 2*numPoints; p+=2) {
5808:       PetscInt b    = points[p];
5809:       PetscInt bDof = 0, bSecDof;

5811:       PetscSectionGetDof(section,b,&bSecDof);
5812:       if (!bSecDof) {
5813:         continue;
5814:       }
5815:       if (b >= aStart && b < aEnd) {
5816:         PetscSectionGetDof(aSec,b,&bDof);
5817:       }
5818:       if (bDof) {
5819:         /* this point is constrained */
5820:         /* it is going to be replaced by its anchors */
5821:         PetscInt bOff, q;

5823:         anyConstrained = PETSC_TRUE;
5824:         newNumPoints  += bDof;
5825:         PetscSectionGetOffset(aSec,b,&bOff);
5826:         for (q = 0; q < bDof; q++) {
5827:           PetscInt a = anchors[bOff + q];
5828:           PetscInt aDof;

5830:           PetscSectionGetDof(section,a,&aDof);
5831:           newNumIndices += aDof;
5832:           for (f = 0; f < numFields; ++f) {
5833:             PetscInt fDof;

5835:             PetscSectionGetFieldDof(section, a, f, &fDof);
5836:             newOffsets[f+1] += fDof;
5837:           }
5838:         }
5839:       }
5840:       else {
5841:         /* this point is not constrained */
5842:         newNumPoints++;
5843:         newNumIndices += bSecDof;
5844:         for (f = 0; f < numFields; ++f) {
5845:           PetscInt fDof;

5847:           PetscSectionGetFieldDof(section, b, f, &fDof);
5848:           newOffsets[f+1] += fDof;
5849:         }
5850:       }
5851:     }
5852:   }
5853:   if (!anyConstrained) {
5854:     if (outNumPoints)  *outNumPoints  = 0;
5855:     if (outNumIndices) *outNumIndices = 0;
5856:     if (outPoints)     *outPoints     = NULL;
5857:     if (outValues)     *outValues     = NULL;
5858:     if (aSec) {ISRestoreIndices(aIS,&anchors);}
5859:     return(0);
5860:   }

5862:   if (outNumPoints)  *outNumPoints  = newNumPoints;
5863:   if (outNumIndices) *outNumIndices = newNumIndices;

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

5867:   if (!outPoints && !outValues) {
5868:     if (offsets) {
5869:       for (f = 0; f <= numFields; f++) {
5870:         offsets[f] = newOffsets[f];
5871:       }
5872:     }
5873:     if (aSec) {ISRestoreIndices(aIS,&anchors);}
5874:     return(0);
5875:   }

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

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

5881:   /* workspaces */
5882:   if (numFields) {
5883:     for (f = 0; f < numFields; f++) {
5884:       DMGetWorkArray(dm,numPoints+1,MPIU_INT,&pointMatOffsets[f]);
5885:       DMGetWorkArray(dm,numPoints+1,MPIU_INT,&newPointOffsets[f]);
5886:     }
5887:   }
5888:   else {
5889:     DMGetWorkArray(dm,numPoints+1,MPIU_INT,&pointMatOffsets[0]);
5890:     DMGetWorkArray(dm,numPoints,MPIU_INT,&newPointOffsets[0]);
5891:   }

5893:   /* get workspaces for the point-to-point matrices */
5894:   if (numFields) {
5895:     PetscInt totalOffset, totalMatOffset;

5897:     for (p = 0; p < numPoints; p++) {
5898:       PetscInt b    = points[2*p];
5899:       PetscInt bDof = 0, bSecDof;

5901:       PetscSectionGetDof(section,b,&bSecDof);
5902:       if (!bSecDof) {
5903:         for (f = 0; f < numFields; f++) {
5904:           newPointOffsets[f][p + 1] = 0;
5905:           pointMatOffsets[f][p + 1] = 0;
5906:         }
5907:         continue;
5908:       }
5909:       if (b >= aStart && b < aEnd) {
5910:         PetscSectionGetDof(aSec, b, &bDof);
5911:       }
5912:       if (bDof) {
5913:         for (f = 0; f < numFields; f++) {
5914:           PetscInt fDof, q, bOff, allFDof = 0;

5916:           PetscSectionGetFieldDof(section, b, f, &fDof);
5917:           PetscSectionGetOffset(aSec, b, &bOff);
5918:           for (q = 0; q < bDof; q++) {
5919:             PetscInt a = anchors[bOff + q];
5920:             PetscInt aFDof;

5922:             PetscSectionGetFieldDof(section, a, f, &aFDof);
5923:             allFDof += aFDof;
5924:           }
5925:           newPointOffsets[f][p+1] = allFDof;
5926:           pointMatOffsets[f][p+1] = fDof * allFDof;
5927:         }
5928:       }
5929:       else {
5930:         for (f = 0; f < numFields; f++) {
5931:           PetscInt fDof;

5933:           PetscSectionGetFieldDof(section, b, f, &fDof);
5934:           newPointOffsets[f][p+1] = fDof;
5935:           pointMatOffsets[f][p+1] = 0;
5936:         }
5937:       }
5938:     }
5939:     for (f = 0, totalOffset = 0, totalMatOffset = 0; f < numFields; f++) {
5940:       newPointOffsets[f][0] = totalOffset;
5941:       pointMatOffsets[f][0] = totalMatOffset;
5942:       for (p = 0; p < numPoints; p++) {
5943:         newPointOffsets[f][p+1] += newPointOffsets[f][p];
5944:         pointMatOffsets[f][p+1] += pointMatOffsets[f][p];
5945:       }
5946:       totalOffset    = newPointOffsets[f][numPoints];
5947:       totalMatOffset = pointMatOffsets[f][numPoints];
5948:       DMGetWorkArray(dm,pointMatOffsets[f][numPoints],MPIU_SCALAR,&pointMat[f]);
5949:     }
5950:   }
5951:   else {
5952:     for (p = 0; p < numPoints; p++) {
5953:       PetscInt b    = points[2*p];
5954:       PetscInt bDof = 0, bSecDof;

5956:       PetscSectionGetDof(section,b,&bSecDof);
5957:       if (!bSecDof) {
5958:         newPointOffsets[0][p + 1] = 0;
5959:         pointMatOffsets[0][p + 1] = 0;
5960:         continue;
5961:       }
5962:       if (b >= aStart && b < aEnd) {
5963:         PetscSectionGetDof(aSec, b, &bDof);
5964:       }
5965:       if (bDof) {
5966:         PetscInt bOff, q, allDof = 0;

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

5972:           PetscSectionGetDof(section, a, &aDof);
5973:           allDof += aDof;
5974:         }
5975:         newPointOffsets[0][p+1] = allDof;
5976:         pointMatOffsets[0][p+1] = bSecDof * allDof;
5977:       }
5978:       else {
5979:         newPointOffsets[0][p+1] = bSecDof;
5980:         pointMatOffsets[0][p+1] = 0;
5981:       }
5982:     }
5983:     newPointOffsets[0][0] = 0;
5984:     pointMatOffsets[0][0] = 0;
5985:     for (p = 0; p < numPoints; p++) {
5986:       newPointOffsets[0][p+1] += newPointOffsets[0][p];
5987:       pointMatOffsets[0][p+1] += pointMatOffsets[0][p];
5988:     }
5989:     DMGetWorkArray(dm,pointMatOffsets[0][numPoints],MPIU_SCALAR,&pointMat[0]);
5990:   }

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

5995:   /* get the point-to-point matrices; construct newPoints */
5996:   PetscSectionGetMaxDof(aSec, &maxAnchor);
5997:   PetscSectionGetMaxDof(section, &maxDof);
5998:   DMGetWorkArray(dm,maxDof,MPIU_INT,&indices);
5999:   DMGetWorkArray(dm,maxAnchor*maxDof,MPIU_INT,&newIndices);
6000:   if (numFields) {
6001:     for (p = 0, newP = 0; p < numPoints; p++) {
6002:       PetscInt b    = points[2*p];
6003:       PetscInt o    = points[2*p+1];
6004:       PetscInt bDof = 0, bSecDof;

6006:       PetscSectionGetDof(section, b, &bSecDof);
6007:       if (!bSecDof) {
6008:         continue;
6009:       }
6010:       if (b >= aStart && b < aEnd) {
6011:         PetscSectionGetDof(aSec, b, &bDof);
6012:       }
6013:       if (bDof) {
6014:         PetscInt fStart[32], fEnd[32], fAnchorStart[32], fAnchorEnd[32], bOff, q;

6016:         fStart[0] = 0;
6017:         fEnd[0]   = 0;
6018:         for (f = 0; f < numFields; f++) {
6019:           PetscInt fDof;

6021:           PetscSectionGetFieldDof(cSec, b, f, &fDof);
6022:           fStart[f+1] = fStart[f] + fDof;
6023:           fEnd[f+1]   = fStart[f+1];
6024:         }
6025:         PetscSectionGetOffset(cSec, b, &bOff);
6026:         DMPlexGetIndicesPointFields_Internal(cSec, PETSC_TRUE, b, bOff, fEnd, PETSC_TRUE, perms, p, NULL, indices);

6028:         fAnchorStart[0] = 0;
6029:         fAnchorEnd[0]   = 0;
6030:         for (f = 0; f < numFields; f++) {
6031:           PetscInt fDof = newPointOffsets[f][p + 1] - newPointOffsets[f][p];

6033:           fAnchorStart[f+1] = fAnchorStart[f] + fDof;
6034:           fAnchorEnd[f+1]   = fAnchorStart[f + 1];
6035:         }
6036:         PetscSectionGetOffset(aSec, b, &bOff);
6037:         for (q = 0; q < bDof; q++) {
6038:           PetscInt a = anchors[bOff + q], aOff;

6040:           /* we take the orientation of ap into account in the order that we constructed the indices above: the newly added points have no orientation */
6041:           newPoints[2*(newP + q)]     = a;
6042:           newPoints[2*(newP + q) + 1] = 0;
6043:           PetscSectionGetOffset(section, a, &aOff);
6044:           DMPlexGetIndicesPointFields_Internal(section, PETSC_TRUE, a, aOff, fAnchorEnd, PETSC_TRUE, NULL, -1, NULL, newIndices);
6045:         }
6046:         newP += bDof;

6048:         if (outValues) {
6049:           /* get the point-to-point submatrix */
6050:           for (f = 0; f < numFields; f++) {
6051:             MatGetValues(cMat,fEnd[f]-fStart[f],indices + fStart[f],fAnchorEnd[f] - fAnchorStart[f],newIndices + fAnchorStart[f],pointMat[f] + pointMatOffsets[f][p]);
6052:           }
6053:         }
6054:       }
6055:       else {
6056:         newPoints[2 * newP]     = b;
6057:         newPoints[2 * newP + 1] = o;
6058:         newP++;
6059:       }
6060:     }
6061:   } else {
6062:     for (p = 0; p < numPoints; p++) {
6063:       PetscInt b    = points[2*p];
6064:       PetscInt o    = points[2*p+1];
6065:       PetscInt bDof = 0, bSecDof;

6067:       PetscSectionGetDof(section, b, &bSecDof);
6068:       if (!bSecDof) {
6069:         continue;
6070:       }
6071:       if (b >= aStart && b < aEnd) {
6072:         PetscSectionGetDof(aSec, b, &bDof);
6073:       }
6074:       if (bDof) {
6075:         PetscInt bEnd = 0, bAnchorEnd = 0, bOff;

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

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

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

6086:           newPoints[2*(newP + q)]     = a;
6087:           newPoints[2*(newP + q) + 1] = 0;
6088:           PetscSectionGetOffset(section, a, &aOff);
6089:           DMPlexGetIndicesPoint_Internal(section, PETSC_TRUE, a, aOff, &bAnchorEnd, PETSC_TRUE, NULL, NULL, newIndices);
6090:         }
6091:         newP += bDof;

6093:         /* get the point-to-point submatrix */
6094:         if (outValues) {
6095:           MatGetValues(cMat,bEnd,indices,bAnchorEnd,newIndices,pointMat[0] + pointMatOffsets[0][p]);
6096:         }
6097:       }
6098:       else {
6099:         newPoints[2 * newP]     = b;
6100:         newPoints[2 * newP + 1] = o;
6101:         newP++;
6102:       }
6103:     }
6104:   }

6106:   if (outValues) {
6107:     DMGetWorkArray(dm,newNumIndices*numIndices,MPIU_SCALAR,&tmpValues);
6108:     PetscArrayzero(tmpValues,newNumIndices*numIndices);
6109:     /* multiply constraints on the right */
6110:     if (numFields) {
6111:       for (f = 0; f < numFields; f++) {
6112:         PetscInt oldOff = offsets[f];

6114:         for (p = 0; p < numPoints; p++) {
6115:           PetscInt cStart = newPointOffsets[f][p];
6116:           PetscInt b      = points[2 * p];
6117:           PetscInt c, r, k;
6118:           PetscInt dof;

6120:           PetscSectionGetFieldDof(section,b,f,&dof);
6121:           if (!dof) {
6122:             continue;
6123:           }
6124:           if (pointMatOffsets[f][p] < pointMatOffsets[f][p + 1]) {
6125:             PetscInt nCols         = newPointOffsets[f][p+1]-cStart;
6126:             const PetscScalar *mat = pointMat[f] + pointMatOffsets[f][p];

6128:             for (r = 0; r < numIndices; r++) {
6129:               for (c = 0; c < nCols; c++) {
6130:                 for (k = 0; k < dof; k++) {
6131:                   tmpValues[r * newNumIndices + cStart + c] += values[r * numIndices + oldOff + k] * mat[k * nCols + c];
6132:                 }
6133:               }
6134:             }
6135:           }
6136:           else {
6137:             /* copy this column as is */
6138:             for (r = 0; r < numIndices; r++) {
6139:               for (c = 0; c < dof; c++) {
6140:                 tmpValues[r * newNumIndices + cStart + c] = values[r * numIndices + oldOff + c];
6141:               }
6142:             }
6143:           }
6144:           oldOff += dof;
6145:         }
6146:       }
6147:     }
6148:     else {
6149:       PetscInt oldOff = 0;
6150:       for (p = 0; p < numPoints; p++) {
6151:         PetscInt cStart = newPointOffsets[0][p];
6152:         PetscInt b      = points[2 * p];
6153:         PetscInt c, r, k;
6154:         PetscInt dof;

6156:         PetscSectionGetDof(section,b,&dof);
6157:         if (!dof) {
6158:           continue;
6159:         }
6160:         if (pointMatOffsets[0][p] < pointMatOffsets[0][p + 1]) {
6161:           PetscInt nCols         = newPointOffsets[0][p+1]-cStart;
6162:           const PetscScalar *mat = pointMat[0] + pointMatOffsets[0][p];

6164:           for (r = 0; r < numIndices; r++) {
6165:             for (c = 0; c < nCols; c++) {
6166:               for (k = 0; k < dof; k++) {
6167:                 tmpValues[r * newNumIndices + cStart + c] += mat[k * nCols + c] * values[r * numIndices + oldOff + k];
6168:               }
6169:             }
6170:           }
6171:         }
6172:         else {
6173:           /* copy this column as is */
6174:           for (r = 0; r < numIndices; r++) {
6175:             for (c = 0; c < dof; c++) {
6176:               tmpValues[r * newNumIndices + cStart + c] = values[r * numIndices + oldOff + c];
6177:             }
6178:           }
6179:         }
6180:         oldOff += dof;
6181:       }
6182:     }

6184:     if (multiplyLeft) {
6185:       DMGetWorkArray(dm,newNumIndices*newNumIndices,MPIU_SCALAR,&newValues);
6186:       PetscArrayzero(newValues,newNumIndices*newNumIndices);
6187:       /* multiply constraints transpose on the left */
6188:       if (numFields) {
6189:         for (f = 0; f < numFields; f++) {
6190:           PetscInt oldOff = offsets[f];

6192:           for (p = 0; p < numPoints; p++) {
6193:             PetscInt rStart = newPointOffsets[f][p];
6194:             PetscInt b      = points[2 * p];
6195:             PetscInt c, r, k;
6196:             PetscInt dof;

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

6203:               for (r = 0; r < nRows; r++) {
6204:                 for (c = 0; c < newNumIndices; c++) {
6205:                   for (k = 0; k < dof; k++) {
6206:                     newValues[(rStart + r) * newNumIndices + c] += mat[k * nRows + r] * tmpValues[(oldOff + k) * newNumIndices + c];
6207:                   }
6208:                 }
6209:               }
6210:             }
6211:             else {
6212:               /* copy this row as is */
6213:               for (r = 0; r < dof; r++) {
6214:                 for (c = 0; c < newNumIndices; c++) {
6215:                   newValues[(rStart + r) * newNumIndices + c] = tmpValues[(oldOff + r) * newNumIndices + c];
6216:                 }
6217:               }
6218:             }
6219:             oldOff += dof;
6220:           }
6221:         }
6222:       }
6223:       else {
6224:         PetscInt oldOff = 0;

6226:         for (p = 0; p < numPoints; p++) {
6227:           PetscInt rStart = newPointOffsets[0][p];
6228:           PetscInt b      = points[2 * p];
6229:           PetscInt c, r, k;
6230:           PetscInt dof;

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

6237:             for (r = 0; r < nRows; r++) {
6238:               for (c = 0; c < newNumIndices; c++) {
6239:                 for (k = 0; k < dof; k++) {
6240:                   newValues[(rStart + r) * newNumIndices + c] += mat[k * nRows + r] * tmpValues[(oldOff + k) * newNumIndices + c];
6241:                 }
6242:               }
6243:             }
6244:           }
6245:           else {
6246:             /* copy this row as is */
6247:             for (r = 0; r < dof; r++) {
6248:               for (c = 0; c < newNumIndices; c++) {
6249:                 newValues[(rStart + r) * newNumIndices + c] = tmpValues[(oldOff + r) * newNumIndices + c];
6250:               }
6251:             }
6252:           }
6253:           oldOff += dof;
6254:         }
6255:       }

6257:       DMRestoreWorkArray(dm,newNumIndices*numIndices,MPIU_SCALAR,&tmpValues);
6258:     }
6259:     else {
6260:       newValues = tmpValues;
6261:     }
6262:   }

6264:   /* clean up */
6265:   DMRestoreWorkArray(dm,maxDof,MPIU_INT,&indices);
6266:   DMRestoreWorkArray(dm,maxAnchor*maxDof,MPIU_INT,&newIndices);

6268:   if (numFields) {
6269:     for (f = 0; f < numFields; f++) {
6270:       DMRestoreWorkArray(dm,pointMatOffsets[f][numPoints],MPIU_SCALAR,&pointMat[f]);
6271:       DMRestoreWorkArray(dm,numPoints+1,MPIU_INT,&pointMatOffsets[f]);
6272:       DMRestoreWorkArray(dm,numPoints+1,MPIU_INT,&newPointOffsets[f]);
6273:     }
6274:   }
6275:   else {
6276:     DMRestoreWorkArray(dm,pointMatOffsets[0][numPoints],MPIU_SCALAR,&pointMat[0]);
6277:     DMRestoreWorkArray(dm,numPoints+1,MPIU_INT,&pointMatOffsets[0]);
6278:     DMRestoreWorkArray(dm,numPoints+1,MPIU_INT,&newPointOffsets[0]);
6279:   }
6280:   ISRestoreIndices(aIS,&anchors);

6282:   /* output */
6283:   if (outPoints) {
6284:     *outPoints = newPoints;
6285:   }
6286:   else {
6287:     DMRestoreWorkArray(dm,2*newNumPoints,MPIU_INT,&newPoints);
6288:   }
6289:   if (outValues) {
6290:     *outValues = newValues;
6291:   }
6292:   for (f = 0; f <= numFields; f++) {
6293:     offsets[f] = newOffsets[f];
6294:   }
6295:   return(0);
6296: }

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

6301:   Not collective

6303:   Input Parameters:
6304: + dm         - The DM
6305: . section    - The PetscSection describing the points (a local section)
6306: . idxSection - The PetscSection from which to obtain indices (may be local or global)
6307: . point      - The point defining the closure
6308: - useClPerm  - Use the closure point permutation if available

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

6316:   Notes:
6317:   Must call DMPlexRestoreClosureIndices() to free allocated memory

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

6325:   Level: advanced

6327: .seealso DMPlexRestoreClosureIndices(), DMPlexVecGetClosure(), DMPlexMatSetClosure(), DMGetLocalSection(), DMGetGlobalSection()
6328: @*/
6329: PetscErrorCode DMPlexGetClosureIndices(DM dm, PetscSection section, PetscSection idxSection, PetscInt point, PetscBool useClPerm,
6330:                                        PetscInt *numIndices, PetscInt *indices[], PetscInt outOffsets[], PetscScalar *values[])
6331: {
6332:   /* Closure ordering */
6333:   PetscSection        clSection;
6334:   IS                  clPoints;
6335:   const PetscInt     *clp;
6336:   PetscInt           *points;
6337:   const PetscInt     *clperm = NULL;
6338:   /* Dof permutation and sign flips */
6339:   const PetscInt    **perms[32] = {NULL};
6340:   const PetscScalar **flips[32] = {NULL};
6341:   PetscScalar        *valCopy   = NULL;
6342:   /* Hanging node constraints */
6343:   PetscInt           *pointsC = NULL;
6344:   PetscScalar        *valuesC = NULL;
6345:   PetscInt            NclC, NiC;

6347:   PetscInt           *idx;
6348:   PetscInt            Nf, Ncl, Ni = 0, offsets[32], p, f;
6349:   PetscBool           isLocal = (section == idxSection) ? PETSC_TRUE : PETSC_FALSE;
6350:   PetscErrorCode      ierr;

6360:   PetscSectionGetNumFields(section, &Nf);
6361:   if (Nf > 31) SETERRQ1(PetscObjectComm((PetscObject) dm), PETSC_ERR_ARG_OUTOFRANGE, "Number of fields %D limited to 31", Nf);
6362:   PetscArrayzero(offsets, 32);
6363:   /* 1) Get points in closure */
6364:   DMPlexGetCompressedClosure(dm, section, point, &Ncl, &points, &clSection, &clPoints, &clp);
6365:   if (useClPerm) {
6366:     PetscInt depth, clsize;
6367:     DMPlexGetPointDepth(dm, point, &depth);
6368:     for (clsize=0,p=0; p<Ncl; p++) {
6369:       PetscInt dof;
6370:       PetscSectionGetDof(section, points[2*p], &dof);
6371:       clsize += dof;
6372:     }
6373:     PetscSectionGetClosureInversePermutation_Internal(section, (PetscObject) dm, depth, clsize, &clperm);
6374:   }
6375:   /* 2) Get number of indices on these points and field offsets from section */
6376:   for (p = 0; p < Ncl*2; p += 2) {
6377:     PetscInt dof, fdof;

6379:     PetscSectionGetDof(section, points[p], &dof);
6380:     for (f = 0; f < Nf; ++f) {
6381:       PetscSectionGetFieldDof(section, points[p], f, &fdof);
6382:       offsets[f+1] += fdof;
6383:     }
6384:     Ni += dof;
6385:   }
6386:   for (f = 1; f < Nf; ++f) offsets[f+1] += offsets[f];
6387:   if (Nf && offsets[Nf] != Ni) SETERRQ2(PetscObjectComm((PetscObject) dm), PETSC_ERR_PLIB, "Invalid size for closure %D should be %D", offsets[Nf], Ni);
6388:   /* 3) Get symmetries and sign flips. Apply sign flips to values if passed in (only works for square values matrix) */
6389:   for (f = 0; f < PetscMax(1, Nf); ++f) {
6390:     if (Nf) {PetscSectionGetFieldPointSyms(section, f, Ncl, points, &perms[f], &flips[f]);}
6391:     else    {PetscSectionGetPointSyms(section, Ncl, points, &perms[f], &flips[f]);}
6392:     /* may need to apply sign changes to the element matrix */
6393:     if (values && flips[f]) {
6394:       PetscInt foffset = offsets[f];

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

6400:         if (!Nf) {PetscSectionGetDof(section, pnt, &fdof);}
6401:         else     {PetscSectionGetFieldDof(section, pnt, f, &fdof);}
6402:         if (flip) {
6403:           PetscInt i, j, k;

6405:           if (!valCopy) {
6406:             DMGetWorkArray(dm, Ni*Ni, MPIU_SCALAR, &valCopy);
6407:             for (j = 0; j < Ni * Ni; ++j) valCopy[j] = (*values)[j];
6408:             *values = valCopy;
6409:           }
6410:           for (i = 0; i < fdof; ++i) {
6411:             PetscScalar fval = flip[i];

6413:             for (k = 0; k < Ni; ++k) {
6414:               valCopy[Ni * (foffset + i) + k] *= fval;
6415:               valCopy[Ni * k + (foffset + i)] *= fval;
6416:             }
6417:           }
6418:         }
6419:         foffset += fdof;
6420:       }
6421:     }
6422:   }
6423:   /* 4) Apply hanging node constraints. Get new symmetries and replace all storage with constrained storage */
6424:   DMPlexAnchorsModifyMat(dm, section, Ncl, Ni, points, perms, values ? *values : NULL, &NclC, &NiC, &pointsC, values ? &valuesC : NULL, offsets, PETSC_TRUE);
6425:   if (NclC) {
6426:     if (valCopy) {DMRestoreWorkArray(dm, Ni*Ni, MPIU_SCALAR, &valCopy);}
6427:     for (f = 0; f < PetscMax(1, Nf); ++f) {
6428:       if (Nf) {PetscSectionRestoreFieldPointSyms(section, f, Ncl, points, &perms[f], &flips[f]);}
6429:       else    {PetscSectionRestorePointSyms(section, Ncl, points, &perms[f], &flips[f]);}
6430:     }
6431:     for (f = 0; f < PetscMax(1, Nf); ++f) {
6432:       if (Nf) {PetscSectionGetFieldPointSyms(section, f, NclC, pointsC, &perms[f], &flips[f]);}
6433:       else    {PetscSectionGetPointSyms(section, NclC, pointsC, &perms[f], &flips[f]);}
6434:     }
6435:     DMPlexRestoreCompressedClosure(dm, section, point, &Ncl, &points, &clSection, &clPoints, &clp);
6436:     Ncl     = NclC;
6437:     Ni      = NiC;
6438:     points  = pointsC;
6439:     if (values) *values = valuesC;
6440:   }
6441:   /* 5) Calculate indices */
6442:   DMGetWorkArray(dm, Ni, MPIU_INT, &idx);
6443:   if (Nf) {
6444:     PetscInt  idxOff;
6445:     PetscBool useFieldOffsets;

6447:     if (outOffsets) {for (f = 0; f <= Nf; f++) outOffsets[f] = offsets[f];}
6448:     PetscSectionGetUseFieldOffsets(idxSection, &useFieldOffsets);
6449:     if (useFieldOffsets) {
6450:       for (p = 0; p < Ncl; ++p) {
6451:         const PetscInt pnt = points[p*2];

6453:         DMPlexGetIndicesPointFieldsSplit_Internal(section, idxSection, pnt, offsets, perms, p, clperm, idx);
6454:       }
6455:     } else {
6456:       for (p = 0; p < Ncl; ++p) {
6457:         const PetscInt pnt = points[p*2];

6459:         PetscSectionGetOffset(idxSection, pnt, &idxOff);
6460:         /* Note that we pass a local section even though we're using global offsets.  This is because global sections do
6461:          * not (at the time of this writing) have fields set. They probably should, in which case we would pass the
6462:          * global section. */
6463:         DMPlexGetIndicesPointFields_Internal(section, isLocal, pnt, idxOff < 0 ? -(idxOff+1) : idxOff, offsets, PETSC_FALSE, perms, p, clperm, idx);
6464:       }
6465:     }
6466:   } else {
6467:     PetscInt off = 0, idxOff;

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

6473:       PetscSectionGetOffset(idxSection, pnt, &idxOff);
6474:       /* Note that we pass a local section even though we're using global offsets.  This is because global sections do
6475:        * not (at the time of this writing) have fields set. They probably should, in which case we would pass the global section. */
6476:       DMPlexGetIndicesPoint_Internal(section, isLocal, pnt, idxOff < 0 ? -(idxOff+1) : idxOff, &off, PETSC_FALSE, perm, clperm, idx);
6477:     }
6478:   }
6479:   /* 6) Cleanup */
6480:   for (f = 0; f < PetscMax(1, Nf); ++f) {
6481:     if (Nf) {PetscSectionRestoreFieldPointSyms(section, f, Ncl, points, &perms[f], &flips[f]);}
6482:     else    {PetscSectionRestorePointSyms(section, Ncl, points, &perms[f], &flips[f]);}
6483:   }
6484:   if (NclC) {
6485:     DMRestoreWorkArray(dm, NclC*2, MPIU_INT, &pointsC);
6486:   } else {
6487:     DMPlexRestoreCompressedClosure(dm, section, point, &Ncl, &points, &clSection, &clPoints, &clp);
6488:   }

6490:   if (numIndices) *numIndices = Ni;
6491:   if (indices)    *indices    = idx;
6492:   return(0);
6493: }

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

6498:   Not collective

6500:   Input Parameters:
6501: + dm         - The DM
6502: . section    - The PetscSection describing the points (a local section)
6503: . idxSection - The PetscSection from which to obtain indices (may be local or global)
6504: . point      - The point defining the closure
6505: - useClPerm  - Use the closure point permutation if available

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

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

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

6522:   Level: advanced

6524: .seealso DMPlexGetClosureIndices(), DMPlexVecGetClosure(), DMPlexMatSetClosure(), DMGetLocalSection(), DMGetGlobalSection()
6525: @*/
6526: PetscErrorCode DMPlexRestoreClosureIndices(DM dm, PetscSection section, PetscSection idxSection, PetscInt point, PetscBool useClPerm,
6527:                                            PetscInt *numIndices, PetscInt *indices[], PetscInt outOffsets[], PetscScalar *values[])
6528: {

6534:   DMRestoreWorkArray(dm, 0, MPIU_INT, indices);
6535:   return(0);
6536: }

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

6541:   Not collective

6543:   Input Parameters:
6544: + dm - The DM
6545: . section - The section describing the layout in v, or NULL to use the default section
6546: . globalSection - The section describing the layout in v, or NULL to use the default global section
6547: . A - The matrix
6548: . point - The point in the DM
6549: . values - The array of values
6550: - mode - The insert mode, where INSERT_ALL_VALUES and ADD_ALL_VALUES also overwrite boundary conditions

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

6555:   Level: intermediate

6557: .seealso DMPlexMatSetClosureGeneral(), DMPlexVecGetClosure(), DMPlexVecSetClosure()
6558: @*/
6559: PetscErrorCode DMPlexMatSetClosure(DM dm, PetscSection section, PetscSection globalSection, Mat A, PetscInt point, const PetscScalar values[], InsertMode mode)
6560: {
6561:   DM_Plex           *mesh = (DM_Plex*) dm->data;
6562:   PetscInt          *indices;
6563:   PetscInt           numIndices;
6564:   const PetscScalar *valuesOrig = values;
6565:   PetscErrorCode     ierr;

6569:   if (!section) {DMGetLocalSection(dm, &section);}
6571:   if (!globalSection) {DMGetGlobalSection(dm, &globalSection);}

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

6577:   if (mesh->printSetValues) {DMPlexPrintMatSetValues(PETSC_VIEWER_STDOUT_SELF, A, point, numIndices, indices, 0, NULL, values);}
6578:   MatSetValues(A, numIndices, indices, numIndices, indices, values, mode);
6579:   if (ierr) {
6580:     PetscMPIInt    rank;
6581:     PetscErrorCode ierr2;

6583:     ierr2 = MPI_Comm_rank(PetscObjectComm((PetscObject)A), &rank);CHKERRQ(ierr2);
6584:     ierr2 = (*PetscErrorPrintf)("[%d]ERROR in DMPlexMatSetClosure\n", rank);CHKERRQ(ierr2);
6585:     ierr2 = DMPlexPrintMatSetValues(PETSC_VIEWER_STDERR_SELF, A, point, numIndices, indices, 0, NULL, values);CHKERRQ(ierr2);
6586:     ierr2 = DMPlexRestoreClosureIndices(dm, section, globalSection, point, PETSC_TRUE, &numIndices, &indices, NULL, (PetscScalar **) &values);CHKERRQ(ierr2);
6587:     if (values != valuesOrig) {ierr2 = DMRestoreWorkArray(dm, 0, MPIU_SCALAR, &values);CHKERRQ(ierr2);}
6588:     
6589:   }
6590:   if (mesh->printFEM > 1) {
6591:     PetscInt i;
6592:     PetscPrintf(PETSC_COMM_SELF, "  Indices:");
6593:     for (i = 0; i < numIndices; ++i) {PetscPrintf(PETSC_COMM_SELF, " %D", indices[i]);}
6594:     PetscPrintf(PETSC_COMM_SELF, "\n");
6595:   }

6597:   DMPlexRestoreClosureIndices(dm, section, globalSection, point, PETSC_TRUE, &numIndices, &indices, NULL, (PetscScalar **) &values);
6598:   if (values != valuesOrig) {DMRestoreWorkArray(dm, 0, MPIU_SCALAR, &values);}
6599:   return(0);
6600: }

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

6605:   Not collective

6607:   Input Parameters:
6608: + dmRow - The DM for the row fields
6609: . sectionRow - The section describing the layout, or NULL to use the default section in dmRow
6610: . globalSectionRow - The section describing the layout, or NULL to use the default global section in dmRow
6611: . dmCol - The DM for the column fields
6612: . sectionCol - The section describing the layout, or NULL to use the default section in dmCol
6613: . globalSectionCol - The section describing the layout, or NULL to use the default global section in dmCol
6614: . A - The matrix
6615: . point - The point in the DMs
6616: . values - The array of values
6617: - mode - The insert mode, where INSERT_ALL_VALUES and ADD_ALL_VALUES also overwrite boundary conditions

6619:   Level: intermediate

6621: .seealso DMPlexMatSetClosure(), DMPlexVecGetClosure(), DMPlexVecSetClosure()
6622: @*/
6623: PetscErrorCode DMPlexMatSetClosureGeneral(DM dmRow, PetscSection sectionRow, PetscSection globalSectionRow, DM dmCol, PetscSection sectionCol, PetscSection globalSectionCol, Mat A, PetscInt point, const PetscScalar values[], InsertMode mode)
6624: {
6625:   DM_Plex           *mesh = (DM_Plex*) dmRow->data;
6626:   PetscInt          *indicesRow, *indicesCol;
6627:   PetscInt           numIndicesRow, numIndicesCol;
6628:   const PetscScalar *valuesOrig = values;
6629:   PetscErrorCode     ierr;

6633:   if (!sectionRow) {DMGetLocalSection(dmRow, &sectionRow);}
6635:   if (!globalSectionRow) {DMGetGlobalSection(dmRow, &globalSectionRow);}
6638:   if (!sectionCol) {DMGetLocalSection(dmCol, &sectionCol);}
6640:   if (!globalSectionCol) {DMGetGlobalSection(dmCol, &globalSectionCol);}

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

6647:   if (mesh->printSetValues) {DMPlexPrintMatSetValues(PETSC_VIEWER_STDOUT_SELF, A, point, numIndicesRow, indicesRow, numIndicesCol, indicesCol, values);}
6648:   MatSetValues(A, numIndicesRow, indicesRow, numIndicesCol, indicesCol, values, mode);
6649:   if (ierr) {
6650:     PetscMPIInt    rank;
6651:     PetscErrorCode ierr2;

6653:     ierr2 = MPI_Comm_rank(PetscObjectComm((PetscObject)A), &rank);CHKERRQ(ierr2);
6654:     ierr2 = (*PetscErrorPrintf)("[%d]ERROR in DMPlexMatSetClosure\n", rank);CHKERRQ(ierr2);
6655:     ierr2 = DMPlexPrintMatSetValues(PETSC_VIEWER_STDERR_SELF, A, point, numIndicesRow, indicesRow, numIndicesCol, indicesCol, values);CHKERRQ(ierr2);
6656:     ierr2 = DMPlexRestoreClosureIndices(dmRow, sectionRow, globalSectionRow, point, PETSC_TRUE, &numIndicesRow, &indicesRow, NULL, (PetscScalar **) &values);CHKERRQ(ierr2);
6657:     ierr2 = DMPlexRestoreClosureIndices(dmCol, sectionCol, globalSectionCol, point, PETSC_TRUE, &numIndicesCol, &indicesRow, NULL, (PetscScalar **) &values);CHKERRQ(ierr2);
6658:     if (values != valuesOrig) {ierr2 = DMRestoreWorkArray(dmRow, 0, MPIU_SCALAR, &values);CHKERRQ(ierr2);}
6659:     
6660:   }

6662:   DMPlexRestoreClosureIndices(dmRow, sectionRow, globalSectionRow, point, PETSC_TRUE, &numIndicesRow, &indicesRow, NULL, (PetscScalar **) &values);
6663:   DMPlexRestoreClosureIndices(dmCol, sectionCol, globalSectionCol, point, PETSC_TRUE, &numIndicesCol, &indicesCol, NULL, (PetscScalar **) &values);
6664:   if (values != valuesOrig) {DMRestoreWorkArray(dmRow, 0, MPIU_SCALAR, &values);}
6665:   return(0);
6666: }

6668: PetscErrorCode DMPlexMatSetClosureRefined(DM dmf, PetscSection fsection, PetscSection globalFSection, DM dmc, PetscSection csection, PetscSection globalCSection, Mat A, PetscInt point, const PetscScalar values[], InsertMode mode)
6669: {
6670:   DM_Plex        *mesh   = (DM_Plex*) dmf->data;
6671:   PetscInt       *fpoints = NULL, *ftotpoints = NULL;
6672:   PetscInt       *cpoints = NULL;
6673:   PetscInt       *findices, *cindices;
6674:   const PetscInt *fclperm = NULL, *cclperm = NULL; /* Closure permutations cannot work here */
6675:   PetscInt        foffsets[32], coffsets[32];
6676:   DMPolytopeType  ct;
6677:   PetscInt        numFields, numSubcells, maxFPoints, numFPoints, numCPoints, numFIndices, numCIndices, dof, off, globalOff, pStart, pEnd, p, q, r, s, f;
6678:   PetscErrorCode  ierr;

6683:   if (!fsection) {DMGetLocalSection(dmf, &fsection);}
6685:   if (!csection) {DMGetLocalSection(dmc, &csection);}
6687:   if (!globalFSection) {DMGetGlobalSection(dmf, &globalFSection);}
6689:   if (!globalCSection) {DMGetGlobalSection(dmc, &globalCSection);}
6692:   PetscSectionGetNumFields(fsection, &numFields);
6693:   if (numFields > 31) SETERRQ1(PetscObjectComm((PetscObject)dmf), PETSC_ERR_ARG_OUTOFRANGE, "Number of fields %D limited to 31", numFields);
6694:   PetscArrayzero(foffsets, 32);
6695:   PetscArrayzero(coffsets, 32);
6696:   /* Column indices */
6697:   DMPlexGetTransitiveClosure(dmc, point, PETSC_TRUE, &numCPoints, &cpoints);
6698:   maxFPoints = numCPoints;
6699:   /* Compress out points not in the section */
6700:   /*   TODO: Squeeze out points with 0 dof as well */
6701:   PetscSectionGetChart(csection, &pStart, &pEnd);
6702:   for (p = 0, q = 0; p < numCPoints*2; p += 2) {
6703:     if ((cpoints[p] >= pStart) && (cpoints[p] < pEnd)) {
6704:       cpoints[q*2]   = cpoints[p];
6705:       cpoints[q*2+1] = cpoints[p+1];
6706:       ++q;
6707:     }
6708:   }
6709:   numCPoints = q;
6710:   for (p = 0, numCIndices = 0; p < numCPoints*2; p += 2) {
6711:     PetscInt fdof;

6713:     PetscSectionGetDof(csection, cpoints[p], &dof);
6714:     if (!dof) continue;
6715:     for (f = 0; f < numFields; ++f) {
6716:       PetscSectionGetFieldDof(csection, cpoints[p], f, &fdof);
6717:       coffsets[f+1] += fdof;
6718:     }
6719:     numCIndices += dof;
6720:   }
6721:   for (f = 1; f < numFields; ++f) coffsets[f+1] += coffsets[f];
6722:   /* Row indices */
6723:   DMPlexGetCellType(dmc, point, &ct);
6724:   {
6725:     DMPlexCellRefiner cr;
6726:     DMPlexCellRefinerCreate(dmc, &cr);
6727:     DMPlexCellRefinerGetAffineTransforms(cr, ct, &numSubcells, NULL, NULL, NULL);
6728:     DMPlexCellRefinerDestroy(&cr);
6729:   }
6730:   DMGetWorkArray(dmf, maxFPoints*2*numSubcells, MPIU_INT, &ftotpoints);
6731:   for (r = 0, q = 0; r < numSubcells; ++r) {
6732:     /* TODO Map from coarse to fine cells */
6733:     DMPlexGetTransitiveClosure(dmf, point*numSubcells + r, PETSC_TRUE, &numFPoints, &fpoints);
6734:     /* Compress out points not in the section */
6735:     PetscSectionGetChart(fsection, &pStart, &pEnd);
6736:     for (p = 0; p < numFPoints*2; p += 2) {
6737:       if ((fpoints[p] >= pStart) && (fpoints[p] < pEnd)) {
6738:         PetscSectionGetDof(fsection, fpoints[p], &dof);
6739:         if (!dof) continue;
6740:         for (s = 0; s < q; ++s) if (fpoints[p] == ftotpoints[s*2]) break;
6741:         if (s < q) continue;
6742:         ftotpoints[q*2]   = fpoints[p];
6743:         ftotpoints[q*2+1] = fpoints[p+1];
6744:         ++q;
6745:       }
6746:     }
6747:     DMPlexRestoreTransitiveClosure(dmf, point, PETSC_TRUE, &numFPoints, &fpoints);
6748:   }
6749:   numFPoints = q;
6750:   for (p = 0, numFIndices = 0; p < numFPoints*2; p += 2) {
6751:     PetscInt fdof;

6753:     PetscSectionGetDof(fsection, ftotpoints[p], &dof);
6754:     if (!dof) continue;
6755:     for (f = 0; f < numFields; ++f) {
6756:       PetscSectionGetFieldDof(fsection, ftotpoints[p], f, &fdof);
6757:       foffsets[f+1] += fdof;
6758:     }
6759:     numFIndices += dof;
6760:   }
6761:   for (f = 1; f < numFields; ++f) foffsets[f+1] += foffsets[f];

6763:   if (numFields && foffsets[numFields] != numFIndices) SETERRQ2(PetscObjectComm((PetscObject)dmf), PETSC_ERR_PLIB, "Invalid size for closure %D should be %D", foffsets[numFields], numFIndices);
6764:   if (numFields && coffsets[numFields] != numCIndices) SETERRQ2(PetscObjectComm((PetscObject)dmc), PETSC_ERR_PLIB, "Invalid size for closure %D should be %D", coffsets[numFields], numCIndices);
6765:   DMGetWorkArray(dmf, numFIndices, MPIU_INT, &findices);
6766:   DMGetWorkArray(dmc, numCIndices, MPIU_INT, &cindices);
6767:   if (numFields) {
6768:     const PetscInt **permsF[32] = {NULL};
6769:     const PetscInt **permsC[32] = {NULL};

6771:     for (f = 0; f < numFields; f++) {
6772:       PetscSectionGetFieldPointSyms(fsection,f,numFPoints,ftotpoints,&permsF[f],NULL);
6773:       PetscSectionGetFieldPointSyms(csection,f,numCPoints,cpoints,&permsC[f],NULL);
6774:     }
6775:     for (p = 0; p < numFPoints; p++) {
6776:       PetscSectionGetOffset(globalFSection, ftotpoints[2*p], &globalOff);
6777:       DMPlexGetIndicesPointFields_Internal(fsection, PETSC_FALSE, ftotpoints[2*p], globalOff < 0 ? -(globalOff+1) : globalOff, foffsets, PETSC_FALSE, permsF, p, fclperm, findices);
6778:     }
6779:     for (p = 0; p < numCPoints; p++) {
6780:       PetscSectionGetOffset(globalCSection, cpoints[2*p], &globalOff);
6781:       DMPlexGetIndicesPointFields_Internal(csection, PETSC_FALSE, cpoints[2*p], globalOff < 0 ? -(globalOff+1) : globalOff, coffsets, PETSC_FALSE, permsC, p, cclperm, cindices);
6782:     }
6783:     for (f = 0; f < numFields; f++) {
6784:       PetscSectionRestoreFieldPointSyms(fsection,f,numFPoints,ftotpoints,&permsF[f],NULL);
6785:       PetscSectionRestoreFieldPointSyms(csection,f,numCPoints,cpoints,&permsC[f],NULL);
6786:     }
6787:   } else {
6788:     const PetscInt **permsF = NULL;
6789:     const PetscInt **permsC = NULL;

6791:     PetscSectionGetPointSyms(fsection,numFPoints,ftotpoints,&permsF,NULL);
6792:     PetscSectionGetPointSyms(csection,numCPoints,cpoints,&permsC,NULL);
6793:     for (p = 0, off = 0; p < numFPoints; p++) {
6794:       const PetscInt *perm = permsF ? permsF[p] : NULL;

6796:       PetscSectionGetOffset(globalFSection, ftotpoints[2*p], &globalOff);
6797:       DMPlexGetIndicesPoint_Internal(fsection, PETSC_FALSE, ftotpoints[2*p], globalOff < 0 ? -(globalOff+1) : globalOff, &off, PETSC_FALSE, perm, fclperm, findices);
6798:     }
6799:     for (p = 0, off = 0; p < numCPoints; p++) {
6800:       const PetscInt *perm = permsC ? permsC[p] : NULL;

6802:       PetscSectionGetOffset(globalCSection, cpoints[2*p], &globalOff);
6803:       DMPlexGetIndicesPoint_Internal(csection, PETSC_FALSE, cpoints[2*p], globalOff < 0 ? -(globalOff+1) : globalOff, &off, PETSC_FALSE, perm, cclperm, cindices);
6804:     }
6805:     PetscSectionRestorePointSyms(fsection,numFPoints,ftotpoints,&permsF,NULL);
6806:     PetscSectionRestorePointSyms(csection,numCPoints,cpoints,&permsC,NULL);
6807:   }
6808:   if (mesh->printSetValues) {DMPlexPrintMatSetValues(PETSC_VIEWER_STDOUT_SELF, A, point, numFIndices, findices, numCIndices, cindices, values);}
6809:   /* TODO: flips */
6810:   MatSetValues(A, numFIndices, findices, numCIndices, cindices, values, mode);
6811:   if (ierr) {
6812:     PetscMPIInt    rank;
6813:     PetscErrorCode ierr2;

6815:     ierr2 = MPI_Comm_rank(PetscObjectComm((PetscObject)A), &rank);CHKERRQ(ierr2);
6816:     ierr2 = (*PetscErrorPrintf)("[%d]ERROR in DMPlexMatSetClosure\n", rank);CHKERRQ(ierr2);
6817:     ierr2 = DMPlexPrintMatSetValues(PETSC_VIEWER_STDERR_SELF, A, point, numFIndices, findices, numCIndices, cindices, values);CHKERRQ(ierr2);
6818:     ierr2 = DMRestoreWorkArray(dmf, numFIndices, MPIU_INT, &findices);CHKERRQ(ierr2);
6819:     ierr2 = DMRestoreWorkArray(dmc, numCIndices, MPIU_INT, &cindices);CHKERRQ(ierr2);
6820:     
6821:   }
6822:   DMRestoreWorkArray(dmf, numCPoints*2*4, MPIU_INT, &ftotpoints);
6823:   DMPlexRestoreTransitiveClosure(dmc, point, PETSC_TRUE, &numCPoints, &cpoints);
6824:   DMRestoreWorkArray(dmf, numFIndices, MPIU_INT, &findices);
6825:   DMRestoreWorkArray(dmc, numCIndices, MPIU_INT, &cindices);
6826:   return(0);
6827: }

6829: PetscErrorCode DMPlexMatGetClosureIndicesRefined(DM dmf, PetscSection fsection, PetscSection globalFSection, DM dmc, PetscSection csection, PetscSection globalCSection, PetscInt point, PetscInt cindices[], PetscInt findices[])
6830: {
6831:   PetscInt      *fpoints = NULL, *ftotpoints = NULL;
6832:   PetscInt      *cpoints = NULL;
6833:   PetscInt       foffsets[32], coffsets[32];
6834:   const PetscInt *fclperm = NULL, *cclperm = NULL; /* Closure permutations cannot work here */
6835:   DMPolytopeType ct;
6836:   PetscInt       numFields, numSubcells, maxFPoints, numFPoints, numCPoints, numFIndices, numCIndices, dof, off, globalOff, pStart, pEnd, p, q, r, s, f;

6842:   if (!fsection) {DMGetLocalSection(dmf, &fsection);}
6844:   if (!csection) {DMGetLocalSection(dmc, &csection);}
6846:   if (!globalFSection) {DMGetGlobalSection(dmf, &globalFSection);}
6848:   if (!globalCSection) {DMGetGlobalSection(dmc, &globalCSection);}
6850:   PetscSectionGetNumFields(fsection, &numFields);
6851:   if (numFields > 31) SETERRQ1(PetscObjectComm((PetscObject)dmf), PETSC_ERR_ARG_OUTOFRANGE, "Number of fields %D limited to 31", numFields);
6852:   PetscArrayzero(foffsets, 32);
6853:   PetscArrayzero(coffsets, 32);
6854:   /* Column indices */
6855:   DMPlexGetTransitiveClosure(dmc, point, PETSC_TRUE, &numCPoints, &cpoints);
6856:   maxFPoints = numCPoints;
6857:   /* Compress out points not in the section */
6858:   /*   TODO: Squeeze out points with 0 dof as well */
6859:   PetscSectionGetChart(csection, &pStart, &pEnd);
6860:   for (p = 0, q = 0; p < numCPoints*2; p += 2) {
6861:     if ((cpoints[p] >= pStart) && (cpoints[p] < pEnd)) {
6862:       cpoints[q*2]   = cpoints[p];
6863:       cpoints[q*2+1] = cpoints[p+1];
6864:       ++q;
6865:     }
6866:   }
6867:   numCPoints = q;
6868:   for (p = 0, numCIndices = 0; p < numCPoints*2; p += 2) {
6869:     PetscInt fdof;

6871:     PetscSectionGetDof(csection, cpoints[p], &dof);
6872:     if (!dof) continue;
6873:     for (f = 0; f < numFields; ++f) {
6874:       PetscSectionGetFieldDof(csection, cpoints[p], f, &fdof);
6875:       coffsets[f+1] += fdof;
6876:     }
6877:     numCIndices += dof;
6878:   }
6879:   for (f = 1; f < numFields; ++f) coffsets[f+1] += coffsets[f];
6880:   /* Row indices */
6881:   DMPlexGetCellType(dmc, point, &ct);
6882:   {
6883:     DMPlexCellRefiner cr;
6884:     DMPlexCellRefinerCreate(dmc, &cr);
6885:     DMPlexCellRefinerGetAffineTransforms(cr, ct, &numSubcells, NULL, NULL, NULL);
6886:     DMPlexCellRefinerDestroy(&cr);
6887:   }
6888:   DMGetWorkArray(dmf, maxFPoints*2*numSubcells, MPIU_INT, &ftotpoints);
6889:   for (r = 0, q = 0; r < numSubcells; ++r) {
6890:     /* TODO Map from coarse to fine cells */
6891:     DMPlexGetTransitiveClosure(dmf, point*numSubcells + r, PETSC_TRUE, &numFPoints, &fpoints);
6892:     /* Compress out points not in the section */
6893:     PetscSectionGetChart(fsection, &pStart, &pEnd);
6894:     for (p = 0; p < numFPoints*2; p += 2) {
6895:       if ((fpoints[p] >= pStart) && (fpoints[p] < pEnd)) {
6896:         PetscSectionGetDof(fsection, fpoints[p], &dof);
6897:         if (!dof) continue;
6898:         for (s = 0; s < q; ++s) if (fpoints[p] == ftotpoints[s*2]) break;
6899:         if (s < q) continue;
6900:         ftotpoints[q*2]   = fpoints[p];
6901:         ftotpoints[q*2+1] = fpoints[p+1];
6902:         ++q;
6903:       }
6904:     }
6905:     DMPlexRestoreTransitiveClosure(dmf, point, PETSC_TRUE, &numFPoints, &fpoints);
6906:   }
6907:   numFPoints = q;
6908:   for (p = 0, numFIndices = 0; p < numFPoints*2; p += 2) {
6909:     PetscInt fdof;

6911:     PetscSectionGetDof(fsection, ftotpoints[p], &dof);
6912:     if (!dof) continue;
6913:     for (f = 0; f < numFields; ++f) {
6914:       PetscSectionGetFieldDof(fsection, ftotpoints[p], f, &fdof);
6915:       foffsets[f+1] += fdof;
6916:     }
6917:     numFIndices += dof;
6918:   }
6919:   for (f = 1; f < numFields; ++f) foffsets[f+1] += foffsets[f];

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

6927:     for (f = 0; f < numFields; f++) {
6928:       PetscSectionGetFieldPointSyms(fsection,f,numFPoints,ftotpoints,&permsF[f],NULL);
6929:       PetscSectionGetFieldPointSyms(csection,f,numCPoints,cpoints,&permsC[f],NULL);
6930:     }
6931:     for (p = 0; p < numFPoints; p++) {
6932:       PetscSectionGetOffset(globalFSection, ftotpoints[2*p], &globalOff);
6933:       DMPlexGetIndicesPointFields_Internal(fsection, PETSC_FALSE, ftotpoints[2*p], globalOff < 0 ? -(globalOff+1) : globalOff, foffsets, PETSC_FALSE, permsF, p, fclperm, findices);
6934:     }
6935:     for (p = 0; p < numCPoints; p++) {
6936:       PetscSectionGetOffset(globalCSection, cpoints[2*p], &globalOff);
6937:       DMPlexGetIndicesPointFields_Internal(csection, PETSC_FALSE, cpoints[2*p], globalOff < 0 ? -(globalOff+1) : globalOff, coffsets, PETSC_FALSE, permsC, p, cclperm, cindices);
6938:     }
6939:     for (f = 0; f < numFields; f++) {
6940:       PetscSectionRestoreFieldPointSyms(fsection,f,numFPoints,ftotpoints,&permsF[f],NULL);
6941:       PetscSectionRestoreFieldPointSyms(csection,f,numCPoints,cpoints,&permsC[f],NULL);
6942:     }
6943:   } else {
6944:     const PetscInt **permsF = NULL;
6945:     const PetscInt **permsC = NULL;

6947:     PetscSectionGetPointSyms(fsection,numFPoints,ftotpoints,&permsF,NULL);
6948:     PetscSectionGetPointSyms(csection,numCPoints,cpoints,&permsC,NULL);
6949:     for (p = 0, off = 0; p < numFPoints; p++) {
6950:       const PetscInt *perm = permsF ? permsF[p] : NULL;

6952:       PetscSectionGetOffset(globalFSection, ftotpoints[2*p], &globalOff);
6953:       DMPlexGetIndicesPoint_Internal(fsection, PETSC_FALSE, ftotpoints[2*p], globalOff < 0 ? -(globalOff+1) : globalOff, &off, PETSC_FALSE, perm, fclperm, findices);
6954:     }
6955:     for (p = 0, off = 0; p < numCPoints; p++) {
6956:       const PetscInt *perm = permsC ? permsC[p] : NULL;

6958:       PetscSectionGetOffset(globalCSection, cpoints[2*p], &globalOff);
6959:       DMPlexGetIndicesPoint_Internal(csection, PETSC_FALSE, cpoints[2*p], globalOff < 0 ? -(globalOff+1) : globalOff, &off, PETSC_FALSE, perm, cclperm, cindices);
6960:     }
6961:     PetscSectionRestorePointSyms(fsection,numFPoints,ftotpoints,&permsF,NULL);
6962:     PetscSectionRestorePointSyms(csection,numCPoints,cpoints,&permsC,NULL);
6963:   }
6964:   DMRestoreWorkArray(dmf, numCPoints*2*4, MPIU_INT, &ftotpoints);
6965:   DMPlexRestoreTransitiveClosure(dmc, point, PETSC_TRUE, &numCPoints, &cpoints);
6966:   return(0);
6967: }

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

6972:   Input Parameter:
6973: . dm   - The DMPlex object

6975:   Output Parameter:
6976: . cellHeight - The height of a cell

6978:   Level: developer

6980: .seealso DMPlexSetVTKCellHeight()
6981: @*/
6982: PetscErrorCode DMPlexGetVTKCellHeight(DM dm, PetscInt *cellHeight)
6983: {
6984:   DM_Plex *mesh = (DM_Plex*) dm->data;

6989:   *cellHeight = mesh->vtkCellHeight;
6990:   return(0);
6991: }

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

6996:   Input Parameters:
6997: + dm   - The DMPlex object
6998: - cellHeight - The height of a cell

7000:   Level: developer

7002: .seealso DMPlexGetVTKCellHeight()
7003: @*/
7004: PetscErrorCode DMPlexSetVTKCellHeight(DM dm, PetscInt cellHeight)
7005: {
7006:   DM_Plex *mesh = (DM_Plex*) dm->data;

7010:   mesh->vtkCellHeight = cellHeight;
7011:   return(0);
7012: }

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

7017:   Input Parameter:
7018: . dm - The DMPlex object

7020:   Output Parameters:
7021: + gcStart - The first ghost cell, or NULL
7022: - gcEnd   - The upper bound on ghost cells, or NULL

7024:   Level: advanced

7026: .seealso DMPlexConstructGhostCells(), DMPlexGetGhostCellStratum()
7027: @*/
7028: PetscErrorCode DMPlexGetGhostCellStratum(DM dm, PetscInt *gcStart, PetscInt *gcEnd)
7029: {
7030:   DMLabel        ctLabel;

7035:   DMPlexGetCellTypeLabel(dm, &ctLabel);
7036:   DMLabelGetStratumBounds(ctLabel, DM_POLYTOPE_FV_GHOST, gcStart, gcEnd);
7037:   return(0);
7038: }

7040: /* We can easily have a form that takes an IS instead */
7041: PetscErrorCode DMPlexCreateNumbering_Plex(DM dm, PetscInt pStart, PetscInt pEnd, PetscInt shift, PetscInt *globalSize, PetscSF sf, IS *numbering)
7042: {
7043:   PetscSection   section, globalSection;
7044:   PetscInt      *numbers, p;

7048:   PetscSectionCreate(PetscObjectComm((PetscObject)dm), &section);
7049:   PetscSectionSetChart(section, pStart, pEnd);
7050:   for (p = pStart; p < pEnd; ++p) {
7051:     PetscSectionSetDof(section, p, 1);
7052:   }
7053:   PetscSectionSetUp(section);
7054:   PetscSectionCreateGlobalSection(section, sf, PETSC_FALSE, PETSC_FALSE, &globalSection);
7055:   PetscMalloc1(pEnd - pStart, &numbers);
7056:   for (p = pStart; p < pEnd; ++p) {
7057:     PetscSectionGetOffset(globalSection, p, &numbers[p-pStart]);
7058:     if (numbers[p-pStart] < 0) numbers[p-pStart] -= shift;
7059:     else                       numbers[p-pStart] += shift;
7060:   }
7061:   ISCreateGeneral(PetscObjectComm((PetscObject) dm), pEnd - pStart, numbers, PETSC_OWN_POINTER, numbering);
7062:   if (globalSize) {
7063:     PetscLayout layout;
7064:     PetscSectionGetPointLayout(PetscObjectComm((PetscObject) dm), globalSection, &layout);
7065:     PetscLayoutGetSize(layout, globalSize);
7066:     PetscLayoutDestroy(&layout);
7067:   }
7068:   PetscSectionDestroy(&section);
7069:   PetscSectionDestroy(&globalSection);
7070:   return(0);
7071: }

7073: PetscErrorCode DMPlexCreateCellNumbering_Internal(DM dm, PetscBool includeHybrid, IS *globalCellNumbers)
7074: {
7075:   PetscInt       cellHeight, cStart, cEnd;

7079:   DMPlexGetVTKCellHeight(dm, &cellHeight);
7080:   if (includeHybrid) {DMPlexGetHeightStratum(dm, cellHeight, &cStart, &cEnd);}
7081:   else               {DMPlexGetSimplexOrBoxCells(dm, cellHeight, &cStart, &cEnd);}
7082:   DMPlexCreateNumbering_Plex(dm, cStart, cEnd, 0, NULL, dm->sf, globalCellNumbers);
7083:   return(0);
7084: }

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

7089:   Input Parameter:
7090: . dm   - The DMPlex object

7092:   Output Parameter:
7093: . globalCellNumbers - Global cell numbers for all cells on this process

7095:   Level: developer

7097: .seealso DMPlexGetVertexNumbering()
7098: @*/
7099: PetscErrorCode DMPlexGetCellNumbering(DM dm, IS *globalCellNumbers)
7100: {
7101:   DM_Plex       *mesh = (DM_Plex*) dm->data;

7106:   if (!mesh->globalCellNumbers) {DMPlexCreateCellNumbering_Internal(dm, PETSC_FALSE, &mesh->globalCellNumbers);}
7107:   *globalCellNumbers = mesh->globalCellNumbers;
7108:   return(0);
7109: }

7111: PetscErrorCode DMPlexCreateVertexNumbering_Internal(DM dm, PetscBool includeHybrid, IS *globalVertexNumbers)
7112: {
7113:   PetscInt       vStart, vEnd;

7118:   DMPlexGetDepthStratum(dm, 0, &vStart, &vEnd);
7119:   DMPlexCreateNumbering_Plex(dm, vStart, vEnd, 0, NULL, dm->sf, globalVertexNumbers);
7120:   return(0);
7121: }

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

7126:   Input Parameter:
7127: . dm   - The DMPlex object

7129:   Output Parameter:
7130: . globalVertexNumbers - Global vertex numbers for all vertices on this process

7132:   Level: developer

7134: .seealso DMPlexGetCellNumbering()
7135: @*/
7136: PetscErrorCode DMPlexGetVertexNumbering(DM dm, IS *globalVertexNumbers)
7137: {
7138:   DM_Plex       *mesh = (DM_Plex*) dm->data;

7143:   if (!mesh->globalVertexNumbers) {DMPlexCreateVertexNumbering_Internal(dm, PETSC_FALSE, &mesh->globalVertexNumbers);}
7144:   *globalVertexNumbers = mesh->globalVertexNumbers;
7145:   return(0);
7146: }

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

7151:   Input Parameter:
7152: . dm   - The DMPlex object

7154:   Output Parameter:
7155: . globalPointNumbers - Global numbers for all points on this process

7157:   Level: developer

7159: .seealso DMPlexGetCellNumbering()
7160: @*/
7161: PetscErrorCode DMPlexCreatePointNumbering(DM dm, IS *globalPointNumbers)
7162: {
7163:   IS             nums[4];
7164:   PetscInt       depths[4], gdepths[4], starts[4];
7165:   PetscInt       depth, d, shift = 0;

7170:   DMPlexGetDepth(dm, &depth);
7171:   /* For unstratified meshes use dim instead of depth */
7172:   if (depth < 0) {DMGetDimension(dm, &depth);}
7173:   for (d = 0; d <= depth; ++d) {
7174:     PetscInt end;

7176:     depths[d] = depth-d;
7177:     DMPlexGetDepthStratum(dm, depths[d], &starts[d], &end);
7178:     if (!(starts[d]-end)) { starts[d] = depths[d] = -1; }
7179:   }
7180:   PetscSortIntWithArray(depth+1, starts, depths);
7181:   MPIU_Allreduce(depths, gdepths, depth+1, MPIU_INT, MPI_MAX, PetscObjectComm((PetscObject) dm));
7182:   for (d = 0; d <= depth; ++d) {
7183:     if (starts[d] >= 0 && depths[d] != gdepths[d]) SETERRQ2(PETSC_COMM_SELF,PETSC_ERR_PLIB,"Expected depth %D, found %D",depths[d],gdepths[d]);
7184:   }
7185:   for (d = 0; d <= depth; ++d) {
7186:     PetscInt pStart, pEnd, gsize;

7188:     DMPlexGetDepthStratum(dm, gdepths[d], &pStart, &pEnd);
7189:     DMPlexCreateNumbering_Plex(dm, pStart, pEnd, shift, &gsize, dm->sf, &nums[d]);
7190:     shift += gsize;
7191:   }
7192:   ISConcatenate(PetscObjectComm((PetscObject) dm), depth+1, nums, globalPointNumbers);
7193:   for (d = 0; d <= depth; ++d) {ISDestroy(&nums[d]);}
7194:   return(0);
7195: }


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

7201:   Input Parameter:
7202: . dm - The DMPlex object

7204:   Output Parameter:
7205: . ranks - The rank field

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

7210:   Level: intermediate

7212: .seealso: DMView()
7213: @*/
7214: PetscErrorCode DMPlexCreateRankField(DM dm, Vec *ranks)
7215: {
7216:   DM             rdm;
7217:   PetscFE        fe;
7218:   PetscScalar   *r;
7219:   PetscMPIInt    rank;
7220:   PetscInt       dim, cStart, cEnd, c;

7226:   MPI_Comm_rank(PetscObjectComm((PetscObject) dm), &rank);
7227:   DMClone(dm, &rdm);
7228:   DMGetDimension(rdm, &dim);
7229:   PetscFECreateDefault(PetscObjectComm((PetscObject) rdm), dim, 1, PETSC_TRUE, "PETSc___rank_", -1, &fe);
7230:   PetscObjectSetName((PetscObject) fe, "rank");
7231:   DMSetField(rdm, 0, NULL, (PetscObject) fe);
7232:   PetscFEDestroy(&fe);
7233:   DMCreateDS(rdm);
7234:   DMPlexGetHeightStratum(rdm, 0, &cStart, &cEnd);
7235:   DMCreateGlobalVector(rdm, ranks);
7236:   PetscObjectSetName((PetscObject) *ranks, "partition");
7237:   VecGetArray(*ranks, &r);
7238:   for (c = cStart; c < cEnd; ++c) {
7239:     PetscScalar *lr;

7241:     DMPlexPointGlobalRef(rdm, c, r, &lr);
7242:     if (lr) *lr = rank;
7243:   }
7244:   VecRestoreArray(*ranks, &r);
7245:   DMDestroy(&rdm);
7246:   return(0);
7247: }

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

7252:   Input Parameters:
7253: + dm    - The DMPlex
7254: - label - The DMLabel

7256:   Output Parameter:
7257: . val - The label value field

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

7262:   Level: intermediate

7264: .seealso: DMView()
7265: @*/
7266: PetscErrorCode DMPlexCreateLabelField(DM dm, DMLabel label, Vec *val)
7267: {
7268:   DM             rdm;
7269:   PetscFE        fe;
7270:   PetscScalar   *v;
7271:   PetscInt       dim, cStart, cEnd, c;

7278:   DMClone(dm, &rdm);
7279:   DMGetDimension(rdm, &dim);
7280:   PetscFECreateDefault(PetscObjectComm((PetscObject) rdm), dim, 1, PETSC_TRUE, "PETSc___label_value_", -1, &fe);
7281:   PetscObjectSetName((PetscObject) fe, "label_value");
7282:   DMSetField(rdm, 0, NULL, (PetscObject) fe);
7283:   PetscFEDestroy(&fe);
7284:   DMCreateDS(rdm);
7285:   DMPlexGetHeightStratum(rdm, 0, &cStart, &cEnd);
7286:   DMCreateGlobalVector(rdm, val);
7287:   PetscObjectSetName((PetscObject) *val, "label_value");
7288:   VecGetArray(*val, &v);
7289:   for (c = cStart; c < cEnd; ++c) {
7290:     PetscScalar *lv;
7291:     PetscInt     cval;

7293:     DMPlexPointGlobalRef(rdm, c, v, &lv);
7294:     DMLabelGetValue(label, c, &cval);
7295:     *lv = cval;
7296:   }
7297:   VecRestoreArray(*val, &v);
7298:   DMDestroy(&rdm);
7299:   return(0);
7300: }

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

7305:   Input Parameter:
7306: . dm - The DMPlex object

7308:   Notes:
7309:   This is a useful diagnostic when creating meshes programmatically.

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

7313:   Level: developer

7315: .seealso: DMCreate(), DMSetFromOptions()
7316: @*/
7317: PetscErrorCode DMPlexCheckSymmetry(DM dm)
7318: {
7319:   PetscSection    coneSection, supportSection;
7320:   const PetscInt *cone, *support;
7321:   PetscInt        coneSize, c, supportSize, s;
7322:   PetscInt        pStart, pEnd, p, pp, csize, ssize;
7323:   PetscBool       storagecheck = PETSC_TRUE;
7324:   PetscErrorCode  ierr;

7328:   DMViewFromOptions(dm, NULL, "-sym_dm_view");
7329:   DMPlexGetConeSection(dm, &coneSection);
7330:   DMPlexGetSupportSection(dm, &supportSection);
7331:   /* Check that point p is found in the support of its cone points, and vice versa */
7332:   DMPlexGetChart(dm, &pStart, &pEnd);
7333:   for (p = pStart; p < pEnd; ++p) {
7334:     DMPlexGetConeSize(dm, p, &coneSize);
7335:     DMPlexGetCone(dm, p, &cone);
7336:     for (c = 0; c < coneSize; ++c) {
7337:       PetscBool dup = PETSC_FALSE;
7338:       PetscInt  d;
7339:       for (d = c-1; d >= 0; --d) {
7340:         if (cone[c] == cone[d]) {dup = PETSC_TRUE; break;}
7341:       }
7342:       DMPlexGetSupportSize(dm, cone[c], &supportSize);
7343:       DMPlexGetSupport(dm, cone[c], &support);
7344:       for (s = 0; s < supportSize; ++s) {
7345:         if (support[s] == p) break;
7346:       }
7347:       if ((s >= supportSize) || (dup && (support[s+1] != p))) {
7348:         PetscPrintf(PETSC_COMM_SELF, "p: %D cone: ", p);
7349:         for (s = 0; s < coneSize; ++s) {
7350:           PetscPrintf(PETSC_COMM_SELF, "%D, ", cone[s]);
7351:         }
7352:         PetscPrintf(PETSC_COMM_SELF, "\n");
7353:         PetscPrintf(PETSC_COMM_SELF, "p: %D support: ", cone[c]);
7354:         for (s = 0; s < supportSize; ++s) {
7355:           PetscPrintf(PETSC_COMM_SELF, "%D, ", support[s]);
7356:         }
7357:         PetscPrintf(PETSC_COMM_SELF, "\n");
7358:         if (dup) SETERRQ2(PETSC_COMM_SELF, PETSC_ERR_PLIB, "Point %D not repeatedly found in support of repeated cone point %D", p, cone[c]);
7359:         else SETERRQ2(PETSC_COMM_SELF, PETSC_ERR_PLIB, "Point %D not found in support of cone point %D", p, cone[c]);
7360:       }
7361:     }
7362:     DMPlexGetTreeParent(dm, p, &pp, NULL);
7363:     if (p != pp) { storagecheck = PETSC_FALSE; continue; }
7364:     DMPlexGetSupportSize(dm, p, &supportSize);
7365:     DMPlexGetSupport(dm, p, &support);
7366:     for (s = 0; s < supportSize; ++s) {
7367:       DMPlexGetConeSize(dm, support[s], &coneSize);
7368:       DMPlexGetCone(dm, support[s], &cone);
7369:       for (c = 0; c < coneSize; ++c) {
7370:         DMPlexGetTreeParent(dm, cone[c], &pp, NULL);
7371:         if (cone[c] != pp) { c = 0; break; }
7372:         if (cone[c] == p) break;
7373:       }
7374:       if (c >= coneSize) {
7375:         PetscPrintf(PETSC_COMM_SELF, "p: %D support: ", p);
7376:         for (c = 0; c < supportSize; ++c) {
7377:           PetscPrintf(PETSC_COMM_SELF, "%D, ", support[c]);
7378:         }
7379:         PetscPrintf(PETSC_COMM_SELF, "\n");
7380:         PetscPrintf(PETSC_COMM_SELF, "p: %D cone: ", support[s]);
7381:         for (c = 0; c < coneSize; ++c) {
7382:           PetscPrintf(PETSC_COMM_SELF, "%D, ", cone[c]);
7383:         }
7384:         PetscPrintf(PETSC_COMM_SELF, "\n");
7385:         SETERRQ2(PETSC_COMM_SELF, PETSC_ERR_PLIB, "Point %D not found in cone of support point %D", p, support[s]);
7386:       }
7387:     }
7388:   }
7389:   if (storagecheck) {
7390:     PetscSectionGetStorageSize(coneSection, &csize);
7391:     PetscSectionGetStorageSize(supportSection, &ssize);
7392:     if (csize != ssize) SETERRQ2(PETSC_COMM_SELF, PETSC_ERR_ARG_SIZ, "Total cone size %D != Total support size %D", csize, ssize);
7393:   }
7394:   return(0);
7395: }

7397: /*
7398:   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.
7399: */
7400: static PetscErrorCode DMPlexCellUnsplitVertices_Private(DM dm, PetscInt c, DMPolytopeType ct, PetscInt *unsplit)
7401: {
7402:   DMPolytopeType  cct;
7403:   PetscInt        ptpoints[4];
7404:   const PetscInt *cone, *ccone, *ptcone;
7405:   PetscInt        coneSize, cp, cconeSize, ccp, npt = 0, pt;
7406:   PetscErrorCode  ierr;

7409:   *unsplit = 0;
7410:   switch (ct) {
7411:     case DM_POLYTOPE_SEG_PRISM_TENSOR:
7412:       DMPlexGetCone(dm, c, &cone);
7413:       DMPlexGetConeSize(dm, c, &coneSize);
7414:       for (cp = 0; cp < coneSize; ++cp) {
7415:         DMPlexGetCellType(dm, cone[cp], &cct);
7416:         if (cct == DM_POLYTOPE_POINT_PRISM_TENSOR) ptpoints[npt++] = cone[cp];
7417:       }
7418:       break;
7419:     case DM_POLYTOPE_TRI_PRISM_TENSOR:
7420:     case DM_POLYTOPE_QUAD_PRISM_TENSOR:
7421:       DMPlexGetCone(dm, c, &cone);
7422:       DMPlexGetConeSize(dm, c, &coneSize);
7423:       for (cp = 0; cp < coneSize; ++cp) {
7424:         DMPlexGetCone(dm, cone[cp], &ccone);
7425:         DMPlexGetConeSize(dm, cone[cp], &cconeSize);
7426:         for (ccp = 0; ccp < cconeSize; ++ccp) {
7427:           DMPlexGetCellType(dm, ccone[ccp], &cct);
7428:           if (cct == DM_POLYTOPE_POINT_PRISM_TENSOR) {
7429:             PetscInt p;
7430:             for (p = 0; p < npt; ++p) if (ptpoints[p] == ccone[ccp]) break;
7431:             if (p == npt) ptpoints[npt++] = ccone[ccp];
7432:           }
7433:         }
7434:       }
7435:       break;
7436:     default: break;
7437:   }
7438:   for (pt = 0; pt < npt; ++pt) {
7439:     DMPlexGetCone(dm, ptpoints[pt], &ptcone);
7440:     if (ptcone[0] == ptcone[1]) ++(*unsplit);
7441:   }
7442:   return(0);
7443: }

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

7448:   Input Parameters:
7449: + dm - The DMPlex object
7450: - cellHeight - Normally 0

7452:   Notes:
7453:   This is a useful diagnostic when creating meshes programmatically.
7454:   Currently applicable only to homogeneous simplex or tensor meshes.

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

7458:   Level: developer

7460: .seealso: DMCreate(), DMSetFromOptions()
7461: @*/
7462: PetscErrorCode DMPlexCheckSkeleton(DM dm, PetscInt cellHeight)
7463: {
7464:   DMPlexInterpolatedFlag interp;
7465:   DMPolytopeType         ct;
7466:   PetscInt               vStart, vEnd, cStart, cEnd, c;
7467:   PetscErrorCode         ierr;

7471:   DMPlexIsInterpolated(dm, &interp);
7472:   DMPlexGetHeightStratum(dm, cellHeight, &cStart, &cEnd);
7473:   DMPlexGetDepthStratum(dm, 0, &vStart, &vEnd);
7474:   for (c = cStart; c < cEnd; ++c) {
7475:     PetscInt *closure = NULL;
7476:     PetscInt  coneSize, closureSize, cl, Nv = 0;

7478:     DMPlexGetCellType(dm, c, &ct);
7479:     if ((PetscInt) ct < 0) SETERRQ1(PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Cell %D has no cell type", c);
7480:     if (ct == DM_POLYTOPE_UNKNOWN) continue;
7481:     if (interp == DMPLEX_INTERPOLATED_FULL) {
7482:       DMPlexGetConeSize(dm, c, &coneSize);
7483:       if (coneSize != DMPolytopeTypeGetConeSize(ct)) SETERRQ4(PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Cell %D of type %s has cone size %D != %D", c, DMPolytopeTypes[ct], coneSize, DMPolytopeTypeGetConeSize(ct));
7484:     }
7485:     DMPlexGetTransitiveClosure(dm, c, PETSC_TRUE, &closureSize, &closure);
7486:     for (cl = 0; cl < closureSize*2; cl += 2) {
7487:       const PetscInt p = closure[cl];
7488:       if ((p >= vStart) && (p < vEnd)) ++Nv;
7489:     }
7490:     DMPlexRestoreTransitiveClosure(dm, c, PETSC_TRUE, &closureSize, &closure);
7491:     /* Special Case: Tensor faces with identified vertices */
7492:     if (Nv < DMPolytopeTypeGetNumVertices(ct)) {
7493:       PetscInt unsplit;

7495:       DMPlexCellUnsplitVertices_Private(dm, c, ct, &unsplit);
7496:       if (Nv + unsplit == DMPolytopeTypeGetNumVertices(ct)) continue;
7497:     }
7498:     if (Nv != DMPolytopeTypeGetNumVertices(ct)) SETERRQ4(PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Cell %D of type %s has %D vertices != %D", c, DMPolytopeTypes[ct], Nv, DMPolytopeTypeGetNumVertices(ct));
7499:   }
7500:   return(0);
7501: }

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

7506:   Not Collective

7508:   Input Parameters:
7509: + dm - The DMPlex object
7510: - cellHeight - Normally 0

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

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

7520:   Level: developer

7522: .seealso: DMCreate(), DMPlexGetVTKCellHeight(), DMSetFromOptions()
7523: @*/
7524: PetscErrorCode DMPlexCheckFaces(DM dm, PetscInt cellHeight)
7525: {
7526:   PetscInt       dim, depth, vStart, vEnd, cStart, cEnd, c, h;
7528:   DMPlexInterpolatedFlag interpEnum;

7532:   DMPlexIsInterpolated(dm, &interpEnum);
7533:   if (interpEnum == DMPLEX_INTERPOLATED_NONE) return(0);
7534:   if (interpEnum == DMPLEX_INTERPOLATED_PARTIAL) {
7535:     PetscMPIInt rank;
7536:     MPI_Comm    comm;

7538:     PetscObjectGetComm((PetscObject) dm, &comm);
7539:     MPI_Comm_rank(comm, &rank);
7540:     SETERRQ1(PETSC_COMM_SELF, PETSC_ERR_SUP, "Mesh is only partially interpolated on rank %d, this is currently not supported", rank);
7541:   }

7543:   DMGetDimension(dm, &dim);
7544:   DMPlexGetDepth(dm, &depth);
7545:   DMPlexGetDepthStratum(dm, 0, &vStart, &vEnd);
7546:   for (h = cellHeight; h < PetscMin(depth, dim); ++h) {
7547:     DMPlexGetHeightStratum(dm, h, &cStart, &cEnd);
7548:     for (c = cStart; c < cEnd; ++c) {
7549:       const PetscInt      *cone, *ornt, *faceSizes, *faces;
7550:       const DMPolytopeType *faceTypes;
7551:       DMPolytopeType        ct;
7552:       PetscInt              numFaces, coneSize, f;
7553:       PetscInt             *closure = NULL, closureSize, cl, numCorners = 0, fOff = 0, unsplit;

7555:       DMPlexGetCellType(dm, c, &ct);
7556:       DMPlexCellUnsplitVertices_Private(dm, c, ct, &unsplit);
7557:       if (unsplit) continue;
7558:       DMPlexGetConeSize(dm, c, &coneSize);
7559:       DMPlexGetCone(dm, c, &cone);
7560:       DMPlexGetConeOrientation(dm, c, &ornt);
7561:       DMPlexGetTransitiveClosure(dm, c, PETSC_TRUE, &closureSize, &closure);
7562:       for (cl = 0; cl < closureSize*2; cl += 2) {
7563:         const PetscInt p = closure[cl];
7564:         if ((p >= vStart) && (p < vEnd)) closure[numCorners++] = p;
7565:       }
7566:       DMPlexGetRawFaces_Internal(dm, ct, closure, &numFaces, &faceTypes, &faceSizes, &faces);
7567:       if (coneSize != numFaces) SETERRQ4(PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Cell %D of type %s has %D faces but should have %D", c, DMPolytopeTypes[ct], coneSize, numFaces);
7568:       for (f = 0; f < numFaces; ++f) {
7569:         DMPolytopeType fct;
7570:         PetscInt       *fclosure = NULL, fclosureSize, cl, fnumCorners = 0, v;

7572:         DMPlexGetCellType(dm, cone[f], &fct);
7573:         DMPlexGetTransitiveClosure_Internal(dm, cone[f], ornt[f], PETSC_TRUE, &fclosureSize, &fclosure);
7574:         for (cl = 0; cl < fclosureSize*2; cl += 2) {
7575:           const PetscInt p = fclosure[cl];
7576:           if ((p >= vStart) && (p < vEnd)) fclosure[fnumCorners++] = p;
7577:         }
7578:         if (fnumCorners != faceSizes[f]) SETERRQ7(PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Face %D of type %s (cone idx %D) of cell %D of type %s has %D vertices but should have %D", cone[f], DMPolytopeTypes[fct], f, c, DMPolytopeTypes[ct], fnumCorners, faceSizes[f]);
7579:         for (v = 0; v < fnumCorners; ++v) {
7580:           if (fclosure[v] != faces[fOff+v]) SETERRQ8(PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Face %D of type %s (cone idx %d) of cell %D of type %s vertex %D, %D != %D", cone[f], DMPolytopeTypes[fct], f, c, DMPolytopeTypes[ct], v, fclosure[v], faces[fOff+v]);
7581:         }
7582:         DMPlexRestoreTransitiveClosure(dm, cone[f], PETSC_TRUE, &fclosureSize, &fclosure);
7583:         fOff += faceSizes[f];
7584:       }
7585:       DMPlexRestoreRawFaces_Internal(dm, ct, closure, &numFaces, &faceTypes, &faceSizes, &faces);
7586:       DMPlexRestoreTransitiveClosure(dm, c, PETSC_TRUE, &closureSize, &closure);
7587:     }
7588:   }
7589:   return(0);
7590: }

7592: /*@
7593:   DMPlexCheckGeometry - Check the geometry of mesh cells

7595:   Input Parameter:
7596: . dm - The DMPlex object

7598:   Notes:
7599:   This is a useful diagnostic when creating meshes programmatically.

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

7603:   Level: developer

7605: .seealso: DMCreate(), DMSetFromOptions()
7606: @*/
7607: PetscErrorCode DMPlexCheckGeometry(DM dm)
7608: {
7609:   PetscReal      detJ, J[9], refVol = 1.0;
7610:   PetscReal      vol;
7611:   PetscBool      periodic;
7612:   PetscInt       dim, depth, dE, d, cStart, cEnd, c;

7616:   DMGetDimension(dm, &dim);
7617:   DMGetCoordinateDim(dm, &dE);
7618:   if (dim != dE) return(0);
7619:   DMPlexGetDepth(dm, &depth);
7620:   DMGetPeriodicity(dm, &periodic, NULL, NULL, NULL);
7621:   for (d = 0; d < dim; ++d) refVol *= 2.0;
7622:   DMPlexGetHeightStratum(dm, 0, &cStart, &cEnd);
7623:   for (c = cStart; c < cEnd; ++c) {
7624:     DMPolytopeType ct;
7625:     PetscInt       unsplit;
7626:     PetscBool      ignoreZeroVol = PETSC_FALSE;

7628:     DMPlexGetCellType(dm, c, &ct);
7629:     switch (ct) {
7630:       case DM_POLYTOPE_SEG_PRISM_TENSOR:
7631:       case DM_POLYTOPE_TRI_PRISM_TENSOR:
7632:       case DM_POLYTOPE_QUAD_PRISM_TENSOR:
7633:         ignoreZeroVol = PETSC_TRUE; break;
7634:       default: break;
7635:     }
7636:     switch (ct) {
7637:       case DM_POLYTOPE_TRI_PRISM:
7638:       case DM_POLYTOPE_TRI_PRISM_TENSOR:
7639:       case DM_POLYTOPE_QUAD_PRISM_TENSOR:
7640:         continue;
7641:       default: break;
7642:     }
7643:     DMPlexCellUnsplitVertices_Private(dm, c, ct, &unsplit);
7644:     if (unsplit) continue;
7645:     DMPlexComputeCellGeometryFEM(dm, c, NULL, NULL, J, NULL, &detJ);
7646:     if (detJ < -PETSC_SMALL || (detJ <= 0.0 && !ignoreZeroVol)) SETERRQ3(PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Mesh cell %D of type %s is inverted, |J| = %g", c, DMPolytopeTypes[ct], (double) detJ);
7647:     PetscInfo2(dm, "Cell %D FEM Volume %g\n", c, (double) detJ*refVol);
7648:     if (depth > 1 && !periodic) {
7649:       DMPlexComputeCellGeometryFVM(dm, c, &vol, NULL, NULL);
7650:       if (vol < -PETSC_SMALL || (vol <= 0.0 && !ignoreZeroVol)) SETERRQ3(PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Mesh cell %D of type %s is inverted, vol = %g", c, DMPolytopeTypes[ct], (double) vol);
7651:       PetscInfo2(dm, "Cell %D FVM Volume %g\n", c, (double) vol);
7652:     }
7653:   }
7654:   return(0);
7655: }

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

7660:   Input Parameters:
7661: . dm - The DMPlex object

7663:   Notes:
7664:   This is mainly intended for debugging/testing purposes.
7665:   It currently checks only meshes with no partition overlapping.

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

7669:   Level: developer

7671: .seealso: DMGetPointSF(), DMSetFromOptions()
7672: @*/
7673: PetscErrorCode DMPlexCheckPointSF(DM dm)
7674: {
7675:   PetscSF         pointSF;
7676:   PetscInt        cellHeight, cStart, cEnd, l, nleaves, nroots, overlap;
7677:   const PetscInt *locals, *rootdegree;
7678:   PetscBool       distributed;
7679:   PetscErrorCode  ierr;

7683:   DMGetPointSF(dm, &pointSF);
7684:   DMPlexIsDistributed(dm, &distributed);
7685:   if (!distributed) return(0);
7686:   DMPlexGetOverlap(dm, &overlap);
7687:   if (overlap) {
7688:     PetscPrintf(PetscObjectComm((PetscObject)dm), "Warning: DMPlexCheckPointSF() is currently not implemented for meshes with partition overlapping");
7689:     return(0);
7690:   }
7691:   if (!pointSF) SETERRQ(PetscObjectComm((PetscObject)dm), PETSC_ERR_ARG_WRONGSTATE, "This DMPlex is distributed but does not have PointSF attached");
7692:   PetscSFGetGraph(pointSF, &nroots, &nleaves, &locals, NULL);
7693:   if (nroots < 0) SETERRQ(PetscObjectComm((PetscObject)dm), PETSC_ERR_ARG_WRONGSTATE, "This DMPlex is distributed but its PointSF has no graph set");
7694:   PetscSFComputeDegreeBegin(pointSF, &rootdegree);
7695:   PetscSFComputeDegreeEnd(pointSF, &rootdegree);

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

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

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

7712:     DMPlexGetConeSize(dm, point, &coneSize);
7713:     DMPlexGetCone(dm, point, &cone);
7714:     for (c = 0; c < coneSize; ++c) {
7715:       if (!rootdegree[cone[c]]) {
7716:         PetscFindInt(cone[c], nleaves, locals, &idx);
7717:         if (idx < 0) SETERRQ2(PETSC_COMM_SELF, PETSC_ERR_PLIB, "Point SF contains %D but not %D from its cone", point, cone[c]);
7718:       }
7719:     }
7720:   }
7721:   return(0);
7722: }

7724: typedef struct cell_stats
7725: {
7726:   PetscReal min, max, sum, squaresum;
7727:   PetscInt  count;
7728: } cell_stats_t;

7730: static void MPIAPI cell_stats_reduce(void *a, void *b, int * len, MPI_Datatype *datatype)
7731: {
7732:   PetscInt i, N = *len;

7734:   for (i = 0; i < N; i++) {
7735:     cell_stats_t *A = (cell_stats_t *) a;
7736:     cell_stats_t *B = (cell_stats_t *) b;

7738:     B->min = PetscMin(A->min,B->min);
7739:     B->max = PetscMax(A->max,B->max);
7740:     B->sum += A->sum;
7741:     B->squaresum += A->squaresum;
7742:     B->count += A->count;
7743:   }
7744: }

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

7749:   Collective on dm

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

7756:   Notes:
7757:   This is mainly intended for debugging/testing purposes.

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

7761:   Level: developer

7763: .seealso: DMSetFromOptions(), DMPlexComputeOrthogonalQuality()
7764: @*/
7765: PetscErrorCode DMPlexCheckCellShape(DM dm, PetscBool output, PetscReal condLimit)
7766: {
7767:   DM             dmCoarse;
7768:   cell_stats_t   stats, globalStats;
7769:   MPI_Comm       comm = PetscObjectComm((PetscObject)dm);
7770:   PetscReal      *J, *invJ, min = 0, max = 0, mean = 0, stdev = 0;
7771:   PetscReal      limit = condLimit > 0 ? condLimit : PETSC_MAX_REAL;
7772:   PetscInt       cdim, cStart, cEnd, c, eStart, eEnd, count = 0;
7773:   PetscMPIInt    rank,size;

7778:   stats.min   = PETSC_MAX_REAL;
7779:   stats.max   = PETSC_MIN_REAL;
7780:   stats.sum   = stats.squaresum = 0.;
7781:   stats.count = 0;

7783:   MPI_Comm_size(comm, &size);
7784:   MPI_Comm_rank(comm, &rank);
7785:   DMGetCoordinateDim(dm,&cdim);
7786:   PetscMalloc2(PetscSqr(cdim), &J, PetscSqr(cdim), &invJ);
7787:   DMPlexGetSimplexOrBoxCells(dm,0,&cStart,&cEnd);
7788:   DMPlexGetDepthStratum(dm,1,&eStart,&eEnd);
7789:   for (c = cStart; c < cEnd; c++) {
7790:     PetscInt  i;
7791:     PetscReal frobJ = 0., frobInvJ = 0., cond2, cond, detJ;

7793:     DMPlexComputeCellGeometryAffineFEM(dm,c,NULL,J,invJ,&detJ);
7794:     if (detJ < 0.0) SETERRQ1(PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Mesh cell %D is inverted", c);
7795:     for (i = 0; i < PetscSqr(cdim); ++i) {
7796:       frobJ    += J[i] * J[i];
7797:       frobInvJ += invJ[i] * invJ[i];
7798:     }
7799:     cond2 = frobJ * frobInvJ;
7800:     cond  = PetscSqrtReal(cond2);

7802:     stats.min        = PetscMin(stats.min,cond);
7803:     stats.max        = PetscMax(stats.max,cond);
7804:     stats.sum       += cond;
7805:     stats.squaresum += cond2;
7806:     stats.count++;
7807:     if (output && cond > limit) {
7808:       PetscSection coordSection;
7809:       Vec          coordsLocal;
7810:       PetscScalar *coords = NULL;
7811:       PetscInt     Nv, d, clSize, cl, *closure = NULL;

7813:       DMGetCoordinatesLocal(dm, &coordsLocal);
7814:       DMGetCoordinateSection(dm, &coordSection);
7815:       DMPlexVecGetClosure(dm, coordSection, coordsLocal, c, &Nv, &coords);
7816:       PetscSynchronizedPrintf(comm, "[%d] Cell %D cond %g\n", rank, c, (double) cond);
7817:       for (i = 0; i < Nv/cdim; ++i) {
7818:         PetscSynchronizedPrintf(comm, "  Vertex %D: (", i);
7819:         for (d = 0; d < cdim; ++d) {
7820:           if (d > 0) {PetscSynchronizedPrintf(comm, ", ");}
7821:           PetscSynchronizedPrintf(comm, "%g", (double) PetscRealPart(coords[i*cdim+d]));
7822:         }
7823:         PetscSynchronizedPrintf(comm, ")\n");
7824:       }
7825:       DMPlexGetTransitiveClosure(dm, c, PETSC_TRUE, &clSize, &closure);
7826:       for (cl = 0; cl < clSize*2; cl += 2) {
7827:         const PetscInt edge = closure[cl];

7829:         if ((edge >= eStart) && (edge < eEnd)) {
7830:           PetscReal len;

7832:           DMPlexComputeCellGeometryFVM(dm, edge, &len, NULL, NULL);
7833:           PetscSynchronizedPrintf(comm, "  Edge %D: length %g\n", edge, (double) len);
7834:         }
7835:       }
7836:       DMPlexRestoreTransitiveClosure(dm, c, PETSC_TRUE, &clSize, &closure);
7837:       DMPlexVecRestoreClosure(dm, coordSection, coordsLocal, c, &Nv, &coords);
7838:     }
7839:   }
7840:   if (output) {PetscSynchronizedFlush(comm, NULL);}

7842:   if (size > 1) {
7843:     PetscMPIInt   blockLengths[2] = {4,1};
7844:     MPI_Aint      blockOffsets[2] = {offsetof(cell_stats_t,min),offsetof(cell_stats_t,count)};
7845:     MPI_Datatype  blockTypes[2]   = {MPIU_REAL,MPIU_INT}, statType;
7846:     MPI_Op        statReduce;

7848:     MPI_Type_create_struct(2,blockLengths,blockOffsets,blockTypes,&statType);
7849:     MPI_Type_commit(&statType);
7850:     MPI_Op_create(cell_stats_reduce, PETSC_TRUE, &statReduce);
7851:     MPI_Reduce(&stats,&globalStats,1,statType,statReduce,0,comm);
7852:     MPI_Op_free(&statReduce);
7853:     MPI_Type_free(&statType);
7854:   } else {
7855:     PetscArraycpy(&globalStats,&stats,1);
7856:   }
7857:   if (!rank) {
7858:     count = globalStats.count;
7859:     min   = globalStats.min;
7860:     max   = globalStats.max;
7861:     mean  = globalStats.sum / globalStats.count;
7862:     stdev = globalStats.count > 1 ? PetscSqrtReal(PetscMax((globalStats.squaresum - globalStats.count * mean * mean) / (globalStats.count - 1),0)) : 0.0;
7863:   }

7865:   if (output) {
7866:     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);
7867:   }
7868:   PetscFree2(J,invJ);

7870:   DMGetCoarseDM(dm,&dmCoarse);
7871:   if (dmCoarse) {
7872:     PetscBool isplex;

7874:     PetscObjectTypeCompare((PetscObject)dmCoarse,DMPLEX,&isplex);
7875:     if (isplex) {
7876:       DMPlexCheckCellShape(dmCoarse,output,condLimit);
7877:     }
7878:   }
7879:   return(0);
7880: }

7882: /*@
7883:   DMPlexComputeOrthogonalQuality - Compute cell-wise orthogonal quality mesh statistic. Optionally tags all cells with
7884:   orthogonal quality below given tolerance.

7886:   Collective

7888:   Input Parameters:
7889: + dm   - The DMPlex object
7890: . fv   - Optional PetscFV object for pre-computed cell/face centroid information
7891: - atol - [0, 1] Absolute tolerance for tagging cells.

7893:   Output Parameters:
7894: + OrthQual      - Vec containing orthogonal quality per cell
7895: - OrthQualLabel - DMLabel tagging cells below atol with DM_ADAPT_REFINE

7897:   Options Database Keys:
7898: + -dm_plex_orthogonal_quality_label_view - view OrthQualLabel if label is requested. Currently only PETSCVIEWERASCII is
7899: supported.
7900: - -dm_plex_orthogonal_quality_vec_view - view OrthQual vector.

7902:   Notes:
7903:   Orthogonal quality is given by the following formula:

7905:   \min \left[ \frac{A_i \cdot f_i}{\|A_i\| \|f_i\|} , \frac{A_i \cdot c_i}{\|A_i\| \|c_i\|} \right]

7907:   Where A_i is the i'th face-normal vector, f_i is the vector from the cell centroid to the i'th face centroid, and c_i
7908:   is the vector from the current cells centroid to the centroid of its i'th neighbor (which shares a face with the
7909:   current cell). This computes the vector similarity between each cell face and its corresponding neighbor centroid by
7910:   calculating the cosine of the angle between these vectors.

7912:   Orthogonal quality ranges from 1 (best) to 0 (worst).

7914:   This routine is mainly useful for FVM, however is not restricted to only FVM. The PetscFV object is optionally used to check for
7915:   pre-computed FVM cell data, but if it is not passed in then this data will be computed.

7917:   Cells are tagged if they have an orthogonal quality less than or equal to the absolute tolerance.

7919:   Level: intermediate

7921: .seealso: DMPlexCheckCellShape(), DMCreateLabel()
7922: @*/
7923: PetscErrorCode DMPlexComputeOrthogonalQuality(DM dm, PetscFV fv, PetscReal atol, Vec *OrthQual, DMLabel *OrthQualLabel)
7924: {
7925:   PetscInt                nc, cellHeight, cStart, cEnd, cell;
7926:   const PetscScalar       *cellGeomArr, *faceGeomArr;
7927:   MPI_Comm                comm;
7928:   Vec                     cellgeom, facegeom;
7929:   DM                      dmFace, dmCell;
7930:   IS                      glob;
7931:   DMPlexInterpolatedFlag  interpFlag;
7932:   ISLocalToGlobalMapping  ltog;
7933:   PetscViewer             vwr;
7934:   PetscErrorCode          ierr;

7939:   PetscObjectGetComm((PetscObject) dm, &comm);
7940:   DMGetDimension(dm, &nc);
7941:   if (nc < 2) {
7942:     SETERRQ1(PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "DM must have dimension >= 2 (current %D)", nc);
7943:   }
7944:   DMPlexIsInterpolated(dm, &interpFlag);
7945:   if (interpFlag != DMPLEX_INTERPOLATED_FULL) {
7946:     PetscMPIInt  rank;

7948:     MPI_Comm_rank(comm, &rank);
7949:     SETERRQ1(PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "DM must be fully interpolated, DM on rank %d is not fully interpolated", rank);
7950:   }
7951:   if (OrthQualLabel) {
7953:     DMCreateLabel(dm, "Orthogonal_Quality");
7954:     DMGetLabel(dm, "Orthogonal_Quality", OrthQualLabel);
7955:   } else {
7956:     *OrthQualLabel = NULL;
7957:   }

7959:   DMPlexGetVTKCellHeight(dm, &cellHeight);
7960:   DMPlexGetHeightStratum(dm, cellHeight, &cStart, &cEnd);
7961:   DMPlexCreateCellNumbering_Internal(dm, PETSC_TRUE, &glob);
7962:   ISLocalToGlobalMappingCreateIS(glob, &ltog);
7963:   ISLocalToGlobalMappingSetType(ltog, ISLOCALTOGLOBALMAPPINGHASH);
7964:   VecCreate(comm, OrthQual);
7965:   VecSetType(*OrthQual, VECSTANDARD);
7966:   VecSetSizes(*OrthQual, cEnd-cStart, PETSC_DETERMINE);
7967:   VecSetLocalToGlobalMapping(*OrthQual, ltog);
7968:   VecSetUp(*OrthQual);
7969:   ISDestroy(&glob);
7970:   ISLocalToGlobalMappingDestroy(&ltog);
7971:   DMPlexGetDataFVM(dm, fv, &cellgeom, &facegeom, NULL);
7972:   VecGetArrayRead(cellgeom, &cellGeomArr);
7973:   VecGetArrayRead(facegeom, &faceGeomArr);
7974:   VecGetDM(cellgeom, &dmCell);
7975:   VecGetDM(facegeom, &dmFace);
7976:   for (cell = cStart; cell < cEnd; cell++) {
7977:     PetscInt           cellneigh, cellneighiter = 0, nf, adjSize = PETSC_DETERMINE, ix = cell-cStart;
7978:     const PetscInt     *cone;
7979:     PetscInt           cellarr[2], *adj = NULL;
7980:     PetscScalar        *cArr, *fArr;
7981:     PetscReal          minvalc = 1.0, minvalf = 1.0, OQ;
7982:     PetscFVCellGeom    *cg;

7984:     cellarr[0] = cell;
7985:     /* Make indexing into cellGeom easier */
7986:     DMPlexPointLocalRead(dmCell, cell, cellGeomArr, &cg);
7987:     DMPlexGetAdjacency_Internal(dm, cell, PETSC_TRUE, PETSC_FALSE, PETSC_FALSE, &adjSize, &adj);
7988:     DMPlexGetConeSize(dm, cell, &nf);
7989:     DMPlexGetCone(dm, cell, &cone);
7990:     /* Technically 1 too big, but easier than fiddling with empty adjacency array */
7991:     PetscCalloc2(adjSize, &cArr, adjSize, &fArr);
7992:     for (cellneigh = 0; cellneigh < adjSize; cellneigh++) {
7993:       PetscInt         numcovpts, i, neigh = adj[cellneigh];
7994:       const PetscInt   *covpts;
7995:       PetscReal        normci = 0, normfi = 0, normai = 0;
7996:       PetscReal        *ci, *fi, *Ai;
7997:       PetscFVCellGeom  *cgneigh;
7998:       PetscFVFaceGeom  *fg;

8000:       /* Don't count ourselves in the neighbor list */
8001:       if (neigh == cell) continue;
8002:       PetscMalloc3(nc, &ci, nc, &fi, nc, &Ai);
8003:       DMPlexPointLocalRead(dmCell, neigh, cellGeomArr, &cgneigh);
8004:       cellarr[1] = neigh;
8005:       DMPlexGetMeet(dm, 2, cellarr, &numcovpts, &covpts);
8006:       DMPlexPointLocalRead(dmFace, covpts[0], faceGeomArr, &fg);
8007:       DMPlexRestoreMeet(dm, 2, cellarr, &numcovpts, &covpts);

8009:       /* Compute c_i, f_i and their norms */
8010:       for (i = 0; i < nc; i++) {
8011:         ci[i] = cgneigh->centroid[i] - cg->centroid[i];
8012:         fi[i] = fg->centroid[i] - cg->centroid[i];
8013:         Ai[i] = fg->normal[i];
8014:         normci += PetscPowScalar(ci[i], 2);
8015:         normfi += PetscPowScalar(fi[i], 2);
8016:         normai += PetscPowScalar(Ai[i], 2);
8017:       }
8018:       normci = PetscSqrtScalar(normci);
8019:       normfi = PetscSqrtScalar(normfi);
8020:       normai = PetscSqrtScalar(normai);

8022:       /* Normalize and compute for each face-cell-normal pair */
8023:       for (i = 0; i < nc; i++) {
8024:         ci[i] = ci[i]/normci;
8025:         fi[i] = fi[i]/normfi;
8026:         Ai[i] = Ai[i]/normai;
8027:         /* PetscAbs because I don't know if normals are guaranteed to point out */
8028:         cArr[cellneighiter] += PetscAbs(Ai[i]*ci[i]);
8029:         fArr[cellneighiter] += PetscAbs(Ai[i]*fi[i]);
8030:       }
8031:       if (PetscRealPart(cArr[cellneighiter]) < minvalc) {
8032:         minvalc = PetscRealPart(cArr[cellneighiter]);
8033:       }
8034:       if (PetscRealPart(fArr[cellneighiter]) < minvalf) {
8035:         minvalf = PetscRealPart(fArr[cellneighiter]);
8036:       }
8037:       cellneighiter++;
8038:       PetscFree3(ci, fi, Ai);
8039:     }
8040:     PetscFree(adj);
8041:     PetscFree2(cArr, fArr);
8042:     /* Defer to cell if they're equal */
8043:     OQ = PetscMin(minvalf, minvalc);
8044:     if (OrthQualLabel) {
8045:       if (OQ <= atol) {
8046:         DMLabelSetValue(*OrthQualLabel, cell, DM_ADAPT_REFINE);
8047:       }
8048:     }
8049:     VecSetValuesLocal(*OrthQual, 1, (const PetscInt *) &ix, (const PetscScalar *) &OQ, INSERT_VALUES);
8050:   }
8051:   VecAssemblyBegin(*OrthQual);
8052:   VecAssemblyEnd(*OrthQual);
8053:   VecRestoreArrayRead(cellgeom, &cellGeomArr);
8054:   VecRestoreArrayRead(facegeom, &faceGeomArr);
8055:   PetscOptionsGetViewer(comm, NULL, NULL, "-dm_plex_orthogonal_quality_label_view", &vwr, NULL, NULL);
8056:   if (OrthQualLabel) {
8057:     if (vwr) {
8058:       DMLabelView(*OrthQualLabel, vwr);
8059:     }
8060:   }
8061:   PetscViewerDestroy(&vwr);
8062:   VecViewFromOptions(*OrthQual, NULL, "-dm_plex_orthogonal_quality_vec_view");
8063:   return(0);
8064: }

8066: /* Pointwise interpolation
8067:      Just code FEM for now
8068:      u^f = I u^c
8069:      sum_k u^f_k phi^f_k = I sum_j u^c_j phi^c_j
8070:      u^f_i = sum_j psi^f_i I phi^c_j u^c_j
8071:      I_{ij} = psi^f_i phi^c_j
8072: */
8073: PetscErrorCode DMCreateInterpolation_Plex(DM dmCoarse, DM dmFine, Mat *interpolation, Vec *scaling)
8074: {
8075:   PetscSection   gsc, gsf;
8076:   PetscInt       m, n;
8077:   void          *ctx;
8078:   DM             cdm;
8079:   PetscBool      regular, ismatis, isRefined = dmCoarse->data == dmFine->data ? PETSC_FALSE : PETSC_TRUE;

8083:   DMGetGlobalSection(dmFine, &gsf);
8084:   PetscSectionGetConstrainedStorageSize(gsf, &m);
8085:   DMGetGlobalSection(dmCoarse, &gsc);
8086:   PetscSectionGetConstrainedStorageSize(gsc, &n);

8088:   PetscStrcmp(dmCoarse->mattype, MATIS, &ismatis);
8089:   MatCreate(PetscObjectComm((PetscObject) dmCoarse), interpolation);
8090:   MatSetSizes(*interpolation, m, n, PETSC_DETERMINE, PETSC_DETERMINE);
8091:   MatSetType(*interpolation, ismatis ? MATAIJ : dmCoarse->mattype);
8092:   DMGetApplicationContext(dmFine, &ctx);

8094:   DMGetCoarseDM(dmFine, &cdm);
8095:   DMPlexGetRegularRefinement(dmFine, &regular);
8096:   if (!isRefined || (regular && cdm == dmCoarse)) {DMPlexComputeInterpolatorNested(dmCoarse, dmFine, isRefined, *interpolation, ctx);}
8097:   else                                            {DMPlexComputeInterpolatorGeneral(dmCoarse, dmFine, *interpolation, ctx);}
8098:   MatViewFromOptions(*interpolation, NULL, "-interp_mat_view");
8099:   if (scaling) {
8100:     /* Use naive scaling */
8101:     DMCreateInterpolationScale(dmCoarse, dmFine, *interpolation, scaling);
8102:   }
8103:   return(0);
8104: }

8106: PetscErrorCode DMCreateInjection_Plex(DM dmCoarse, DM dmFine, Mat *mat)
8107: {
8109:   VecScatter     ctx;

8112:   DMPlexComputeInjectorFEM(dmCoarse, dmFine, &ctx, NULL);
8113:   MatCreateScatter(PetscObjectComm((PetscObject)ctx), ctx, mat);
8114:   VecScatterDestroy(&ctx);
8115:   return(0);
8116: }

8118: static void g0_identity_private(PetscInt dim, PetscInt Nf, PetscInt NfAux,
8119:                                 const PetscInt uOff[], const PetscInt uOff_x[], const PetscScalar u[], const PetscScalar u_t[], const PetscScalar u_x[],
8120:                                 const PetscInt aOff[], const PetscInt aOff_x[], const PetscScalar a[], const PetscScalar a_t[], const PetscScalar a_x[],
8121:                                 PetscReal t, PetscReal u_tShift, const PetscReal x[], PetscInt numConstants, const PetscScalar constants[], PetscScalar g0[])
8122: {
8123:   g0[0] = 1.0;
8124: }

8126: PetscErrorCode DMCreateMassMatrix_Plex(DM dmCoarse, DM dmFine, Mat *mass)
8127: {
8128:   PetscSection   gsc, gsf;
8129:   PetscInt       m, n;
8130:   void          *ctx;
8131:   DM             cdm;
8132:   PetscBool      regular;

8136:   if (dmFine == dmCoarse) {
8137:     DM       dmc;
8138:     PetscDS  ds;
8139:     Vec      u;
8140:     IS       cellIS;
8141:     PetscInt depth;

8143:     DMClone(dmFine, &dmc);
8144:     DMCopyDisc(dmFine, dmc);
8145:     DMGetDS(dmc, &ds);
8146:     PetscDSSetJacobian(ds, 0, 0, g0_identity_private, NULL, NULL, NULL);
8147:     DMCreateMatrix(dmc, mass);
8148:     DMGetGlobalVector(dmc, &u);
8149:     DMPlexGetDepth(dmc, &depth);
8150:     DMGetStratumIS(dmc, "depth", depth, &cellIS);
8151:     MatZeroEntries(*mass);
8152:     DMPlexComputeJacobian_Internal(dmc, cellIS, 0.0, 0.0, u, NULL, *mass, *mass, NULL);
8153:     ISDestroy(&cellIS);
8154:     DMRestoreGlobalVector(dmc, &u);
8155:     DMDestroy(&dmc);
8156:   } else {
8157:     DMGetGlobalSection(dmFine, &gsf);
8158:     PetscSectionGetConstrainedStorageSize(gsf, &m);
8159:     DMGetGlobalSection(dmCoarse, &gsc);
8160:     PetscSectionGetConstrainedStorageSize(gsc, &n);

8162:     MatCreate(PetscObjectComm((PetscObject) dmCoarse), mass);
8163:     MatSetSizes(*mass, m, n, PETSC_DETERMINE, PETSC_DETERMINE);
8164:     MatSetType(*mass, dmCoarse->mattype);
8165:     DMGetApplicationContext(dmFine, &ctx);

8167:     DMGetCoarseDM(dmFine, &cdm);
8168:     DMPlexGetRegularRefinement(dmFine, &regular);
8169:     if (regular && cdm == dmCoarse) {DMPlexComputeMassMatrixNested(dmCoarse, dmFine, *mass, ctx);}
8170:     else                            {DMPlexComputeMassMatrixGeneral(dmCoarse, dmFine, *mass, ctx);}
8171:   }
8172:   MatViewFromOptions(*mass, NULL, "-mass_mat_view");
8173:   return(0);
8174: }

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

8179:   Input Parameter:
8180: . dm - The DMPlex object

8182:   Output Parameter:
8183: . regular - The flag

8185:   Level: intermediate

8187: .seealso: DMPlexSetRegularRefinement()
8188: @*/
8189: PetscErrorCode DMPlexGetRegularRefinement(DM dm, PetscBool *regular)
8190: {
8194:   *regular = ((DM_Plex *) dm->data)->regularRefinement;
8195:   return(0);
8196: }

8198: /*@
8199:   DMPlexSetRegularRefinement - Set the flag indicating that this mesh was obtained by regular refinement from its coarse mesh

8201:   Input Parameters:
8202: + dm - The DMPlex object
8203: - regular - The flag

8205:   Level: intermediate

8207: .seealso: DMPlexGetRegularRefinement()
8208: @*/
8209: PetscErrorCode DMPlexSetRegularRefinement(DM dm, PetscBool regular)
8210: {
8213:   ((DM_Plex *) dm->data)->regularRefinement = regular;
8214:   return(0);
8215: }

8217: /*@
8218:   DMPlexGetCellRefinerType - Get the strategy for refining a cell

8220:   Input Parameter:
8221: . dm - The DMPlex object

8223:   Output Parameter:
8224: . cr - The strategy number

8226:   Level: intermediate

8228: .seealso: DMPlexSetCellRefinerType(), DMPlexSetRegularRefinement()
8229: @*/
8230: PetscErrorCode DMPlexGetCellRefinerType(DM dm, DMPlexCellRefinerType *cr)
8231: {
8235:   *cr = ((DM_Plex *) dm->data)->cellRefiner;
8236:   return(0);
8237: }

8239: /*@
8240:   DMPlexSetCellRefinerType - Set the strategy for refining a cell

8242:   Input Parameters:
8243: + dm - The DMPlex object
8244: - cr - The strategy number

8246:   Level: intermediate

8248: .seealso: DMPlexGetCellRefinerType(), DMPlexGetRegularRefinement()
8249: @*/
8250: PetscErrorCode DMPlexSetCellRefinerType(DM dm, DMPlexCellRefinerType cr)
8251: {
8254:   ((DM_Plex *) dm->data)->cellRefiner = cr;
8255:   return(0);
8256: }

8258: /* anchors */
8259: /*@
8260:   DMPlexGetAnchors - Get the layout of the anchor (point-to-point) constraints.  Typically, the user will not have to
8261:   call DMPlexGetAnchors() directly: if there are anchors, then DMPlexGetAnchors() is called during DMGetConstraints().

8263:   not collective

8265:   Input Parameters:
8266: . dm - The DMPlex object

8268:   Output Parameters:
8269: + anchorSection - If not NULL, set to the section describing which points anchor the constrained points.
8270: - anchorIS - If not NULL, set to the list of anchors indexed by anchorSection


8273:   Level: intermediate

8275: .seealso: DMPlexSetAnchors(), DMGetConstraints(), DMSetConstraints()
8276: @*/
8277: PetscErrorCode DMPlexGetAnchors(DM dm, PetscSection *anchorSection, IS *anchorIS)
8278: {
8279:   DM_Plex *plex = (DM_Plex *)dm->data;

8284:   if (!plex->anchorSection && !plex->anchorIS && plex->createanchors) {(*plex->createanchors)(dm);}
8285:   if (anchorSection) *anchorSection = plex->anchorSection;
8286:   if (anchorIS) *anchorIS = plex->anchorIS;
8287:   return(0);
8288: }

8290: /*@
8291:   DMPlexSetAnchors - Set the layout of the local anchor (point-to-point) constraints.  Unlike boundary conditions,
8292:   when a point's degrees of freedom in a section are constrained to an outside value, the anchor constraints set a
8293:   point's degrees of freedom to be a linear combination of other points' degrees of freedom.

8295:   After specifying the layout of constraints with DMPlexSetAnchors(), one specifies the constraints by calling
8296:   DMGetConstraints() and filling in the entries in the constraint matrix.

8298:   collective on dm

8300:   Input Parameters:
8301: + dm - The DMPlex object
8302: . 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).
8303: - anchorIS - The list of all anchor points.  Must have a local communicator (PETSC_COMM_SELF or derivative).

8305:   The reference counts of anchorSection and anchorIS are incremented.

8307:   Level: intermediate

8309: .seealso: DMPlexGetAnchors(), DMGetConstraints(), DMSetConstraints()
8310: @*/
8311: PetscErrorCode DMPlexSetAnchors(DM dm, PetscSection anchorSection, IS anchorIS)
8312: {
8313:   DM_Plex        *plex = (DM_Plex *)dm->data;
8314:   PetscMPIInt    result;

8319:   if (anchorSection) {
8321:     MPI_Comm_compare(PETSC_COMM_SELF,PetscObjectComm((PetscObject)anchorSection),&result);
8322:     if (result != MPI_CONGRUENT && result != MPI_IDENT) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_NOTSAMECOMM,"anchor section must have local communicator");
8323:   }
8324:   if (anchorIS) {
8326:     MPI_Comm_compare(PETSC_COMM_SELF,PetscObjectComm((PetscObject)anchorIS),&result);
8327:     if (result != MPI_CONGRUENT && result != MPI_IDENT) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_NOTSAMECOMM,"anchor IS must have local communicator");
8328:   }

8330:   PetscObjectReference((PetscObject)anchorSection);
8331:   PetscSectionDestroy(&plex->anchorSection);
8332:   plex->anchorSection = anchorSection;

8334:   PetscObjectReference((PetscObject)anchorIS);
8335:   ISDestroy(&plex->anchorIS);
8336:   plex->anchorIS = anchorIS;

8338:   if (PetscUnlikelyDebug(anchorIS && anchorSection)) {
8339:     PetscInt size, a, pStart, pEnd;
8340:     const PetscInt *anchors;

8342:     PetscSectionGetChart(anchorSection,&pStart,&pEnd);
8343:     ISGetLocalSize(anchorIS,&size);
8344:     ISGetIndices(anchorIS,&anchors);
8345:     for (a = 0; a < size; a++) {
8346:       PetscInt p;

8348:       p = anchors[a];
8349:       if (p >= pStart && p < pEnd) {
8350:         PetscInt dof;

8352:         PetscSectionGetDof(anchorSection,p,&dof);
8353:         if (dof) {
8354:           PetscErrorCode ierr2;

8356:           ierr2 = ISRestoreIndices(anchorIS,&anchors);CHKERRQ(ierr2);
8357:           SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_ARG_INCOMP,"Point %D cannot be constrained and an anchor",p);
8358:         }
8359:       }
8360:     }
8361:     ISRestoreIndices(anchorIS,&anchors);
8362:   }
8363:   /* reset the generic constraints */
8364:   DMSetDefaultConstraints(dm,NULL,NULL);
8365:   return(0);
8366: }

8368: static PetscErrorCode DMPlexCreateConstraintSection_Anchors(DM dm, PetscSection section, PetscSection *cSec)
8369: {
8370:   PetscSection anchorSection;
8371:   PetscInt pStart, pEnd, sStart, sEnd, p, dof, numFields, f;

8376:   DMPlexGetAnchors(dm,&anchorSection,NULL);
8377:   PetscSectionCreate(PETSC_COMM_SELF,cSec);
8378:   PetscSectionGetNumFields(section,&numFields);
8379:   if (numFields) {
8380:     PetscInt f;
8381:     PetscSectionSetNumFields(*cSec,numFields);

8383:     for (f = 0; f < numFields; f++) {
8384:       PetscInt numComp;

8386:       PetscSectionGetFieldComponents(section,f,&numComp);
8387:       PetscSectionSetFieldComponents(*cSec,f,numComp);
8388:     }
8389:   }
8390:   PetscSectionGetChart(anchorSection,&pStart,&pEnd);
8391:   PetscSectionGetChart(section,&sStart,&sEnd);
8392:   pStart = PetscMax(pStart,sStart);
8393:   pEnd   = PetscMin(pEnd,sEnd);
8394:   pEnd   = PetscMax(pStart,pEnd);
8395:   PetscSectionSetChart(*cSec,pStart,pEnd);
8396:   for (p = pStart; p < pEnd; p++) {
8397:     PetscSectionGetDof(anchorSection,p,&dof);
8398:     if (dof) {
8399:       PetscSectionGetDof(section,p,&dof);
8400:       PetscSectionSetDof(*cSec,p,dof);
8401:       for (f = 0; f < numFields; f++) {
8402:         PetscSectionGetFieldDof(section,p,f,&dof);
8403:         PetscSectionSetFieldDof(*cSec,p,f,dof);
8404:       }
8405:     }
8406:   }
8407:   PetscSectionSetUp(*cSec);
8408:   return(0);
8409: }

8411: static PetscErrorCode DMPlexCreateConstraintMatrix_Anchors(DM dm, PetscSection section, PetscSection cSec, Mat *cMat)
8412: {
8413:   PetscSection aSec;
8414:   PetscInt pStart, pEnd, p, dof, aDof, aOff, off, nnz, annz, m, n, q, a, offset, *i, *j;
8415:   const PetscInt *anchors;
8416:   PetscInt numFields, f;
8417:   IS aIS;

8422:   PetscSectionGetStorageSize(cSec, &m);
8423:   PetscSectionGetStorageSize(section, &n);
8424:   MatCreate(PETSC_COMM_SELF,cMat);
8425:   MatSetSizes(*cMat,m,n,m,n);
8426:   MatSetType(*cMat,MATSEQAIJ);
8427:   DMPlexGetAnchors(dm,&aSec,&aIS);
8428:   ISGetIndices(aIS,&anchors);
8429:   /* cSec will be a subset of aSec and section */
8430:   PetscSectionGetChart(cSec,&pStart,&pEnd);
8431:   PetscMalloc1(m+1,&i);
8432:   i[0] = 0;
8433:   PetscSectionGetNumFields(section,&numFields);
8434:   for (p = pStart; p < pEnd; p++) {
8435:     PetscInt rDof, rOff, r;

8437:     PetscSectionGetDof(aSec,p,&rDof);
8438:     if (!rDof) continue;
8439:     PetscSectionGetOffset(aSec,p,&rOff);
8440:     if (numFields) {
8441:       for (f = 0; f < numFields; f++) {
8442:         annz = 0;
8443:         for (r = 0; r < rDof; r++) {
8444:           a = anchors[rOff + r];
8445:           PetscSectionGetFieldDof(section,a,f,&aDof);
8446:           annz += aDof;
8447:         }
8448:         PetscSectionGetFieldDof(cSec,p,f,&dof);
8449:         PetscSectionGetFieldOffset(cSec,p,f,&off);
8450:         for (q = 0; q < dof; q++) {
8451:           i[off + q + 1] = i[off + q] + annz;
8452:         }
8453:       }
8454:     }
8455:     else {
8456:       annz = 0;
8457:       PetscSectionGetDof(cSec,p,&dof);
8458:       for (q = 0; q < dof; q++) {
8459:         a = anchors[off + q];
8460:         PetscSectionGetDof(section,a,&aDof);
8461:         annz += aDof;
8462:       }
8463:       PetscSectionGetDof(cSec,p,&dof);
8464:       PetscSectionGetOffset(cSec,p,&off);
8465:       for (q = 0; q < dof; q++) {
8466:         i[off + q + 1] = i[off + q] + annz;
8467:       }
8468:     }
8469:   }
8470:   nnz = i[m];
8471:   PetscMalloc1(nnz,&j);
8472:   offset = 0;
8473:   for (p = pStart; p < pEnd; p++) {
8474:     if (numFields) {
8475:       for (f = 0; f < numFields; f++) {
8476:         PetscSectionGetFieldDof(cSec,p,f,&dof);
8477:         for (q = 0; q < dof; q++) {
8478:           PetscInt rDof, rOff, r;
8479:           PetscSectionGetDof(aSec,p,&rDof);
8480:           PetscSectionGetOffset(aSec,p,&rOff);
8481:           for (r = 0; r < rDof; r++) {
8482:             PetscInt s;

8484:             a = anchors[rOff + r];
8485:             PetscSectionGetFieldDof(section,a,f,&aDof);
8486:             PetscSectionGetFieldOffset(section,a,f,&aOff);
8487:             for (s = 0; s < aDof; s++) {
8488:               j[offset++] = aOff + s;
8489:             }
8490:           }
8491:         }
8492:       }
8493:     }
8494:     else {
8495:       PetscSectionGetDof(cSec,p,&dof);
8496:       for (q = 0; q < dof; q++) {
8497:         PetscInt rDof, rOff, r;
8498:         PetscSectionGetDof(aSec,p,&rDof);
8499:         PetscSectionGetOffset(aSec,p,&rOff);
8500:         for (r = 0; r < rDof; r++) {
8501:           PetscInt s;

8503:           a = anchors[rOff + r];
8504:           PetscSectionGetDof(section,a,&aDof);
8505:           PetscSectionGetOffset(section,a,&aOff);
8506:           for (s = 0; s < aDof; s++) {
8507:             j[offset++] = aOff + s;
8508:           }
8509:         }
8510:       }
8511:     }
8512:   }
8513:   MatSeqAIJSetPreallocationCSR(*cMat,i,j,NULL);
8514:   PetscFree(i);
8515:   PetscFree(j);
8516:   ISRestoreIndices(aIS,&anchors);
8517:   return(0);
8518: }

8520: PetscErrorCode DMCreateDefaultConstraints_Plex(DM dm)
8521: {
8522:   DM_Plex        *plex = (DM_Plex *)dm->data;
8523:   PetscSection   anchorSection, section, cSec;
8524:   Mat            cMat;

8529:   DMPlexGetAnchors(dm,&anchorSection,NULL);
8530:   if (anchorSection) {
8531:     PetscInt Nf;

8533:     DMGetLocalSection(dm,&section);
8534:     DMPlexCreateConstraintSection_Anchors(dm,section,&cSec);
8535:     DMPlexCreateConstraintMatrix_Anchors(dm,section,cSec,&cMat);
8536:     DMGetNumFields(dm,&Nf);
8537:     if (Nf && plex->computeanchormatrix) {(*plex->computeanchormatrix)(dm,section,cSec,cMat);}
8538:     DMSetDefaultConstraints(dm,cSec,cMat);
8539:     PetscSectionDestroy(&cSec);
8540:     MatDestroy(&cMat);
8541:   }
8542:   return(0);
8543: }

8545: PetscErrorCode DMCreateSubDomainDM_Plex(DM dm, DMLabel label, PetscInt value, IS *is, DM *subdm)
8546: {
8547:   IS             subis;
8548:   PetscSection   section, subsection;

8552:   DMGetLocalSection(dm, &section);
8553:   if (!section) SETERRQ(PetscObjectComm((PetscObject) dm), PETSC_ERR_ARG_WRONG, "Must set default section for DM before splitting subdomain");
8554:   if (!subdm)   SETERRQ(PetscObjectComm((PetscObject) dm), PETSC_ERR_ARG_WRONG, "Must set output subDM for splitting subdomain");
8555:   /* Create subdomain */
8556:   DMPlexFilter(dm, label, value, subdm);
8557:   /* Create submodel */
8558:   DMPlexGetSubpointIS(*subdm, &subis);
8559:   PetscSectionCreateSubmeshSection(section, subis, &subsection);
8560:   DMSetLocalSection(*subdm, subsection);
8561:   PetscSectionDestroy(&subsection);
8562:   DMCopyDisc(dm, *subdm);
8563:   /* Create map from submodel to global model */
8564:   if (is) {
8565:     PetscSection    sectionGlobal, subsectionGlobal;
8566:     IS              spIS;
8567:     const PetscInt *spmap;
8568:     PetscInt       *subIndices;
8569:     PetscInt        subSize = 0, subOff = 0, pStart, pEnd, p;
8570:     PetscInt        Nf, f, bs = -1, bsLocal[2], bsMinMax[2];

8572:     DMPlexGetSubpointIS(*subdm, &spIS);
8573:     ISGetIndices(spIS, &spmap);
8574:     PetscSectionGetNumFields(section, &Nf);
8575:     DMGetGlobalSection(dm, &sectionGlobal);
8576:     DMGetGlobalSection(*subdm, &subsectionGlobal);
8577:     PetscSectionGetChart(subsection, &pStart, &pEnd);
8578:     for (p = pStart; p < pEnd; ++p) {
8579:       PetscInt gdof, pSubSize  = 0;

8581:       PetscSectionGetDof(sectionGlobal, p, &gdof);
8582:       if (gdof > 0) {
8583:         for (f = 0; f < Nf; ++f) {
8584:           PetscInt fdof, fcdof;

8586:           PetscSectionGetFieldDof(subsection, p, f, &fdof);
8587:           PetscSectionGetFieldConstraintDof(subsection, p, f, &fcdof);
8588:           pSubSize += fdof-fcdof;
8589:         }
8590:         subSize += pSubSize;
8591:         if (pSubSize) {
8592:           if (bs < 0) {
8593:             bs = pSubSize;
8594:           } else if (bs != pSubSize) {
8595:             /* Layout does not admit a pointwise block size */
8596:             bs = 1;
8597:           }
8598:         }
8599:       }
8600:     }
8601:     /* Must have same blocksize on all procs (some might have no points) */
8602:     bsLocal[0] = bs < 0 ? PETSC_MAX_INT : bs; bsLocal[1] = bs;
8603:     PetscGlobalMinMaxInt(PetscObjectComm((PetscObject) dm), bsLocal, bsMinMax);
8604:     if (bsMinMax[0] != bsMinMax[1]) {bs = 1;}
8605:     else                            {bs = bsMinMax[0];}
8606:     PetscMalloc1(subSize, &subIndices);
8607:     for (p = pStart; p < pEnd; ++p) {
8608:       PetscInt gdof, goff;

8610:       PetscSectionGetDof(subsectionGlobal, p, &gdof);
8611:       if (gdof > 0) {
8612:         const PetscInt point = spmap[p];

8614:         PetscSectionGetOffset(sectionGlobal, point, &goff);
8615:         for (f = 0; f < Nf; ++f) {
8616:           PetscInt fdof, fcdof, fc, f2, poff = 0;

8618:           /* Can get rid of this loop by storing field information in the global section */
8619:           for (f2 = 0; f2 < f; ++f2) {
8620:             PetscSectionGetFieldDof(section, p, f2, &fdof);
8621:             PetscSectionGetFieldConstraintDof(section, p, f2, &fcdof);
8622:             poff += fdof-fcdof;
8623:           }
8624:           PetscSectionGetFieldDof(section, p, f, &fdof);
8625:           PetscSectionGetFieldConstraintDof(section, p, f, &fcdof);
8626:           for (fc = 0; fc < fdof-fcdof; ++fc, ++subOff) {
8627:             subIndices[subOff] = goff+poff+fc;
8628:           }
8629:         }
8630:       }
8631:     }
8632:     ISRestoreIndices(spIS, &spmap);
8633:     ISCreateGeneral(PetscObjectComm((PetscObject)dm), subSize, subIndices, PETSC_OWN_POINTER, is);
8634:     if (bs > 1) {
8635:       /* We need to check that the block size does not come from non-contiguous fields */
8636:       PetscInt i, j, set = 1;
8637:       for (i = 0; i < subSize; i += bs) {
8638:         for (j = 0; j < bs; ++j) {
8639:           if (subIndices[i+j] != subIndices[i]+j) {set = 0; break;}
8640:         }
8641:       }
8642:       if (set) {ISSetBlockSize(*is, bs);}
8643:     }
8644:     /* Attach nullspace */
8645:     for (f = 0; f < Nf; ++f) {
8646:       (*subdm)->nullspaceConstructors[f] = dm->nullspaceConstructors[f];
8647:       if ((*subdm)->nullspaceConstructors[f]) break;
8648:     }
8649:     if (f < Nf) {
8650:       MatNullSpace nullSpace;

8652:       (*(*subdm)->nullspaceConstructors[f])(*subdm, f, f, &nullSpace);
8653:       PetscObjectCompose((PetscObject) *is, "nullspace", (PetscObject) nullSpace);
8654:       MatNullSpaceDestroy(&nullSpace);
8655:     }
8656:   }
8657:   return(0);
8658: }

8660: /*@
8661:   DMPlexMonitorThroughput - Report the cell throughput of FE integration

8663:   Input Parameter:
8664: - dm - The DM

8666:   Level: developer

8668:   Options Database Keys:
8669: . -dm_plex_monitor_throughput - Activate the monitor

8671: .seealso: DMSetFromOptions(), DMPlexCreate()
8672: @*/
8673: PetscErrorCode DMPlexMonitorThroughput(DM dm, void *dummy)
8674: {
8675: #if defined(PETSC_USE_LOG)
8676:   PetscStageLog      stageLog;
8677:   PetscLogEvent      event;
8678:   PetscLogStage      stage;
8679:   PetscEventPerfInfo eventInfo;
8680:   PetscReal          cellRate, flopRate;
8681:   PetscInt           cStart, cEnd, Nf, N;
8682:   const char        *name;
8683:   PetscErrorCode     ierr;
8684: #endif

8688: #if defined(PETSC_USE_LOG)
8689:   PetscObjectGetName((PetscObject) dm, &name);
8690:   DMPlexGetHeightStratum(dm, 0, &cStart, &cEnd);
8691:   DMGetNumFields(dm, &Nf);
8692:   PetscLogGetStageLog(&stageLog);
8693:   PetscStageLogGetCurrent(stageLog, &stage);
8694:   PetscLogEventGetId("DMPlexResidualFE", &event);
8695:   PetscLogEventGetPerfInfo(stage, event, &eventInfo);
8696:   N        = (cEnd - cStart)*Nf*eventInfo.count;
8697:   flopRate = eventInfo.flops/eventInfo.time;
8698:   cellRate = N/eventInfo.time;
8699:   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));
8700: #else
8701:   SETERRQ(PetscObjectComm((PetscObject) dm), PETSC_ERR_SUP, "Plex Throughput Monitor is not supported if logging is turned off. Reconfigure using --with-log.");
8702: #endif
8703:   return(0);
8704: }