Actual source code: plex.c

petsc-master 2020-11-24
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(), DMPlexSetGhostCellStratum()
 31: @*/
 32: PetscErrorCode DMPlexGetSimplexOrBoxCells(DM dm, PetscInt height, PetscInt *cStart, PetscInt *cEnd)
 33: {
 34:   DMPolytopeType ct = DM_POLYTOPE_UNKNOWN;
 35:   PetscInt       cS, cE, c;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

679:     DMGetDimension(dm, &dim);
680:     DMPlexGetDepth(dm, &depth);
681:     DMGetNumLabels(dm, &numLabels);
682:     numLabels  = PetscMax(numLabels, 10);
683:     numColors  = 10;
684:     numLColors = 10;
685:     PetscCalloc3(numLabels, &names, numColors, &colors, numLColors, &lcolors);
686:     PetscOptionsGetReal(((PetscObject) viewer)->options,((PetscObject) viewer)->prefix, "-dm_plex_view_scale", &scale, NULL);
687:     PetscOptionsGetReal(((PetscObject) viewer)->options,((PetscObject) viewer)->prefix, "-dm_plex_view_tikzscale", &tikzscale, NULL);
688:     PetscOptionsGetBool(((PetscObject) viewer)->options,((PetscObject) viewer)->prefix, "-dm_plex_view_numbers", &useNumbers, NULL);
689:     PetscOptionsGetStringArray(((PetscObject) viewer)->options,((PetscObject) viewer)->prefix, "-dm_plex_view_labels", names, &numLabels, &useLabels);
690:     if (!useLabels) numLabels = 0;
691:     PetscOptionsGetStringArray(((PetscObject) viewer)->options,((PetscObject) viewer)->prefix, "-dm_plex_view_colors", colors, &numColors, &useColors);
692:     if (!useColors) {
693:       numColors = 3;
694:       for (c = 0; c < numColors; ++c) {PetscStrallocpy(defcolors[c], &colors[c]);}
695:     }
696:     PetscOptionsGetStringArray(((PetscObject) viewer)->options,((PetscObject) viewer)->prefix, "-dm_plex_view_lcolors", lcolors, &numLColors, &useColors);
697:     if (!useColors) {
698:       numLColors = 4;
699:       for (c = 0; c < numLColors; ++c) {PetscStrallocpy(deflcolors[c], &lcolors[c]);}
700:     }
701:     PetscOptionsGetString(((PetscObject) viewer)->options, ((PetscObject) viewer)->prefix, "-dm_plex_view_label_filter", lname, 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: #else
1368:     SETERRQ(PetscObjectComm((PetscObject) dm), PETSC_ERR_SUP, "HDF5 not supported in this build.\nPlease reconfigure using --download-hdf5");
1369: #endif
1370:   } else {
1371:     SETERRQ1(PetscObjectComm((PetscObject) dm), PETSC_ERR_SUP, "Viewer type %s not yet supported for DMPlex loading", ((PetscObject)viewer)->type_name);
1372:   }
1373:   return(0);
1374: }

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

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

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

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

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

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

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

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

1507: /*@
1508:   DMPlexGetSubdomainSection - Returns the section associated with the subdomain

1510:   Not collective

1512:   Input Parameter:
1513: . mesh - The DMPlex

1515:   Output Parameters:
1516: . subsection - The subdomain section

1518:   Level: developer

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

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

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

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

1545:   Not collective

1547:   Input Parameter:
1548: . mesh - The DMPlex

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

1554:   Level: beginner

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

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

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

1572:   Not collective

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

1579:   Output Parameters:

1581:   Level: beginner

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

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

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

1600:   Not collective

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

1606:   Output Parameter:
1607: . size - The cone size for point p

1609:   Level: beginner

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

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

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

1628:   Not collective

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

1635:   Output Parameter:

1637:   Note:
1638:   This should be called after DMPlexSetChart().

1640:   Level: beginner

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

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

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

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

1660:   Not collective

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

1667:   Output Parameter:

1669:   Note:
1670:   This should be called after DMPlexSetChart().

1672:   Level: beginner

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

1684:   PetscSectionAddDof(mesh->coneSection, p, size);
1685:   PetscSectionGetDof(mesh->coneSection, p, &csize);

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

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

1694:   Not collective

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

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

1703:   Level: beginner

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

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

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

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

1730:   Not collective

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

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

1740:   Level: intermediate

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

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

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

1767:   Not collective

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

1773:   Output Parameter:
1774: . expandedPoints - An array of vertices recursively expanded from input points

1776:   Level: advanced

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

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

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

1801: /*@
1802:   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).

1804:   Not collective

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

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

1815:   Level: advanced

1817:   Notes:
1818:   Like DMPlexGetConeTuple() but recursive.

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

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

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

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

1894: /*@
1895:   DMPlexRestoreConeRecursive - Deallocates arrays created by DMPlexGetConeRecursive

1897:   Not collective

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

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

1908:   Level: advanced

1910:   Notes:
1911:   See DMPlexGetConeRecursive() for details.

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

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

1935: /*@
1936:   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

1938:   Not collective

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

1945:   Output Parameter:

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

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

1952:   Level: beginner

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

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

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

1980:   Not collective

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

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

1992:   Level: beginner

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

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

2010:   if (PetscDefined(USE_DEBUG)) {
2011:     PetscInt dof;
2012:     PetscSectionGetDof(mesh->coneSection, p, &dof);
2014:   }
2015:   PetscSectionGetOffset(mesh->coneSection, p, &off);

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

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

2024:   Not collective

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

2034:   Output Parameter:

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

2039:   Level: beginner

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

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

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

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

2070:   Not collective

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

2078:   Level: beginner

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

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

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

2104:   Not collective

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

2112:   Level: beginner

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

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

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

2137:   Not collective

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

2143:   Output Parameter:
2144: . size - The support size for point p

2146:   Level: beginner

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

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

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

2165:   Not collective

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

2172:   Output Parameter:

2174:   Note:
2175:   This should be called after DMPlexSetChart().

2177:   Level: beginner

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

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

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

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

2197:   Not collective

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

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

2206:   Level: beginner

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

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

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

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

2233:   Not collective

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

2240:   Output Parameter:

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

2245:   Level: beginner

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

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

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

2273:   Not collective

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

2281:   Level: beginner

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

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

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

2307:   Not collective

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

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

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

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

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

2328:   Level: beginner

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

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

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

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

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

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

2447: /*@C
2448:   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

2450:   Not collective

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

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

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

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

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

2472:   Level: beginner

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

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

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

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

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

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

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

2602:   Not collective

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

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

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

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

2620:   Level: beginner

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

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

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

2640:   Not collective

2642:   Input Parameter:
2643: . mesh - The DMPlex

2645:   Output Parameters:
2646: + maxConeSize - The maximum number of in-edges
2647: - maxSupportSize - The maximum number of out-edges

2649:   Level: beginner

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

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

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

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

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

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

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

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

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

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

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

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

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

2748:   Not collective

2750:   Input Parameter:
2751: . mesh - The DMPlex

2753:   Output Parameter:

2755:   Note:
2756:   This should be called after all calls to DMPlexSetCone()

2758:   Level: beginner

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

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

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

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

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

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

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

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

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

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

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

2846:   Collective on dm

2848:   Input Parameter:
2849: . mesh - The DMPlex

2851:   Output Parameter:

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

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

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

2873:   Level: beginner

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

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

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

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

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

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

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

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

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

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

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

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

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

3028:               DMPlexGetCone(dm, p, &cone);
3029:               DMPlexGetConeSize(dm, cone[0], &faceConeSize);
3030:               switch (faceConeSize) {
3031:                 case 3: ct = DM_POLYTOPE_TRI_PRISM_TENSOR;break;
3032:                 case 4: ct = DM_POLYTOPE_PYRAMID;break;
3033:               }
3034:             }
3035:             break;
3036:             case 6: ct = DM_POLYTOPE_HEXAHEDRON;break;
3037:             default: break;
3038:           }
3039:           break;
3040:         default: break;
3041:       }
3042:     } else if (pheight > 0) {
3043:       switch (coneSize) {
3044:         case 2: ct = DM_POLYTOPE_SEGMENT;break;
3045:         case 3: ct = DM_POLYTOPE_TRIANGLE;break;
3046:         case 4: ct = DM_POLYTOPE_QUADRILATERAL;break;
3047:         default: break;
3048:       }
3049:     }
3050:   }
3051:   *pt = ct;
3052:   return(0);
3053: }

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

3058:   Collective on dm

3060:   Input Parameter:
3061: . mesh - The DMPlex

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

3065:   Level: developer

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

3071: .seealso: DMPlexCreate(), DMPlexSymmetrize(), DMPlexStratify(), DMGetLabel(), DMCreateLabel()
3072: @*/
3073: PetscErrorCode DMPlexComputeCellTypes(DM dm)
3074: {
3075:   DM_Plex       *mesh;
3076:   DMLabel        ctLabel;
3077:   PetscInt       pStart, pEnd, p;

3082:   mesh = (DM_Plex *) dm->data;
3083:   DMCreateLabel(dm, "celltype");
3084:   DMPlexGetCellTypeLabel(dm, &ctLabel);
3085:   DMPlexGetChart(dm, &pStart, &pEnd);
3086:   for (p = pStart; p < pEnd; ++p) {
3087:     DMPolytopeType ct = DM_POLYTOPE_UNKNOWN;
3088:     PetscInt       pdepth;

3090:     DMPlexGetPointDepth(dm, p, &pdepth);
3091:     DMPlexComputeCellType_Internal(dm, p, pdepth, &ct);
3092:     if (ct == DM_POLYTOPE_UNKNOWN) SETERRQ1(PETSC_COMM_SELF, PETSC_ERR_SUP, "Point %D is screwed up", p);
3093:     DMLabelSetValue(ctLabel, p, ct);
3094:   }
3095:   PetscObjectStateGet((PetscObject) ctLabel, &mesh->celltypeState);
3096:   PetscObjectViewFromOptions((PetscObject) ctLabel, NULL, "-dm_plex_celltypes_view");
3097:   return(0);
3098: }

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

3103:   Not Collective

3105:   Input Parameters:
3106: + dm - The DMPlex object
3107: . numPoints - The number of input points for the join
3108: - points - The input points

3110:   Output Parameters:
3111: + numCoveredPoints - The number of points in the join
3112: - coveredPoints - The points in the join

3114:   Level: intermediate

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

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

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

3124: .seealso: DMPlexRestoreJoin(), DMPlexGetMeet()
3125: @*/
3126: PetscErrorCode DMPlexGetJoin(DM dm, PetscInt numPoints, const PetscInt points[], PetscInt *numCoveredPoints, const PetscInt **coveredPoints)
3127: {
3128:   DM_Plex       *mesh = (DM_Plex*) dm->data;
3129:   PetscInt      *join[2];
3130:   PetscInt       joinSize, i = 0;
3131:   PetscInt       dof, off, p, c, m;

3139:   DMGetWorkArray(dm, mesh->maxSupportSize, MPIU_INT, &join[0]);
3140:   DMGetWorkArray(dm, mesh->maxSupportSize, MPIU_INT, &join[1]);
3141:   /* Copy in support of first point */
3142:   PetscSectionGetDof(mesh->supportSection, points[0], &dof);
3143:   PetscSectionGetOffset(mesh->supportSection, points[0], &off);
3144:   for (joinSize = 0; joinSize < dof; ++joinSize) {
3145:     join[i][joinSize] = mesh->supports[off+joinSize];
3146:   }
3147:   /* Check each successive support */
3148:   for (p = 1; p < numPoints; ++p) {
3149:     PetscInt newJoinSize = 0;

3151:     PetscSectionGetDof(mesh->supportSection, points[p], &dof);
3152:     PetscSectionGetOffset(mesh->supportSection, points[p], &off);
3153:     for (c = 0; c < dof; ++c) {
3154:       const PetscInt point = mesh->supports[off+c];

3156:       for (m = 0; m < joinSize; ++m) {
3157:         if (point == join[i][m]) {
3158:           join[1-i][newJoinSize++] = point;
3159:           break;
3160:         }
3161:       }
3162:     }
3163:     joinSize = newJoinSize;
3164:     i        = 1-i;
3165:   }
3166:   *numCoveredPoints = joinSize;
3167:   *coveredPoints    = join[i];
3168:   DMRestoreWorkArray(dm, mesh->maxSupportSize, MPIU_INT, &join[1-i]);
3169:   return(0);
3170: }

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

3175:   Not Collective

3177:   Input Parameters:
3178: + dm - The DMPlex object
3179: . numPoints - The number of input points for the join
3180: - points - The input points

3182:   Output Parameters:
3183: + numCoveredPoints - The number of points in the join
3184: - coveredPoints - The points in the join

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

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

3192:   Level: intermediate

3194: .seealso: DMPlexGetJoin(), DMPlexGetFullJoin(), DMPlexGetMeet()
3195: @*/
3196: PetscErrorCode DMPlexRestoreJoin(DM dm, PetscInt numPoints, const PetscInt points[], PetscInt *numCoveredPoints, const PetscInt **coveredPoints)
3197: {

3205:   DMRestoreWorkArray(dm, 0, MPIU_INT, (void*) coveredPoints);
3206:   if (numCoveredPoints) *numCoveredPoints = 0;
3207:   return(0);
3208: }

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

3213:   Not Collective

3215:   Input Parameters:
3216: + dm - The DMPlex object
3217: . numPoints - The number of input points for the join
3218: - points - The input points

3220:   Output Parameters:
3221: + numCoveredPoints - The number of points in the join
3222: - coveredPoints - The points in the join

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

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

3230:   Level: intermediate

3232: .seealso: DMPlexGetJoin(), DMPlexRestoreJoin(), DMPlexGetMeet()
3233: @*/
3234: PetscErrorCode DMPlexGetFullJoin(DM dm, PetscInt numPoints, const PetscInt points[], PetscInt *numCoveredPoints, const PetscInt **coveredPoints)
3235: {
3236:   DM_Plex       *mesh = (DM_Plex*) dm->data;
3237:   PetscInt      *offsets, **closures;
3238:   PetscInt      *join[2];
3239:   PetscInt       depth = 0, maxSize, joinSize = 0, i = 0;
3240:   PetscInt       p, d, c, m, ms;


3249:   DMPlexGetDepth(dm, &depth);
3250:   PetscCalloc1(numPoints, &closures);
3251:   DMGetWorkArray(dm, numPoints*(depth+2), MPIU_INT, &offsets);
3252:   ms      = mesh->maxSupportSize;
3253:   maxSize = (ms > 1) ? ((PetscPowInt(ms,depth+1)-1)/(ms-1)) : depth + 1;
3254:   DMGetWorkArray(dm, maxSize, MPIU_INT, &join[0]);
3255:   DMGetWorkArray(dm, maxSize, MPIU_INT, &join[1]);

3257:   for (p = 0; p < numPoints; ++p) {
3258:     PetscInt closureSize;

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

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

3266:       DMPlexGetDepthStratum(dm, d, &pStart, &pEnd);
3267:       for (i = offsets[p*(depth+2)+d]; i < closureSize; ++i) {
3268:         if ((pStart > closures[p][i*2]) || (pEnd <= closures[p][i*2])) {
3269:           offsets[p*(depth+2)+d+1] = i;
3270:           break;
3271:         }
3272:       }
3273:       if (i == closureSize) offsets[p*(depth+2)+d+1] = i;
3274:     }
3275:     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);
3276:   }
3277:   for (d = 0; d < depth+1; ++d) {
3278:     PetscInt dof;

3280:     /* Copy in support of first point */
3281:     dof = offsets[d+1] - offsets[d];
3282:     for (joinSize = 0; joinSize < dof; ++joinSize) {
3283:       join[i][joinSize] = closures[0][(offsets[d]+joinSize)*2];
3284:     }
3285:     /* Check each successive cone */
3286:     for (p = 1; p < numPoints && joinSize; ++p) {
3287:       PetscInt newJoinSize = 0;

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

3293:         for (m = 0; m < joinSize; ++m) {
3294:           if (point == join[i][m]) {
3295:             join[1-i][newJoinSize++] = point;
3296:             break;
3297:           }
3298:         }
3299:       }
3300:       joinSize = newJoinSize;
3301:       i        = 1-i;
3302:     }
3303:     if (joinSize) break;
3304:   }
3305:   *numCoveredPoints = joinSize;
3306:   *coveredPoints    = join[i];
3307:   for (p = 0; p < numPoints; ++p) {
3308:     DMPlexRestoreTransitiveClosure(dm, points[p], PETSC_FALSE, NULL, &closures[p]);
3309:   }
3310:   PetscFree(closures);
3311:   DMRestoreWorkArray(dm, numPoints*(depth+2), MPIU_INT, &offsets);
3312:   DMRestoreWorkArray(dm, mesh->maxSupportSize, MPIU_INT, &join[1-i]);
3313:   return(0);
3314: }

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

3319:   Not Collective

3321:   Input Parameters:
3322: + dm - The DMPlex object
3323: . numPoints - The number of input points for the meet
3324: - points - The input points

3326:   Output Parameters:
3327: + numCoveredPoints - The number of points in the meet
3328: - coveredPoints - The points in the meet

3330:   Level: intermediate

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

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

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

3340: .seealso: DMPlexRestoreMeet(), DMPlexGetJoin()
3341: @*/
3342: PetscErrorCode DMPlexGetMeet(DM dm, PetscInt numPoints, const PetscInt points[], PetscInt *numCoveringPoints, const PetscInt **coveringPoints)
3343: {
3344:   DM_Plex       *mesh = (DM_Plex*) dm->data;
3345:   PetscInt      *meet[2];
3346:   PetscInt       meetSize, i = 0;
3347:   PetscInt       dof, off, p, c, m;

3355:   DMGetWorkArray(dm, mesh->maxConeSize, MPIU_INT, &meet[0]);
3356:   DMGetWorkArray(dm, mesh->maxConeSize, MPIU_INT, &meet[1]);
3357:   /* Copy in cone of first point */
3358:   PetscSectionGetDof(mesh->coneSection, points[0], &dof);
3359:   PetscSectionGetOffset(mesh->coneSection, points[0], &off);
3360:   for (meetSize = 0; meetSize < dof; ++meetSize) {
3361:     meet[i][meetSize] = mesh->cones[off+meetSize];
3362:   }
3363:   /* Check each successive cone */
3364:   for (p = 1; p < numPoints; ++p) {
3365:     PetscInt newMeetSize = 0;

3367:     PetscSectionGetDof(mesh->coneSection, points[p], &dof);
3368:     PetscSectionGetOffset(mesh->coneSection, points[p], &off);
3369:     for (c = 0; c < dof; ++c) {
3370:       const PetscInt point = mesh->cones[off+c];

3372:       for (m = 0; m < meetSize; ++m) {
3373:         if (point == meet[i][m]) {
3374:           meet[1-i][newMeetSize++] = point;
3375:           break;
3376:         }
3377:       }
3378:     }
3379:     meetSize = newMeetSize;
3380:     i        = 1-i;
3381:   }
3382:   *numCoveringPoints = meetSize;
3383:   *coveringPoints    = meet[i];
3384:   DMRestoreWorkArray(dm, mesh->maxConeSize, MPIU_INT, &meet[1-i]);
3385:   return(0);
3386: }

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

3391:   Not Collective

3393:   Input Parameters:
3394: + dm - The DMPlex object
3395: . numPoints - The number of input points for the meet
3396: - points - The input points

3398:   Output Parameters:
3399: + numCoveredPoints - The number of points in the meet
3400: - coveredPoints - The points in the meet

3402:   Level: intermediate

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

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

3410: .seealso: DMPlexGetMeet(), DMPlexGetFullMeet(), DMPlexGetJoin()
3411: @*/
3412: PetscErrorCode DMPlexRestoreMeet(DM dm, PetscInt numPoints, const PetscInt points[], PetscInt *numCoveredPoints, const PetscInt **coveredPoints)
3413: {

3421:   DMRestoreWorkArray(dm, 0, MPIU_INT, (void*) coveredPoints);
3422:   if (numCoveredPoints) *numCoveredPoints = 0;
3423:   return(0);
3424: }

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

3429:   Not Collective

3431:   Input Parameters:
3432: + dm - The DMPlex object
3433: . numPoints - The number of input points for the meet
3434: - points - The input points

3436:   Output Parameters:
3437: + numCoveredPoints - The number of points in the meet
3438: - coveredPoints - The points in the meet

3440:   Level: intermediate

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

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

3448: .seealso: DMPlexGetMeet(), DMPlexRestoreMeet(), DMPlexGetJoin()
3449: @*/
3450: PetscErrorCode DMPlexGetFullMeet(DM dm, PetscInt numPoints, const PetscInt points[], PetscInt *numCoveredPoints, const PetscInt **coveredPoints)
3451: {
3452:   DM_Plex       *mesh = (DM_Plex*) dm->data;
3453:   PetscInt      *offsets, **closures;
3454:   PetscInt      *meet[2];
3455:   PetscInt       height = 0, maxSize, meetSize = 0, i = 0;
3456:   PetscInt       p, h, c, m, mc;


3465:   DMPlexGetDepth(dm, &height);
3466:   PetscMalloc1(numPoints, &closures);
3467:   DMGetWorkArray(dm, numPoints*(height+2), MPIU_INT, &offsets);
3468:   mc      = mesh->maxConeSize;
3469:   maxSize = (mc > 1) ? ((PetscPowInt(mc,height+1)-1)/(mc-1)) : height + 1;
3470:   DMGetWorkArray(dm, maxSize, MPIU_INT, &meet[0]);
3471:   DMGetWorkArray(dm, maxSize, MPIU_INT, &meet[1]);

3473:   for (p = 0; p < numPoints; ++p) {
3474:     PetscInt closureSize;

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

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

3482:       DMPlexGetHeightStratum(dm, h, &pStart, &pEnd);
3483:       for (i = offsets[p*(height+2)+h]; i < closureSize; ++i) {
3484:         if ((pStart > closures[p][i*2]) || (pEnd <= closures[p][i*2])) {
3485:           offsets[p*(height+2)+h+1] = i;
3486:           break;
3487:         }
3488:       }
3489:       if (i == closureSize) offsets[p*(height+2)+h+1] = i;
3490:     }
3491:     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);
3492:   }
3493:   for (h = 0; h < height+1; ++h) {
3494:     PetscInt dof;

3496:     /* Copy in cone of first point */
3497:     dof = offsets[h+1] - offsets[h];
3498:     for (meetSize = 0; meetSize < dof; ++meetSize) {
3499:       meet[i][meetSize] = closures[0][(offsets[h]+meetSize)*2];
3500:     }
3501:     /* Check each successive cone */
3502:     for (p = 1; p < numPoints && meetSize; ++p) {
3503:       PetscInt newMeetSize = 0;

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

3509:         for (m = 0; m < meetSize; ++m) {
3510:           if (point == meet[i][m]) {
3511:             meet[1-i][newMeetSize++] = point;
3512:             break;
3513:           }
3514:         }
3515:       }
3516:       meetSize = newMeetSize;
3517:       i        = 1-i;
3518:     }
3519:     if (meetSize) break;
3520:   }
3521:   *numCoveredPoints = meetSize;
3522:   *coveredPoints    = meet[i];
3523:   for (p = 0; p < numPoints; ++p) {
3524:     DMPlexRestoreTransitiveClosure(dm, points[p], PETSC_TRUE, NULL, &closures[p]);
3525:   }
3526:   PetscFree(closures);
3527:   DMRestoreWorkArray(dm, numPoints*(height+2), MPIU_INT, &offsets);
3528:   DMRestoreWorkArray(dm, mesh->maxConeSize, MPIU_INT, &meet[1-i]);
3529:   return(0);
3530: }

3532: /*@C
3533:   DMPlexEqual - Determine if two DMs have the same topology

3535:   Not Collective

3537:   Input Parameters:
3538: + dmA - A DMPlex object
3539: - dmB - A DMPlex object

3541:   Output Parameters:
3542: . equal - PETSC_TRUE if the topologies are identical

3544:   Level: intermediate

3546:   Notes:
3547:   We are not solving graph isomorphism, so we do not permutation.

3549: .seealso: DMPlexGetCone()
3550: @*/
3551: PetscErrorCode DMPlexEqual(DM dmA, DM dmB, PetscBool *equal)
3552: {
3553:   PetscInt       depth, depthB, pStart, pEnd, pStartB, pEndB, p;


3561:   *equal = PETSC_FALSE;
3562:   DMPlexGetDepth(dmA, &depth);
3563:   DMPlexGetDepth(dmB, &depthB);
3564:   if (depth != depthB) return(0);
3565:   DMPlexGetChart(dmA, &pStart,  &pEnd);
3566:   DMPlexGetChart(dmB, &pStartB, &pEndB);
3567:   if ((pStart != pStartB) || (pEnd != pEndB)) return(0);
3568:   for (p = pStart; p < pEnd; ++p) {
3569:     const PetscInt *cone, *coneB, *ornt, *orntB, *support, *supportB;
3570:     PetscInt        coneSize, coneSizeB, c, supportSize, supportSizeB, s;

3572:     DMPlexGetConeSize(dmA, p, &coneSize);
3573:     DMPlexGetCone(dmA, p, &cone);
3574:     DMPlexGetConeOrientation(dmA, p, &ornt);
3575:     DMPlexGetConeSize(dmB, p, &coneSizeB);
3576:     DMPlexGetCone(dmB, p, &coneB);
3577:     DMPlexGetConeOrientation(dmB, p, &orntB);
3578:     if (coneSize != coneSizeB) return(0);
3579:     for (c = 0; c < coneSize; ++c) {
3580:       if (cone[c] != coneB[c]) return(0);
3581:       if (ornt[c] != orntB[c]) return(0);
3582:     }
3583:     DMPlexGetSupportSize(dmA, p, &supportSize);
3584:     DMPlexGetSupport(dmA, p, &support);
3585:     DMPlexGetSupportSize(dmB, p, &supportSizeB);
3586:     DMPlexGetSupport(dmB, p, &supportB);
3587:     if (supportSize != supportSizeB) return(0);
3588:     for (s = 0; s < supportSize; ++s) {
3589:       if (support[s] != supportB[s]) return(0);
3590:     }
3591:   }
3592:   *equal = PETSC_TRUE;
3593:   return(0);
3594: }

3596: /*@C
3597:   DMPlexGetNumFaceVertices - Returns the number of vertices on a face

3599:   Not Collective

3601:   Input Parameters:
3602: + dm         - The DMPlex
3603: . cellDim    - The cell dimension
3604: - numCorners - The number of vertices on a cell

3606:   Output Parameters:
3607: . numFaceVertices - The number of vertices on a face

3609:   Level: developer

3611:   Notes:
3612:   Of course this can only work for a restricted set of symmetric shapes

3614: .seealso: DMPlexGetCone()
3615: @*/
3616: PetscErrorCode DMPlexGetNumFaceVertices(DM dm, PetscInt cellDim, PetscInt numCorners, PetscInt *numFaceVertices)
3617: {
3618:   MPI_Comm       comm;

3622:   PetscObjectGetComm((PetscObject)dm,&comm);
3624:   switch (cellDim) {
3625:   case 0:
3626:     *numFaceVertices = 0;
3627:     break;
3628:   case 1:
3629:     *numFaceVertices = 1;
3630:     break;
3631:   case 2:
3632:     switch (numCorners) {
3633:     case 3: /* triangle */
3634:       *numFaceVertices = 2; /* Edge has 2 vertices */
3635:       break;
3636:     case 4: /* quadrilateral */
3637:       *numFaceVertices = 2; /* Edge has 2 vertices */
3638:       break;
3639:     case 6: /* quadratic triangle, tri and quad cohesive Lagrange cells */
3640:       *numFaceVertices = 3; /* Edge has 3 vertices */
3641:       break;
3642:     case 9: /* quadratic quadrilateral, quadratic quad cohesive Lagrange cells */
3643:       *numFaceVertices = 3; /* Edge has 3 vertices */
3644:       break;
3645:     default:
3646:       SETERRQ2(comm, PETSC_ERR_ARG_OUTOFRANGE, "Invalid number of face corners %D for dimension %D", numCorners, cellDim);
3647:     }
3648:     break;
3649:   case 3:
3650:     switch (numCorners) {
3651:     case 4: /* tetradehdron */
3652:       *numFaceVertices = 3; /* Face has 3 vertices */
3653:       break;
3654:     case 6: /* tet cohesive cells */
3655:       *numFaceVertices = 4; /* Face has 4 vertices */
3656:       break;
3657:     case 8: /* hexahedron */
3658:       *numFaceVertices = 4; /* Face has 4 vertices */
3659:       break;
3660:     case 9: /* tet cohesive Lagrange cells */
3661:       *numFaceVertices = 6; /* Face has 6 vertices */
3662:       break;
3663:     case 10: /* quadratic tetrahedron */
3664:       *numFaceVertices = 6; /* Face has 6 vertices */
3665:       break;
3666:     case 12: /* hex cohesive Lagrange cells */
3667:       *numFaceVertices = 6; /* Face has 6 vertices */
3668:       break;
3669:     case 18: /* quadratic tet cohesive Lagrange cells */
3670:       *numFaceVertices = 6; /* Face has 6 vertices */
3671:       break;
3672:     case 27: /* quadratic hexahedron, quadratic hex cohesive Lagrange cells */
3673:       *numFaceVertices = 9; /* Face has 9 vertices */
3674:       break;
3675:     default:
3676:       SETERRQ2(comm, PETSC_ERR_ARG_OUTOFRANGE, "Invalid number of face corners %D for dimension %D", numCorners, cellDim);
3677:     }
3678:     break;
3679:   default:
3680:     SETERRQ1(comm, PETSC_ERR_ARG_OUTOFRANGE, "Invalid cell dimension %D", cellDim);
3681:   }
3682:   return(0);
3683: }

3685: /*@
3686:   DMPlexGetDepthLabel - Get the DMLabel recording the depth of each point

3688:   Not Collective

3690:   Input Parameter:
3691: . dm    - The DMPlex object

3693:   Output Parameter:
3694: . depthLabel - The DMLabel recording point depth

3696:   Level: developer

3698: .seealso: DMPlexGetDepth(), DMPlexGetHeightStratum(), DMPlexGetDepthStratum(), DMPlexGetPointDepth(),
3699: @*/
3700: PetscErrorCode DMPlexGetDepthLabel(DM dm, DMLabel *depthLabel)
3701: {
3705:   *depthLabel = dm->depthLabel;
3706:   return(0);
3707: }

3709: /*@
3710:   DMPlexGetDepth - Get the depth of the DAG representing this mesh

3712:   Not Collective

3714:   Input Parameter:
3715: . dm    - The DMPlex object

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

3720:   Level: developer

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

3727: .seealso: DMPlexGetDepthLabel(), DMPlexGetDepthStratum(), DMPlexGetPointDepth(), DMPlexSymmetrize()
3728: @*/
3729: PetscErrorCode DMPlexGetDepth(DM dm, PetscInt *depth)
3730: {
3731:   DMLabel        label;
3732:   PetscInt       d = 0;

3738:   DMPlexGetDepthLabel(dm, &label);
3739:   if (label) {DMLabelGetNumValues(label, &d);}
3740:   *depth = d-1;
3741:   return(0);
3742: }

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

3747:   Not Collective

3749:   Input Parameters:
3750: + dm           - The DMPlex object
3751: - stratumValue - The requested depth

3753:   Output Parameters:
3754: + start - The first point at this depth
3755: - end   - One beyond the last point at this depth

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

3762:   Level: developer

3764: .seealso: DMPlexGetHeightStratum(), DMPlexGetDepth(), DMPlexGetDepthLabel(), DMPlexGetPointDepth(), DMPlexSymmetrize(), DMPlexInterpolate()
3765: @*/
3766: PetscErrorCode DMPlexGetDepthStratum(DM dm, PetscInt stratumValue, PetscInt *start, PetscInt *end)
3767: {
3768:   DMLabel        label;
3769:   PetscInt       pStart, pEnd;

3776:   DMPlexGetChart(dm, &pStart, &pEnd);
3777:   if (pStart == pEnd) return(0);
3778:   if (stratumValue < 0) {
3779:     if (start) *start = pStart;
3780:     if (end)   *end   = pEnd;
3781:     return(0);
3782:   }
3783:   DMPlexGetDepthLabel(dm, &label);
3784:   if (!label) SETERRQ(PetscObjectComm((PetscObject) dm), PETSC_ERR_ARG_WRONG, "No label named depth was found");
3785:   DMLabelGetStratumBounds(label, stratumValue, start, end);
3786:   return(0);
3787: }

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

3792:   Not Collective

3794:   Input Parameters:
3795: + dm           - The DMPlex object
3796: - stratumValue - The requested height

3798:   Output Parameters:
3799: + start - The first point at this height
3800: - end   - One beyond the last point at this height

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

3807:   Level: developer

3809: .seealso: DMPlexGetDepthStratum(), DMPlexGetDepth(), DMPlexGetPointHeight()
3810: @*/
3811: PetscErrorCode DMPlexGetHeightStratum(DM dm, PetscInt stratumValue, PetscInt *start, PetscInt *end)
3812: {
3813:   DMLabel        label;
3814:   PetscInt       depth, pStart, pEnd;

3821:   DMPlexGetChart(dm, &pStart, &pEnd);
3822:   if (pStart == pEnd) return(0);
3823:   if (stratumValue < 0) {
3824:     if (start) *start = pStart;
3825:     if (end)   *end   = pEnd;
3826:     return(0);
3827:   }
3828:   DMPlexGetDepthLabel(dm, &label);
3829:   if (!label) SETERRQ(PetscObjectComm((PetscObject) dm), PETSC_ERR_ARG_WRONG, "No label named depth was found");
3830:   DMLabelGetNumValues(label, &depth);
3831:   DMLabelGetStratumBounds(label, depth-1-stratumValue, start, end);
3832:   return(0);
3833: }

3835: /*@
3836:   DMPlexGetPointDepth - Get the depth of a given point

3838:   Not Collective

3840:   Input Parameter:
3841: + dm    - The DMPlex object
3842: - point - The point

3844:   Output Parameter:
3845: . depth - The depth of the point

3847:   Level: intermediate

3849: .seealso: DMPlexGetCellType(), DMPlexGetDepthLabel(), DMPlexGetDepth(), DMPlexGetPointHeight()
3850: @*/
3851: PetscErrorCode DMPlexGetPointDepth(DM dm, PetscInt point, PetscInt *depth)
3852: {

3858:   DMLabelGetValue(dm->depthLabel, point, depth);
3859:   return(0);
3860: }

3862: /*@
3863:   DMPlexGetPointHeight - Get the height of a given point

3865:   Not Collective

3867:   Input Parameter:
3868: + dm    - The DMPlex object
3869: - point - The point

3871:   Output Parameter:
3872: . height - The height of the point

3874:   Level: intermediate

3876: .seealso: DMPlexGetCellType(), DMPlexGetDepthLabel(), DMPlexGetDepth(), DMPlexGetPointDepth()
3877: @*/
3878: PetscErrorCode DMPlexGetPointHeight(DM dm, PetscInt point, PetscInt *height)
3879: {
3880:   PetscInt       n, pDepth;

3886:   DMLabelGetNumValues(dm->depthLabel, &n);
3887:   DMLabelGetValue(dm->depthLabel, point, &pDepth);
3888:   *height = n - 1 - pDepth;  /* DAG depth is n-1 */
3889:   return(0);
3890: }

3892: /*@
3893:   DMPlexGetCellTypeLabel - Get the DMLabel recording the polytope type of each cell

3895:   Not Collective

3897:   Input Parameter:
3898: . dm - The DMPlex object

3900:   Output Parameter:
3901: . celltypeLabel - The DMLabel recording cell polytope type

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

3906:   Level: developer

3908: .seealso: DMPlexGetCellType(), DMPlexGetDepthLabel(), DMCreateLabel()
3909: @*/
3910: PetscErrorCode DMPlexGetCellTypeLabel(DM dm, DMLabel *celltypeLabel)
3911: {

3917:   if (!dm->celltypeLabel) {DMPlexComputeCellTypes(dm);}
3918:   *celltypeLabel = dm->celltypeLabel;
3919:   return(0);
3920: }

3922: /*@
3923:   DMPlexGetCellType - Get the polytope type of a given cell

3925:   Not Collective

3927:   Input Parameter:
3928: + dm   - The DMPlex object
3929: - cell - The cell

3931:   Output Parameter:
3932: . celltype - The polytope type of the cell

3934:   Level: intermediate

3936: .seealso: DMPlexGetCellTypeLabel(), DMPlexGetDepthLabel(), DMPlexGetDepth()
3937: @*/
3938: PetscErrorCode DMPlexGetCellType(DM dm, PetscInt cell, DMPolytopeType *celltype)
3939: {
3940:   DMLabel        label;
3941:   PetscInt       ct;

3947:   DMPlexGetCellTypeLabel(dm, &label);
3948:   DMLabelGetValue(label, cell, &ct);
3949:   *celltype = (DMPolytopeType) ct;
3950:   return(0);
3951: }

3953: /*@
3954:   DMPlexSetCellType - Set the polytope type of a given cell

3956:   Not Collective

3958:   Input Parameters:
3959: + dm   - The DMPlex object
3960: . cell - The cell
3961: - celltype - The polytope type of the cell

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

3968:   Level: advanced

3970: .seealso: DMPlexGetCellTypeLabel(), DMPlexGetDepthLabel(), DMPlexGetDepth(), DMPlexComputeCellTypes(), DMCreateLabel()
3971: @*/
3972: PetscErrorCode DMPlexSetCellType(DM dm, PetscInt cell, DMPolytopeType celltype)
3973: {
3974:   DMLabel        label;

3979:   DMPlexGetCellTypeLabel(dm, &label);
3980:   DMLabelSetValue(label, cell, celltype);
3981:   return(0);
3982: }

3984: PetscErrorCode DMCreateCoordinateDM_Plex(DM dm, DM *cdm)
3985: {
3986:   PetscSection   section, s;
3987:   Mat            m;
3988:   PetscInt       maxHeight;

3992:   DMClone(dm, cdm);
3993:   DMPlexGetMaxProjectionHeight(dm, &maxHeight);
3994:   DMPlexSetMaxProjectionHeight(*cdm, maxHeight);
3995:   PetscSectionCreate(PetscObjectComm((PetscObject)dm), &section);
3996:   DMSetLocalSection(*cdm, section);
3997:   PetscSectionDestroy(&section);
3998:   PetscSectionCreate(PETSC_COMM_SELF, &s);
3999:   MatCreate(PETSC_COMM_SELF, &m);
4000:   DMSetDefaultConstraints(*cdm, s, m);
4001:   PetscSectionDestroy(&s);
4002:   MatDestroy(&m);

4004:   DMSetNumFields(*cdm, 1);
4005:   DMCreateDS(*cdm);
4006:   return(0);
4007: }

4009: PetscErrorCode DMCreateCoordinateField_Plex(DM dm, DMField *field)
4010: {
4011:   Vec            coordsLocal;
4012:   DM             coordsDM;

4016:   *field = NULL;
4017:   DMGetCoordinatesLocal(dm,&coordsLocal);
4018:   DMGetCoordinateDM(dm,&coordsDM);
4019:   if (coordsLocal && coordsDM) {
4020:     DMFieldCreateDS(coordsDM, 0, coordsLocal, field);
4021:   }
4022:   return(0);
4023: }

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

4028:   Not Collective

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

4033:   Output Parameter:
4034: . section - The PetscSection object

4036:   Level: developer

4038: .seealso: DMPlexGetSupportSection(), DMPlexGetCones(), DMPlexGetConeOrientations()
4039: @*/
4040: PetscErrorCode DMPlexGetConeSection(DM dm, PetscSection *section)
4041: {
4042:   DM_Plex *mesh = (DM_Plex*) dm->data;

4046:   if (section) *section = mesh->coneSection;
4047:   return(0);
4048: }

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

4053:   Not Collective

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

4058:   Output Parameter:
4059: . section - The PetscSection object

4061:   Level: developer

4063: .seealso: DMPlexGetConeSection()
4064: @*/
4065: PetscErrorCode DMPlexGetSupportSection(DM dm, PetscSection *section)
4066: {
4067:   DM_Plex *mesh = (DM_Plex*) dm->data;

4071:   if (section) *section = mesh->supportSection;
4072:   return(0);
4073: }

4075: /*@C
4076:   DMPlexGetCones - Return cone data

4078:   Not Collective

4080:   Input Parameters:
4081: . dm        - The DMPlex object

4083:   Output Parameter:
4084: . cones - The cone for each point

4086:   Level: developer

4088: .seealso: DMPlexGetConeSection()
4089: @*/
4090: PetscErrorCode DMPlexGetCones(DM dm, PetscInt *cones[])
4091: {
4092:   DM_Plex *mesh = (DM_Plex*) dm->data;

4096:   if (cones) *cones = mesh->cones;
4097:   return(0);
4098: }

4100: /*@C
4101:   DMPlexGetConeOrientations - Return cone orientation data

4103:   Not Collective

4105:   Input Parameters:
4106: . dm        - The DMPlex object

4108:   Output Parameter:
4109: . coneOrientations - The cone orientation for each point

4111:   Level: developer

4113: .seealso: DMPlexGetConeSection()
4114: @*/
4115: PetscErrorCode DMPlexGetConeOrientations(DM dm, PetscInt *coneOrientations[])
4116: {
4117:   DM_Plex *mesh = (DM_Plex*) dm->data;

4121:   if (coneOrientations) *coneOrientations = mesh->coneOrientations;
4122:   return(0);
4123: }

4125: /******************************** FEM Support **********************************/

4127: /*
4128:  Returns number of components and tensor degree for the field.  For interpolated meshes, line should be a point
4129:  representing a line in the section.
4130: */
4131: static PetscErrorCode PetscSectionFieldGetTensorDegree_Private(PetscSection section,PetscInt field,PetscInt line,PetscBool vertexchart,PetscInt *Nc,PetscInt *k)
4132: {

4136:   PetscSectionGetFieldComponents(section, field, Nc);
4137:   if (line < 0) {
4138:     *k = 0;
4139:     *Nc = 0;
4140:   } else if (vertexchart) {            /* If we only have a vertex chart, we must have degree k=1 */
4141:     *k = 1;
4142:   } else {                      /* Assume the full interpolated mesh is in the chart; lines in particular */
4143:     /* An order k SEM disc has k-1 dofs on an edge */
4144:     PetscSectionGetFieldDof(section, line, field, k);
4145:     *k = *k / *Nc + 1;
4146:   }
4147:   return(0);
4148: }

4150: /*@

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

4156:   Input Parameters:
4157: + dm      - The DM
4158: . point   - Either a cell (highest dim point) or an edge (dim 1 point), or PETSC_DETERMINE
4159: - section - The PetscSection to reorder, or NULL for the default section

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

4164:   Example:
4165:   A typical interpolated single-quad mesh might order points as
4166: .vb
4167:   [c0, v1, v2, v3, v4, e5, e6, e7, e8]

4169:   v4 -- e6 -- v3
4170:   |           |
4171:   e7    c0    e8
4172:   |           |
4173:   v1 -- e5 -- v2
4174: .ve

4176:   (There is no significance to the ordering described here.)  The default section for a Q3 quad might typically assign
4177:   dofs in the order of points, e.g.,
4178: .vb
4179:     c0 -> [0,1,2,3]
4180:     v1 -> [4]
4181:     ...
4182:     e5 -> [8, 9]
4183: .ve

4185:   which corresponds to the dofs
4186: .vb
4187:     6   10  11  7
4188:     13  2   3   15
4189:     12  0   1   14
4190:     4   8   9   5
4191: .ve

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

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

4203:   Level: developer

4205: .seealso: DMGetLocalSection(), PetscSectionSetClosurePermutation(), DMSetGlobalSection()
4206: @*/
4207: PetscErrorCode DMPlexSetClosurePermutationTensor(DM dm, PetscInt point, PetscSection section)
4208: {
4209:   DMLabel        label;
4210:   PetscInt       dim, depth = -1, eStart = -1, Nf;
4211:   PetscBool      vertexchart;

4215:   DMGetDimension(dm, &dim);
4216:   if (dim < 1) return(0);
4217:   if (point < 0) {
4218:     PetscInt sStart,sEnd;

4220:     DMPlexGetDepthStratum(dm, 1, &sStart, &sEnd);
4221:     point = sEnd-sStart ? sStart : point;
4222:   }
4223:   DMPlexGetDepthLabel(dm, &label);
4224:   if (point >= 0) { DMLabelGetValue(label, point, &depth); }
4225:   if (!section) {DMGetLocalSection(dm, &section);}
4226:   if (depth == 1) {eStart = point;}
4227:   else if  (depth == dim) {
4228:     const PetscInt *cone;

4230:     DMPlexGetCone(dm, point, &cone);
4231:     if (dim == 2) eStart = cone[0];
4232:     else if (dim == 3) {
4233:       const PetscInt *cone2;
4234:       DMPlexGetCone(dm, cone[0], &cone2);
4235:       eStart = cone2[0];
4236:     } 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);
4237:   } 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);
4238:   {                             /* Determine whether the chart covers all points or just vertices. */
4239:     PetscInt pStart,pEnd,cStart,cEnd;
4240:     DMPlexGetDepthStratum(dm,0,&pStart,&pEnd);
4241:     PetscSectionGetChart(section,&cStart,&cEnd);
4242:     if (pStart == cStart && pEnd == cEnd) vertexchart = PETSC_TRUE; /* Just vertices */
4243:     else vertexchart = PETSC_FALSE;                                 /* Assume all interpolated points are in chart */
4244:   }
4245:   PetscSectionGetNumFields(section, &Nf);
4246:   for (PetscInt d=1; d<=dim; d++) {
4247:     PetscInt k, f, Nc, c, i, j, size = 0, offset = 0, foffset = 0;
4248:     PetscInt *perm;

4250:     for (f = 0; f < Nf; ++f) {
4251:       PetscSectionFieldGetTensorDegree_Private(section,f,eStart,vertexchart,&Nc,&k);
4252:       size += PetscPowInt(k+1, d)*Nc;
4253:     }
4254:     PetscMalloc1(size, &perm);
4255:     for (f = 0; f < Nf; ++f) {
4256:       switch (d) {
4257:       case 1:
4258:         PetscSectionFieldGetTensorDegree_Private(section,f,eStart,vertexchart,&Nc,&k);
4259:         /*
4260:          Original ordering is [ edge of length k-1; vtx0; vtx1 ]
4261:          We want              [ vtx0; edge of length k-1; vtx1 ]
4262:          */
4263:         for (c=0; c<Nc; c++,offset++) perm[offset] = (k-1)*Nc + c + foffset;
4264:         for (i=0; i<k-1; i++) for (c=0; c<Nc; c++,offset++) perm[offset] = i*Nc + c + foffset;
4265:         for (c=0; c<Nc; c++,offset++) perm[offset] = k*Nc + c + foffset;
4266:         foffset = offset;
4267:         break;
4268:       case 2:
4269:         /* The original quad closure is oriented clockwise, {f, e_b, e_r, e_t, e_l, v_lb, v_rb, v_tr, v_tl} */
4270:         PetscSectionFieldGetTensorDegree_Private(section,f,eStart,vertexchart,&Nc,&k);
4271:         /* The SEM order is

4273:          v_lb, {e_b}, v_rb,
4274:          e^{(k-1)-i}_l, {f^{i*(k-1)}}, e^i_r,
4275:          v_lt, reverse {e_t}, v_rt
4276:          */
4277:         {
4278:           const PetscInt of   = 0;
4279:           const PetscInt oeb  = of   + PetscSqr(k-1);
4280:           const PetscInt oer  = oeb  + (k-1);
4281:           const PetscInt oet  = oer  + (k-1);
4282:           const PetscInt oel  = oet  + (k-1);
4283:           const PetscInt ovlb = oel  + (k-1);
4284:           const PetscInt ovrb = ovlb + 1;
4285:           const PetscInt ovrt = ovrb + 1;
4286:           const PetscInt ovlt = ovrt + 1;
4287:           PetscInt       o;

4289:           /* bottom */
4290:           for (c = 0; c < Nc; ++c, ++offset) perm[offset] = ovlb*Nc + c + foffset;
4291:           for (o = oeb; o < oer; ++o) for (c = 0; c < Nc; ++c, ++offset) perm[offset] = o*Nc + c + foffset;
4292:           for (c = 0; c < Nc; ++c, ++offset) perm[offset] = ovrb*Nc + c + foffset;
4293:           /* middle */
4294:           for (i = 0; i < k-1; ++i) {
4295:             for (c = 0; c < Nc; ++c, ++offset) perm[offset] = (oel+(k-2)-i)*Nc + c + foffset;
4296:             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;
4297:             for (c = 0; c < Nc; ++c, ++offset) perm[offset] = (oer+i)*Nc + c + foffset;
4298:           }
4299:           /* top */
4300:           for (c = 0; c < Nc; ++c, ++offset) perm[offset] = ovlt*Nc + c + foffset;
4301:           for (o = oel-1; o >= oet; --o) for (c = 0; c < Nc; ++c, ++offset) perm[offset] = o*Nc + c + foffset;
4302:           for (c = 0; c < Nc; ++c, ++offset) perm[offset] = ovrt*Nc + c + foffset;
4303:           foffset = offset;
4304:         }
4305:         break;
4306:       case 3:
4307:         /* The original hex closure is

4309:          {c,
4310:          f_b, f_t, f_f, f_b, f_r, f_l,
4311:          e_bl, e_bb, e_br, e_bf,  e_tf, e_tr, e_tb, e_tl,  e_rf, e_lf, e_lb, e_rb,
4312:          v_blf, v_blb, v_brb, v_brf, v_tlf, v_trf, v_trb, v_tlb}
4313:          */
4314:         PetscSectionFieldGetTensorDegree_Private(section,f,eStart,vertexchart,&Nc,&k);
4315:         /* The SEM order is
4316:          Bottom Slice
4317:          v_blf, {e^{(k-1)-n}_bf}, v_brf,
4318:          e^{i}_bl, f^{n*(k-1)+(k-1)-i}_b, e^{(k-1)-i}_br,
4319:          v_blb, {e_bb}, v_brb,

4321:          Middle Slice (j)
4322:          {e^{(k-1)-j}_lf}, {f^{j*(k-1)+n}_f}, e^j_rf,
4323:          f^{i*(k-1)+j}_l, {c^{(j*(k-1) + i)*(k-1)+n}_t}, f^{j*(k-1)+i}_r,
4324:          e^j_lb, {f^{j*(k-1)+(k-1)-n}_b}, e^{(k-1)-j}_rb,

4326:          Top Slice
4327:          v_tlf, {e_tf}, v_trf,
4328:          e^{(k-1)-i}_tl, {f^{i*(k-1)}_t}, e^{i}_tr,
4329:          v_tlb, {e^{(k-1)-n}_tb}, v_trb,
4330:          */
4331:         {
4332:           const PetscInt oc    = 0;
4333:           const PetscInt ofb   = oc    + PetscSqr(k-1)*(k-1);
4334:           const PetscInt oft   = ofb   + PetscSqr(k-1);
4335:           const PetscInt off   = oft   + PetscSqr(k-1);
4336:           const PetscInt ofk   = off   + PetscSqr(k-1);
4337:           const PetscInt ofr   = ofk   + PetscSqr(k-1);
4338:           const PetscInt ofl   = ofr   + PetscSqr(k-1);
4339:           const PetscInt oebl  = ofl   + PetscSqr(k-1);
4340:           const PetscInt oebb  = oebl  + (k-1);
4341:           const PetscInt oebr  = oebb  + (k-1);
4342:           const PetscInt oebf  = oebr  + (k-1);
4343:           const PetscInt oetf  = oebf  + (k-1);
4344:           const PetscInt oetr  = oetf  + (k-1);
4345:           const PetscInt oetb  = oetr  + (k-1);
4346:           const PetscInt oetl  = oetb  + (k-1);
4347:           const PetscInt oerf  = oetl  + (k-1);
4348:           const PetscInt oelf  = oerf  + (k-1);
4349:           const PetscInt oelb  = oelf  + (k-1);
4350:           const PetscInt oerb  = oelb  + (k-1);
4351:           const PetscInt ovblf = oerb  + (k-1);
4352:           const PetscInt ovblb = ovblf + 1;
4353:           const PetscInt ovbrb = ovblb + 1;
4354:           const PetscInt ovbrf = ovbrb + 1;
4355:           const PetscInt ovtlf = ovbrf + 1;
4356:           const PetscInt ovtrf = ovtlf + 1;
4357:           const PetscInt ovtrb = ovtrf + 1;
4358:           const PetscInt ovtlb = ovtrb + 1;
4359:           PetscInt       o, n;

4361:           /* Bottom Slice */
4362:           /*   bottom */
4363:           for (c = 0; c < Nc; ++c, ++offset) perm[offset] = ovblf*Nc + c + foffset;
4364:           for (o = oetf-1; o >= oebf; --o) for (c = 0; c < Nc; ++c, ++offset) perm[offset] = o*Nc + c + foffset;
4365:           for (c = 0; c < Nc; ++c, ++offset) perm[offset] = ovbrf*Nc + c + foffset;
4366:           /*   middle */
4367:           for (i = 0; i < k-1; ++i) {
4368:             for (c = 0; c < Nc; ++c, ++offset) perm[offset] = (oebl+i)*Nc + c + foffset;
4369:             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;}
4370:             for (c = 0; c < Nc; ++c, ++offset) perm[offset] = (oebr+(k-2)-i)*Nc + c + foffset;
4371:           }
4372:           /*   top */
4373:           for (c = 0; c < Nc; ++c, ++offset) perm[offset] = ovblb*Nc + c + foffset;
4374:           for (o = oebb; o < oebr; ++o) for (c = 0; c < Nc; ++c, ++offset) perm[offset] = o*Nc + c + foffset;
4375:           for (c = 0; c < Nc; ++c, ++offset) perm[offset] = ovbrb*Nc + c + foffset;

4377:           /* Middle Slice */
4378:           for (j = 0; j < k-1; ++j) {
4379:             /*   bottom */
4380:             for (c = 0; c < Nc; ++c, ++offset) perm[offset] = (oelf+(k-2)-j)*Nc + c + foffset;
4381:             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;
4382:             for (c = 0; c < Nc; ++c, ++offset) perm[offset] = (oerf+j)*Nc + c + foffset;
4383:             /*   middle */
4384:             for (i = 0; i < k-1; ++i) {
4385:               for (c = 0; c < Nc; ++c, ++offset) perm[offset] = (ofl+i*(k-1)+j)*Nc + c + foffset;
4386:               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;
4387:               for (c = 0; c < Nc; ++c, ++offset) perm[offset] = (ofr+j*(k-1)+i)*Nc + c + foffset;
4388:             }
4389:             /*   top */
4390:             for (c = 0; c < Nc; ++c, ++offset) perm[offset] = (oelb+j)*Nc + c + foffset;
4391:             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;
4392:             for (c = 0; c < Nc; ++c, ++offset) perm[offset] = (oerb+(k-2)-j)*Nc + c + foffset;
4393:           }

4395:           /* Top Slice */
4396:           /*   bottom */
4397:           for (c = 0; c < Nc; ++c, ++offset) perm[offset] = ovtlf*Nc + c + foffset;
4398:           for (o = oetf; o < oetr; ++o) for (c = 0; c < Nc; ++c, ++offset) perm[offset] = o*Nc + c + foffset;
4399:           for (c = 0; c < Nc; ++c, ++offset) perm[offset] = ovtrf*Nc + c + foffset;
4400:           /*   middle */
4401:           for (i = 0; i < k-1; ++i) {
4402:             for (c = 0; c < Nc; ++c, ++offset) perm[offset] = (oetl+(k-2)-i)*Nc + c + foffset;
4403:             for (n = 0; n < k-1; ++n) for (c = 0; c < Nc; ++c, ++offset) perm[offset] = (oft+i*(k-1)+n)*Nc + c + foffset;
4404:             for (c = 0; c < Nc; ++c, ++offset) perm[offset] = (oetr+i)*Nc + c + foffset;
4405:           }
4406:           /*   top */
4407:           for (c = 0; c < Nc; ++c, ++offset) perm[offset] = ovtlb*Nc + c + foffset;
4408:           for (o = oetl-1; o >= oetb; --o) for (c = 0; c < Nc; ++c, ++offset) perm[offset] = o*Nc + c + foffset;
4409:           for (c = 0; c < Nc; ++c, ++offset) perm[offset] = ovtrb*Nc + c + foffset;

4411:           foffset = offset;
4412:         }
4413:         break;
4414:       default: SETERRQ1(PetscObjectComm((PetscObject) dm), PETSC_ERR_ARG_OUTOFRANGE, "No spectral ordering for dimension %D", d);
4415:       }
4416:     }
4417:     if (offset != size) SETERRQ2(PetscObjectComm((PetscObject) dm), PETSC_ERR_PLIB, "Number of permutation entries %D != %D", offset, size);
4418:     /* Check permutation */
4419:     {
4420:       PetscInt *check;

4422:       PetscMalloc1(size, &check);
4423:       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]);}
4424:       for (i = 0; i < size; ++i) check[perm[i]] = i;
4425:       for (i = 0; i < size; ++i) {if (check[i] < 0) SETERRQ1(PetscObjectComm((PetscObject) dm), PETSC_ERR_PLIB, "Missing permutation index %D", i);}
4426:       PetscFree(check);
4427:     }
4428:     PetscSectionSetClosurePermutation_Internal(section, (PetscObject) dm, d, size, PETSC_OWN_POINTER, perm);
4429:   }
4430:   return(0);
4431: }

4433: PetscErrorCode DMPlexGetPointDualSpaceFEM(DM dm, PetscInt point, PetscInt field, PetscDualSpace *dspace)
4434: {
4435:   PetscDS        prob;
4436:   PetscInt       depth, Nf, h;
4437:   DMLabel        label;

4441:   DMGetDS(dm, &prob);
4442:   Nf      = prob->Nf;
4443:   label   = dm->depthLabel;
4444:   *dspace = NULL;
4445:   if (field < Nf) {
4446:     PetscObject disc = prob->disc[field];

4448:     if (disc->classid == PETSCFE_CLASSID) {
4449:       PetscDualSpace dsp;

4451:       PetscFEGetDualSpace((PetscFE)disc,&dsp);
4452:       DMLabelGetNumValues(label,&depth);
4453:       DMLabelGetValue(label,point,&h);
4454:       h    = depth - 1 - h;
4455:       if (h) {
4456:         PetscDualSpaceGetHeightSubspace(dsp,h,dspace);
4457:       } else {
4458:         *dspace = dsp;
4459:       }
4460:     }
4461:   }
4462:   return(0);
4463: }


4466: PETSC_STATIC_INLINE PetscErrorCode DMPlexVecGetClosure_Depth1_Static(DM dm, PetscSection section, Vec v, PetscInt point, PetscInt *csize, PetscScalar *values[])
4467: {
4468:   PetscScalar    *array, *vArray;
4469:   const PetscInt *cone, *coneO;
4470:   PetscInt        pStart, pEnd, p, numPoints, size = 0, offset = 0;
4471:   PetscErrorCode  ierr;

4474:   PetscSectionGetChart(section, &pStart, &pEnd);
4475:   DMPlexGetConeSize(dm, point, &numPoints);
4476:   DMPlexGetCone(dm, point, &cone);
4477:   DMPlexGetConeOrientation(dm, point, &coneO);
4478:   if (!values || !*values) {
4479:     if ((point >= pStart) && (point < pEnd)) {
4480:       PetscInt dof;

4482:       PetscSectionGetDof(section, point, &dof);
4483:       size += dof;
4484:     }
4485:     for (p = 0; p < numPoints; ++p) {
4486:       const PetscInt cp = cone[p];
4487:       PetscInt       dof;

4489:       if ((cp < pStart) || (cp >= pEnd)) continue;
4490:       PetscSectionGetDof(section, cp, &dof);
4491:       size += dof;
4492:     }
4493:     if (!values) {
4494:       if (csize) *csize = size;
4495:       return(0);
4496:     }
4497:     DMGetWorkArray(dm, size, MPIU_SCALAR, &array);
4498:   } else {
4499:     array = *values;
4500:   }
4501:   size = 0;
4502:   VecGetArray(v, &vArray);
4503:   if ((point >= pStart) && (point < pEnd)) {
4504:     PetscInt     dof, off, d;
4505:     PetscScalar *varr;

4507:     PetscSectionGetDof(section, point, &dof);
4508:     PetscSectionGetOffset(section, point, &off);
4509:     varr = &vArray[off];
4510:     for (d = 0; d < dof; ++d, ++offset) {
4511:       array[offset] = varr[d];
4512:     }
4513:     size += dof;
4514:   }
4515:   for (p = 0; p < numPoints; ++p) {
4516:     const PetscInt cp = cone[p];
4517:     PetscInt       o  = coneO[p];
4518:     PetscInt       dof, off, d;
4519:     PetscScalar   *varr;

4521:     if ((cp < pStart) || (cp >= pEnd)) continue;
4522:     PetscSectionGetDof(section, cp, &dof);
4523:     PetscSectionGetOffset(section, cp, &off);
4524:     varr = &vArray[off];
4525:     if (o >= 0) {
4526:       for (d = 0; d < dof; ++d, ++offset) {
4527:         array[offset] = varr[d];
4528:       }
4529:     } else {
4530:       for (d = dof-1; d >= 0; --d, ++offset) {
4531:         array[offset] = varr[d];
4532:       }
4533:     }
4534:     size += dof;
4535:   }
4536:   VecRestoreArray(v, &vArray);
4537:   if (!*values) {
4538:     if (csize) *csize = size;
4539:     *values = array;
4540:   } else {
4541:     if (size > *csize) SETERRQ2(PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Size of input array %D < actual size %D", *csize, size);
4542:     *csize = size;
4543:   }
4544:   return(0);
4545: }

4547: /* Compress out points not in the section */
4548: PETSC_STATIC_INLINE PetscErrorCode CompressPoints_Private(PetscSection section, PetscInt *numPoints, PetscInt points[])
4549: {
4550:   const PetscInt np = *numPoints;
4551:   PetscInt       pStart, pEnd, p, q;

4554:   PetscSectionGetChart(section, &pStart, &pEnd);
4555:   for (p = 0, q = 0; p < np; ++p) {
4556:     const PetscInt r = points[p*2];
4557:     if ((r >= pStart) && (r < pEnd)) {
4558:       points[q*2]   = r;
4559:       points[q*2+1] = points[p*2+1];
4560:       ++q;
4561:     }
4562:   }
4563:   *numPoints = q;
4564:   return 0;
4565: }

4567: static PetscErrorCode DMPlexTransitiveClosure_Hybrid_Internal(DM dm, PetscInt point, PetscInt np, PetscInt *numPoints, PetscInt **points)
4568: {
4569:   const PetscInt *cone, *ornt;
4570:   PetscInt       *pts,  *closure = NULL;
4571:   PetscInt        dim, coneSize, c, d, clSize, cl;
4572:   PetscErrorCode  ierr;

4575:   DMGetDimension(dm, &dim);
4576:   DMPlexGetConeSize(dm, point, &coneSize);
4577:   DMPlexGetCone(dm, point, &cone);
4578:   DMPlexGetConeOrientation(dm, point, &ornt);
4579:   DMPlexGetTransitiveClosure(dm, cone[0], PETSC_TRUE, &clSize, &closure);
4580:   DMGetWorkArray(dm, np*2, MPIU_INT, &pts);
4581:   c    = 0;
4582:   pts[c*2+0] = point;
4583:   pts[c*2+1] = 0;
4584:   ++c;
4585:   for (cl = 0; cl < clSize*2; cl += 2, ++c) {pts[c*2+0] = closure[cl]; pts[c*2+1] = closure[cl+1];}
4586:   DMPlexGetTransitiveClosure(dm, cone[1], PETSC_TRUE, &clSize, &closure);
4587:   for (cl = 0; cl < clSize*2; cl += 2, ++c) {pts[c*2+0] = closure[cl]; pts[c*2+1] = closure[cl+1];}
4588:   DMPlexRestoreTransitiveClosure(dm, cone[0], PETSC_TRUE, &clSize, &closure);
4589:   if (dim >= 2) {
4590:     for (d = 2; d < coneSize; ++d, ++c) {pts[c*2+0] = cone[d]; pts[c*2+1] = ornt[d];}
4591:   }
4592:   if (dim >= 3) {
4593:     for (d = 2; d < coneSize; ++d) {
4594:       const PetscInt  fpoint = cone[d];
4595:       const PetscInt *fcone;
4596:       PetscInt        fconeSize, fc, i;

4598:       DMPlexGetConeSize(dm, fpoint, &fconeSize);
4599:       DMPlexGetCone(dm, fpoint, &fcone);
4600:       for (fc = 0; fc < fconeSize; ++fc) {
4601:         for (i = 0; i < c; ++i) if (pts[i*2] == fcone[fc]) break;
4602:         if (i == c) {pts[c*2+0] = fcone[fc]; pts[c*2+1] = 0; ++c;}
4603:       }
4604:     }
4605:   }
4606:   if (c != np) SETERRQ3(PETSC_COMM_SELF, PETSC_ERR_PLIB, "Invalid closure for hybrid point %D, size %D != %D", point, c, np);
4607:   *numPoints = np;
4608:   *points    = pts;
4609:   return(0);
4610: }

4612: /* Compressed closure does not apply closure permutation */
4613: PetscErrorCode DMPlexGetCompressedClosure(DM dm, PetscSection section, PetscInt point, PetscInt *numPoints, PetscInt **points, PetscSection *clSec, IS *clPoints, const PetscInt **clp)
4614: {
4615:   const PetscInt *cla = NULL;
4616:   PetscInt       np, *pts = NULL;

4620:   PetscSectionGetClosureIndex(section, (PetscObject) dm, clSec, clPoints);
4621:   if (*clPoints) {
4622:     PetscInt dof, off;

4624:     PetscSectionGetDof(*clSec, point, &dof);
4625:     PetscSectionGetOffset(*clSec, point, &off);
4626:     ISGetIndices(*clPoints, &cla);
4627:     np   = dof/2;
4628:     pts  = (PetscInt *) &cla[off];
4629:   } else {
4630:     DMPolytopeType ct;

4632:     /* Do not make the label if it does not exist */
4633:     if (!dm->celltypeLabel) {ct = DM_POLYTOPE_POINT;}
4634:     else                    {DMPlexGetCellType(dm, point, &ct);}
4635:     switch (ct) {
4636:       case DM_POLYTOPE_SEG_PRISM_TENSOR:
4637:         DMPlexTransitiveClosure_Hybrid_Internal(dm, point, 9, &np, &pts);
4638:         break;
4639:       case DM_POLYTOPE_TRI_PRISM_TENSOR:
4640:         DMPlexTransitiveClosure_Hybrid_Internal(dm, point, 21, &np, &pts);
4641:         break;
4642:       case DM_POLYTOPE_QUAD_PRISM_TENSOR:
4643:         DMPlexTransitiveClosure_Hybrid_Internal(dm, point, 27, &np, &pts);
4644:         break;
4645:       default:
4646:         DMPlexGetTransitiveClosure(dm, point, PETSC_TRUE, &np, &pts);
4647:     }
4648:     CompressPoints_Private(section, &np, pts);
4649:   }
4650:   *numPoints = np;
4651:   *points    = pts;
4652:   *clp       = cla;
4653:   return(0);
4654: }

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

4661:   if (!*clPoints) {
4662:     DMPlexRestoreTransitiveClosure(dm, point, PETSC_TRUE, numPoints, points);
4663:   } else {
4664:     ISRestoreIndices(*clPoints, clp);
4665:   }
4666:   *numPoints = 0;
4667:   *points    = NULL;
4668:   *clSec     = NULL;
4669:   *clPoints  = NULL;
4670:   *clp       = NULL;
4671:   return(0);
4672: }

4674: 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[])
4675: {
4676:   PetscInt          offset = 0, p;
4677:   const PetscInt    **perms = NULL;
4678:   const PetscScalar **flips = NULL;
4679:   PetscErrorCode    ierr;

4682:   *size = 0;
4683:   PetscSectionGetPointSyms(section,numPoints,points,&perms,&flips);
4684:   for (p = 0; p < numPoints; p++) {
4685:     const PetscInt    point = points[2*p];
4686:     const PetscInt    *perm = perms ? perms[p] : NULL;
4687:     const PetscScalar *flip = flips ? flips[p] : NULL;
4688:     PetscInt          dof, off, d;
4689:     const PetscScalar *varr;

4691:     PetscSectionGetDof(section, point, &dof);
4692:     PetscSectionGetOffset(section, point, &off);
4693:     varr = &vArray[off];
4694:     if (clperm) {
4695:       if (perm) {
4696:         for (d = 0; d < dof; d++) array[clperm[offset + perm[d]]]  = varr[d];
4697:       } else {
4698:         for (d = 0; d < dof; d++) array[clperm[offset +      d ]]  = varr[d];
4699:       }
4700:       if (flip) {
4701:         for (d = 0; d < dof; d++) array[clperm[offset +      d ]] *= flip[d];
4702:       }
4703:     } else {
4704:       if (perm) {
4705:         for (d = 0; d < dof; d++) array[offset + perm[d]]  = varr[d];
4706:       } else {
4707:         for (d = 0; d < dof; d++) array[offset +      d ]  = varr[d];
4708:       }
4709:       if (flip) {
4710:         for (d = 0; d < dof; d++) array[offset +      d ] *= flip[d];
4711:       }
4712:     }
4713:     offset += dof;
4714:   }
4715:   PetscSectionRestorePointSyms(section,numPoints,points,&perms,&flips);
4716:   *size = offset;
4717:   return(0);
4718: }

4720: 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[])
4721: {
4722:   PetscInt          offset = 0, f;
4723:   PetscErrorCode    ierr;

4726:   *size = 0;
4727:   for (f = 0; f < numFields; ++f) {
4728:     PetscInt          p;
4729:     const PetscInt    **perms = NULL;
4730:     const PetscScalar **flips = NULL;

4732:     PetscSectionGetFieldPointSyms(section,f,numPoints,points,&perms,&flips);
4733:     for (p = 0; p < numPoints; p++) {
4734:       const PetscInt    point = points[2*p];
4735:       PetscInt          fdof, foff, b;
4736:       const PetscScalar *varr;
4737:       const PetscInt    *perm = perms ? perms[p] : NULL;
4738:       const PetscScalar *flip = flips ? flips[p] : NULL;

4740:       PetscSectionGetFieldDof(section, point, f, &fdof);
4741:       PetscSectionGetFieldOffset(section, point, f, &foff);
4742:       varr = &vArray[foff];
4743:       if (clperm) {
4744:         if (perm) {for (b = 0; b < fdof; b++) {array[clperm[offset + perm[b]]]  = varr[b];}}
4745:         else      {for (b = 0; b < fdof; b++) {array[clperm[offset +      b ]]  = varr[b];}}
4746:         if (flip) {for (b = 0; b < fdof; b++) {array[clperm[offset +      b ]] *= flip[b];}}
4747:       } else {
4748:         if (perm) {for (b = 0; b < fdof; b++) {array[offset + perm[b]]  = varr[b];}}
4749:         else      {for (b = 0; b < fdof; b++) {array[offset +      b ]  = varr[b];}}
4750:         if (flip) {for (b = 0; b < fdof; b++) {array[offset +      b ] *= flip[b];}}
4751:       }
4752:       offset += fdof;
4753:     }
4754:     PetscSectionRestoreFieldPointSyms(section,f,numPoints,points,&perms,&flips);
4755:   }
4756:   *size = offset;
4757:   return(0);
4758: }

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

4763:   Not collective

4765:   Input Parameters:
4766: + dm - The DM
4767: . section - The section describing the layout in v, or NULL to use the default section
4768: . v - The local vector
4769: . point - The point in the DM
4770: . csize - The size of the input values array, or NULL
4771: - values - An array to use for the values, or NULL to have it allocated automatically

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

4777: $ Note that DMPlexVecGetClosure/DMPlexVecRestoreClosure only allocates the values array if it set to NULL in the
4778: $ calling function. This is because DMPlexVecGetClosure() is typically called in the inner loop of a Vec or Mat
4779: $ assembly function, and a user may already have allocated storage for this operation.
4780: $
4781: $ A typical use could be
4782: $
4783: $  values = NULL;
4784: $  DMPlexVecGetClosure(dm, NULL, v, p, &clSize, &values);
4785: $  for (cl = 0; cl < clSize; ++cl) {
4786: $    <Compute on closure>
4787: $  }
4788: $  DMPlexVecRestoreClosure(dm, NULL, v, p, &clSize, &values);
4789: $
4790: $ or
4791: $
4792: $  PetscMalloc1(clMaxSize, &values);
4793: $  for (p = pStart; p < pEnd; ++p) {
4794: $    clSize = clMaxSize;
4795: $    DMPlexVecGetClosure(dm, NULL, v, p, &clSize, &values);
4796: $    for (cl = 0; cl < clSize; ++cl) {
4797: $      <Compute on closure>
4798: $    }
4799: $  }
4800: $  PetscFree(values);

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

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

4808:   Level: intermediate

4810: .seealso DMPlexVecRestoreClosure(), DMPlexVecSetClosure(), DMPlexMatSetClosure()
4811: @*/
4812: PetscErrorCode DMPlexVecGetClosure(DM dm, PetscSection section, Vec v, PetscInt point, PetscInt *csize, PetscScalar *values[])
4813: {
4814:   PetscSection       clSection;
4815:   IS                 clPoints;
4816:   PetscInt          *points = NULL;
4817:   const PetscInt    *clp, *perm;
4818:   PetscInt           depth, numFields, numPoints, asize;
4819:   PetscErrorCode     ierr;

4823:   if (!section) {DMGetLocalSection(dm, &section);}
4826:   DMPlexGetDepth(dm, &depth);
4827:   PetscSectionGetNumFields(section, &numFields);
4828:   if (depth == 1 && numFields < 2) {
4829:     DMPlexVecGetClosure_Depth1_Static(dm, section, v, point, csize, values);
4830:     return(0);
4831:   }
4832:   /* Get points */
4833:   DMPlexGetCompressedClosure(dm,section,point,&numPoints,&points,&clSection,&clPoints,&clp);
4834:   /* Get sizes */
4835:   asize = 0;
4836:   for (PetscInt p = 0; p < numPoints*2; p += 2) {
4837:     PetscInt dof;
4838:     PetscSectionGetDof(section, points[p], &dof);
4839:     asize += dof;
4840:   }
4841:   if (values) {
4842:     const PetscScalar *vArray;
4843:     PetscInt          size;

4845:     if (*values) {
4846:       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);
4847:     } else {DMGetWorkArray(dm, asize, MPIU_SCALAR, values);}
4848:     PetscSectionGetClosureInversePermutation_Internal(section, (PetscObject) dm, depth, asize, &perm);
4849:     VecGetArrayRead(v, &vArray);
4850:     /* Get values */
4851:     if (numFields > 0) {DMPlexVecGetClosure_Fields_Static(dm, section, numPoints, points, numFields, perm, vArray, &size, *values);}
4852:     else               {DMPlexVecGetClosure_Static(dm, section, numPoints, points, perm, vArray, &size, *values);}
4853:     if (PetscUnlikely(asize != size)) SETERRQ2(PETSC_COMM_SELF, PETSC_ERR_PLIB, "Section size %D does not match Vec closure size %D", asize, size);
4854:     /* Cleanup array */
4855:     VecRestoreArrayRead(v, &vArray);
4856:   }
4857:   if (csize) *csize = asize;
4858:   /* Cleanup points */
4859:   DMPlexRestoreCompressedClosure(dm,section,point,&numPoints,&points,&clSection,&clPoints,&clp);
4860:   return(0);
4861: }

4863: PetscErrorCode DMPlexVecGetClosureAtDepth_Internal(DM dm, PetscSection section, Vec v, PetscInt point, PetscInt depth, PetscInt *csize, PetscScalar *values[])
4864: {
4865:   DMLabel            depthLabel;
4866:   PetscSection       clSection;
4867:   IS                 clPoints;
4868:   PetscScalar       *array;
4869:   const PetscScalar *vArray;
4870:   PetscInt          *points = NULL;
4871:   const PetscInt    *clp, *perm = NULL;
4872:   PetscInt           mdepth, numFields, numPoints, Np = 0, p, clsize, size;
4873:   PetscErrorCode     ierr;

4877:   if (!section) {DMGetLocalSection(dm, &section);}
4880:   DMPlexGetDepth(dm, &mdepth);
4881:   DMPlexGetDepthLabel(dm, &depthLabel);
4882:   PetscSectionGetNumFields(section, &numFields);
4883:   if (mdepth == 1 && numFields < 2) {
4884:     DMPlexVecGetClosure_Depth1_Static(dm, section, v, point, csize, values);
4885:     return(0);
4886:   }
4887:   /* Get points */
4888:   DMPlexGetCompressedClosure(dm,section,point,&numPoints,&points,&clSection,&clPoints,&clp);
4889:   for (clsize=0,p=0; p<Np; p++) {
4890:     PetscInt dof;
4891:     PetscSectionGetDof(section, points[2*p], &dof);
4892:     clsize += dof;
4893:   }
4894:   PetscSectionGetClosureInversePermutation_Internal(section, (PetscObject) dm, depth, clsize, &perm);
4895:   /* Filter points */
4896:   for (p = 0; p < numPoints*2; p += 2) {
4897:     PetscInt dep;

4899:     DMLabelGetValue(depthLabel, points[p], &dep);
4900:     if (dep != depth) continue;
4901:     points[Np*2+0] = points[p];
4902:     points[Np*2+1] = points[p+1];
4903:     ++Np;
4904:   }
4905:   /* Get array */
4906:   if (!values || !*values) {
4907:     PetscInt asize = 0, dof;

4909:     for (p = 0; p < Np*2; p += 2) {
4910:       PetscSectionGetDof(section, points[p], &dof);
4911:       asize += dof;
4912:     }
4913:     if (!values) {
4914:       DMPlexRestoreCompressedClosure(dm,section,point,&numPoints,&points,&clSection,&clPoints,&clp);
4915:       if (csize) *csize = asize;
4916:       return(0);
4917:     }
4918:     DMGetWorkArray(dm, asize, MPIU_SCALAR, &array);
4919:   } else {
4920:     array = *values;
4921:   }
4922:   VecGetArrayRead(v, &vArray);
4923:   /* Get values */
4924:   if (numFields > 0) {DMPlexVecGetClosure_Fields_Static(dm, section, Np, points, numFields, perm, vArray, &size, array);}
4925:   else               {DMPlexVecGetClosure_Static(dm, section, Np, points, perm, vArray, &size, array);}
4926:   /* Cleanup points */
4927:   DMPlexRestoreCompressedClosure(dm,section,point,&numPoints,&points,&clSection,&clPoints,&clp);
4928:   /* Cleanup array */
4929:   VecRestoreArrayRead(v, &vArray);
4930:   if (!*values) {
4931:     if (csize) *csize = size;
4932:     *values = array;
4933:   } else {
4934:     if (size > *csize) SETERRQ2(PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Size of input array %D < actual size %D", *csize, size);
4935:     *csize = size;
4936:   }
4937:   return(0);
4938: }

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

4943:   Not collective

4945:   Input Parameters:
4946: + dm - The DM
4947: . section - The section describing the layout in v, or NULL to use the default section
4948: . v - The local vector
4949: . point - The point in the DM
4950: . csize - The number of values in the closure, or NULL
4951: - values - The array of values, which is a borrowed array and should not be freed

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

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

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

4961:   Level: intermediate

4963: .seealso DMPlexVecGetClosure(), DMPlexVecSetClosure(), DMPlexMatSetClosure()
4964: @*/
4965: PetscErrorCode DMPlexVecRestoreClosure(DM dm, PetscSection section, Vec v, PetscInt point, PetscInt *csize, PetscScalar *values[])
4966: {
4967:   PetscInt       size = 0;

4971:   /* Should work without recalculating size */
4972:   DMRestoreWorkArray(dm, size, MPIU_SCALAR, (void*) values);
4973:   *values = NULL;
4974:   return(0);
4975: }

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

4980: 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[])
4981: {
4982:   PetscInt        cdof;   /* The number of constraints on this point */
4983:   const PetscInt *cdofs; /* The indices of the constrained dofs on this point */
4984:   PetscScalar    *a;
4985:   PetscInt        off, cind = 0, k;
4986:   PetscErrorCode  ierr;

4989:   PetscSectionGetConstraintDof(section, point, &cdof);
4990:   PetscSectionGetOffset(section, point, &off);
4991:   a    = &array[off];
4992:   if (!cdof || setBC) {
4993:     if (clperm) {
4994:       if (perm) {for (k = 0; k < dof; ++k) {fuse(&a[k], values[clperm[offset+perm[k]]] * (flip ? flip[perm[k]] : 1.));}}
4995:       else      {for (k = 0; k < dof; ++k) {fuse(&a[k], values[clperm[offset+     k ]] * (flip ? flip[     k ] : 1.));}}
4996:     } else {
4997:       if (perm) {for (k = 0; k < dof; ++k) {fuse(&a[k], values[offset+perm[k]] * (flip ? flip[perm[k]] : 1.));}}
4998:       else      {for (k = 0; k < dof; ++k) {fuse(&a[k], values[offset+     k ] * (flip ? flip[     k ] : 1.));}}
4999:     }
5000:   } else {
5001:     PetscSectionGetConstraintIndices(section, point, &cdofs);
5002:     if (clperm) {
5003:       if (perm) {for (k = 0; k < dof; ++k) {
5004:           if ((cind < cdof) && (k == cdofs[cind])) {++cind; continue;}
5005:           fuse(&a[k], values[clperm[offset+perm[k]]] * (flip ? flip[perm[k]] : 1.));
5006:         }
5007:       } else {
5008:         for (k = 0; k < dof; ++k) {
5009:           if ((cind < cdof) && (k == cdofs[cind])) {++cind; continue;}
5010:           fuse(&a[k], values[clperm[offset+     k ]] * (flip ? flip[     k ] : 1.));
5011:         }
5012:       }
5013:     } else {
5014:       if (perm) {
5015:         for (k = 0; k < dof; ++k) {
5016:           if ((cind < cdof) && (k == cdofs[cind])) {++cind; continue;}
5017:           fuse(&a[k], values[offset+perm[k]] * (flip ? flip[perm[k]] : 1.));
5018:         }
5019:       } else {
5020:         for (k = 0; k < dof; ++k) {
5021:           if ((cind < cdof) && (k == cdofs[cind])) {++cind; continue;}
5022:           fuse(&a[k], values[offset+     k ] * (flip ? flip[     k ] : 1.));
5023:         }
5024:       }
5025:     }
5026:   }
5027:   return(0);
5028: }

5030: 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[])
5031: {
5032:   PetscInt        cdof;   /* The number of constraints on this point */
5033:   const PetscInt *cdofs; /* The indices of the constrained dofs on this point */
5034:   PetscScalar    *a;
5035:   PetscInt        off, cind = 0, k;
5036:   PetscErrorCode  ierr;

5039:   PetscSectionGetConstraintDof(section, point, &cdof);
5040:   PetscSectionGetOffset(section, point, &off);
5041:   a    = &array[off];
5042:   if (cdof) {
5043:     PetscSectionGetConstraintIndices(section, point, &cdofs);
5044:     if (clperm) {
5045:       if (perm) {
5046:         for (k = 0; k < dof; ++k) {
5047:           if ((cind < cdof) && (k == cdofs[cind])) {
5048:             fuse(&a[k], values[clperm[offset+perm[k]]] * (flip ? flip[perm[k]] : 1.));
5049:             cind++;
5050:           }
5051:         }
5052:       } else {
5053:         for (k = 0; k < dof; ++k) {
5054:           if ((cind < cdof) && (k == cdofs[cind])) {
5055:             fuse(&a[k], values[clperm[offset+     k ]] * (flip ? flip[     k ] : 1.));
5056:             cind++;
5057:           }
5058:         }
5059:       }
5060:     } else {
5061:       if (perm) {
5062:         for (k = 0; k < dof; ++k) {
5063:           if ((cind < cdof) && (k == cdofs[cind])) {
5064:             fuse(&a[k], values[offset+perm[k]] * (flip ? flip[perm[k]] : 1.));
5065:             cind++;
5066:           }
5067:         }
5068:       } else {
5069:         for (k = 0; k < dof; ++k) {
5070:           if ((cind < cdof) && (k == cdofs[cind])) {
5071:             fuse(&a[k], values[offset+     k ] * (flip ? flip[     k ] : 1.));
5072:             cind++;
5073:           }
5074:         }
5075:       }
5076:     }
5077:   }
5078:   return(0);
5079: }

5081: 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[])
5082: {
5083:   PetscScalar    *a;
5084:   PetscInt        fdof, foff, fcdof, foffset = *offset;
5085:   const PetscInt *fcdofs; /* The indices of the constrained dofs for field f on this point */
5086:   PetscInt        cind = 0, b;
5087:   PetscErrorCode  ierr;

5090:   PetscSectionGetFieldDof(section, point, f, &fdof);
5091:   PetscSectionGetFieldConstraintDof(section, point, f, &fcdof);
5092:   PetscSectionGetFieldOffset(section, point, f, &foff);
5093:   a    = &array[foff];
5094:   if (!fcdof || setBC) {
5095:     if (clperm) {
5096:       if (perm) {for (b = 0; b < fdof; b++) {fuse(&a[b], values[clperm[foffset+perm[b]]] * (flip ? flip[perm[b]] : 1.));}}
5097:       else      {for (b = 0; b < fdof; b++) {fuse(&a[b], values[clperm[foffset+     b ]] * (flip ? flip[     b ] : 1.));}}
5098:     } else {
5099:       if (perm) {for (b = 0; b < fdof; b++) {fuse(&a[b], values[foffset+perm[b]] * (flip ? flip[perm[b]] : 1.));}}
5100:       else      {for (b = 0; b < fdof; b++) {fuse(&a[b], values[foffset+     b ] * (flip ? flip[     b ] : 1.));}}
5101:     }
5102:   } else {
5103:     PetscSectionGetFieldConstraintIndices(section, point, f, &fcdofs);
5104:     if (clperm) {
5105:       if (perm) {
5106:         for (b = 0; b < fdof; b++) {
5107:           if ((cind < fcdof) && (b == fcdofs[cind])) {++cind; continue;}
5108:           fuse(&a[b], values[clperm[foffset+perm[b]]] * (flip ? flip[perm[b]] : 1.));
5109:         }
5110:       } else {
5111:         for (b = 0; b < fdof; b++) {
5112:           if ((cind < fcdof) && (b == fcdofs[cind])) {++cind; continue;}
5113:           fuse(&a[b], values[clperm[foffset+     b ]] * (flip ? flip[     b ] : 1.));
5114:         }
5115:       }
5116:     } else {
5117:       if (perm) {
5118:         for (b = 0; b < fdof; b++) {
5119:           if ((cind < fcdof) && (b == fcdofs[cind])) {++cind; continue;}
5120:           fuse(&a[b], values[foffset+perm[b]] * (flip ? flip[perm[b]] : 1.));
5121:         }
5122:       } else {
5123:         for (b = 0; b < fdof; b++) {
5124:           if ((cind < fcdof) && (b == fcdofs[cind])) {++cind; continue;}
5125:           fuse(&a[b], values[foffset+     b ] * (flip ? flip[     b ] : 1.));
5126:         }
5127:       }
5128:     }
5129:   }
5130:   *offset += fdof;
5131:   return(0);
5132: }

5134: 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[])
5135: {
5136:   PetscScalar    *a;
5137:   PetscInt        fdof, foff, fcdof, foffset = *offset;
5138:   const PetscInt *fcdofs; /* The indices of the constrained dofs for field f on this point */
5139:   PetscInt        Nc, cind = 0, ncind = 0, b;
5140:   PetscBool       ncSet, fcSet;
5141:   PetscErrorCode  ierr;

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

5226: PETSC_STATIC_INLINE PetscErrorCode DMPlexVecSetClosure_Depth1_Static(DM dm, PetscSection section, Vec v, PetscInt point, const PetscScalar values[], InsertMode mode)
5227: {
5228:   PetscScalar    *array;
5229:   const PetscInt *cone, *coneO;
5230:   PetscInt        pStart, pEnd, p, numPoints, off, dof;
5231:   PetscErrorCode  ierr;

5234:   PetscSectionGetChart(section, &pStart, &pEnd);
5235:   DMPlexGetConeSize(dm, point, &numPoints);
5236:   DMPlexGetCone(dm, point, &cone);
5237:   DMPlexGetConeOrientation(dm, point, &coneO);
5238:   VecGetArray(v, &array);
5239:   for (p = 0, off = 0; p <= numPoints; ++p, off += dof) {
5240:     const PetscInt cp = !p ? point : cone[p-1];
5241:     const PetscInt o  = !p ? 0     : coneO[p-1];

5243:     if ((cp < pStart) || (cp >= pEnd)) {dof = 0; continue;}
5244:     PetscSectionGetDof(section, cp, &dof);
5245:     /* ADD_VALUES */
5246:     {
5247:       const PetscInt *cdofs; /* The indices of the constrained dofs on this point */
5248:       PetscScalar    *a;
5249:       PetscInt        cdof, coff, cind = 0, k;

5251:       PetscSectionGetConstraintDof(section, cp, &cdof);
5252:       PetscSectionGetOffset(section, cp, &coff);
5253:       a    = &array[coff];
5254:       if (!cdof) {
5255:         if (o >= 0) {
5256:           for (k = 0; k < dof; ++k) {
5257:             a[k] += values[off+k];
5258:           }
5259:         } else {
5260:           for (k = 0; k < dof; ++k) {
5261:             a[k] += values[off+dof-k-1];
5262:           }
5263:         }
5264:       } else {
5265:         PetscSectionGetConstraintIndices(section, cp, &cdofs);
5266:         if (o >= 0) {
5267:           for (k = 0; k < dof; ++k) {
5268:             if ((cind < cdof) && (k == cdofs[cind])) {++cind; continue;}
5269:             a[k] += values[off+k];
5270:           }
5271:         } else {
5272:           for (k = 0; k < dof; ++k) {
5273:             if ((cind < cdof) && (k == cdofs[cind])) {++cind; continue;}
5274:             a[k] += values[off+dof-k-1];
5275:           }
5276:         }
5277:       }
5278:     }
5279:   }
5280:   VecRestoreArray(v, &array);
5281:   return(0);
5282: }

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

5287:   Not collective

5289:   Input Parameters:
5290: + dm - The DM
5291: . section - The section describing the layout in v, or NULL to use the default section
5292: . v - The local vector
5293: . point - The point in the DM
5294: . values - The array of values
5295: - mode - The insert mode. One of INSERT_ALL_VALUES, ADD_ALL_VALUES, INSERT_VALUES, ADD_VALUES, INSERT_BC_VALUES, and ADD_BC_VALUES,
5296:          where INSERT_ALL_VALUES and ADD_ALL_VALUES also overwrite boundary conditions.

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

5301:   Level: intermediate

5303: .seealso DMPlexVecGetClosure(), DMPlexMatSetClosure()
5304: @*/
5305: PetscErrorCode DMPlexVecSetClosure(DM dm, PetscSection section, Vec v, PetscInt point, const PetscScalar values[], InsertMode mode)
5306: {
5307:   PetscSection    clSection;
5308:   IS              clPoints;
5309:   PetscScalar    *array;
5310:   PetscInt       *points = NULL;
5311:   const PetscInt *clp, *clperm = NULL;
5312:   PetscInt        depth, numFields, numPoints, p, clsize;
5313:   PetscErrorCode  ierr;

5317:   if (!section) {DMGetLocalSection(dm, &section);}
5320:   DMPlexGetDepth(dm, &depth);
5321:   PetscSectionGetNumFields(section, &numFields);
5322:   if (depth == 1 && numFields < 2 && mode == ADD_VALUES) {
5323:     DMPlexVecSetClosure_Depth1_Static(dm, section, v, point, values, mode);
5324:     return(0);
5325:   }
5326:   /* Get points */
5327:   DMPlexGetCompressedClosure(dm,section,point,&numPoints,&points,&clSection,&clPoints,&clp);
5328:   for (clsize=0,p=0; p<numPoints; p++) {
5329:     PetscInt dof;
5330:     PetscSectionGetDof(section, points[2*p], &dof);
5331:     clsize += dof;
5332:   }
5333:   PetscSectionGetClosureInversePermutation_Internal(section, (PetscObject) dm, depth, clsize, &clperm);
5334:   /* Get array */
5335:   VecGetArray(v, &array);
5336:   /* Get values */
5337:   if (numFields > 0) {
5338:     PetscInt offset = 0, f;
5339:     for (f = 0; f < numFields; ++f) {
5340:       const PetscInt    **perms = NULL;
5341:       const PetscScalar **flips = NULL;

5343:       PetscSectionGetFieldPointSyms(section,f,numPoints,points,&perms,&flips);
5344:       switch (mode) {
5345:       case INSERT_VALUES:
5346:         for (p = 0; p < numPoints; p++) {
5347:           const PetscInt    point = points[2*p];
5348:           const PetscInt    *perm = perms ? perms[p] : NULL;
5349:           const PetscScalar *flip = flips ? flips[p] : NULL;
5350:           updatePointFields_private(section, point, perm, flip, f, insert, PETSC_FALSE, clperm, values, &offset, array);
5351:         } break;
5352:       case INSERT_ALL_VALUES:
5353:         for (p = 0; p < numPoints; p++) {
5354:           const PetscInt    point = points[2*p];
5355:           const PetscInt    *perm = perms ? perms[p] : NULL;
5356:           const PetscScalar *flip = flips ? flips[p] : NULL;
5357:           updatePointFields_private(section, point, perm, flip, f, insert, PETSC_TRUE, clperm, values, &offset, array);
5358:         } break;
5359:       case INSERT_BC_VALUES:
5360:         for (p = 0; p < numPoints; p++) {
5361:           const PetscInt    point = points[2*p];
5362:           const PetscInt    *perm = perms ? perms[p] : NULL;
5363:           const PetscScalar *flip = flips ? flips[p] : NULL;
5364:           updatePointFieldsBC_private(section, point, perm, flip, f, -1, NULL, insert, clperm, values, &offset, array);
5365:         } break;
5366:       case ADD_VALUES:
5367:         for (p = 0; p < numPoints; p++) {
5368:           const PetscInt    point = points[2*p];
5369:           const PetscInt    *perm = perms ? perms[p] : NULL;
5370:           const PetscScalar *flip = flips ? flips[p] : NULL;
5371:           updatePointFields_private(section, point, perm, flip, f, add, PETSC_FALSE, clperm, values, &offset, array);
5372:         } break;
5373:       case ADD_ALL_VALUES:
5374:         for (p = 0; p < numPoints; p++) {
5375:           const PetscInt    point = points[2*p];
5376:           const PetscInt    *perm = perms ? perms[p] : NULL;
5377:           const PetscScalar *flip = flips ? flips[p] : NULL;
5378:           updatePointFields_private(section, point, perm, flip, f, add, PETSC_TRUE, clperm, values, &offset, array);
5379:         } break;
5380:       case ADD_BC_VALUES:
5381:         for (p = 0; p < numPoints; p++) {
5382:           const PetscInt    point = points[2*p];
5383:           const PetscInt    *perm = perms ? perms[p] : NULL;
5384:           const PetscScalar *flip = flips ? flips[p] : NULL;
5385:           updatePointFieldsBC_private(section, point, perm, flip, f, -1, NULL, add, clperm, values, &offset, array);
5386:         } break;
5387:       default:
5388:         SETERRQ1(PetscObjectComm((PetscObject)dm), PETSC_ERR_ARG_OUTOFRANGE, "Invalid insert mode %d", mode);
5389:       }
5390:       PetscSectionRestoreFieldPointSyms(section,f,numPoints,points,&perms,&flips);
5391:     }
5392:   } else {
5393:     PetscInt dof, off;
5394:     const PetscInt    **perms = NULL;
5395:     const PetscScalar **flips = NULL;

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

5459: /* Check whether the given point is in the label. If not, update the offset to skip this point */
5460: PETSC_STATIC_INLINE PetscErrorCode CheckPoint_Private(DMLabel label, PetscInt labelId, PetscSection section, PetscInt point, PetscInt f, PetscInt *offset)
5461: {
5463:   if (label) {
5464:     PetscInt       val, fdof;

5467:     /* There is a problem with this:
5468:          Suppose we have two label values, defining surfaces, interecting along a line in 3D. When we add cells to the label, the cells that
5469:        touch both surfaces must pick a label value. Thus we miss setting values for the surface with that other value intersecting that cell.
5470:        Thus I am only going to check val != -1, not val != labelId
5471:     */
5472:     DMLabelGetValue(label, point, &val);
5473:     if (val < 0) {
5474:       PetscSectionGetFieldDof(section, point, f, &fdof);
5475:       *offset += fdof;
5476:       PetscFunctionReturn(1);
5477:     }
5478:   }
5479:   return(0);
5480: }

5482: /* Unlike DMPlexVecSetClosure(), this uses plex-native closure permutation, not a user-specified permutation such as DMPlexSetClosurePermutationTensor(). */
5483: 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)
5484: {
5485:   PetscSection      clSection;
5486:   IS                clPoints;
5487:   PetscScalar       *array;
5488:   PetscInt          *points = NULL;
5489:   const PetscInt    *clp;
5490:   PetscInt          numFields, numPoints, p;
5491:   PetscInt          offset = 0, f;
5492:   PetscErrorCode    ierr;

5496:   if (!section) {DMGetLocalSection(dm, &section);}
5499:   PetscSectionGetNumFields(section, &numFields);
5500:   /* Get points */
5501:   DMPlexGetCompressedClosure(dm,section,point,&numPoints,&points,&clSection,&clPoints,&clp);
5502:   /* Get array */
5503:   VecGetArray(v, &array);
5504:   /* Get values */
5505:   for (f = 0; f < numFields; ++f) {
5506:     const PetscInt    **perms = NULL;
5507:     const PetscScalar **flips = NULL;

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

5571: static PetscErrorCode DMPlexPrintMatSetValues(PetscViewer viewer, Mat A, PetscInt point, PetscInt numRIndices, const PetscInt rindices[], PetscInt numCIndices, const PetscInt cindices[], const PetscScalar values[])
5572: {
5573:   PetscMPIInt    rank;
5574:   PetscInt       i, j;

5578:   MPI_Comm_rank(PetscObjectComm((PetscObject)A), &rank);
5579:   PetscViewerASCIIPrintf(viewer, "[%d]mat for point %D\n", rank, point);
5580:   for (i = 0; i < numRIndices; i++) {PetscViewerASCIIPrintf(viewer, "[%d]mat row indices[%D] = %D\n", rank, i, rindices[i]);}
5581:   for (i = 0; i < numCIndices; i++) {PetscViewerASCIIPrintf(viewer, "[%d]mat col indices[%D] = %D\n", rank, i, cindices[i]);}
5582:   numCIndices = numCIndices ? numCIndices : numRIndices;
5583:   if (!values) return(0);
5584:   for (i = 0; i < numRIndices; i++) {
5585:     PetscViewerASCIIPrintf(viewer, "[%d]", rank);
5586:     for (j = 0; j < numCIndices; j++) {
5587: #if defined(PETSC_USE_COMPLEX)
5588:       PetscViewerASCIIPrintf(viewer, " (%g,%g)", (double)PetscRealPart(values[i*numCIndices+j]), (double)PetscImaginaryPart(values[i*numCIndices+j]));
5589: #else
5590:       PetscViewerASCIIPrintf(viewer, " %g", (double)values[i*numCIndices+j]);
5591: #endif
5592:     }
5593:     PetscViewerASCIIPrintf(viewer, "\n");
5594:   }
5595:   return(0);
5596: }

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

5601:   Input Parameters:
5602: + section - The section for this data layout
5603: . islocal - Is the section (and thus indices being requested) local or global?
5604: . point   - The point contributing dofs with these indices
5605: . off     - The global offset of this point
5606: . loff    - The local offset of each field
5607: . setBC   - The flag determining whether to include indices of bounsary values
5608: . perm    - A permutation of the dofs on this point, or NULL
5609: - indperm - A permutation of the entire indices array, or NULL

5611:   Output Parameter:
5612: . indices - Indices for dofs on this point

5614:   Level: developer

5616:   Note: The indices could be local or global, depending on the value of 'off'.
5617: */
5618: PetscErrorCode DMPlexGetIndicesPoint_Internal(PetscSection section, PetscBool islocal,PetscInt point, PetscInt off, PetscInt *loff, PetscBool setBC, const PetscInt perm[], const PetscInt indperm[], PetscInt indices[])
5619: {
5620:   PetscInt        dof;   /* The number of unknowns on this point */
5621:   PetscInt        cdof;  /* The number of constraints on this point */
5622:   const PetscInt *cdofs; /* The indices of the constrained dofs on this point */
5623:   PetscInt        cind = 0, k;
5624:   PetscErrorCode  ierr;

5627:   if (!islocal && setBC) SETERRQ(PetscObjectComm((PetscObject)section),PETSC_ERR_ARG_INCOMP,"setBC incompatible with global indices; use a local section or disable setBC");
5628:   PetscSectionGetDof(section, point, &dof);
5629:   PetscSectionGetConstraintDof(section, point, &cdof);
5630:   if (!cdof || setBC) {
5631:     for (k = 0; k < dof; ++k) {
5632:       const PetscInt preind = perm ? *loff+perm[k] : *loff+k;
5633:       const PetscInt ind    = indperm ? indperm[preind] : preind;

5635:       indices[ind] = off + k;
5636:     }
5637:   } else {
5638:     PetscSectionGetConstraintIndices(section, point, &cdofs);
5639:     for (k = 0; k < dof; ++k) {
5640:       const PetscInt preind = perm ? *loff+perm[k] : *loff+k;
5641:       const PetscInt ind    = indperm ? indperm[preind] : preind;

5643:       if ((cind < cdof) && (k == cdofs[cind])) {
5644:         /* Insert check for returning constrained indices */
5645:         indices[ind] = -(off+k+1);
5646:         ++cind;
5647:       } else {
5648:         indices[ind] = off + k - (islocal ? 0 : cind);
5649:       }
5650:     }
5651:   }
5652:   *loff += dof;
5653:   return(0);
5654: }

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

5659:  Input Parameters:
5660: + section - a section (global or local)
5661: - islocal - PETSC_TRUE if requesting local indices (i.e., section is local); PETSC_FALSE for global
5662: . point - point within section
5663: . off - The offset of this point in the (local or global) indexed space - should match islocal and (usually) the section
5664: . foffs - array of length numFields containing the offset in canonical point ordering (the location in indices) of each field
5665: . setBC - identify constrained (boundary condition) points via involution.
5666: . perms - perms[f][permsoff][:] is a permutation of dofs within each field
5667: . permsoff - offset
5668: - indperm - index permutation

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

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

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

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

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

5693:  Level: developer
5694: */
5695: 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[])
5696: {
5697:   PetscInt       numFields, foff, f;

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

5709:     PetscSectionGetFieldDof(section, point, f, &fdof);
5710:     PetscSectionGetFieldConstraintDof(section, point, f, &cfdof);
5711:     if (!cfdof || setBC) {
5712:       for (b = 0; b < fdof; ++b) {
5713:         const PetscInt preind = perm ? foffs[f]+perm[b] : foffs[f]+b;
5714:         const PetscInt ind    = indperm ? indperm[preind] : preind;

5716:         indices[ind] = off+foff+b;
5717:       }
5718:     } else {
5719:       PetscSectionGetFieldConstraintIndices(section, point, f, &fcdofs);
5720:       for (b = 0; b < fdof; ++b) {
5721:         const PetscInt preind = perm ? foffs[f]+perm[b] : foffs[f]+b;
5722:         const PetscInt ind    = indperm ? indperm[preind] : preind;

5724:         if ((cind < cfdof) && (b == fcdofs[cind])) {
5725:           indices[ind] = -(off+foff+b+1);
5726:           ++cind;
5727:         } else {
5728:           indices[ind] = off + foff + b - (islocal ? 0 : cind);
5729:         }
5730:       }
5731:     }
5732:     foff     += (setBC || islocal ? fdof : (fdof - cfdof));
5733:     foffs[f] += fdof;
5734:   }
5735:   return(0);
5736: }

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

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

5743:  Notes:
5744:  The semantics of this function relate to that of setBC=FALSE in DMPlexGetIndicesPointFields_Internal.
5745:  Since this function uses global indices, setBC=TRUE would be invalid, so no such argument exists.
5746: */
5747: static PetscErrorCode DMPlexGetIndicesPointFieldsSplit_Internal(PetscSection section, PetscSection globalSection, PetscInt point, PetscInt foffs[], const PetscInt ***perms, PetscInt permsoff, const PetscInt indperm[], PetscInt indices[])
5748: {
5749:   PetscInt       numFields, foff, f;

5753:   PetscSectionGetNumFields(section, &numFields);
5754:   for (f = 0; f < numFields; ++f) {
5755:     PetscInt        fdof, cfdof;
5756:     const PetscInt *fcdofs; /* The indices of the constrained dofs for field f on this point */
5757:     PetscInt        cind = 0, b;
5758:     const PetscInt  *perm = (perms && perms[f]) ? perms[f][permsoff] : NULL;

5760:     PetscSectionGetFieldDof(section, point, f, &fdof);
5761:     PetscSectionGetFieldConstraintDof(section, point, f, &cfdof);
5762:     PetscSectionGetFieldOffset(globalSection, point, f, &foff);
5763:     if (!cfdof) {
5764:       for (b = 0; b < fdof; ++b) {
5765:         const PetscInt preind = perm ? foffs[f]+perm[b] : foffs[f]+b;
5766:         const PetscInt ind    = indperm ? indperm[preind] : preind;

5768:         indices[ind] = foff+b;
5769:       }
5770:     } else {
5771:       PetscSectionGetFieldConstraintIndices(section, point, f, &fcdofs);
5772:       for (b = 0; b < fdof; ++b) {
5773:         const PetscInt preind = perm ? foffs[f]+perm[b] : foffs[f]+b;
5774:         const PetscInt ind    = indperm ? indperm[preind] : preind;

5776:         if ((cind < cfdof) && (b == fcdofs[cind])) {
5777:           indices[ind] = -(foff+b+1);
5778:           ++cind;
5779:         } else {
5780:           indices[ind] = foff+b-cind;
5781:         }
5782:       }
5783:     }
5784:     foffs[f] += fdof;
5785:   }
5786:   return(0);
5787: }

5789: 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)
5790: {
5791:   Mat             cMat;
5792:   PetscSection    aSec, cSec;
5793:   IS              aIS;
5794:   PetscInt        aStart = -1, aEnd = -1;
5795:   const PetscInt  *anchors;
5796:   PetscInt        numFields, f, p, q, newP = 0;
5797:   PetscInt        newNumPoints = 0, newNumIndices = 0;
5798:   PetscInt        *newPoints, *indices, *newIndices;
5799:   PetscInt        maxAnchor, maxDof;
5800:   PetscInt        newOffsets[32];
5801:   PetscInt        *pointMatOffsets[32];
5802:   PetscInt        *newPointOffsets[32];
5803:   PetscScalar     *pointMat[32];
5804:   PetscScalar     *newValues=NULL,*tmpValues;
5805:   PetscBool       anyConstrained = PETSC_FALSE;
5806:   PetscErrorCode  ierr;

5811:   PetscSectionGetNumFields(section, &numFields);

5813:   DMPlexGetAnchors(dm,&aSec,&aIS);
5814:   /* if there are point-to-point constraints */
5815:   if (aSec) {
5816:     PetscArrayzero(newOffsets, 32);
5817:     ISGetIndices(aIS,&anchors);
5818:     PetscSectionGetChart(aSec,&aStart,&aEnd);
5819:     /* figure out how many points are going to be in the new element matrix
5820:      * (we allow double counting, because it's all just going to be summed
5821:      * into the global matrix anyway) */
5822:     for (p = 0; p < 2*numPoints; p+=2) {
5823:       PetscInt b    = points[p];
5824:       PetscInt bDof = 0, bSecDof;

5826:       PetscSectionGetDof(section,b,&bSecDof);
5827:       if (!bSecDof) {
5828:         continue;
5829:       }
5830:       if (b >= aStart && b < aEnd) {
5831:         PetscSectionGetDof(aSec,b,&bDof);
5832:       }
5833:       if (bDof) {
5834:         /* this point is constrained */
5835:         /* it is going to be replaced by its anchors */
5836:         PetscInt bOff, q;

5838:         anyConstrained = PETSC_TRUE;
5839:         newNumPoints  += bDof;
5840:         PetscSectionGetOffset(aSec,b,&bOff);
5841:         for (q = 0; q < bDof; q++) {
5842:           PetscInt a = anchors[bOff + q];
5843:           PetscInt aDof;

5845:           PetscSectionGetDof(section,a,&aDof);
5846:           newNumIndices += aDof;
5847:           for (f = 0; f < numFields; ++f) {
5848:             PetscInt fDof;

5850:             PetscSectionGetFieldDof(section, a, f, &fDof);
5851:             newOffsets[f+1] += fDof;
5852:           }
5853:         }
5854:       }
5855:       else {
5856:         /* this point is not constrained */
5857:         newNumPoints++;
5858:         newNumIndices += bSecDof;
5859:         for (f = 0; f < numFields; ++f) {
5860:           PetscInt fDof;

5862:           PetscSectionGetFieldDof(section, b, f, &fDof);
5863:           newOffsets[f+1] += fDof;
5864:         }
5865:       }
5866:     }
5867:   }
5868:   if (!anyConstrained) {
5869:     if (outNumPoints)  *outNumPoints  = 0;
5870:     if (outNumIndices) *outNumIndices = 0;
5871:     if (outPoints)     *outPoints     = NULL;
5872:     if (outValues)     *outValues     = NULL;
5873:     if (aSec) {ISRestoreIndices(aIS,&anchors);}
5874:     return(0);
5875:   }

5877:   if (outNumPoints)  *outNumPoints  = newNumPoints;
5878:   if (outNumIndices) *outNumIndices = newNumIndices;

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

5882:   if (!outPoints && !outValues) {
5883:     if (offsets) {
5884:       for (f = 0; f <= numFields; f++) {
5885:         offsets[f] = newOffsets[f];
5886:       }
5887:     }
5888:     if (aSec) {ISRestoreIndices(aIS,&anchors);}
5889:     return(0);
5890:   }

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

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

5896:   /* workspaces */
5897:   if (numFields) {
5898:     for (f = 0; f < numFields; f++) {
5899:       DMGetWorkArray(dm,numPoints+1,MPIU_INT,&pointMatOffsets[f]);
5900:       DMGetWorkArray(dm,numPoints+1,MPIU_INT,&newPointOffsets[f]);
5901:     }
5902:   }
5903:   else {
5904:     DMGetWorkArray(dm,numPoints+1,MPIU_INT,&pointMatOffsets[0]);
5905:     DMGetWorkArray(dm,numPoints,MPIU_INT,&newPointOffsets[0]);
5906:   }

5908:   /* get workspaces for the point-to-point matrices */
5909:   if (numFields) {
5910:     PetscInt totalOffset, totalMatOffset;

5912:     for (p = 0; p < numPoints; p++) {
5913:       PetscInt b    = points[2*p];
5914:       PetscInt bDof = 0, bSecDof;

5916:       PetscSectionGetDof(section,b,&bSecDof);
5917:       if (!bSecDof) {
5918:         for (f = 0; f < numFields; f++) {
5919:           newPointOffsets[f][p + 1] = 0;
5920:           pointMatOffsets[f][p + 1] = 0;
5921:         }
5922:         continue;
5923:       }
5924:       if (b >= aStart && b < aEnd) {
5925:         PetscSectionGetDof(aSec, b, &bDof);
5926:       }
5927:       if (bDof) {
5928:         for (f = 0; f < numFields; f++) {
5929:           PetscInt fDof, q, bOff, allFDof = 0;

5931:           PetscSectionGetFieldDof(section, b, f, &fDof);
5932:           PetscSectionGetOffset(aSec, b, &bOff);
5933:           for (q = 0; q < bDof; q++) {
5934:             PetscInt a = anchors[bOff + q];
5935:             PetscInt aFDof;

5937:             PetscSectionGetFieldDof(section, a, f, &aFDof);
5938:             allFDof += aFDof;
5939:           }
5940:           newPointOffsets[f][p+1] = allFDof;
5941:           pointMatOffsets[f][p+1] = fDof * allFDof;
5942:         }
5943:       }
5944:       else {
5945:         for (f = 0; f < numFields; f++) {
5946:           PetscInt fDof;

5948:           PetscSectionGetFieldDof(section, b, f, &fDof);
5949:           newPointOffsets[f][p+1] = fDof;
5950:           pointMatOffsets[f][p+1] = 0;
5951:         }
5952:       }
5953:     }
5954:     for (f = 0, totalOffset = 0, totalMatOffset = 0; f < numFields; f++) {
5955:       newPointOffsets[f][0] = totalOffset;
5956:       pointMatOffsets[f][0] = totalMatOffset;
5957:       for (p = 0; p < numPoints; p++) {
5958:         newPointOffsets[f][p+1] += newPointOffsets[f][p];
5959:         pointMatOffsets[f][p+1] += pointMatOffsets[f][p];
5960:       }
5961:       totalOffset    = newPointOffsets[f][numPoints];
5962:       totalMatOffset = pointMatOffsets[f][numPoints];
5963:       DMGetWorkArray(dm,pointMatOffsets[f][numPoints],MPIU_SCALAR,&pointMat[f]);
5964:     }
5965:   }
5966:   else {
5967:     for (p = 0; p < numPoints; p++) {
5968:       PetscInt b    = points[2*p];
5969:       PetscInt bDof = 0, bSecDof;

5971:       PetscSectionGetDof(section,b,&bSecDof);
5972:       if (!bSecDof) {
5973:         newPointOffsets[0][p + 1] = 0;
5974:         pointMatOffsets[0][p + 1] = 0;
5975:         continue;
5976:       }
5977:       if (b >= aStart && b < aEnd) {
5978:         PetscSectionGetDof(aSec, b, &bDof);
5979:       }
5980:       if (bDof) {
5981:         PetscInt bOff, q, allDof = 0;

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

5987:           PetscSectionGetDof(section, a, &aDof);
5988:           allDof += aDof;
5989:         }
5990:         newPointOffsets[0][p+1] = allDof;
5991:         pointMatOffsets[0][p+1] = bSecDof * allDof;
5992:       }
5993:       else {
5994:         newPointOffsets[0][p+1] = bSecDof;
5995:         pointMatOffsets[0][p+1] = 0;
5996:       }
5997:     }
5998:     newPointOffsets[0][0] = 0;
5999:     pointMatOffsets[0][0] = 0;
6000:     for (p = 0; p < numPoints; p++) {
6001:       newPointOffsets[0][p+1] += newPointOffsets[0][p];
6002:       pointMatOffsets[0][p+1] += pointMatOffsets[0][p];
6003:     }
6004:     DMGetWorkArray(dm,pointMatOffsets[0][numPoints],MPIU_SCALAR,&pointMat[0]);
6005:   }

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

6010:   /* get the point-to-point matrices; construct newPoints */
6011:   PetscSectionGetMaxDof(aSec, &maxAnchor);
6012:   PetscSectionGetMaxDof(section, &maxDof);
6013:   DMGetWorkArray(dm,maxDof,MPIU_INT,&indices);
6014:   DMGetWorkArray(dm,maxAnchor*maxDof,MPIU_INT,&newIndices);
6015:   if (numFields) {
6016:     for (p = 0, newP = 0; p < numPoints; p++) {
6017:       PetscInt b    = points[2*p];
6018:       PetscInt o    = points[2*p+1];
6019:       PetscInt bDof = 0, bSecDof;

6021:       PetscSectionGetDof(section, b, &bSecDof);
6022:       if (!bSecDof) {
6023:         continue;
6024:       }
6025:       if (b >= aStart && b < aEnd) {
6026:         PetscSectionGetDof(aSec, b, &bDof);
6027:       }
6028:       if (bDof) {
6029:         PetscInt fStart[32], fEnd[32], fAnchorStart[32], fAnchorEnd[32], bOff, q;

6031:         fStart[0] = 0;
6032:         fEnd[0]   = 0;
6033:         for (f = 0; f < numFields; f++) {
6034:           PetscInt fDof;

6036:           PetscSectionGetFieldDof(cSec, b, f, &fDof);
6037:           fStart[f+1] = fStart[f] + fDof;
6038:           fEnd[f+1]   = fStart[f+1];
6039:         }
6040:         PetscSectionGetOffset(cSec, b, &bOff);
6041:         DMPlexGetIndicesPointFields_Internal(cSec, PETSC_TRUE, b, bOff, fEnd, PETSC_TRUE, perms, p, NULL, indices);

6043:         fAnchorStart[0] = 0;
6044:         fAnchorEnd[0]   = 0;
6045:         for (f = 0; f < numFields; f++) {
6046:           PetscInt fDof = newPointOffsets[f][p + 1] - newPointOffsets[f][p];

6048:           fAnchorStart[f+1] = fAnchorStart[f] + fDof;
6049:           fAnchorEnd[f+1]   = fAnchorStart[f + 1];
6050:         }
6051:         PetscSectionGetOffset(aSec, b, &bOff);
6052:         for (q = 0; q < bDof; q++) {
6053:           PetscInt a = anchors[bOff + q], aOff;

6055:           /* we take the orientation of ap into account in the order that we constructed the indices above: the newly added points have no orientation */
6056:           newPoints[2*(newP + q)]     = a;
6057:           newPoints[2*(newP + q) + 1] = 0;
6058:           PetscSectionGetOffset(section, a, &aOff);
6059:           DMPlexGetIndicesPointFields_Internal(section, PETSC_TRUE, a, aOff, fAnchorEnd, PETSC_TRUE, NULL, -1, NULL, newIndices);
6060:         }
6061:         newP += bDof;

6063:         if (outValues) {
6064:           /* get the point-to-point submatrix */
6065:           for (f = 0; f < numFields; f++) {
6066:             MatGetValues(cMat,fEnd[f]-fStart[f],indices + fStart[f],fAnchorEnd[f] - fAnchorStart[f],newIndices + fAnchorStart[f],pointMat[f] + pointMatOffsets[f][p]);
6067:           }
6068:         }
6069:       }
6070:       else {
6071:         newPoints[2 * newP]     = b;
6072:         newPoints[2 * newP + 1] = o;
6073:         newP++;
6074:       }
6075:     }
6076:   } else {
6077:     for (p = 0; p < numPoints; p++) {
6078:       PetscInt b    = points[2*p];
6079:       PetscInt o    = points[2*p+1];
6080:       PetscInt bDof = 0, bSecDof;

6082:       PetscSectionGetDof(section, b, &bSecDof);
6083:       if (!bSecDof) {
6084:         continue;
6085:       }
6086:       if (b >= aStart && b < aEnd) {
6087:         PetscSectionGetDof(aSec, b, &bDof);
6088:       }
6089:       if (bDof) {
6090:         PetscInt bEnd = 0, bAnchorEnd = 0, bOff;

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

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

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

6101:           newPoints[2*(newP + q)]     = a;
6102:           newPoints[2*(newP + q) + 1] = 0;
6103:           PetscSectionGetOffset(section, a, &aOff);
6104:           DMPlexGetIndicesPoint_Internal(section, PETSC_TRUE, a, aOff, &bAnchorEnd, PETSC_TRUE, NULL, NULL, newIndices);
6105:         }
6106:         newP += bDof;

6108:         /* get the point-to-point submatrix */
6109:         if (outValues) {
6110:           MatGetValues(cMat,bEnd,indices,bAnchorEnd,newIndices,pointMat[0] + pointMatOffsets[0][p]);
6111:         }
6112:       }
6113:       else {
6114:         newPoints[2 * newP]     = b;
6115:         newPoints[2 * newP + 1] = o;
6116:         newP++;
6117:       }
6118:     }
6119:   }

6121:   if (outValues) {
6122:     DMGetWorkArray(dm,newNumIndices*numIndices,MPIU_SCALAR,&tmpValues);
6123:     PetscArrayzero(tmpValues,newNumIndices*numIndices);
6124:     /* multiply constraints on the right */
6125:     if (numFields) {
6126:       for (f = 0; f < numFields; f++) {
6127:         PetscInt oldOff = offsets[f];

6129:         for (p = 0; p < numPoints; p++) {
6130:           PetscInt cStart = newPointOffsets[f][p];
6131:           PetscInt b      = points[2 * p];
6132:           PetscInt c, r, k;
6133:           PetscInt dof;

6135:           PetscSectionGetFieldDof(section,b,f,&dof);
6136:           if (!dof) {
6137:             continue;
6138:           }
6139:           if (pointMatOffsets[f][p] < pointMatOffsets[f][p + 1]) {
6140:             PetscInt nCols         = newPointOffsets[f][p+1]-cStart;
6141:             const PetscScalar *mat = pointMat[f] + pointMatOffsets[f][p];

6143:             for (r = 0; r < numIndices; r++) {
6144:               for (c = 0; c < nCols; c++) {
6145:                 for (k = 0; k < dof; k++) {
6146:                   tmpValues[r * newNumIndices + cStart + c] += values[r * numIndices + oldOff + k] * mat[k * nCols + c];
6147:                 }
6148:               }
6149:             }
6150:           }
6151:           else {
6152:             /* copy this column as is */
6153:             for (r = 0; r < numIndices; r++) {
6154:               for (c = 0; c < dof; c++) {
6155:                 tmpValues[r * newNumIndices + cStart + c] = values[r * numIndices + oldOff + c];
6156:               }
6157:             }
6158:           }
6159:           oldOff += dof;
6160:         }
6161:       }
6162:     }
6163:     else {
6164:       PetscInt oldOff = 0;
6165:       for (p = 0; p < numPoints; p++) {
6166:         PetscInt cStart = newPointOffsets[0][p];
6167:         PetscInt b      = points[2 * p];
6168:         PetscInt c, r, k;
6169:         PetscInt dof;

6171:         PetscSectionGetDof(section,b,&dof);
6172:         if (!dof) {
6173:           continue;
6174:         }
6175:         if (pointMatOffsets[0][p] < pointMatOffsets[0][p + 1]) {
6176:           PetscInt nCols         = newPointOffsets[0][p+1]-cStart;
6177:           const PetscScalar *mat = pointMat[0] + pointMatOffsets[0][p];

6179:           for (r = 0; r < numIndices; r++) {
6180:             for (c = 0; c < nCols; c++) {
6181:               for (k = 0; k < dof; k++) {
6182:                 tmpValues[r * newNumIndices + cStart + c] += mat[k * nCols + c] * values[r * numIndices + oldOff + k];
6183:               }
6184:             }
6185:           }
6186:         }
6187:         else {
6188:           /* copy this column as is */
6189:           for (r = 0; r < numIndices; r++) {
6190:             for (c = 0; c < dof; c++) {
6191:               tmpValues[r * newNumIndices + cStart + c] = values[r * numIndices + oldOff + c];
6192:             }
6193:           }
6194:         }
6195:         oldOff += dof;
6196:       }
6197:     }

6199:     if (multiplyLeft) {
6200:       DMGetWorkArray(dm,newNumIndices*newNumIndices,MPIU_SCALAR,&newValues);
6201:       PetscArrayzero(newValues,newNumIndices*newNumIndices);
6202:       /* multiply constraints transpose on the left */
6203:       if (numFields) {
6204:         for (f = 0; f < numFields; f++) {
6205:           PetscInt oldOff = offsets[f];

6207:           for (p = 0; p < numPoints; p++) {
6208:             PetscInt rStart = newPointOffsets[f][p];
6209:             PetscInt b      = points[2 * p];
6210:             PetscInt c, r, k;
6211:             PetscInt dof;

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

6218:               for (r = 0; r < nRows; r++) {
6219:                 for (c = 0; c < newNumIndices; c++) {
6220:                   for (k = 0; k < dof; k++) {
6221:                     newValues[(rStart + r) * newNumIndices + c] += mat[k * nRows + r] * tmpValues[(oldOff + k) * newNumIndices + c];
6222:                   }
6223:                 }
6224:               }
6225:             }
6226:             else {
6227:               /* copy this row as is */
6228:               for (r = 0; r < dof; r++) {
6229:                 for (c = 0; c < newNumIndices; c++) {
6230:                   newValues[(rStart + r) * newNumIndices + c] = tmpValues[(oldOff + r) * newNumIndices + c];
6231:                 }
6232:               }
6233:             }
6234:             oldOff += dof;
6235:           }
6236:         }
6237:       }
6238:       else {
6239:         PetscInt oldOff = 0;

6241:         for (p = 0; p < numPoints; p++) {
6242:           PetscInt rStart = newPointOffsets[0][p];
6243:           PetscInt b      = points[2 * p];
6244:           PetscInt c, r, k;
6245:           PetscInt dof;

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

6252:             for (r = 0; r < nRows; r++) {
6253:               for (c = 0; c < newNumIndices; c++) {
6254:                 for (k = 0; k < dof; k++) {
6255:                   newValues[(rStart + r) * newNumIndices + c] += mat[k * nRows + r] * tmpValues[(oldOff + k) * newNumIndices + c];
6256:                 }
6257:               }
6258:             }
6259:           }
6260:           else {
6261:             /* copy this row as is */
6262:             for (r = 0; r < dof; r++) {
6263:               for (c = 0; c < newNumIndices; c++) {
6264:                 newValues[(rStart + r) * newNumIndices + c] = tmpValues[(oldOff + r) * newNumIndices + c];
6265:               }
6266:             }
6267:           }
6268:           oldOff += dof;
6269:         }
6270:       }

6272:       DMRestoreWorkArray(dm,newNumIndices*numIndices,MPIU_SCALAR,&tmpValues);
6273:     }
6274:     else {
6275:       newValues = tmpValues;
6276:     }
6277:   }

6279:   /* clean up */
6280:   DMRestoreWorkArray(dm,maxDof,MPIU_INT,&indices);
6281:   DMRestoreWorkArray(dm,maxAnchor*maxDof,MPIU_INT,&newIndices);

6283:   if (numFields) {
6284:     for (f = 0; f < numFields; f++) {
6285:       DMRestoreWorkArray(dm,pointMatOffsets[f][numPoints],MPIU_SCALAR,&pointMat[f]);
6286:       DMRestoreWorkArray(dm,numPoints+1,MPIU_INT,&pointMatOffsets[f]);
6287:       DMRestoreWorkArray(dm,numPoints+1,MPIU_INT,&newPointOffsets[f]);
6288:     }
6289:   }
6290:   else {
6291:     DMRestoreWorkArray(dm,pointMatOffsets[0][numPoints],MPIU_SCALAR,&pointMat[0]);
6292:     DMRestoreWorkArray(dm,numPoints+1,MPIU_INT,&pointMatOffsets[0]);
6293:     DMRestoreWorkArray(dm,numPoints+1,MPIU_INT,&newPointOffsets[0]);
6294:   }
6295:   ISRestoreIndices(aIS,&anchors);

6297:   /* output */
6298:   if (outPoints) {
6299:     *outPoints = newPoints;
6300:   }
6301:   else {
6302:     DMRestoreWorkArray(dm,2*newNumPoints,MPIU_INT,&newPoints);
6303:   }
6304:   if (outValues) {
6305:     *outValues = newValues;
6306:   }
6307:   for (f = 0; f <= numFields; f++) {
6308:     offsets[f] = newOffsets[f];
6309:   }
6310:   return(0);
6311: }

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

6316:   Not collective

6318:   Input Parameters:
6319: + dm         - The DM
6320: . section    - The PetscSection describing the points (a local section)
6321: . idxSection - The PetscSection from which to obtain indices (may be local or global)
6322: . point      - The point defining the closure
6323: - useClPerm  - Use the closure point permutation if available

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

6331:   Notes:
6332:   Must call DMPlexRestoreClosureIndices() to free allocated memory

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

6340:   Level: advanced

6342: .seealso DMPlexRestoreClosureIndices(), DMPlexVecGetClosure(), DMPlexMatSetClosure(), DMGetLocalSection(), DMGetGlobalSection()
6343: @*/
6344: PetscErrorCode DMPlexGetClosureIndices(DM dm, PetscSection section, PetscSection idxSection, PetscInt point, PetscBool useClPerm,
6345:                                        PetscInt *numIndices, PetscInt *indices[], PetscInt outOffsets[], PetscScalar *values[])
6346: {
6347:   /* Closure ordering */
6348:   PetscSection        clSection;
6349:   IS                  clPoints;
6350:   const PetscInt     *clp;
6351:   PetscInt           *points;
6352:   const PetscInt     *clperm = NULL;
6353:   /* Dof permutation and sign flips */
6354:   const PetscInt    **perms[32] = {NULL};
6355:   const PetscScalar **flips[32] = {NULL};
6356:   PetscScalar        *valCopy   = NULL;
6357:   /* Hanging node constraints */
6358:   PetscInt           *pointsC = NULL;
6359:   PetscScalar        *valuesC = NULL;
6360:   PetscInt            NclC, NiC;

6362:   PetscInt           *idx;
6363:   PetscInt            Nf, Ncl, Ni = 0, offsets[32], p, f;
6364:   PetscBool           isLocal = (section == idxSection) ? PETSC_TRUE : PETSC_FALSE;
6365:   PetscErrorCode      ierr;

6375:   PetscSectionGetNumFields(section, &Nf);
6376:   if (Nf > 31) SETERRQ1(PetscObjectComm((PetscObject) dm), PETSC_ERR_ARG_OUTOFRANGE, "Number of fields %D limited to 31", Nf);
6377:   PetscArrayzero(offsets, 32);
6378:   /* 1) Get points in closure */
6379:   DMPlexGetCompressedClosure(dm, section, point, &Ncl, &points, &clSection, &clPoints, &clp);
6380:   if (useClPerm) {
6381:     PetscInt depth, clsize;
6382:     DMPlexGetPointDepth(dm, point, &depth);
6383:     for (clsize=0,p=0; p<Ncl; p++) {
6384:       PetscInt dof;
6385:       PetscSectionGetDof(section, points[2*p], &dof);
6386:       clsize += dof;
6387:     }
6388:     PetscSectionGetClosureInversePermutation_Internal(section, (PetscObject) dm, depth, clsize, &clperm);
6389:   }
6390:   /* 2) Get number of indices on these points and field offsets from section */
6391:   for (p = 0; p < Ncl*2; p += 2) {
6392:     PetscInt dof, fdof;

6394:     PetscSectionGetDof(section, points[p], &dof);
6395:     for (f = 0; f < Nf; ++f) {
6396:       PetscSectionGetFieldDof(section, points[p], f, &fdof);
6397:       offsets[f+1] += fdof;
6398:     }
6399:     Ni += dof;
6400:   }
6401:   for (f = 1; f < Nf; ++f) offsets[f+1] += offsets[f];
6402:   if (Nf && offsets[Nf] != Ni) SETERRQ2(PetscObjectComm((PetscObject) dm), PETSC_ERR_PLIB, "Invalid size for closure %D should be %D", offsets[Nf], Ni);
6403:   /* 3) Get symmetries and sign flips. Apply sign flips to values if passed in (only works for square values matrix) */
6404:   for (f = 0; f < PetscMax(1, Nf); ++f) {
6405:     if (Nf) {PetscSectionGetFieldPointSyms(section, f, Ncl, points, &perms[f], &flips[f]);}
6406:     else    {PetscSectionGetPointSyms(section, Ncl, points, &perms[f], &flips[f]);}
6407:     /* may need to apply sign changes to the element matrix */
6408:     if (values && flips[f]) {
6409:       PetscInt foffset = offsets[f];

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

6415:         if (!Nf) {PetscSectionGetDof(section, pnt, &fdof);}
6416:         else     {PetscSectionGetFieldDof(section, pnt, f, &fdof);}
6417:         if (flip) {
6418:           PetscInt i, j, k;

6420:           if (!valCopy) {
6421:             DMGetWorkArray(dm, Ni*Ni, MPIU_SCALAR, &valCopy);
6422:             for (j = 0; j < Ni * Ni; ++j) valCopy[j] = (*values)[j];
6423:             *values = valCopy;
6424:           }
6425:           for (i = 0; i < fdof; ++i) {
6426:             PetscScalar fval = flip[i];

6428:             for (k = 0; k < Ni; ++k) {
6429:               valCopy[Ni * (foffset + i) + k] *= fval;
6430:               valCopy[Ni * k + (foffset + i)] *= fval;
6431:             }
6432:           }
6433:         }
6434:         foffset += fdof;
6435:       }
6436:     }
6437:   }
6438:   /* 4) Apply hanging node constraints. Get new symmetries and replace all storage with constrained storage */
6439:   DMPlexAnchorsModifyMat(dm, section, Ncl, Ni, points, perms, values ? *values : NULL, &NclC, &NiC, &pointsC, values ? &valuesC : NULL, offsets, PETSC_TRUE);
6440:   if (NclC) {
6441:     if (valCopy) {DMRestoreWorkArray(dm, Ni*Ni, MPIU_SCALAR, &valCopy);}
6442:     for (f = 0; f < PetscMax(1, Nf); ++f) {
6443:       if (Nf) {PetscSectionRestoreFieldPointSyms(section, f, Ncl, points, &perms[f], &flips[f]);}
6444:       else    {PetscSectionRestorePointSyms(section, Ncl, points, &perms[f], &flips[f]);}
6445:     }
6446:     for (f = 0; f < PetscMax(1, Nf); ++f) {
6447:       if (Nf) {PetscSectionGetFieldPointSyms(section, f, NclC, pointsC, &perms[f], &flips[f]);}
6448:       else    {PetscSectionGetPointSyms(section, NclC, pointsC, &perms[f], &flips[f]);}
6449:     }
6450:     DMPlexRestoreCompressedClosure(dm, section, point, &Ncl, &points, &clSection, &clPoints, &clp);
6451:     Ncl     = NclC;
6452:     Ni      = NiC;
6453:     points  = pointsC;
6454:     if (values) *values = valuesC;
6455:   }
6456:   /* 5) Calculate indices */
6457:   DMGetWorkArray(dm, Ni, MPIU_INT, &idx);
6458:   if (Nf) {
6459:     PetscInt  idxOff;
6460:     PetscBool useFieldOffsets;

6462:     if (outOffsets) {for (f = 0; f <= Nf; f++) outOffsets[f] = offsets[f];}
6463:     PetscSectionGetUseFieldOffsets(idxSection, &useFieldOffsets);
6464:     if (useFieldOffsets) {
6465:       for (p = 0; p < Ncl; ++p) {
6466:         const PetscInt pnt = points[p*2];

6468:         DMPlexGetIndicesPointFieldsSplit_Internal(section, idxSection, pnt, offsets, perms, p, clperm, idx);
6469:       }
6470:     } else {
6471:       for (p = 0; p < Ncl; ++p) {
6472:         const PetscInt pnt = points[p*2];

6474:         PetscSectionGetOffset(idxSection, pnt, &idxOff);
6475:         /* Note that we pass a local section even though we're using global offsets.  This is because global sections do
6476:          * not (at the time of this writing) have fields set. They probably should, in which case we would pass the
6477:          * global section. */
6478:         DMPlexGetIndicesPointFields_Internal(section, isLocal, pnt, idxOff < 0 ? -(idxOff+1) : idxOff, offsets, PETSC_FALSE, perms, p, clperm, idx);
6479:       }
6480:     }
6481:   } else {
6482:     PetscInt off = 0, idxOff;

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

6488:       PetscSectionGetOffset(idxSection, pnt, &idxOff);
6489:       /* Note that we pass a local section even though we're using global offsets.  This is because global sections do
6490:        * not (at the time of this writing) have fields set. They probably should, in which case we would pass the global section. */
6491:       DMPlexGetIndicesPoint_Internal(section, isLocal, pnt, idxOff < 0 ? -(idxOff+1) : idxOff, &off, PETSC_FALSE, perm, clperm, idx);
6492:     }
6493:   }
6494:   /* 6) Cleanup */
6495:   for (f = 0; f < PetscMax(1, Nf); ++f) {
6496:     if (Nf) {PetscSectionRestoreFieldPointSyms(section, f, Ncl, points, &perms[f], &flips[f]);}
6497:     else    {PetscSectionRestorePointSyms(section, Ncl, points, &perms[f], &flips[f]);}
6498:   }
6499:   if (NclC) {
6500:     DMRestoreWorkArray(dm, NclC*2, MPIU_INT, &pointsC);
6501:   } else {
6502:     DMPlexRestoreCompressedClosure(dm, section, point, &Ncl, &points, &clSection, &clPoints, &clp);
6503:   }

6505:   if (numIndices) *numIndices = Ni;
6506:   if (indices)    *indices    = idx;
6507:   return(0);
6508: }

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

6513:   Not collective

6515:   Input Parameters:
6516: + dm         - The DM
6517: . section    - The PetscSection describing the points (a local section)
6518: . idxSection - The PetscSection from which to obtain indices (may be local or global)
6519: . point      - The point defining the closure
6520: - useClPerm  - Use the closure point permutation if available

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

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

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

6537:   Level: advanced

6539: .seealso DMPlexGetClosureIndices(), DMPlexVecGetClosure(), DMPlexMatSetClosure(), DMGetLocalSection(), DMGetGlobalSection()
6540: @*/
6541: PetscErrorCode DMPlexRestoreClosureIndices(DM dm, PetscSection section, PetscSection idxSection, PetscInt point, PetscBool useClPerm,
6542:                                            PetscInt *numIndices, PetscInt *indices[], PetscInt outOffsets[], PetscScalar *values[])
6543: {

6549:   DMRestoreWorkArray(dm, 0, MPIU_INT, indices);
6550:   return(0);
6551: }

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

6556:   Not collective

6558:   Input Parameters:
6559: + dm - The DM
6560: . section - The section describing the layout in v, or NULL to use the default section
6561: . globalSection - The section describing the layout in v, or NULL to use the default global section
6562: . A - The matrix
6563: . point - The point in the DM
6564: . values - The array of values
6565: - mode - The insert mode, where INSERT_ALL_VALUES and ADD_ALL_VALUES also overwrite boundary conditions

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

6570:   Level: intermediate

6572: .seealso DMPlexMatSetClosureGeneral(), DMPlexVecGetClosure(), DMPlexVecSetClosure()
6573: @*/
6574: PetscErrorCode DMPlexMatSetClosure(DM dm, PetscSection section, PetscSection globalSection, Mat A, PetscInt point, const PetscScalar values[], InsertMode mode)
6575: {
6576:   DM_Plex           *mesh = (DM_Plex*) dm->data;
6577:   PetscInt          *indices;
6578:   PetscInt           numIndices;
6579:   const PetscScalar *valuesOrig = values;
6580:   PetscErrorCode     ierr;

6584:   if (!section) {DMGetLocalSection(dm, &section);}
6586:   if (!globalSection) {DMGetGlobalSection(dm, &globalSection);}

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

6592:   if (mesh->printSetValues) {DMPlexPrintMatSetValues(PETSC_VIEWER_STDOUT_SELF, A, point, numIndices, indices, 0, NULL, values);}
6593:   MatSetValues(A, numIndices, indices, numIndices, indices, values, mode);
6594:   if (ierr) {
6595:     PetscMPIInt    rank;
6596:     PetscErrorCode ierr2;

6598:     ierr2 = MPI_Comm_rank(PetscObjectComm((PetscObject)A), &rank);CHKERRQ(ierr2);
6599:     ierr2 = (*PetscErrorPrintf)("[%d]ERROR in DMPlexMatSetClosure\n", rank);CHKERRQ(ierr2);
6600:     ierr2 = DMPlexPrintMatSetValues(PETSC_VIEWER_STDERR_SELF, A, point, numIndices, indices, 0, NULL, values);CHKERRQ(ierr2);
6601:     ierr2 = DMPlexRestoreClosureIndices(dm, section, globalSection, point, PETSC_TRUE, &numIndices, &indices, NULL, (PetscScalar **) &values);CHKERRQ(ierr2);
6602:     if (values != valuesOrig) {ierr2 = DMRestoreWorkArray(dm, 0, MPIU_SCALAR, &values);CHKERRQ(ierr2);}
6603:     
6604:   }
6605:   if (mesh->printFEM > 1) {
6606:     PetscInt i;
6607:     PetscPrintf(PETSC_COMM_SELF, "  Indices:");
6608:     for (i = 0; i < numIndices; ++i) {PetscPrintf(PETSC_COMM_SELF, " %D", indices[i]);}
6609:     PetscPrintf(PETSC_COMM_SELF, "\n");
6610:   }

6612:   DMPlexRestoreClosureIndices(dm, section, globalSection, point, PETSC_TRUE, &numIndices, &indices, NULL, (PetscScalar **) &values);
6613:   if (values != valuesOrig) {DMRestoreWorkArray(dm, 0, MPIU_SCALAR, &values);}
6614:   return(0);
6615: }

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

6620:   Not collective

6622:   Input Parameters:
6623: + dmRow - The DM for the row fields
6624: . sectionRow - The section describing the layout, or NULL to use the default section in dmRow
6625: . globalSectionRow - The section describing the layout, or NULL to use the default global section in dmRow
6626: . dmCol - The DM for the column fields
6627: . sectionCol - The section describing the layout, or NULL to use the default section in dmCol
6628: . globalSectionCol - The section describing the layout, or NULL to use the default global section in dmCol
6629: . A - The matrix
6630: . point - The point in the DMs
6631: . values - The array of values
6632: - mode - The insert mode, where INSERT_ALL_VALUES and ADD_ALL_VALUES also overwrite boundary conditions

6634:   Level: intermediate

6636: .seealso DMPlexMatSetClosure(), DMPlexVecGetClosure(), DMPlexVecSetClosure()
6637: @*/
6638: PetscErrorCode DMPlexMatSetClosureGeneral(DM dmRow, PetscSection sectionRow, PetscSection globalSectionRow, DM dmCol, PetscSection sectionCol, PetscSection globalSectionCol, Mat A, PetscInt point, const PetscScalar values[], InsertMode mode)
6639: {
6640:   DM_Plex           *mesh = (DM_Plex*) dmRow->data;
6641:   PetscInt          *indicesRow, *indicesCol;
6642:   PetscInt           numIndicesRow, numIndicesCol;
6643:   const PetscScalar *valuesOrig = values;
6644:   PetscErrorCode     ierr;

6648:   if (!sectionRow) {DMGetLocalSection(dmRow, &sectionRow);}
6650:   if (!globalSectionRow) {DMGetGlobalSection(dmRow, &globalSectionRow);}
6653:   if (!sectionCol) {DMGetLocalSection(dmCol, &sectionCol);}
6655:   if (!globalSectionCol) {DMGetGlobalSection(dmCol, &globalSectionCol);}

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

6662:   if (mesh->printSetValues) {DMPlexPrintMatSetValues(PETSC_VIEWER_STDOUT_SELF, A, point, numIndicesRow, indicesRow, numIndicesCol, indicesCol, values);}
6663:   MatSetValues(A, numIndicesRow, indicesRow, numIndicesCol, indicesCol, values, mode);
6664:   if (ierr) {
6665:     PetscMPIInt    rank;
6666:     PetscErrorCode ierr2;

6668:     ierr2 = MPI_Comm_rank(PetscObjectComm((PetscObject)A), &rank);CHKERRQ(ierr2);
6669:     ierr2 = (*PetscErrorPrintf)("[%d]ERROR in DMPlexMatSetClosure\n", rank);CHKERRQ(ierr2);
6670:     ierr2 = DMPlexPrintMatSetValues(PETSC_VIEWER_STDERR_SELF, A, point, numIndicesRow, indicesRow, numIndicesCol, indicesCol, values);CHKERRQ(ierr2);
6671:     ierr2 = DMPlexRestoreClosureIndices(dmRow, sectionRow, globalSectionRow, point, PETSC_TRUE, &numIndicesRow, &indicesRow, NULL, (PetscScalar **) &values);CHKERRQ(ierr2);
6672:     ierr2 = DMPlexRestoreClosureIndices(dmCol, sectionCol, globalSectionCol, point, PETSC_TRUE, &numIndicesCol, &indicesRow, NULL, (PetscScalar **) &values);CHKERRQ(ierr2);
6673:     if (values != valuesOrig) {ierr2 = DMRestoreWorkArray(dmRow, 0, MPIU_SCALAR, &values);CHKERRQ(ierr2);}
6674:     
6675:   }

6677:   DMPlexRestoreClosureIndices(dmRow, sectionRow, globalSectionRow, point, PETSC_TRUE, &numIndicesRow, &indicesRow, NULL, (PetscScalar **) &values);
6678:   DMPlexRestoreClosureIndices(dmCol, sectionCol, globalSectionCol, point, PETSC_TRUE, &numIndicesCol, &indicesCol, NULL, (PetscScalar **) &values);
6679:   if (values != valuesOrig) {DMRestoreWorkArray(dmRow, 0, MPIU_SCALAR, &values);}
6680:   return(0);
6681: }

6683: PetscErrorCode DMPlexMatSetClosureRefined(DM dmf, PetscSection fsection, PetscSection globalFSection, DM dmc, PetscSection csection, PetscSection globalCSection, Mat A, PetscInt point, const PetscScalar values[], InsertMode mode)
6684: {
6685:   DM_Plex        *mesh   = (DM_Plex*) dmf->data;
6686:   PetscInt       *fpoints = NULL, *ftotpoints = NULL;
6687:   PetscInt       *cpoints = NULL;
6688:   PetscInt       *findices, *cindices;
6689:   const PetscInt *fclperm = NULL, *cclperm = NULL; /* Closure permutations cannot work here */
6690:   PetscInt        foffsets[32], coffsets[32];
6691:   DMPolytopeType  ct;
6692:   PetscInt        numFields, numSubcells, maxFPoints, numFPoints, numCPoints, numFIndices, numCIndices, dof, off, globalOff, pStart, pEnd, p, q, r, s, f;
6693:   PetscErrorCode  ierr;

6698:   if (!fsection) {DMGetLocalSection(dmf, &fsection);}
6700:   if (!csection) {DMGetLocalSection(dmc, &csection);}
6702:   if (!globalFSection) {DMGetGlobalSection(dmf, &globalFSection);}
6704:   if (!globalCSection) {DMGetGlobalSection(dmc, &globalCSection);}
6707:   PetscSectionGetNumFields(fsection, &numFields);
6708:   if (numFields > 31) SETERRQ1(PetscObjectComm((PetscObject)dmf), PETSC_ERR_ARG_OUTOFRANGE, "Number of fields %D limited to 31", numFields);
6709:   PetscArrayzero(foffsets, 32);
6710:   PetscArrayzero(coffsets, 32);
6711:   /* Column indices */
6712:   DMPlexGetTransitiveClosure(dmc, point, PETSC_TRUE, &numCPoints, &cpoints);
6713:   maxFPoints = numCPoints;
6714:   /* Compress out points not in the section */
6715:   /*   TODO: Squeeze out points with 0 dof as well */
6716:   PetscSectionGetChart(csection, &pStart, &pEnd);
6717:   for (p = 0, q = 0; p < numCPoints*2; p += 2) {
6718:     if ((cpoints[p] >= pStart) && (cpoints[p] < pEnd)) {
6719:       cpoints[q*2]   = cpoints[p];
6720:       cpoints[q*2+1] = cpoints[p+1];
6721:       ++q;
6722:     }
6723:   }
6724:   numCPoints = q;
6725:   for (p = 0, numCIndices = 0; p < numCPoints*2; p += 2) {
6726:     PetscInt fdof;

6728:     PetscSectionGetDof(csection, cpoints[p], &dof);
6729:     if (!dof) continue;
6730:     for (f = 0; f < numFields; ++f) {
6731:       PetscSectionGetFieldDof(csection, cpoints[p], f, &fdof);
6732:       coffsets[f+1] += fdof;
6733:     }
6734:     numCIndices += dof;
6735:   }
6736:   for (f = 1; f < numFields; ++f) coffsets[f+1] += coffsets[f];
6737:   /* Row indices */
6738:   DMPlexGetCellType(dmc, point, &ct);
6739:   {
6740:     DMPlexCellRefiner cr;
6741:     DMPlexCellRefinerCreate(dmc, &cr);
6742:     DMPlexCellRefinerGetAffineTransforms(cr, ct, &numSubcells, NULL, NULL, NULL);
6743:     DMPlexCellRefinerDestroy(&cr);
6744:   }
6745:   DMGetWorkArray(dmf, maxFPoints*2*numSubcells, MPIU_INT, &ftotpoints);
6746:   for (r = 0, q = 0; r < numSubcells; ++r) {
6747:     /* TODO Map from coarse to fine cells */
6748:     DMPlexGetTransitiveClosure(dmf, point*numSubcells + r, PETSC_TRUE, &numFPoints, &fpoints);
6749:     /* Compress out points not in the section */
6750:     PetscSectionGetChart(fsection, &pStart, &pEnd);
6751:     for (p = 0; p < numFPoints*2; p += 2) {
6752:       if ((fpoints[p] >= pStart) && (fpoints[p] < pEnd)) {
6753:         PetscSectionGetDof(fsection, fpoints[p], &dof);
6754:         if (!dof) continue;
6755:         for (s = 0; s < q; ++s) if (fpoints[p] == ftotpoints[s*2]) break;
6756:         if (s < q) continue;
6757:         ftotpoints[q*2]   = fpoints[p];
6758:         ftotpoints[q*2+1] = fpoints[p+1];
6759:         ++q;
6760:       }
6761:     }
6762:     DMPlexRestoreTransitiveClosure(dmf, point, PETSC_TRUE, &numFPoints, &fpoints);
6763:   }
6764:   numFPoints = q;
6765:   for (p = 0, numFIndices = 0; p < numFPoints*2; p += 2) {
6766:     PetscInt fdof;

6768:     PetscSectionGetDof(fsection, ftotpoints[p], &dof);
6769:     if (!dof) continue;
6770:     for (f = 0; f < numFields; ++f) {
6771:       PetscSectionGetFieldDof(fsection, ftotpoints[p], f, &fdof);
6772:       foffsets[f+1] += fdof;
6773:     }
6774:     numFIndices += dof;
6775:   }
6776:   for (f = 1; f < numFields; ++f) foffsets[f+1] += foffsets[f];

6778:   if (numFields && foffsets[numFields] != numFIndices) SETERRQ2(PetscObjectComm((PetscObject)dmf), PETSC_ERR_PLIB, "Invalid size for closure %D should be %D", foffsets[numFields], numFIndices);
6779:   if (numFields && coffsets[numFields] != numCIndices) SETERRQ2(PetscObjectComm((PetscObject)dmc), PETSC_ERR_PLIB, "Invalid size for closure %D should be %D", coffsets[numFields], numCIndices);
6780:   DMGetWorkArray(dmf, numFIndices, MPIU_INT, &findices);
6781:   DMGetWorkArray(dmc, numCIndices, MPIU_INT, &cindices);
6782:   if (numFields) {
6783:     const PetscInt **permsF[32] = {NULL};
6784:     const PetscInt **permsC[32] = {NULL};

6786:     for (f = 0; f < numFields; f++) {
6787:       PetscSectionGetFieldPointSyms(fsection,f,numFPoints,ftotpoints,&permsF[f],NULL);
6788:       PetscSectionGetFieldPointSyms(csection,f,numCPoints,cpoints,&permsC[f],NULL);
6789:     }
6790:     for (p = 0; p < numFPoints; p++) {
6791:       PetscSectionGetOffset(globalFSection, ftotpoints[2*p], &globalOff);
6792:       DMPlexGetIndicesPointFields_Internal(fsection, PETSC_FALSE, ftotpoints[2*p], globalOff < 0 ? -(globalOff+1) : globalOff, foffsets, PETSC_FALSE, permsF, p, fclperm, findices);
6793:     }
6794:     for (p = 0; p < numCPoints; p++) {
6795:       PetscSectionGetOffset(globalCSection, cpoints[2*p], &globalOff);
6796:       DMPlexGetIndicesPointFields_Internal(csection, PETSC_FALSE, cpoints[2*p], globalOff < 0 ? -(globalOff+1) : globalOff, coffsets, PETSC_FALSE, permsC, p, cclperm, cindices);
6797:     }
6798:     for (f = 0; f < numFields; f++) {
6799:       PetscSectionRestoreFieldPointSyms(fsection,f,numFPoints,ftotpoints,&permsF[f],NULL);
6800:       PetscSectionRestoreFieldPointSyms(csection,f,numCPoints,cpoints,&permsC[f],NULL);
6801:     }
6802:   } else {
6803:     const PetscInt **permsF = NULL;
6804:     const PetscInt **permsC = NULL;

6806:     PetscSectionGetPointSyms(fsection,numFPoints,ftotpoints,&permsF,NULL);
6807:     PetscSectionGetPointSyms(csection,numCPoints,cpoints,&permsC,NULL);
6808:     for (p = 0, off = 0; p < numFPoints; p++) {
6809:       const PetscInt *perm = permsF ? permsF[p] : NULL;

6811:       PetscSectionGetOffset(globalFSection, ftotpoints[2*p], &globalOff);
6812:       DMPlexGetIndicesPoint_Internal(fsection, PETSC_FALSE, ftotpoints[2*p], globalOff < 0 ? -(globalOff+1) : globalOff, &off, PETSC_FALSE, perm, fclperm, findices);
6813:     }
6814:     for (p = 0, off = 0; p < numCPoints; p++) {
6815:       const PetscInt *perm = permsC ? permsC[p] : NULL;

6817:       PetscSectionGetOffset(globalCSection, cpoints[2*p], &globalOff);
6818:       DMPlexGetIndicesPoint_Internal(csection, PETSC_FALSE, cpoints[2*p], globalOff < 0 ? -(globalOff+1) : globalOff, &off, PETSC_FALSE, perm, cclperm, cindices);
6819:     }
6820:     PetscSectionRestorePointSyms(fsection,numFPoints,ftotpoints,&permsF,NULL);
6821:     PetscSectionRestorePointSyms(csection,numCPoints,cpoints,&permsC,NULL);
6822:   }
6823:   if (mesh->printSetValues) {DMPlexPrintMatSetValues(PETSC_VIEWER_STDOUT_SELF, A, point, numFIndices, findices, numCIndices, cindices, values);}
6824:   /* TODO: flips */
6825:   MatSetValues(A, numFIndices, findices, numCIndices, cindices, values, mode);
6826:   if (ierr) {
6827:     PetscMPIInt    rank;
6828:     PetscErrorCode ierr2;

6830:     ierr2 = MPI_Comm_rank(PetscObjectComm((PetscObject)A), &rank);CHKERRQ(ierr2);
6831:     ierr2 = (*PetscErrorPrintf)("[%d]ERROR in DMPlexMatSetClosure\n", rank);CHKERRQ(ierr2);
6832:     ierr2 = DMPlexPrintMatSetValues(PETSC_VIEWER_STDERR_SELF, A, point, numFIndices, findices, numCIndices, cindices, values);CHKERRQ(ierr2);
6833:     ierr2 = DMRestoreWorkArray(dmf, numFIndices, MPIU_INT, &findices);CHKERRQ(ierr2);
6834:     ierr2 = DMRestoreWorkArray(dmc, numCIndices, MPIU_INT, &cindices);CHKERRQ(ierr2);
6835:     
6836:   }
6837:   DMRestoreWorkArray(dmf, numCPoints*2*4, MPIU_INT, &ftotpoints);
6838:   DMPlexRestoreTransitiveClosure(dmc, point, PETSC_TRUE, &numCPoints, &cpoints);
6839:   DMRestoreWorkArray(dmf, numFIndices, MPIU_INT, &findices);
6840:   DMRestoreWorkArray(dmc, numCIndices, MPIU_INT, &cindices);
6841:   return(0);
6842: }

6844: PetscErrorCode DMPlexMatGetClosureIndicesRefined(DM dmf, PetscSection fsection, PetscSection globalFSection, DM dmc, PetscSection csection, PetscSection globalCSection, PetscInt point, PetscInt cindices[], PetscInt findices[])
6845: {
6846:   PetscInt      *fpoints = NULL, *ftotpoints = NULL;
6847:   PetscInt      *cpoints = NULL;
6848:   PetscInt       foffsets[32], coffsets[32];
6849:   const PetscInt *fclperm = NULL, *cclperm = NULL; /* Closure permutations cannot work here */
6850:   DMPolytopeType ct;
6851:   PetscInt       numFields, numSubcells, maxFPoints, numFPoints, numCPoints, numFIndices, numCIndices, dof, off, globalOff, pStart, pEnd, p, q, r, s, f;

6857:   if (!fsection) {DMGetLocalSection(dmf, &fsection);}
6859:   if (!csection) {DMGetLocalSection(dmc, &csection);}
6861:   if (!globalFSection) {DMGetGlobalSection(dmf, &globalFSection);}
6863:   if (!globalCSection) {DMGetGlobalSection(dmc, &globalCSection);}
6865:   PetscSectionGetNumFields(fsection, &numFields);
6866:   if (numFields > 31) SETERRQ1(PetscObjectComm((PetscObject)dmf), PETSC_ERR_ARG_OUTOFRANGE, "Number of fields %D limited to 31", numFields);
6867:   PetscArrayzero(foffsets, 32);
6868:   PetscArrayzero(coffsets, 32);
6869:   /* Column indices */
6870:   DMPlexGetTransitiveClosure(dmc, point, PETSC_TRUE, &numCPoints, &cpoints);
6871:   maxFPoints = numCPoints;
6872:   /* Compress out points not in the section */
6873:   /*   TODO: Squeeze out points with 0 dof as well */
6874:   PetscSectionGetChart(csection, &pStart, &pEnd);
6875:   for (p = 0, q = 0; p < numCPoints*2; p += 2) {
6876:     if ((cpoints[p] >= pStart) && (cpoints[p] < pEnd)) {
6877:       cpoints[q*2]   = cpoints[p];
6878:       cpoints[q*2+1] = cpoints[p+1];
6879:       ++q;
6880:     }
6881:   }
6882:   numCPoints = q;
6883:   for (p = 0, numCIndices = 0; p < numCPoints*2; p += 2) {
6884:     PetscInt fdof;

6886:     PetscSectionGetDof(csection, cpoints[p], &dof);
6887:     if (!dof) continue;
6888:     for (f = 0; f < numFields; ++f) {
6889:       PetscSectionGetFieldDof(csection, cpoints[p], f, &fdof);
6890:       coffsets[f+1] += fdof;
6891:     }
6892:     numCIndices += dof;
6893:   }
6894:   for (f = 1; f < numFields; ++f) coffsets[f+1] += coffsets[f];
6895:   /* Row indices */
6896:   DMPlexGetCellType(dmc, point, &ct);
6897:   {
6898:     DMPlexCellRefiner cr;
6899:     DMPlexCellRefinerCreate(dmc, &cr);
6900:     DMPlexCellRefinerGetAffineTransforms(cr, ct, &numSubcells, NULL, NULL, NULL);
6901:     DMPlexCellRefinerDestroy(&cr);
6902:   }
6903:   DMGetWorkArray(dmf, maxFPoints*2*numSubcells, MPIU_INT, &ftotpoints);
6904:   for (r = 0, q = 0; r < numSubcells; ++r) {
6905:     /* TODO Map from coarse to fine cells */
6906:     DMPlexGetTransitiveClosure(dmf, point*numSubcells + r, PETSC_TRUE, &numFPoints, &fpoints);
6907:     /* Compress out points not in the section */
6908:     PetscSectionGetChart(fsection, &pStart, &pEnd);
6909:     for (p = 0; p < numFPoints*2; p += 2) {
6910:       if ((fpoints[p] >= pStart) && (fpoints[p] < pEnd)) {
6911:         PetscSectionGetDof(fsection, fpoints[p], &dof);
6912:         if (!dof) continue;
6913:         for (s = 0; s < q; ++s) if (fpoints[p] == ftotpoints[s*2]) break;
6914:         if (s < q) continue;
6915:         ftotpoints[q*2]   = fpoints[p];
6916:         ftotpoints[q*2+1] = fpoints[p+1];
6917:         ++q;
6918:       }
6919:     }
6920:     DMPlexRestoreTransitiveClosure(dmf, point, PETSC_TRUE, &numFPoints, &fpoints);
6921:   }
6922:   numFPoints = q;
6923:   for (p = 0, numFIndices = 0; p < numFPoints*2; p += 2) {
6924:     PetscInt fdof;

6926:     PetscSectionGetDof(fsection, ftotpoints[p], &dof);
6927:     if (!dof) continue;
6928:     for (f = 0; f < numFields; ++f) {
6929:       PetscSectionGetFieldDof(fsection, ftotpoints[p], f, &fdof);
6930:       foffsets[f+1] += fdof;
6931:     }
6932:     numFIndices += dof;
6933:   }
6934:   for (f = 1; f < numFields; ++f) foffsets[f+1] += foffsets[f];

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

6942:     for (f = 0; f < numFields; f++) {
6943:       PetscSectionGetFieldPointSyms(fsection,f,numFPoints,ftotpoints,&permsF[f],NULL);
6944:       PetscSectionGetFieldPointSyms(csection,f,numCPoints,cpoints,&permsC[f],NULL);
6945:     }
6946:     for (p = 0; p < numFPoints; p++) {
6947:       PetscSectionGetOffset(globalFSection, ftotpoints[2*p], &globalOff);
6948:       DMPlexGetIndicesPointFields_Internal(fsection, PETSC_FALSE, ftotpoints[2*p], globalOff < 0 ? -(globalOff+1) : globalOff, foffsets, PETSC_FALSE, permsF, p, fclperm, findices);
6949:     }
6950:     for (p = 0; p < numCPoints; p++) {
6951:       PetscSectionGetOffset(globalCSection, cpoints[2*p], &globalOff);
6952:       DMPlexGetIndicesPointFields_Internal(csection, PETSC_FALSE, cpoints[2*p], globalOff < 0 ? -(globalOff+1) : globalOff, coffsets, PETSC_FALSE, permsC, p, cclperm, cindices);
6953:     }
6954:     for (f = 0; f < numFields; f++) {
6955:       PetscSectionRestoreFieldPointSyms(fsection,f,numFPoints,ftotpoints,&permsF[f],NULL);
6956:       PetscSectionRestoreFieldPointSyms(csection,f,numCPoints,cpoints,&permsC[f],NULL);
6957:     }
6958:   } else {
6959:     const PetscInt **permsF = NULL;
6960:     const PetscInt **permsC = NULL;

6962:     PetscSectionGetPointSyms(fsection,numFPoints,ftotpoints,&permsF,NULL);
6963:     PetscSectionGetPointSyms(csection,numCPoints,cpoints,&permsC,NULL);
6964:     for (p = 0, off = 0; p < numFPoints; p++) {
6965:       const PetscInt *perm = permsF ? permsF[p] : NULL;

6967:       PetscSectionGetOffset(globalFSection, ftotpoints[2*p], &globalOff);
6968:       DMPlexGetIndicesPoint_Internal(fsection, PETSC_FALSE, ftotpoints[2*p], globalOff < 0 ? -(globalOff+1) : globalOff, &off, PETSC_FALSE, perm, fclperm, findices);
6969:     }
6970:     for (p = 0, off = 0; p < numCPoints; p++) {
6971:       const PetscInt *perm = permsC ? permsC[p] : NULL;

6973:       PetscSectionGetOffset(globalCSection, cpoints[2*p], &globalOff);
6974:       DMPlexGetIndicesPoint_Internal(csection, PETSC_FALSE, cpoints[2*p], globalOff < 0 ? -(globalOff+1) : globalOff, &off, PETSC_FALSE, perm, cclperm, cindices);
6975:     }
6976:     PetscSectionRestorePointSyms(fsection,numFPoints,ftotpoints,&permsF,NULL);
6977:     PetscSectionRestorePointSyms(csection,numCPoints,cpoints,&permsC,NULL);
6978:   }
6979:   DMRestoreWorkArray(dmf, numCPoints*2*4, MPIU_INT, &ftotpoints);
6980:   DMPlexRestoreTransitiveClosure(dmc, point, PETSC_TRUE, &numCPoints, &cpoints);
6981:   return(0);
6982: }

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

6987:   Input Parameter:
6988: . dm   - The DMPlex object

6990:   Output Parameter:
6991: . cellHeight - The height of a cell

6993:   Level: developer

6995: .seealso DMPlexSetVTKCellHeight()
6996: @*/
6997: PetscErrorCode DMPlexGetVTKCellHeight(DM dm, PetscInt *cellHeight)
6998: {
6999:   DM_Plex *mesh = (DM_Plex*) dm->data;

7004:   *cellHeight = mesh->vtkCellHeight;
7005:   return(0);
7006: }

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

7011:   Input Parameters:
7012: + dm   - The DMPlex object
7013: - cellHeight - The height of a cell

7015:   Level: developer

7017: .seealso DMPlexGetVTKCellHeight()
7018: @*/
7019: PetscErrorCode DMPlexSetVTKCellHeight(DM dm, PetscInt cellHeight)
7020: {
7021:   DM_Plex *mesh = (DM_Plex*) dm->data;

7025:   mesh->vtkCellHeight = cellHeight;
7026:   return(0);
7027: }

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

7032:   Input Parameter:
7033: . dm - The DMPlex object

7035:   Output Parameters:
7036: + gcStart - The first ghost cell, or NULL
7037: - gcEnd   - The upper bound on ghost cells, or NULL

7039:   Level: advanced

7041: .seealso DMPlexConstructGhostCells(), DMPlexSetGhostCellStratum()
7042: @*/
7043: PetscErrorCode DMPlexGetGhostCellStratum(DM dm, PetscInt *gcStart, PetscInt *gcEnd)
7044: {
7045:   DMLabel        ctLabel;

7050:   DMPlexGetCellTypeLabel(dm, &ctLabel);
7051:   DMLabelGetStratumBounds(ctLabel, DM_POLYTOPE_FV_GHOST, gcStart, gcEnd);
7052:   return(0);
7053: }

7055: /* We can easily have a form that takes an IS instead */
7056: PetscErrorCode DMPlexCreateNumbering_Plex(DM dm, PetscInt pStart, PetscInt pEnd, PetscInt shift, PetscInt *globalSize, PetscSF sf, IS *numbering)
7057: {
7058:   PetscSection   section, globalSection;
7059:   PetscInt      *numbers, p;

7063:   PetscSectionCreate(PetscObjectComm((PetscObject)dm), &section);
7064:   PetscSectionSetChart(section, pStart, pEnd);
7065:   for (p = pStart; p < pEnd; ++p) {
7066:     PetscSectionSetDof(section, p, 1);
7067:   }
7068:   PetscSectionSetUp(section);
7069:   PetscSectionCreateGlobalSection(section, sf, PETSC_FALSE, PETSC_FALSE, &globalSection);
7070:   PetscMalloc1(pEnd - pStart, &numbers);
7071:   for (p = pStart; p < pEnd; ++p) {
7072:     PetscSectionGetOffset(globalSection, p, &numbers[p-pStart]);
7073:     if (numbers[p-pStart] < 0) numbers[p-pStart] -= shift;
7074:     else                       numbers[p-pStart] += shift;
7075:   }
7076:   ISCreateGeneral(PetscObjectComm((PetscObject) dm), pEnd - pStart, numbers, PETSC_OWN_POINTER, numbering);
7077:   if (globalSize) {
7078:     PetscLayout layout;
7079:     PetscSectionGetPointLayout(PetscObjectComm((PetscObject) dm), globalSection, &layout);
7080:     PetscLayoutGetSize(layout, globalSize);
7081:     PetscLayoutDestroy(&layout);
7082:   }
7083:   PetscSectionDestroy(&section);
7084:   PetscSectionDestroy(&globalSection);
7085:   return(0);
7086: }

7088: PetscErrorCode DMPlexCreateCellNumbering_Internal(DM dm, PetscBool includeHybrid, IS *globalCellNumbers)
7089: {
7090:   PetscInt       cellHeight, cStart, cEnd;

7094:   DMPlexGetVTKCellHeight(dm, &cellHeight);
7095:   if (includeHybrid) {DMPlexGetHeightStratum(dm, cellHeight, &cStart, &cEnd);}
7096:   else               {DMPlexGetSimplexOrBoxCells(dm, cellHeight, &cStart, &cEnd);}
7097:   DMPlexCreateNumbering_Plex(dm, cStart, cEnd, 0, NULL, dm->sf, globalCellNumbers);
7098:   return(0);
7099: }

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

7104:   Input Parameter:
7105: . dm   - The DMPlex object

7107:   Output Parameter:
7108: . globalCellNumbers - Global cell numbers for all cells on this process

7110:   Level: developer

7112: .seealso DMPlexGetVertexNumbering()
7113: @*/
7114: PetscErrorCode DMPlexGetCellNumbering(DM dm, IS *globalCellNumbers)
7115: {
7116:   DM_Plex       *mesh = (DM_Plex*) dm->data;

7121:   if (!mesh->globalCellNumbers) {DMPlexCreateCellNumbering_Internal(dm, PETSC_FALSE, &mesh->globalCellNumbers);}
7122:   *globalCellNumbers = mesh->globalCellNumbers;
7123:   return(0);
7124: }

7126: PetscErrorCode DMPlexCreateVertexNumbering_Internal(DM dm, PetscBool includeHybrid, IS *globalVertexNumbers)
7127: {
7128:   PetscInt       vStart, vEnd;

7133:   DMPlexGetDepthStratum(dm, 0, &vStart, &vEnd);
7134:   DMPlexCreateNumbering_Plex(dm, vStart, vEnd, 0, NULL, dm->sf, globalVertexNumbers);
7135:   return(0);
7136: }

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

7141:   Input Parameter:
7142: . dm   - The DMPlex object

7144:   Output Parameter:
7145: . globalVertexNumbers - Global vertex numbers for all vertices on this process

7147:   Level: developer

7149: .seealso DMPlexGetCellNumbering()
7150: @*/
7151: PetscErrorCode DMPlexGetVertexNumbering(DM dm, IS *globalVertexNumbers)
7152: {
7153:   DM_Plex       *mesh = (DM_Plex*) dm->data;

7158:   if (!mesh->globalVertexNumbers) {DMPlexCreateVertexNumbering_Internal(dm, PETSC_FALSE, &mesh->globalVertexNumbers);}
7159:   *globalVertexNumbers = mesh->globalVertexNumbers;
7160:   return(0);
7161: }

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

7166:   Input Parameter:
7167: . dm   - The DMPlex object

7169:   Output Parameter:
7170: . globalPointNumbers - Global numbers for all points on this process

7172:   Level: developer

7174: .seealso DMPlexGetCellNumbering()
7175: @*/
7176: PetscErrorCode DMPlexCreatePointNumbering(DM dm, IS *globalPointNumbers)
7177: {
7178:   IS             nums[4];
7179:   PetscInt       depths[4], gdepths[4], starts[4];
7180:   PetscInt       depth, d, shift = 0;

7185:   DMPlexGetDepth(dm, &depth);
7186:   /* For unstratified meshes use dim instead of depth */
7187:   if (depth < 0) {DMGetDimension(dm, &depth);}
7188:   for (d = 0; d <= depth; ++d) {
7189:     PetscInt end;

7191:     depths[d] = depth-d;
7192:     DMPlexGetDepthStratum(dm, depths[d], &starts[d], &end);
7193:     if (!(starts[d]-end)) { starts[d] = depths[d] = -1; }
7194:   }
7195:   PetscSortIntWithArray(depth+1, starts, depths);
7196:   MPIU_Allreduce(depths, gdepths, depth+1, MPIU_INT, MPI_MAX, PetscObjectComm((PetscObject) dm));
7197:   for (d = 0; d <= depth; ++d) {
7198:     if (starts[d] >= 0 && depths[d] != gdepths[d]) SETERRQ2(PETSC_COMM_SELF,PETSC_ERR_PLIB,"Expected depth %D, found %D",depths[d],gdepths[d]);
7199:   }
7200:   for (d = 0; d <= depth; ++d) {
7201:     PetscInt pStart, pEnd, gsize;

7203:     DMPlexGetDepthStratum(dm, gdepths[d], &pStart, &pEnd);
7204:     DMPlexCreateNumbering_Plex(dm, pStart, pEnd, shift, &gsize, dm->sf, &nums[d]);
7205:     shift += gsize;
7206:   }
7207:   ISConcatenate(PetscObjectComm((PetscObject) dm), depth+1, nums, globalPointNumbers);
7208:   for (d = 0; d <= depth; ++d) {ISDestroy(&nums[d]);}
7209:   return(0);
7210: }


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

7216:   Input Parameter:
7217: . dm - The DMPlex object

7219:   Output Parameter:
7220: . ranks - The rank field

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

7225:   Level: intermediate

7227: .seealso: DMView()
7228: @*/
7229: PetscErrorCode DMPlexCreateRankField(DM dm, Vec *ranks)
7230: {
7231:   DM             rdm;
7232:   PetscFE        fe;
7233:   PetscScalar   *r;
7234:   PetscMPIInt    rank;
7235:   DMPolytopeType ct;
7236:   PetscInt       dim, cStart, cEnd, c;
7237:   PetscBool      simplex;

7243:   MPI_Comm_rank(PetscObjectComm((PetscObject) dm), &rank);
7244:   DMClone(dm, &rdm);
7245:   DMGetDimension(rdm, &dim);
7246:   DMPlexGetHeightStratum(rdm, 0, &cStart, &cEnd);
7247:   DMPlexGetCellType(dm, cStart, &ct);
7248:   simplex = DMPolytopeTypeGetNumVertices(ct) == DMPolytopeTypeGetDim(ct)+1 ? PETSC_TRUE : PETSC_FALSE;
7249:   PetscFECreateDefault(PETSC_COMM_SELF, dim, 1, simplex, "PETSc___rank_", -1, &fe);
7250:   PetscObjectSetName((PetscObject) fe, "rank");
7251:   DMSetField(rdm, 0, NULL, (PetscObject) fe);
7252:   PetscFEDestroy(&fe);
7253:   DMCreateDS(rdm);
7254:   DMCreateGlobalVector(rdm, ranks);
7255:   PetscObjectSetName((PetscObject) *ranks, "partition");
7256:   VecGetArray(*ranks, &r);
7257:   for (c = cStart; c < cEnd; ++c) {
7258:     PetscScalar *lr;

7260:     DMPlexPointGlobalRef(rdm, c, r, &lr);
7261:     if (lr) *lr = rank;
7262:   }
7263:   VecRestoreArray(*ranks, &r);
7264:   DMDestroy(&rdm);
7265:   return(0);
7266: }

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

7271:   Input Parameters:
7272: + dm    - The DMPlex
7273: - label - The DMLabel

7275:   Output Parameter:
7276: . val - The label value field

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

7281:   Level: intermediate

7283: .seealso: DMView()
7284: @*/
7285: PetscErrorCode DMPlexCreateLabelField(DM dm, DMLabel label, Vec *val)
7286: {
7287:   DM             rdm;
7288:   PetscFE        fe;
7289:   PetscScalar   *v;
7290:   PetscInt       dim, cStart, cEnd, c;

7297:   DMClone(dm, &rdm);
7298:   DMGetDimension(rdm, &dim);
7299:   PetscFECreateDefault(PetscObjectComm((PetscObject) rdm), dim, 1, PETSC_TRUE, "PETSc___label_value_", -1, &fe);
7300:   PetscObjectSetName((PetscObject) fe, "label_value");
7301:   DMSetField(rdm, 0, NULL, (PetscObject) fe);
7302:   PetscFEDestroy(&fe);
7303:   DMCreateDS(rdm);
7304:   DMPlexGetHeightStratum(rdm, 0, &cStart, &cEnd);
7305:   DMCreateGlobalVector(rdm, val);
7306:   PetscObjectSetName((PetscObject) *val, "label_value");
7307:   VecGetArray(*val, &v);
7308:   for (c = cStart; c < cEnd; ++c) {
7309:     PetscScalar *lv;
7310:     PetscInt     cval;

7312:     DMPlexPointGlobalRef(rdm, c, v, &lv);
7313:     DMLabelGetValue(label, c, &cval);
7314:     *lv = cval;
7315:   }
7316:   VecRestoreArray(*val, &v);
7317:   DMDestroy(&rdm);
7318:   return(0);
7319: }

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

7324:   Input Parameter:
7325: . dm - The DMPlex object

7327:   Notes:
7328:   This is a useful diagnostic when creating meshes programmatically.

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

7332:   Level: developer

7334: .seealso: DMCreate(), DMSetFromOptions()
7335: @*/
7336: PetscErrorCode DMPlexCheckSymmetry(DM dm)
7337: {
7338:   PetscSection    coneSection, supportSection;
7339:   const PetscInt *cone, *support;
7340:   PetscInt        coneSize, c, supportSize, s;
7341:   PetscInt        pStart, pEnd, p, pp, csize, ssize;
7342:   PetscBool       storagecheck = PETSC_TRUE;
7343:   PetscErrorCode  ierr;

7347:   DMViewFromOptions(dm, NULL, "-sym_dm_view");
7348:   DMPlexGetConeSection(dm, &coneSection);
7349:   DMPlexGetSupportSection(dm, &supportSection);
7350:   /* Check that point p is found in the support of its cone points, and vice versa */
7351:   DMPlexGetChart(dm, &pStart, &pEnd);
7352:   for (p = pStart; p < pEnd; ++p) {
7353:     DMPlexGetConeSize(dm, p, &coneSize);
7354:     DMPlexGetCone(dm, p, &cone);
7355:     for (c = 0; c < coneSize; ++c) {
7356:       PetscBool dup = PETSC_FALSE;
7357:       PetscInt  d;
7358:       for (d = c-1; d >= 0; --d) {
7359:         if (cone[c] == cone[d]) {dup = PETSC_TRUE; break;}
7360:       }
7361:       DMPlexGetSupportSize(dm, cone[c], &supportSize);
7362:       DMPlexGetSupport(dm, cone[c], &support);
7363:       for (s = 0; s < supportSize; ++s) {
7364:         if (support[s] == p) break;
7365:       }
7366:       if ((s >= supportSize) || (dup && (support[s+1] != p))) {
7367:         PetscPrintf(PETSC_COMM_SELF, "p: %D cone: ", p);
7368:         for (s = 0; s < coneSize; ++s) {
7369:           PetscPrintf(PETSC_COMM_SELF, "%D, ", cone[s]);
7370:         }
7371:         PetscPrintf(PETSC_COMM_SELF, "\n");
7372:         PetscPrintf(PETSC_COMM_SELF, "p: %D support: ", cone[c]);
7373:         for (s = 0; s < supportSize; ++s) {
7374:           PetscPrintf(PETSC_COMM_SELF, "%D, ", support[s]);
7375:         }
7376:         PetscPrintf(PETSC_COMM_SELF, "\n");
7377:         if (dup) SETERRQ2(PETSC_COMM_SELF, PETSC_ERR_PLIB, "Point %D not repeatedly found in support of repeated cone point %D", p, cone[c]);
7378:         else SETERRQ2(PETSC_COMM_SELF, PETSC_ERR_PLIB, "Point %D not found in support of cone point %D", p, cone[c]);
7379:       }
7380:     }
7381:     DMPlexGetTreeParent(dm, p, &pp, NULL);
7382:     if (p != pp) { storagecheck = PETSC_FALSE; continue; }
7383:     DMPlexGetSupportSize(dm, p, &supportSize);
7384:     DMPlexGetSupport(dm, p, &support);
7385:     for (s = 0; s < supportSize; ++s) {
7386:       DMPlexGetConeSize(dm, support[s], &coneSize);
7387:       DMPlexGetCone(dm, support[s], &cone);
7388:       for (c = 0; c < coneSize; ++c) {
7389:         DMPlexGetTreeParent(dm, cone[c], &pp, NULL);
7390:         if (cone[c] != pp) { c = 0; break; }
7391:         if (cone[c] == p) break;
7392:       }
7393:       if (c >= coneSize) {
7394:         PetscPrintf(PETSC_COMM_SELF, "p: %D support: ", p);
7395:         for (c = 0; c < supportSize; ++c) {
7396:           PetscPrintf(PETSC_COMM_SELF, "%D, ", support[c]);
7397:         }
7398:         PetscPrintf(PETSC_COMM_SELF, "\n");
7399:         PetscPrintf(PETSC_COMM_SELF, "p: %D cone: ", support[s]);
7400:         for (c = 0; c < coneSize; ++c) {
7401:           PetscPrintf(PETSC_COMM_SELF, "%D, ", cone[c]);
7402:         }
7403:         PetscPrintf(PETSC_COMM_SELF, "\n");
7404:         SETERRQ2(PETSC_COMM_SELF, PETSC_ERR_PLIB, "Point %D not found in cone of support point %D", p, support[s]);
7405:       }
7406:     }
7407:   }
7408:   if (storagecheck) {
7409:     PetscSectionGetStorageSize(coneSection, &csize);
7410:     PetscSectionGetStorageSize(supportSection, &ssize);
7411:     if (csize != ssize) SETERRQ2(PETSC_COMM_SELF, PETSC_ERR_ARG_SIZ, "Total cone size %D != Total support size %D", csize, ssize);
7412:   }
7413:   return(0);
7414: }

7416: /*
7417:   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.
7418: */
7419: static PetscErrorCode DMPlexCellUnsplitVertices_Private(DM dm, PetscInt c, DMPolytopeType ct, PetscInt *unsplit)
7420: {
7421:   DMPolytopeType  cct;
7422:   PetscInt        ptpoints[4];
7423:   const PetscInt *cone, *ccone, *ptcone;
7424:   PetscInt        coneSize, cp, cconeSize, ccp, npt = 0, pt;
7425:   PetscErrorCode  ierr;

7428:   *unsplit = 0;
7429:   switch (ct) {
7430:     case DM_POLYTOPE_SEG_PRISM_TENSOR:
7431:       DMPlexGetCone(dm, c, &cone);
7432:       DMPlexGetConeSize(dm, c, &coneSize);
7433:       for (cp = 0; cp < coneSize; ++cp) {
7434:         DMPlexGetCellType(dm, cone[cp], &cct);
7435:         if (cct == DM_POLYTOPE_POINT_PRISM_TENSOR) ptpoints[npt++] = cone[cp];
7436:       }
7437:       break;
7438:     case DM_POLYTOPE_TRI_PRISM_TENSOR:
7439:     case DM_POLYTOPE_QUAD_PRISM_TENSOR:
7440:       DMPlexGetCone(dm, c, &cone);
7441:       DMPlexGetConeSize(dm, c, &coneSize);
7442:       for (cp = 0; cp < coneSize; ++cp) {
7443:         DMPlexGetCone(dm, cone[cp], &ccone);
7444:         DMPlexGetConeSize(dm, cone[cp], &cconeSize);
7445:         for (ccp = 0; ccp < cconeSize; ++ccp) {
7446:           DMPlexGetCellType(dm, ccone[ccp], &cct);
7447:           if (cct == DM_POLYTOPE_POINT_PRISM_TENSOR) {
7448:             PetscInt p;
7449:             for (p = 0; p < npt; ++p) if (ptpoints[p] == ccone[ccp]) break;
7450:             if (p == npt) ptpoints[npt++] = ccone[ccp];
7451:           }
7452:         }
7453:       }
7454:       break;
7455:     default: break;
7456:   }
7457:   for (pt = 0; pt < npt; ++pt) {
7458:     DMPlexGetCone(dm, ptpoints[pt], &ptcone);
7459:     if (ptcone[0] == ptcone[1]) ++(*unsplit);
7460:   }
7461:   return(0);
7462: }

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

7467:   Input Parameters:
7468: + dm - The DMPlex object
7469: - cellHeight - Normally 0

7471:   Notes:
7472:   This is a useful diagnostic when creating meshes programmatically.
7473:   Currently applicable only to homogeneous simplex or tensor meshes.

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

7477:   Level: developer

7479: .seealso: DMCreate(), DMSetFromOptions()
7480: @*/
7481: PetscErrorCode DMPlexCheckSkeleton(DM dm, PetscInt cellHeight)
7482: {
7483:   DMPlexInterpolatedFlag interp;
7484:   DMPolytopeType         ct;
7485:   PetscInt               vStart, vEnd, cStart, cEnd, c;
7486:   PetscErrorCode         ierr;

7490:   DMPlexIsInterpolated(dm, &interp);
7491:   DMPlexGetHeightStratum(dm, cellHeight, &cStart, &cEnd);
7492:   DMPlexGetDepthStratum(dm, 0, &vStart, &vEnd);
7493:   for (c = cStart; c < cEnd; ++c) {
7494:     PetscInt *closure = NULL;
7495:     PetscInt  coneSize, closureSize, cl, Nv = 0;

7497:     DMPlexGetCellType(dm, c, &ct);
7498:     if ((PetscInt) ct < 0) SETERRQ1(PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Cell %D has no cell type", c);
7499:     if (ct == DM_POLYTOPE_UNKNOWN) continue;
7500:     if (interp == DMPLEX_INTERPOLATED_FULL) {
7501:       DMPlexGetConeSize(dm, c, &coneSize);
7502:       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));
7503:     }
7504:     DMPlexGetTransitiveClosure(dm, c, PETSC_TRUE, &closureSize, &closure);
7505:     for (cl = 0; cl < closureSize*2; cl += 2) {
7506:       const PetscInt p = closure[cl];
7507:       if ((p >= vStart) && (p < vEnd)) ++Nv;
7508:     }
7509:     DMPlexRestoreTransitiveClosure(dm, c, PETSC_TRUE, &closureSize, &closure);
7510:     /* Special Case: Tensor faces with identified vertices */
7511:     if (Nv < DMPolytopeTypeGetNumVertices(ct)) {
7512:       PetscInt unsplit;

7514:       DMPlexCellUnsplitVertices_Private(dm, c, ct, &unsplit);
7515:       if (Nv + unsplit == DMPolytopeTypeGetNumVertices(ct)) continue;
7516:     }
7517:     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));
7518:   }
7519:   return(0);
7520: }

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

7525:   Not Collective

7527:   Input Parameters:
7528: + dm - The DMPlex object
7529: - cellHeight - Normally 0

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

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

7539:   Level: developer

7541: .seealso: DMCreate(), DMPlexGetVTKCellHeight(), DMSetFromOptions()
7542: @*/
7543: PetscErrorCode DMPlexCheckFaces(DM dm, PetscInt cellHeight)
7544: {
7545:   PetscInt       dim, depth, vStart, vEnd, cStart, cEnd, c, h;
7547:   DMPlexInterpolatedFlag interpEnum;

7551:   DMPlexIsInterpolated(dm, &interpEnum);
7552:   if (interpEnum == DMPLEX_INTERPOLATED_NONE) return(0);
7553:   if (interpEnum == DMPLEX_INTERPOLATED_PARTIAL) {
7554:     PetscMPIInt rank;
7555:     MPI_Comm    comm;

7557:     PetscObjectGetComm((PetscObject) dm, &comm);
7558:     MPI_Comm_rank(comm, &rank);
7559:     SETERRQ1(PETSC_COMM_SELF, PETSC_ERR_SUP, "Mesh is only partially interpolated on rank %d, this is currently not supported", rank);
7560:   }

7562:   DMGetDimension(dm, &dim);
7563:   DMPlexGetDepth(dm, &depth);
7564:   DMPlexGetDepthStratum(dm, 0, &vStart, &vEnd);
7565:   for (h = cellHeight; h < PetscMin(depth, dim); ++h) {
7566:     DMPlexGetHeightStratum(dm, h, &cStart, &cEnd);
7567:     for (c = cStart; c < cEnd; ++c) {
7568:       const PetscInt      *cone, *ornt, *faceSizes, *faces;
7569:       const DMPolytopeType *faceTypes;
7570:       DMPolytopeType        ct;
7571:       PetscInt              numFaces, coneSize, f;
7572:       PetscInt             *closure = NULL, closureSize, cl, numCorners = 0, fOff = 0, unsplit;

7574:       DMPlexGetCellType(dm, c, &ct);
7575:       DMPlexCellUnsplitVertices_Private(dm, c, ct, &unsplit);
7576:       if (unsplit) continue;
7577:       DMPlexGetConeSize(dm, c, &coneSize);
7578:       DMPlexGetCone(dm, c, &cone);
7579:       DMPlexGetConeOrientation(dm, c, &ornt);
7580:       DMPlexGetTransitiveClosure(dm, c, PETSC_TRUE, &closureSize, &closure);
7581:       for (cl = 0; cl < closureSize*2; cl += 2) {
7582:         const PetscInt p = closure[cl];
7583:         if ((p >= vStart) && (p < vEnd)) closure[numCorners++] = p;
7584:       }
7585:       DMPlexGetRawFaces_Internal(dm, ct, closure, &numFaces, &faceTypes, &faceSizes, &faces);
7586:       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);
7587:       for (f = 0; f < numFaces; ++f) {
7588:         DMPolytopeType fct;
7589:         PetscInt       *fclosure = NULL, fclosureSize, cl, fnumCorners = 0, v;

7591:         DMPlexGetCellType(dm, cone[f], &fct);
7592:         DMPlexGetTransitiveClosure_Internal(dm, cone[f], ornt[f], PETSC_TRUE, &fclosureSize, &fclosure);
7593:         for (cl = 0; cl < fclosureSize*2; cl += 2) {
7594:           const PetscInt p = fclosure[cl];
7595:           if ((p >= vStart) && (p < vEnd)) fclosure[fnumCorners++] = p;
7596:         }
7597:         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]);
7598:         for (v = 0; v < fnumCorners; ++v) {
7599:           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]);
7600:         }
7601:         DMPlexRestoreTransitiveClosure(dm, cone[f], PETSC_TRUE, &fclosureSize, &fclosure);
7602:         fOff += faceSizes[f];
7603:       }
7604:       DMPlexRestoreRawFaces_Internal(dm, ct, closure, &numFaces, &faceTypes, &faceSizes, &faces);
7605:       DMPlexRestoreTransitiveClosure(dm, c, PETSC_TRUE, &closureSize, &closure);
7606:     }
7607:   }
7608:   return(0);
7609: }

7611: /*@
7612:   DMPlexCheckGeometry - Check the geometry of mesh cells

7614:   Input Parameter:
7615: . dm - The DMPlex object

7617:   Notes:
7618:   This is a useful diagnostic when creating meshes programmatically.

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

7622:   Level: developer

7624: .seealso: DMCreate(), DMSetFromOptions()
7625: @*/
7626: PetscErrorCode DMPlexCheckGeometry(DM dm)
7627: {
7628:   PetscReal      detJ, J[9], refVol = 1.0;
7629:   PetscReal      vol;
7630:   PetscBool      periodic;
7631:   PetscInt       dim, depth, dE, d, cStart, cEnd, c;

7635:   DMGetDimension(dm, &dim);
7636:   DMGetCoordinateDim(dm, &dE);
7637:   if (dim != dE) return(0);
7638:   DMPlexGetDepth(dm, &depth);
7639:   DMGetPeriodicity(dm, &periodic, NULL, NULL, NULL);
7640:   for (d = 0; d < dim; ++d) refVol *= 2.0;
7641:   DMPlexGetHeightStratum(dm, 0, &cStart, &cEnd);
7642:   for (c = cStart; c < cEnd; ++c) {
7643:     DMPolytopeType ct;
7644:     PetscInt       unsplit;
7645:     PetscBool      ignoreZeroVol = PETSC_FALSE;

7647:     DMPlexGetCellType(dm, c, &ct);
7648:     switch (ct) {
7649:       case DM_POLYTOPE_SEG_PRISM_TENSOR:
7650:       case DM_POLYTOPE_TRI_PRISM_TENSOR:
7651:       case DM_POLYTOPE_QUAD_PRISM_TENSOR:
7652:         ignoreZeroVol = PETSC_TRUE; break;
7653:       default: break;
7654:     }
7655:     switch (ct) {
7656:       case DM_POLYTOPE_TRI_PRISM:
7657:       case DM_POLYTOPE_TRI_PRISM_TENSOR:
7658:       case DM_POLYTOPE_QUAD_PRISM_TENSOR:
7659:         continue;
7660:       default: break;
7661:     }
7662:     DMPlexCellUnsplitVertices_Private(dm, c, ct, &unsplit);
7663:     if (unsplit) continue;
7664:     DMPlexComputeCellGeometryFEM(dm, c, NULL, NULL, J, NULL, &detJ);
7665:     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);
7666:     PetscInfo2(dm, "Cell %D FEM Volume %g\n", c, (double) detJ*refVol);
7667:     if (depth > 1 && !periodic) {
7668:       DMPlexComputeCellGeometryFVM(dm, c, &vol, NULL, NULL);
7669:       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);
7670:       PetscInfo2(dm, "Cell %D FVM Volume %g\n", c, (double) vol);
7671:     }
7672:   }
7673:   return(0);
7674: }

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

7679:   Input Parameters:
7680: . dm - The DMPlex object

7682:   Notes:
7683:   This is mainly intended for debugging/testing purposes.
7684:   It currently checks only meshes with no partition overlapping.

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

7688:   Level: developer

7690: .seealso: DMGetPointSF(), DMSetFromOptions()
7691: @*/
7692: PetscErrorCode DMPlexCheckPointSF(DM dm)
7693: {
7694:   PetscSF         pointSF;
7695:   PetscInt        cellHeight, cStart, cEnd, l, nleaves, nroots, overlap;
7696:   const PetscInt *locals, *rootdegree;
7697:   PetscBool       distributed;
7698:   PetscErrorCode  ierr;

7702:   DMGetPointSF(dm, &pointSF);
7703:   DMPlexIsDistributed(dm, &distributed);
7704:   if (!distributed) return(0);
7705:   DMPlexGetOverlap(dm, &overlap);
7706:   if (overlap) {
7707:     PetscPrintf(PetscObjectComm((PetscObject)dm), "Warning: DMPlexCheckPointSF() is currently not implemented for meshes with partition overlapping");
7708:     return(0);
7709:   }
7710:   if (!pointSF) SETERRQ(PetscObjectComm((PetscObject)dm), PETSC_ERR_ARG_WRONGSTATE, "This DMPlex is distributed but does not have PointSF attached");
7711:   PetscSFGetGraph(pointSF, &nroots, &nleaves, &locals, NULL);
7712:   if (nroots < 0) SETERRQ(PetscObjectComm((PetscObject)dm), PETSC_ERR_ARG_WRONGSTATE, "This DMPlex is distributed but its PointSF has no graph set");
7713:   PetscSFComputeDegreeBegin(pointSF, &rootdegree);
7714:   PetscSFComputeDegreeEnd(pointSF, &rootdegree);

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

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

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

7731:     DMPlexGetConeSize(dm, point, &coneSize);
7732:     DMPlexGetCone(dm, point, &cone);
7733:     for (c = 0; c < coneSize; ++c) {
7734:       if (!rootdegree[cone[c]]) {
7735:         PetscFindInt(cone[c], nleaves, locals, &idx);
7736:         if (idx < 0) SETERRQ2(PETSC_COMM_SELF, PETSC_ERR_PLIB, "Point SF contains %D but not %D from its cone", point, cone[c]);
7737:       }
7738:     }
7739:   }
7740:   return(0);
7741: }

7743: typedef struct cell_stats
7744: {
7745:   PetscReal min, max, sum, squaresum;
7746:   PetscInt  count;
7747: } cell_stats_t;

7749: static void MPIAPI cell_stats_reduce(void *a, void *b, int * len, MPI_Datatype *datatype)
7750: {
7751:   PetscInt i, N = *len;

7753:   for (i = 0; i < N; i++) {
7754:     cell_stats_t *A = (cell_stats_t *) a;
7755:     cell_stats_t *B = (cell_stats_t *) b;

7757:     B->min = PetscMin(A->min,B->min);
7758:     B->max = PetscMax(A->max,B->max);
7759:     B->sum += A->sum;
7760:     B->squaresum += A->squaresum;
7761:     B->count += A->count;
7762:   }
7763: }

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

7768:   Collective on dm

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

7775:   Notes:
7776:   This is mainly intended for debugging/testing purposes.

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

7780:   Level: developer

7782: .seealso: DMSetFromOptions(), DMPlexComputeOrthogonalQuality()
7783: @*/
7784: PetscErrorCode DMPlexCheckCellShape(DM dm, PetscBool output, PetscReal condLimit)
7785: {
7786:   DM             dmCoarse;
7787:   cell_stats_t   stats, globalStats;
7788:   MPI_Comm       comm = PetscObjectComm((PetscObject)dm);
7789:   PetscReal      *J, *invJ, min = 0, max = 0, mean = 0, stdev = 0;
7790:   PetscReal      limit = condLimit > 0 ? condLimit : PETSC_MAX_REAL;
7791:   PetscInt       cdim, cStart, cEnd, c, eStart, eEnd, count = 0;
7792:   PetscMPIInt    rank,size;

7797:   stats.min   = PETSC_MAX_REAL;
7798:   stats.max   = PETSC_MIN_REAL;
7799:   stats.sum   = stats.squaresum = 0.;
7800:   stats.count = 0;

7802:   MPI_Comm_size(comm, &size);
7803:   MPI_Comm_rank(comm, &rank);
7804:   DMGetCoordinateDim(dm,&cdim);
7805:   PetscMalloc2(PetscSqr(cdim), &J, PetscSqr(cdim), &invJ);
7806:   DMPlexGetSimplexOrBoxCells(dm,0,&cStart,&cEnd);
7807:   DMPlexGetDepthStratum(dm,1,&eStart,&eEnd);
7808:   for (c = cStart; c < cEnd; c++) {
7809:     PetscInt  i;
7810:     PetscReal frobJ = 0., frobInvJ = 0., cond2, cond, detJ;

7812:     DMPlexComputeCellGeometryAffineFEM(dm,c,NULL,J,invJ,&detJ);
7813:     if (detJ < 0.0) SETERRQ1(PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Mesh cell %D is inverted", c);
7814:     for (i = 0; i < PetscSqr(cdim); ++i) {
7815:       frobJ    += J[i] * J[i];
7816:       frobInvJ += invJ[i] * invJ[i];
7817:     }
7818:     cond2 = frobJ * frobInvJ;
7819:     cond  = PetscSqrtReal(cond2);

7821:     stats.min        = PetscMin(stats.min,cond);
7822:     stats.max        = PetscMax(stats.max,cond);
7823:     stats.sum       += cond;
7824:     stats.squaresum += cond2;
7825:     stats.count++;
7826:     if (output && cond > limit) {
7827:       PetscSection coordSection;
7828:       Vec          coordsLocal;
7829:       PetscScalar *coords = NULL;
7830:       PetscInt     Nv, d, clSize, cl, *closure = NULL;

7832:       DMGetCoordinatesLocal(dm, &coordsLocal);
7833:       DMGetCoordinateSection(dm, &coordSection);
7834:       DMPlexVecGetClosure(dm, coordSection, coordsLocal, c, &Nv, &coords);
7835:       PetscSynchronizedPrintf(comm, "[%d] Cell %D cond %g\n", rank, c, (double) cond);
7836:       for (i = 0; i < Nv/cdim; ++i) {
7837:         PetscSynchronizedPrintf(comm, "  Vertex %D: (", i);
7838:         for (d = 0; d < cdim; ++d) {
7839:           if (d > 0) {PetscSynchronizedPrintf(comm, ", ");}
7840:           PetscSynchronizedPrintf(comm, "%g", (double) PetscRealPart(coords[i*cdim+d]));
7841:         }
7842:         PetscSynchronizedPrintf(comm, ")\n");
7843:       }
7844:       DMPlexGetTransitiveClosure(dm, c, PETSC_TRUE, &clSize, &closure);
7845:       for (cl = 0; cl < clSize*2; cl += 2) {
7846:         const PetscInt edge = closure[cl];

7848:         if ((edge >= eStart) && (edge < eEnd)) {
7849:           PetscReal len;

7851:           DMPlexComputeCellGeometryFVM(dm, edge, &len, NULL, NULL);
7852:           PetscSynchronizedPrintf(comm, "  Edge %D: length %g\n", edge, (double) len);
7853:         }
7854:       }
7855:       DMPlexRestoreTransitiveClosure(dm, c, PETSC_TRUE, &clSize, &closure);
7856:       DMPlexVecRestoreClosure(dm, coordSection, coordsLocal, c, &Nv, &coords);
7857:     }
7858:   }
7859:   if (output) {PetscSynchronizedFlush(comm, NULL);}

7861:   if (size > 1) {
7862:     PetscMPIInt   blockLengths[2] = {4,1};
7863:     MPI_Aint      blockOffsets[2] = {offsetof(cell_stats_t,min),offsetof(cell_stats_t,count)};
7864:     MPI_Datatype  blockTypes[2]   = {MPIU_REAL,MPIU_INT}, statType;
7865:     MPI_Op        statReduce;

7867:     MPI_Type_create_struct(2,blockLengths,blockOffsets,blockTypes,&statType);
7868:     MPI_Type_commit(&statType);
7869:     MPI_Op_create(cell_stats_reduce, PETSC_TRUE, &statReduce);
7870:     MPI_Reduce(&stats,&globalStats,1,statType,statReduce,0,comm);
7871:     MPI_Op_free(&statReduce);
7872:     MPI_Type_free(&statType);
7873:   } else {
7874:     PetscArraycpy(&globalStats,&stats,1);
7875:   }
7876:   if (!rank) {
7877:     count = globalStats.count;
7878:     min   = globalStats.min;
7879:     max   = globalStats.max;
7880:     mean  = globalStats.sum / globalStats.count;
7881:     stdev = globalStats.count > 1 ? PetscSqrtReal(PetscMax((globalStats.squaresum - globalStats.count * mean * mean) / (globalStats.count - 1),0)) : 0.0;
7882:   }

7884:   if (output) {
7885:     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);
7886:   }
7887:   PetscFree2(J,invJ);

7889:   DMGetCoarseDM(dm,&dmCoarse);
7890:   if (dmCoarse) {
7891:     PetscBool isplex;

7893:     PetscObjectTypeCompare((PetscObject)dmCoarse,DMPLEX,&isplex);
7894:     if (isplex) {
7895:       DMPlexCheckCellShape(dmCoarse,output,condLimit);
7896:     }
7897:   }
7898:   return(0);
7899: }

7901: /*@
7902:   DMPlexComputeOrthogonalQuality - Compute cell-wise orthogonal quality mesh statistic. Optionally tags all cells with
7903:   orthogonal quality below given tolerance.

7905:   Collective

7907:   Input Parameters:
7908: + dm   - The DMPlex object
7909: . fv   - Optional PetscFV object for pre-computed cell/face centroid information
7910: - atol - [0, 1] Absolute tolerance for tagging cells.

7912:   Output Parameters:
7913: + OrthQual      - Vec containing orthogonal quality per cell
7914: - OrthQualLabel - DMLabel tagging cells below atol with DM_ADAPT_REFINE

7916:   Options Database Keys:
7917: + -dm_plex_orthogonal_quality_label_view - view OrthQualLabel if label is requested. Currently only PETSCVIEWERASCII is
7918: supported.
7919: - -dm_plex_orthogonal_quality_vec_view - view OrthQual vector.

7921:   Notes:
7922:   Orthogonal quality is given by the following formula:

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

7926:   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
7927:   is the vector from the current cells centroid to the centroid of its i'th neighbor (which shares a face with the
7928:   current cell). This computes the vector similarity between each cell face and its corresponding neighbor centroid by
7929:   calculating the cosine of the angle between these vectors.

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

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

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

7938:   Level: intermediate

7940: .seealso: DMPlexCheckCellShape(), DMCreateLabel()
7941: @*/
7942: PetscErrorCode DMPlexComputeOrthogonalQuality(DM dm, PetscFV fv, PetscReal atol, Vec *OrthQual, DMLabel *OrthQualLabel)
7943: {
7944:   PetscInt                nc, cellHeight, cStart, cEnd, cell;
7945:   const PetscScalar       *cellGeomArr, *faceGeomArr;
7946:   MPI_Comm                comm;
7947:   Vec                     cellgeom, facegeom;
7948:   DM                      dmFace, dmCell;
7949:   IS                      glob;
7950:   DMPlexInterpolatedFlag  interpFlag;
7951:   ISLocalToGlobalMapping  ltog;
7952:   PetscViewer             vwr;
7953:   PetscErrorCode          ierr;

7958:   PetscObjectGetComm((PetscObject) dm, &comm);
7959:   DMGetDimension(dm, &nc);
7960:   if (nc < 2) {
7961:     SETERRQ1(PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "DM must have dimension >= 2 (current %D)", nc);
7962:   }
7963:   DMPlexIsInterpolated(dm, &interpFlag);
7964:   if (interpFlag != DMPLEX_INTERPOLATED_FULL) {
7965:     PetscMPIInt  rank;

7967:     MPI_Comm_rank(comm, &rank);
7968:     SETERRQ1(PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "DM must be fully interpolated, DM on rank %d is not fully interpolated", rank);
7969:   }
7970:   if (OrthQualLabel) {
7972:     DMCreateLabel(dm, "Orthogonal_Quality");
7973:     DMGetLabel(dm, "Orthogonal_Quality", OrthQualLabel);
7974:   } else {
7975:     *OrthQualLabel = NULL;
7976:   }

7978:   DMPlexGetVTKCellHeight(dm, &cellHeight);
7979:   DMPlexGetHeightStratum(dm, cellHeight, &cStart, &cEnd);
7980:   DMPlexCreateCellNumbering_Internal(dm, PETSC_TRUE, &glob);
7981:   ISLocalToGlobalMappingCreateIS(glob, &ltog);
7982:   ISLocalToGlobalMappingSetType(ltog, ISLOCALTOGLOBALMAPPINGHASH);
7983:   VecCreate(comm, OrthQual);
7984:   VecSetType(*OrthQual, VECSTANDARD);
7985:   VecSetSizes(*OrthQual, cEnd-cStart, PETSC_DETERMINE);
7986:   VecSetLocalToGlobalMapping(*OrthQual, ltog);
7987:   VecSetUp(*OrthQual);
7988:   ISDestroy(&glob);
7989:   ISLocalToGlobalMappingDestroy(&ltog);
7990:   DMPlexGetDataFVM(dm, fv, &cellgeom, &facegeom, NULL);
7991:   VecGetArrayRead(cellgeom, &cellGeomArr);
7992:   VecGetArrayRead(facegeom, &faceGeomArr);
7993:   VecGetDM(cellgeom, &dmCell);
7994:   VecGetDM(facegeom, &dmFace);
7995:   for (cell = cStart; cell < cEnd; cell++) {
7996:     PetscInt           cellneigh, cellneighiter = 0, nf, adjSize = PETSC_DETERMINE, ix = cell-cStart;
7997:     const PetscInt     *cone;
7998:     PetscInt           cellarr[2], *adj = NULL;
7999:     PetscScalar        *cArr, *fArr;
8000:     PetscReal          minvalc = 1.0, minvalf = 1.0, OQ;
8001:     PetscFVCellGeom    *cg;

8003:     cellarr[0] = cell;
8004:     /* Make indexing into cellGeom easier */
8005:     DMPlexPointLocalRead(dmCell, cell, cellGeomArr, &cg);
8006:     DMPlexGetAdjacency_Internal(dm, cell, PETSC_TRUE, PETSC_FALSE, PETSC_FALSE, &adjSize, &adj);
8007:     DMPlexGetConeSize(dm, cell, &nf);
8008:     DMPlexGetCone(dm, cell, &cone);
8009:     /* Technically 1 too big, but easier than fiddling with empty adjacency array */
8010:     PetscCalloc2(adjSize, &cArr, adjSize, &fArr);
8011:     for (cellneigh = 0; cellneigh < adjSize; cellneigh++) {
8012:       PetscInt         numcovpts, i, neigh = adj[cellneigh];
8013:       const PetscInt   *covpts;
8014:       PetscReal        normci = 0, normfi = 0, normai = 0;
8015:       PetscReal        *ci, *fi, *Ai;
8016:       PetscFVCellGeom  *cgneigh;
8017:       PetscFVFaceGeom  *fg;

8019:       /* Don't count ourselves in the neighbor list */
8020:       if (neigh == cell) continue;
8021:       PetscMalloc3(nc, &ci, nc, &fi, nc, &Ai);
8022:       DMPlexPointLocalRead(dmCell, neigh, cellGeomArr, &cgneigh);
8023:       cellarr[1] = neigh;
8024:       DMPlexGetMeet(dm, 2, cellarr, &numcovpts, &covpts);
8025:       DMPlexPointLocalRead(dmFace, covpts[0], faceGeomArr, &fg);
8026:       DMPlexRestoreMeet(dm, 2, cellarr, &numcovpts, &covpts);

8028:       /* Compute c_i, f_i and their norms */
8029:       for (i = 0; i < nc; i++) {
8030:         ci[i] = cgneigh->centroid[i] - cg->centroid[i];
8031:         fi[i] = fg->centroid[i] - cg->centroid[i];
8032:         Ai[i] = fg->normal[i];
8033:         normci += PetscPowScalar(ci[i], 2);
8034:         normfi += PetscPowScalar(fi[i], 2);
8035:         normai += PetscPowScalar(Ai[i], 2);
8036:       }
8037:       normci = PetscSqrtScalar(normci);
8038:       normfi = PetscSqrtScalar(normfi);
8039:       normai = PetscSqrtScalar(normai);

8041:       /* Normalize and compute for each face-cell-normal pair */
8042:       for (i = 0; i < nc; i++) {
8043:         ci[i] = ci[i]/normci;
8044:         fi[i] = fi[i]/normfi;
8045:         Ai[i] = Ai[i]/normai;
8046:         /* PetscAbs because I don't know if normals are guaranteed to point out */
8047:         cArr[cellneighiter] += PetscAbs(Ai[i]*ci[i]);
8048:         fArr[cellneighiter] += PetscAbs(Ai[i]*fi[i]);
8049:       }
8050:       if (PetscRealPart(cArr[cellneighiter]) < minvalc) {
8051:         minvalc = PetscRealPart(cArr[cellneighiter]);
8052:       }
8053:       if (PetscRealPart(fArr[cellneighiter]) < minvalf) {
8054:         minvalf = PetscRealPart(fArr[cellneighiter]);
8055:       }
8056:       cellneighiter++;
8057:       PetscFree3(ci, fi, Ai);
8058:     }
8059:     PetscFree(adj);
8060:     PetscFree2(cArr, fArr);
8061:     /* Defer to cell if they're equal */
8062:     OQ = PetscMin(minvalf, minvalc);
8063:     if (OrthQualLabel) {
8064:       if (OQ <= atol) {
8065:         DMLabelSetValue(*OrthQualLabel, cell, DM_ADAPT_REFINE);
8066:       }
8067:     }
8068:     VecSetValuesLocal(*OrthQual, 1, (const PetscInt *) &ix, (const PetscScalar *) &OQ, INSERT_VALUES);
8069:   }
8070:   VecAssemblyBegin(*OrthQual);
8071:   VecAssemblyEnd(*OrthQual);
8072:   VecRestoreArrayRead(cellgeom, &cellGeomArr);
8073:   VecRestoreArrayRead(facegeom, &faceGeomArr);
8074:   PetscOptionsGetViewer(comm, NULL, NULL, "-dm_plex_orthogonal_quality_label_view", &vwr, NULL, NULL);
8075:   if (OrthQualLabel) {
8076:     if (vwr) {
8077:       DMLabelView(*OrthQualLabel, vwr);
8078:     }
8079:   }
8080:   PetscViewerDestroy(&vwr);
8081:   VecViewFromOptions(*OrthQual, NULL, "-dm_plex_orthogonal_quality_vec_view");
8082:   return(0);
8083: }

8085: /* Pointwise interpolation
8086:      Just code FEM for now
8087:      u^f = I u^c
8088:      sum_k u^f_k phi^f_k = I sum_j u^c_j phi^c_j
8089:      u^f_i = sum_j psi^f_i I phi^c_j u^c_j
8090:      I_{ij} = psi^f_i phi^c_j
8091: */
8092: PetscErrorCode DMCreateInterpolation_Plex(DM dmCoarse, DM dmFine, Mat *interpolation, Vec *scaling)
8093: {
8094:   PetscSection   gsc, gsf;
8095:   PetscInt       m, n;
8096:   void          *ctx;
8097:   DM             cdm;
8098:   PetscBool      regular, ismatis, isRefined = dmCoarse->data == dmFine->data ? PETSC_FALSE : PETSC_TRUE;

8102:   DMGetGlobalSection(dmFine, &gsf);
8103:   PetscSectionGetConstrainedStorageSize(gsf, &m);
8104:   DMGetGlobalSection(dmCoarse, &gsc);
8105:   PetscSectionGetConstrainedStorageSize(gsc, &n);

8107:   PetscStrcmp(dmCoarse->mattype, MATIS, &ismatis);
8108:   MatCreate(PetscObjectComm((PetscObject) dmCoarse), interpolation);
8109:   MatSetSizes(*interpolation, m, n, PETSC_DETERMINE, PETSC_DETERMINE);
8110:   MatSetType(*interpolation, ismatis ? MATAIJ : dmCoarse->mattype);
8111:   DMGetApplicationContext(dmFine, &ctx);

8113:   DMGetCoarseDM(dmFine, &cdm);
8114:   DMPlexGetRegularRefinement(dmFine, &regular);
8115:   if (!isRefined || (regular && cdm == dmCoarse)) {DMPlexComputeInterpolatorNested(dmCoarse, dmFine, isRefined, *interpolation, ctx);}
8116:   else                                            {DMPlexComputeInterpolatorGeneral(dmCoarse, dmFine, *interpolation, ctx);}
8117:   MatViewFromOptions(*interpolation, NULL, "-interp_mat_view");
8118:   if (scaling) {
8119:     /* Use naive scaling */
8120:     DMCreateInterpolationScale(dmCoarse, dmFine, *interpolation, scaling);
8121:   }
8122:   return(0);
8123: }

8125: PetscErrorCode DMCreateInjection_Plex(DM dmCoarse, DM dmFine, Mat *mat)
8126: {
8128:   VecScatter     ctx;

8131:   DMPlexComputeInjectorFEM(dmCoarse, dmFine, &ctx, NULL);
8132:   MatCreateScatter(PetscObjectComm((PetscObject)ctx), ctx, mat);
8133:   VecScatterDestroy(&ctx);
8134:   return(0);
8135: }

8137: static void g0_identity_private(PetscInt dim, PetscInt Nf, PetscInt NfAux,
8138:                                 const PetscInt uOff[], const PetscInt uOff_x[], const PetscScalar u[], const PetscScalar u_t[], const PetscScalar u_x[],
8139:                                 const PetscInt aOff[], const PetscInt aOff_x[], const PetscScalar a[], const PetscScalar a_t[], const PetscScalar a_x[],
8140:                                 PetscReal t, PetscReal u_tShift, const PetscReal x[], PetscInt numConstants, const PetscScalar constants[], PetscScalar g0[])
8141: {
8142:   g0[0] = 1.0;
8143: }

8145: PetscErrorCode DMCreateMassMatrix_Plex(DM dmCoarse, DM dmFine, Mat *mass)
8146: {
8147:   PetscSection   gsc, gsf;
8148:   PetscInt       m, n;
8149:   void          *ctx;
8150:   DM             cdm;
8151:   PetscBool      regular;

8155:   if (dmFine == dmCoarse) {
8156:     DM       dmc;
8157:     PetscDS  ds;
8158:     Vec      u;
8159:     IS       cellIS;
8160:     PetscInt depth;

8162:     DMClone(dmFine, &dmc);
8163:     DMCopyDisc(dmFine, dmc);
8164:     DMGetDS(dmc, &ds);
8165:     PetscDSSetJacobian(ds, 0, 0, g0_identity_private, NULL, NULL, NULL);
8166:     DMCreateMatrix(dmc, mass);
8167:     DMGetGlobalVector(dmc, &u);
8168:     DMPlexGetDepth(dmc, &depth);
8169:     DMGetStratumIS(dmc, "depth", depth, &cellIS);
8170:     MatZeroEntries(*mass);
8171:     DMPlexComputeJacobian_Internal(dmc, cellIS, 0.0, 0.0, u, NULL, *mass, *mass, NULL);
8172:     ISDestroy(&cellIS);
8173:     DMRestoreGlobalVector(dmc, &u);
8174:     DMDestroy(&dmc);
8175:   } else {
8176:     DMGetGlobalSection(dmFine, &gsf);
8177:     PetscSectionGetConstrainedStorageSize(gsf, &m);
8178:     DMGetGlobalSection(dmCoarse, &gsc);
8179:     PetscSectionGetConstrainedStorageSize(gsc, &n);

8181:     MatCreate(PetscObjectComm((PetscObject) dmCoarse), mass);
8182:     MatSetSizes(*mass, m, n, PETSC_DETERMINE, PETSC_DETERMINE);
8183:     MatSetType(*mass, dmCoarse->mattype);
8184:     DMGetApplicationContext(dmFine, &ctx);

8186:     DMGetCoarseDM(dmFine, &cdm);
8187:     DMPlexGetRegularRefinement(dmFine, &regular);
8188:     if (regular && cdm == dmCoarse) {DMPlexComputeMassMatrixNested(dmCoarse, dmFine, *mass, ctx);}
8189:     else                            {DMPlexComputeMassMatrixGeneral(dmCoarse, dmFine, *mass, ctx);}
8190:   }
8191:   MatViewFromOptions(*mass, NULL, "-mass_mat_view");
8192:   return(0);
8193: }

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

8198:   Input Parameter:
8199: . dm - The DMPlex object

8201:   Output Parameter:
8202: . regular - The flag

8204:   Level: intermediate

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

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

8220:   Input Parameters:
8221: + dm - The DMPlex object
8222: - regular - The flag

8224:   Level: intermediate

8226: .seealso: DMPlexGetRegularRefinement()
8227: @*/
8228: PetscErrorCode DMPlexSetRegularRefinement(DM dm, PetscBool regular)
8229: {
8232:   ((DM_Plex *) dm->data)->regularRefinement = regular;
8233:   return(0);
8234: }

8236: /*@
8237:   DMPlexGetCellRefinerType - Get the strategy for refining a cell

8239:   Input Parameter:
8240: . dm - The DMPlex object

8242:   Output Parameter:
8243: . cr - The strategy number

8245:   Level: intermediate

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

8258: /*@
8259:   DMPlexSetCellRefinerType - Set the strategy for refining a cell

8261:   Input Parameters:
8262: + dm - The DMPlex object
8263: - cr - The strategy number

8265:   Level: intermediate

8267: .seealso: DMPlexGetCellRefinerType(), DMPlexGetRegularRefinement()
8268: @*/
8269: PetscErrorCode DMPlexSetCellRefinerType(DM dm, DMPlexCellRefinerType cr)
8270: {
8273:   ((DM_Plex *) dm->data)->cellRefiner = cr;
8274:   return(0);
8275: }

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

8282:   not collective

8284:   Input Parameters:
8285: . dm - The DMPlex object

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


8292:   Level: intermediate

8294: .seealso: DMPlexSetAnchors(), DMGetConstraints(), DMSetConstraints()
8295: @*/
8296: PetscErrorCode DMPlexGetAnchors(DM dm, PetscSection *anchorSection, IS *anchorIS)
8297: {
8298:   DM_Plex *plex = (DM_Plex *)dm->data;

8303:   if (!plex->anchorSection && !plex->anchorIS && plex->createanchors) {(*plex->createanchors)(dm);}
8304:   if (anchorSection) *anchorSection = plex->anchorSection;
8305:   if (anchorIS) *anchorIS = plex->anchorIS;
8306:   return(0);
8307: }

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

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

8317:   collective on dm

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

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

8326:   Level: intermediate

8328: .seealso: DMPlexGetAnchors(), DMGetConstraints(), DMSetConstraints()
8329: @*/
8330: PetscErrorCode DMPlexSetAnchors(DM dm, PetscSection anchorSection, IS anchorIS)
8331: {
8332:   DM_Plex        *plex = (DM_Plex *)dm->data;
8333:   PetscMPIInt    result;

8338:   if (anchorSection) {
8340:     MPI_Comm_compare(PETSC_COMM_SELF,PetscObjectComm((PetscObject)anchorSection),&result);
8341:     if (result != MPI_CONGRUENT && result != MPI_IDENT) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_NOTSAMECOMM,"anchor section must have local communicator");
8342:   }
8343:   if (anchorIS) {
8345:     MPI_Comm_compare(PETSC_COMM_SELF,PetscObjectComm((PetscObject)anchorIS),&result);
8346:     if (result != MPI_CONGRUENT && result != MPI_IDENT) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_NOTSAMECOMM,"anchor IS must have local communicator");
8347:   }

8349:   PetscObjectReference((PetscObject)anchorSection);
8350:   PetscSectionDestroy(&plex->anchorSection);
8351:   plex->anchorSection = anchorSection;

8353:   PetscObjectReference((PetscObject)anchorIS);
8354:   ISDestroy(&plex->anchorIS);
8355:   plex->anchorIS = anchorIS;

8357:   if (PetscUnlikelyDebug(anchorIS && anchorSection)) {
8358:     PetscInt size, a, pStart, pEnd;
8359:     const PetscInt *anchors;

8361:     PetscSectionGetChart(anchorSection,&pStart,&pEnd);
8362:     ISGetLocalSize(anchorIS,&size);
8363:     ISGetIndices(anchorIS,&anchors);
8364:     for (a = 0; a < size; a++) {
8365:       PetscInt p;

8367:       p = anchors[a];
8368:       if (p >= pStart && p < pEnd) {
8369:         PetscInt dof;

8371:         PetscSectionGetDof(anchorSection,p,&dof);
8372:         if (dof) {
8373:           PetscErrorCode ierr2;

8375:           ierr2 = ISRestoreIndices(anchorIS,&anchors);CHKERRQ(ierr2);
8376:           SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_ARG_INCOMP,"Point %D cannot be constrained and an anchor",p);
8377:         }
8378:       }
8379:     }
8380:     ISRestoreIndices(anchorIS,&anchors);
8381:   }
8382:   /* reset the generic constraints */
8383:   DMSetDefaultConstraints(dm,NULL,NULL);
8384:   return(0);
8385: }

8387: static PetscErrorCode DMPlexCreateConstraintSection_Anchors(DM dm, PetscSection section, PetscSection *cSec)
8388: {
8389:   PetscSection anchorSection;
8390:   PetscInt pStart, pEnd, sStart, sEnd, p, dof, numFields, f;

8395:   DMPlexGetAnchors(dm,&anchorSection,NULL);
8396:   PetscSectionCreate(PETSC_COMM_SELF,cSec);
8397:   PetscSectionGetNumFields(section,&numFields);
8398:   if (numFields) {
8399:     PetscInt f;
8400:     PetscSectionSetNumFields(*cSec,numFields);

8402:     for (f = 0; f < numFields; f++) {
8403:       PetscInt numComp;

8405:       PetscSectionGetFieldComponents(section,f,&numComp);
8406:       PetscSectionSetFieldComponents(*cSec,f,numComp);
8407:     }
8408:   }
8409:   PetscSectionGetChart(anchorSection,&pStart,&pEnd);
8410:   PetscSectionGetChart(section,&sStart,&sEnd);
8411:   pStart = PetscMax(pStart,sStart);
8412:   pEnd   = PetscMin(pEnd,sEnd);
8413:   pEnd   = PetscMax(pStart,pEnd);
8414:   PetscSectionSetChart(*cSec,pStart,pEnd);
8415:   for (p = pStart; p < pEnd; p++) {
8416:     PetscSectionGetDof(anchorSection,p,&dof);
8417:     if (dof) {
8418:       PetscSectionGetDof(section,p,&dof);
8419:       PetscSectionSetDof(*cSec,p,dof);
8420:       for (f = 0; f < numFields; f++) {
8421:         PetscSectionGetFieldDof(section,p,f,&dof);
8422:         PetscSectionSetFieldDof(*cSec,p,f,dof);
8423:       }
8424:     }
8425:   }
8426:   PetscSectionSetUp(*cSec);
8427:   return(0);
8428: }

8430: static PetscErrorCode DMPlexCreateConstraintMatrix_Anchors(DM dm, PetscSection section, PetscSection cSec, Mat *cMat)
8431: {
8432:   PetscSection aSec;
8433:   PetscInt pStart, pEnd, p, dof, aDof, aOff, off, nnz, annz, m, n, q, a, offset, *i, *j;
8434:   const PetscInt *anchors;
8435:   PetscInt numFields, f;
8436:   IS aIS;

8441:   PetscSectionGetStorageSize(cSec, &m);
8442:   PetscSectionGetStorageSize(section, &n);
8443:   MatCreate(PETSC_COMM_SELF,cMat);
8444:   MatSetSizes(*cMat,m,n,m,n);
8445:   MatSetType(*cMat,MATSEQAIJ);
8446:   DMPlexGetAnchors(dm,&aSec,&aIS);
8447:   ISGetIndices(aIS,&anchors);
8448:   /* cSec will be a subset of aSec and section */
8449:   PetscSectionGetChart(cSec,&pStart,&pEnd);
8450:   PetscMalloc1(m+1,&i);
8451:   i[0] = 0;
8452:   PetscSectionGetNumFields(section,&numFields);
8453:   for (p = pStart; p < pEnd; p++) {
8454:     PetscInt rDof, rOff, r;

8456:     PetscSectionGetDof(aSec,p,&rDof);
8457:     if (!rDof) continue;
8458:     PetscSectionGetOffset(aSec,p,&rOff);
8459:     if (numFields) {
8460:       for (f = 0; f < numFields; f++) {
8461:         annz = 0;
8462:         for (r = 0; r < rDof; r++) {
8463:           a = anchors[rOff + r];
8464:           PetscSectionGetFieldDof(section,a,f,&aDof);
8465:           annz += aDof;
8466:         }
8467:         PetscSectionGetFieldDof(cSec,p,f,&dof);
8468:         PetscSectionGetFieldOffset(cSec,p,f,&off);
8469:         for (q = 0; q < dof; q++) {
8470:           i[off + q + 1] = i[off + q] + annz;
8471:         }
8472:       }
8473:     }
8474:     else {
8475:       annz = 0;
8476:       for (q = 0; q < dof; q++) {
8477:         a = anchors[off + q];
8478:         PetscSectionGetDof(section,a,&aDof);
8479:         annz += aDof;
8480:       }
8481:       PetscSectionGetDof(cSec,p,&dof);
8482:       PetscSectionGetOffset(cSec,p,&off);
8483:       for (q = 0; q < dof; q++) {
8484:         i[off + q + 1] = i[off + q] + annz;
8485:       }
8486:     }
8487:   }
8488:   nnz = i[m];
8489:   PetscMalloc1(nnz,&j);
8490:   offset = 0;
8491:   for (p = pStart; p < pEnd; p++) {
8492:     if (numFields) {
8493:       for (f = 0; f < numFields; f++) {
8494:         PetscSectionGetFieldDof(cSec,p,f,&dof);
8495:         for (q = 0; q < dof; q++) {
8496:           PetscInt rDof, rOff, r;
8497:           PetscSectionGetDof(aSec,p,&rDof);
8498:           PetscSectionGetOffset(aSec,p,&rOff);
8499:           for (r = 0; r < rDof; r++) {
8500:             PetscInt s;

8502:             a = anchors[rOff + r];
8503:             PetscSectionGetFieldDof(section,a,f,&aDof);
8504:             PetscSectionGetFieldOffset(section,a,f,&aOff);
8505:             for (s = 0; s < aDof; s++) {
8506:               j[offset++] = aOff + s;
8507:             }
8508:           }
8509:         }
8510:       }
8511:     }
8512:     else {
8513:       PetscSectionGetDof(cSec,p,&dof);
8514:       for (q = 0; q < dof; q++) {
8515:         PetscInt rDof, rOff, r;
8516:         PetscSectionGetDof(aSec,p,&rDof);
8517:         PetscSectionGetOffset(aSec,p,&rOff);
8518:         for (r = 0; r < rDof; r++) {
8519:           PetscInt s;

8521:           a = anchors[rOff + r];
8522:           PetscSectionGetDof(section,a,&aDof);
8523:           PetscSectionGetOffset(section,a,&aOff);
8524:           for (s = 0; s < aDof; s++) {
8525:             j[offset++] = aOff + s;
8526:           }
8527:         }
8528:       }
8529:     }
8530:   }
8531:   MatSeqAIJSetPreallocationCSR(*cMat,i,j,NULL);
8532:   PetscFree(i);
8533:   PetscFree(j);
8534:   ISRestoreIndices(aIS,&anchors);
8535:   return(0);
8536: }

8538: PetscErrorCode DMCreateDefaultConstraints_Plex(DM dm)
8539: {
8540:   DM_Plex        *plex = (DM_Plex *)dm->data;
8541:   PetscSection   anchorSection, section, cSec;
8542:   Mat            cMat;

8547:   DMPlexGetAnchors(dm,&anchorSection,NULL);
8548:   if (anchorSection) {
8549:     PetscInt Nf;

8551:     DMGetLocalSection(dm,&section);
8552:     DMPlexCreateConstraintSection_Anchors(dm,section,&cSec);
8553:     DMPlexCreateConstraintMatrix_Anchors(dm,section,cSec,&cMat);
8554:     DMGetNumFields(dm,&Nf);
8555:     if (Nf && plex->computeanchormatrix) {(*plex->computeanchormatrix)(dm,section,cSec,cMat);}
8556:     DMSetDefaultConstraints(dm,cSec,cMat);
8557:     PetscSectionDestroy(&cSec);
8558:     MatDestroy(&cMat);
8559:   }
8560:   return(0);
8561: }

8563: PetscErrorCode DMCreateSubDomainDM_Plex(DM dm, DMLabel label, PetscInt value, IS *is, DM *subdm)
8564: {
8565:   IS             subis;
8566:   PetscSection   section, subsection;

8570:   DMGetLocalSection(dm, &section);
8571:   if (!section) SETERRQ(PetscObjectComm((PetscObject) dm), PETSC_ERR_ARG_WRONG, "Must set default section for DM before splitting subdomain");
8572:   if (!subdm)   SETERRQ(PetscObjectComm((PetscObject) dm), PETSC_ERR_ARG_WRONG, "Must set output subDM for splitting subdomain");
8573:   /* Create subdomain */
8574:   DMPlexFilter(dm, label, value, subdm);
8575:   /* Create submodel */
8576:   DMPlexGetSubpointIS(*subdm, &subis);
8577:   PetscSectionCreateSubmeshSection(section, subis, &subsection);
8578:   DMSetLocalSection(*subdm, subsection);
8579:   PetscSectionDestroy(&subsection);
8580:   DMCopyDisc(dm, *subdm);
8581:   /* Create map from submodel to global model */
8582:   if (is) {
8583:     PetscSection    sectionGlobal, subsectionGlobal;
8584:     IS              spIS;
8585:     const PetscInt *spmap;
8586:     PetscInt       *subIndices;
8587:     PetscInt        subSize = 0, subOff = 0, pStart, pEnd, p;
8588:     PetscInt        Nf, f, bs = -1, bsLocal[2], bsMinMax[2];

8590:     DMPlexGetSubpointIS(*subdm, &spIS);
8591:     ISGetIndices(spIS, &spmap);
8592:     PetscSectionGetNumFields(section, &Nf);
8593:     DMGetGlobalSection(dm, &sectionGlobal);
8594:     DMGetGlobalSection(*subdm, &subsectionGlobal);
8595:     PetscSectionGetChart(subsection, &pStart, &pEnd);
8596:     for (p = pStart; p < pEnd; ++p) {
8597:       PetscInt gdof, pSubSize  = 0;

8599:       PetscSectionGetDof(sectionGlobal, p, &gdof);
8600:       if (gdof > 0) {
8601:         for (f = 0; f < Nf; ++f) {
8602:           PetscInt fdof, fcdof;

8604:           PetscSectionGetFieldDof(subsection, p, f, &fdof);
8605:           PetscSectionGetFieldConstraintDof(subsection, p, f, &fcdof);
8606:           pSubSize += fdof-fcdof;
8607:         }
8608:         subSize += pSubSize;
8609:         if (pSubSize) {
8610:           if (bs < 0) {
8611:             bs = pSubSize;
8612:           } else if (bs != pSubSize) {
8613:             /* Layout does not admit a pointwise block size */
8614:             bs = 1;
8615:           }
8616:         }
8617:       }
8618:     }
8619:     /* Must have same blocksize on all procs (some might have no points) */
8620:     bsLocal[0] = bs < 0 ? PETSC_MAX_INT : bs; bsLocal[1] = bs;
8621:     PetscGlobalMinMaxInt(PetscObjectComm((PetscObject) dm), bsLocal, bsMinMax);
8622:     if (bsMinMax[0] != bsMinMax[1]) {bs = 1;}
8623:     else                            {bs = bsMinMax[0];}
8624:     PetscMalloc1(subSize, &subIndices);
8625:     for (p = pStart; p < pEnd; ++p) {
8626:       PetscInt gdof, goff;

8628:       PetscSectionGetDof(subsectionGlobal, p, &gdof);
8629:       if (gdof > 0) {
8630:         const PetscInt point = spmap[p];

8632:         PetscSectionGetOffset(sectionGlobal, point, &goff);
8633:         for (f = 0; f < Nf; ++f) {
8634:           PetscInt fdof, fcdof, fc, f2, poff = 0;

8636:           /* Can get rid of this loop by storing field information in the global section */
8637:           for (f2 = 0; f2 < f; ++f2) {
8638:             PetscSectionGetFieldDof(section, p, f2, &fdof);
8639:             PetscSectionGetFieldConstraintDof(section, p, f2, &fcdof);
8640:             poff += fdof-fcdof;
8641:           }
8642:           PetscSectionGetFieldDof(section, p, f, &fdof);
8643:           PetscSectionGetFieldConstraintDof(section, p, f, &fcdof);
8644:           for (fc = 0; fc < fdof-fcdof; ++fc, ++subOff) {
8645:             subIndices[subOff] = goff+poff+fc;
8646:           }
8647:         }
8648:       }
8649:     }
8650:     ISRestoreIndices(spIS, &spmap);
8651:     ISCreateGeneral(PetscObjectComm((PetscObject)dm), subSize, subIndices, PETSC_OWN_POINTER, is);
8652:     if (bs > 1) {
8653:       /* We need to check that the block size does not come from non-contiguous fields */
8654:       PetscInt i, j, set = 1;
8655:       for (i = 0; i < subSize; i += bs) {
8656:         for (j = 0; j < bs; ++j) {
8657:           if (subIndices[i+j] != subIndices[i]+j) {set = 0; break;}
8658:         }
8659:       }
8660:       if (set) {ISSetBlockSize(*is, bs);}
8661:     }
8662:     /* Attach nullspace */
8663:     for (f = 0; f < Nf; ++f) {
8664:       (*subdm)->nullspaceConstructors[f] = dm->nullspaceConstructors[f];
8665:       if ((*subdm)->nullspaceConstructors[f]) break;
8666:     }
8667:     if (f < Nf) {
8668:       MatNullSpace nullSpace;

8670:       (*(*subdm)->nullspaceConstructors[f])(*subdm, f, f, &nullSpace);
8671:       PetscObjectCompose((PetscObject) *is, "nullspace", (PetscObject) nullSpace);
8672:       MatNullSpaceDestroy(&nullSpace);
8673:     }
8674:   }
8675:   return(0);
8676: }

8678: /*@
8679:   DMPlexMonitorThroughput - Report the cell throughput of FE integration

8681:   Input Parameter:
8682: - dm - The DM

8684:   Level: developer

8686:   Options Database Keys:
8687: . -dm_plex_monitor_throughput - Activate the monitor

8689: .seealso: DMSetFromOptions(), DMPlexCreate()
8690: @*/
8691: PetscErrorCode DMPlexMonitorThroughput(DM dm, void *dummy)
8692: {
8693: #if defined(PETSC_USE_LOG)
8694:   PetscStageLog      stageLog;
8695:   PetscLogEvent      event;
8696:   PetscLogStage      stage;
8697:   PetscEventPerfInfo eventInfo;
8698:   PetscReal          cellRate, flopRate;
8699:   PetscInt           cStart, cEnd, Nf, N;
8700:   const char        *name;
8701:   PetscErrorCode     ierr;
8702: #endif

8706: #if defined(PETSC_USE_LOG)
8707:   PetscObjectGetName((PetscObject) dm, &name);
8708:   DMPlexGetHeightStratum(dm, 0, &cStart, &cEnd);
8709:   DMGetNumFields(dm, &Nf);
8710:   PetscLogGetStageLog(&stageLog);
8711:   PetscStageLogGetCurrent(stageLog, &stage);
8712:   PetscLogEventGetId("DMPlexResidualFE", &event);
8713:   PetscLogEventGetPerfInfo(stage, event, &eventInfo);
8714:   N        = (cEnd - cStart)*Nf*eventInfo.count;
8715:   flopRate = eventInfo.flops/eventInfo.time;
8716:   cellRate = N/eventInfo.time;
8717:   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));
8718: #else
8719:   SETERRQ(PetscObjectComm((PetscObject) dm), PETSC_ERR_SUP, "Plex Throughput Monitor is not supported if logging is turned off. Reconfigure using --with-log.");
8720: #endif
8721:   return(0);
8722: }