Actual source code: plex.c

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

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

 13: PETSC_EXTERN PetscErrorCode VecView_MPI(Vec, PetscViewer);

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

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

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

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

 28:   Level: developer

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

1469:   Not collective

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

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

1477:   Level: developer

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

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

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

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

1504:   Not collective

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

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

1513:   Level: beginner

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

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

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

1531:   Not collective

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

1538:   Output Parameters:

1540:   Level: beginner

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

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

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

1559:   Not collective

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

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

1568:   Level: beginner

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

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

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

1587:   Not collective

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

1594:   Output Parameter:

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

1599:   Level: beginner

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

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

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

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

1619:   Not collective

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

1626:   Output Parameter:

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

1631:   Level: beginner

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

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

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

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

1653:   Not collective

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

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

1662:   Level: beginner

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

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

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

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

1689:   Not collective

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

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

1699:   Level: intermediate

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

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

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

1726:   Not collective

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

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

1735:   Level: advanced

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

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

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

1760: /*@
1761:   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).

1763:   Not collective

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

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

1774:   Level: advanced

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

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

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

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

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

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

1856:   Not collective

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

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

1867:   Level: advanced

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

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

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

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

1897:   Not collective

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

1904:   Output Parameter:

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

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

1911:   Level: beginner

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

1924:   PetscSectionGetChart(mesh->coneSection, &pStart, &pEnd);
1925:   PetscSectionGetDof(mesh->coneSection, p, &dof);
1927:   PetscSectionGetOffset(mesh->coneSection, p, &off);
1928:   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);
1929:   for (c = 0; c < dof; ++c) {
1930:     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);
1931:     mesh->cones[off+c] = cone[c];
1932:   }
1933:   return(0);
1934: }

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

1939:   Not collective

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

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

1951:   Level: beginner

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

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

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

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

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

1985:   Not collective

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

1995:   Output Parameter:

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

2000:   Level: beginner

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

2013:   PetscSectionGetChart(mesh->coneSection, &pStart, &pEnd);
2014:   PetscSectionGetDof(mesh->coneSection, p, &dof);
2016:   PetscSectionGetOffset(mesh->coneSection, p, &off);
2017:   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);
2018:   for (c = 0; c < dof; ++c) {
2019:     PetscInt cdof, o = coneOrientation[c];

2021:     PetscSectionGetDof(mesh->coneSection, mesh->cones[off+c], &cdof);
2022:     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);
2023:     mesh->coneOrientations[off+c] = o;
2024:   }
2025:   return(0);
2026: }

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

2031:   Not collective

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

2039:   Level: beginner

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

2052:   PetscSectionGetChart(mesh->coneSection, &pStart, &pEnd);
2053:   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);
2054:   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);
2055:   PetscSectionGetDof(mesh->coneSection, p, &dof);
2056:   PetscSectionGetOffset(mesh->coneSection, p, &off);
2057:   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);
2058:   mesh->cones[off+conePos] = conePoint;
2059:   return(0);
2060: }

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

2065:   Not collective

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

2073:   Level: beginner

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

2086:   PetscSectionGetChart(mesh->coneSection, &pStart, &pEnd);
2087:   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);
2088:   PetscSectionGetDof(mesh->coneSection, p, &dof);
2089:   PetscSectionGetOffset(mesh->coneSection, p, &off);
2090:   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);
2091:   mesh->coneOrientations[off+conePos] = coneOrientation;
2092:   return(0);
2093: }

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

2098:   Not collective

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

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

2107:   Level: beginner

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

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

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

2126:   Not collective

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

2133:   Output Parameter:

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

2138:   Level: beginner

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

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

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

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

2158:   Not collective

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

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

2167:   Level: beginner

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

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

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

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

2194:   Not collective

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

2201:   Output Parameter:

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

2206:   Level: beginner

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

2219:   PetscSectionGetChart(mesh->supportSection, &pStart, &pEnd);
2220:   PetscSectionGetDof(mesh->supportSection, p, &dof);
2222:   PetscSectionGetOffset(mesh->supportSection, p, &off);
2223:   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);
2224:   for (c = 0; c < dof; ++c) {
2225:     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);
2226:     mesh->supports[off+c] = support[c];
2227:   }
2228:   return(0);
2229: }

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

2234:   Not collective

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

2242:   Level: beginner

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

2255:   PetscSectionGetChart(mesh->supportSection, &pStart, &pEnd);
2256:   PetscSectionGetDof(mesh->supportSection, p, &dof);
2257:   PetscSectionGetOffset(mesh->supportSection, p, &off);
2258:   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);
2259:   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);
2260:   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);
2261:   mesh->supports[off+supportPos] = supportPoint;
2262:   return(0);
2263: }

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

2268:   Not collective

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

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

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

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

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

2289:   Level: beginner

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

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

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

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

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

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

2408: /*@C
2409:   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

2411:   Not collective

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

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

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

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

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

2433:   Level: beginner

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

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

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

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

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

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

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

2563:   Not collective

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

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

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

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

2581:   Level: beginner

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

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

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

2601:   Not collective

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

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

2610:   Level: beginner

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

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

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

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

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

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

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

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

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

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

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

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

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

2707:   Not collective

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

2712:   Output Parameter:

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

2717:   Level: beginner

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

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

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

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

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

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

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

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

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

2782:   if (pStart >= pEnd) return(0);
2783: #if defined(PETSC_USE_DEBUG)
2784:   {
2785:     PetscInt  qStart, qEnd, numLevels, level;
2786:     PetscBool overlap = PETSC_FALSE;
2787:     DMLabelGetNumValues(label, &numLevels);
2788:     for (level = 0; level < numLevels; level++) {
2789:       DMLabelGetStratumBounds(label, level, &qStart, &qEnd);
2790:       if ((pStart >= qStart && pStart < qEnd) || (pEnd > qStart && pEnd <= qEnd)) {overlap = PETSC_TRUE; break;}
2791:     }
2792:     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);
2793:   }
2794: #endif
2795:   ISCreateStride(PETSC_COMM_SELF, pEnd-pStart, pStart, 1, &stratumIS);
2796:   DMLabelSetStratumIS(label, depth, stratumIS);
2797:   ISDestroy(&stratumIS);
2798:   return(0);
2799: }

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

2807:   Collective on dm

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

2812:   Output Parameter:

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

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

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

2834:   Level: beginner

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

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

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

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

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

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

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

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

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

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

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

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

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

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

3006:   Collective on dm

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

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

3013:   Level: developer

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

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

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

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

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

3051:   Not Collective

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

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

3062:   Level: intermediate

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

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

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

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

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

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

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

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

3123:   Not Collective

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

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

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

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

3140:   Level: intermediate

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

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

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

3161:   Not Collective

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

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

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

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

3178:   Level: intermediate

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


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

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

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

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

3214:       DMPlexGetDepthStratum(dm, d, &pStart, &pEnd);
3215:       for (i = offsets[p*(depth+2)+d]; i < closureSize; ++i) {
3216:         if ((pStart > closures[p][i*2]) || (pEnd <= closures[p][i*2])) {
3217:           offsets[p*(depth+2)+d+1] = i;
3218:           break;
3219:         }
3220:       }
3221:       if (i == closureSize) offsets[p*(depth+2)+d+1] = i;
3222:     }
3223:     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);
3224:   }
3225:   for (d = 0; d < depth+1; ++d) {
3226:     PetscInt dof;

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

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

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

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

3267:   Not Collective

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

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

3278:   Level: intermediate

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

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

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

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

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

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

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

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

3339:   Not Collective

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

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

3350:   Level: intermediate

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

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

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

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

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

3377:   Not Collective

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

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

3388:   Level: intermediate

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

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

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


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

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

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

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

3430:       DMPlexGetHeightStratum(dm, h, &pStart, &pEnd);
3431:       for (i = offsets[p*(height+2)+h]; i < closureSize; ++i) {
3432:         if ((pStart > closures[p][i*2]) || (pEnd <= closures[p][i*2])) {
3433:           offsets[p*(height+2)+h+1] = i;
3434:           break;
3435:         }
3436:       }
3437:       if (i == closureSize) offsets[p*(height+2)+h+1] = i;
3438:     }
3439:     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);
3440:   }
3441:   for (h = 0; h < height+1; ++h) {
3442:     PetscInt dof;

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

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

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

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

3483:   Not Collective

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

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

3492:   Level: intermediate

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

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


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

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

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

3547:   Not Collective

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

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

3557:   Level: developer

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

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

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

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

3636:   Not Collective

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

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

3644:   Level: developer

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

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

3660:   Not Collective

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

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

3668:   Level: developer

3670:   Notes:
3671:   This returns maximum of point depths over all points, i.e. maximum value of the label returned by DMPlexGetDepthLabel().
3672:   The point depth is described more in detail in DMPlexSymmetrize().

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

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

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

3694:   Not Collective

3696:   Input Parameters:
3697: + dm           - The DMPlex object
3698: - stratumValue - The requested depth

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

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

3709:   Level: developer

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

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

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

3739:   Not Collective

3741:   Input Parameters:
3742: + dm           - The DMPlex object
3743: - stratumValue - The requested height

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

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

3754:   Level: developer

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

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

3782: /*@
3783:   DMPlexGetPointDepth - Get the depth of a given point

3785:   Not Collective

3787:   Input Parameter:
3788: + dm    - The DMPlex object
3789: - point - The point

3791:   Output Parameter:
3792: . depth - The depth of the point

3794:   Level: intermediate

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

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

3809: /*@
3810:   DMPlexGetPointHeight - Get the height of a given point

3812:   Not Collective

3814:   Input Parameter:
3815: + dm    - The DMPlex object
3816: - point - The point

3818:   Output Parameter:
3819: . height - The height of the point

3821:   Level: intermediate

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

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

3839: /*@
3840:   DMPlexGetCellTypeLabel - Get the DMLabel recording the polytope type of each cell

3842:   Not Collective

3844:   Input Parameter:
3845: . dm - The DMPlex object

3847:   Output Parameter:
3848: . celltypeLabel - The DMLabel recording cell polytope type

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

3853:   Level: developer

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

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

3869: /*@
3870:   DMPlexGetCellType - Get the polytope type of a given cell

3872:   Not Collective

3874:   Input Parameter:
3875: + dm   - The DMPlex object
3876: - cell - The cell

3878:   Output Parameter:
3879: . celltype - The polytope type of the cell

3881:   Level: intermediate

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

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

3900: /*@
3901:   DMPlexSetCellType - Set the polytope type of a given cell

3903:   Not Collective

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

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

3915:   Level: advanced

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

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

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

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

3951:   DMSetNumFields(*cdm, 1);
3952:   DMCreateDS(*cdm);
3953:   return(0);
3954: }

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

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

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

3975:   Not Collective

3977:   Input Parameters:
3978: . dm        - The DMPlex object

3980:   Output Parameter:
3981: . section - The PetscSection object

3983:   Level: developer

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

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

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

4000:   Not Collective

4002:   Input Parameters:
4003: . dm        - The DMPlex object

4005:   Output Parameter:
4006: . section - The PetscSection object

4008:   Level: developer

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

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

4022: /*@C
4023:   DMPlexGetCones - Return cone data

4025:   Not Collective

4027:   Input Parameters:
4028: . dm        - The DMPlex object

4030:   Output Parameter:
4031: . cones - The cone for each point

4033:   Level: developer

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

4043:   if (cones) *cones = mesh->cones;
4044:   return(0);
4045: }

4047: /*@C
4048:   DMPlexGetConeOrientations - Return cone orientation data

4050:   Not Collective

4052:   Input Parameters:
4053: . dm        - The DMPlex object

4055:   Output Parameter:
4056: . coneOrientations - The cone orientation for each point

4058:   Level: developer

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

4068:   if (coneOrientations) *coneOrientations = mesh->coneOrientations;
4069:   return(0);
4070: }

4072: /******************************** FEM Support **********************************/

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

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

4097: /*@

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

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

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

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

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

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

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

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

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

4150:   Level: developer

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

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

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

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

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

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

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

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

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

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

4321:         /* Middle Slice */
4322:         for (j = 0; j < k-1; ++j) {
4323:           /*   bottom */
4324:           for (c = 0; c < Nc; ++c, ++offset) perm[offset] = (oelf+(k-2)-j)*Nc + c + foffset;
4325:           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;
4326:           for (c = 0; c < Nc; ++c, ++offset) perm[offset] = (oerf+j)*Nc + c + foffset;
4327:           /*   middle */
4328:           for (i = 0; i < k-1; ++i) {
4329:             for (c = 0; c < Nc; ++c, ++offset) perm[offset] = (ofl+i*(k-1)+j)*Nc + c + foffset;
4330:             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;
4331:             for (c = 0; c < Nc; ++c, ++offset) perm[offset] = (ofr+j*(k-1)+i)*Nc + c + foffset;
4332:           }
4333:           /*   top */
4334:           for (c = 0; c < Nc; ++c, ++offset) perm[offset] = (oelb+j)*Nc + c + foffset;
4335:           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;
4336:           for (c = 0; c < Nc; ++c, ++offset) perm[offset] = (oerb+(k-2)-j)*Nc + c + foffset;
4337:         }

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

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

4366:     PetscMalloc1(size, &check);
4367:     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]);}
4368:     for (i = 0; i < size; ++i) check[perm[i]] = i;
4369:     for (i = 0; i < size; ++i) {if (check[i] < 0) SETERRQ1(PetscObjectComm((PetscObject) dm), PETSC_ERR_PLIB, "Missing permutation index %D", i);}
4370:     PetscFree(check);
4371:   }
4372:   PetscSectionSetClosurePermutation_Internal(section, (PetscObject) dm, size, PETSC_OWN_POINTER, perm);
4373:   return(0);
4374: }

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

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

4391:     if (disc->classid == PETSCFE_CLASSID) {
4392:       PetscDualSpace dsp;

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


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

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

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

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

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

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

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

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

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

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

4528:   return(0);
4529: }

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

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

4549: 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[])
4550: {
4551:   PetscInt          offset = 0, p;
4552:   const PetscInt    **perms = NULL;
4553:   const PetscScalar **flips = NULL;
4554:   PetscErrorCode    ierr;

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

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

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

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

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

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

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

4638:   Not collective

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

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

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

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

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

4683:   Level: intermediate

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

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

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

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

4750:   Not collective

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

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

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

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

4768:   Level: intermediate

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

5094:   Not collective

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

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

5108:   Level: intermediate

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

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

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

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

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

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

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

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

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

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

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

5384:   Output Parameter:
5385: . indices - Indices for dofs on this point

5387:   Level: developer

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

5584:   PetscSectionGetNumFields(section, &numFields);

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

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

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

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

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

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

5650:   if (outNumPoints)  *outNumPoints  = newNumPoints;
5651:   if (outNumIndices) *outNumIndices = newNumIndices;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

6089:   Not collective

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

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

6102:   Notes:
6103:   Must call DMPlexRestoreClosureIndices() to free allocated memory

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

6111:   Level: advanced

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

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

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

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

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

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

6216:   Not collective

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

6227:   Level: advanced

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

6238:   DMRestoreWorkArray(dm, 0, MPIU_INT, indices);
6239:   return(0);
6240: }

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

6245:   Not collective

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

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

6259:   Level: intermediate

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

6728:   Input Parameter:
6729: . dm   - The DMPlex object

6731:   Output Parameter:
6732: . cellHeight - The height of a cell

6734:   Level: developer

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

6745:   *cellHeight = mesh->vtkCellHeight;
6746:   return(0);
6747: }

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

6752:   Input Parameters:
6753: + dm   - The DMPlex object
6754: - cellHeight - The height of a cell

6756:   Level: developer

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

6766:   mesh->vtkCellHeight = cellHeight;
6767:   return(0);
6768: }

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

6773:   Input Parameter:
6774: . dm - The DMPlex object

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

6780:   Level: advanced

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

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

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

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

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

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

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

6845:   Input Parameter:
6846: . dm   - The DMPlex object

6848:   Output Parameter:
6849: . globalCellNumbers - Global cell numbers for all cells on this process

6851:   Level: developer

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

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

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

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

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

6882:   Input Parameter:
6883: . dm   - The DMPlex object

6885:   Output Parameter:
6886: . globalVertexNumbers - Global vertex numbers for all vertices on this process

6888:   Level: developer

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

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

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

6907:   Input Parameter:
6908: . dm   - The DMPlex object

6910:   Output Parameter:
6911: . globalPointNumbers - Global numbers for all points on this process

6913:   Level: developer

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

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

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

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


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

6957:   Input Parameter:
6958: . dm - The DMPlex object

6960:   Output Parameter:
6961: . ranks - The rank field

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

6966:   Level: intermediate

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

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

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

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

7008:   Input Parameters:
7009: + dm    - The DMPlex
7010: - label - The DMLabel

7012:   Output Parameter:
7013: . val - The label value field

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

7018:   Level: intermediate

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

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

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

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

7061:   Input Parameter:
7062: . dm - The DMPlex object

7064:   Notes:
7065:   This is a useful diagnostic when creating meshes programmatically.

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

7069:   Level: developer

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

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

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

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

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

7204:   Input Parameters:
7205: + dm - The DMPlex object
7206: - cellHeight - Normally 0

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

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

7214:   Level: developer

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

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

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

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

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

7262:   Not Collective

7264:   Input Parameters:
7265: + dm - The DMPlex object
7266: - cellHeight - Normally 0

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

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

7276:   Level: developer

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

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

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

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

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

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

7346: /*@
7347:   DMPlexCheckGeometry - Check the geometry of mesh cells

7349:   Input Parameter:
7350: . dm - The DMPlex object

7352:   Notes:
7353:   This is a useful diagnostic when creating meshes programmatically.

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

7357:   Level: developer

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

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

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

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

7412:   Input Parameters:
7413: . dm - The DMPlex object

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

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

7421:   Level: developer

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

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

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

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

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

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

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

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

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

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

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

7501:   Collective on dm

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

7508:   Notes:
7509:   This is mainly intended for debugging/testing purposes.

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

7513:   Level: developer

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

7530:   stats.min   = PETSC_MAX_REAL;
7531:   stats.max   = PETSC_MIN_REAL;
7532:   stats.sum   = stats.squaresum = 0.;
7533:   stats.count = 0;

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

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

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

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

7581:         if ((edge >= eStart) && (edge < eEnd)) {
7582:           PetscReal len;

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

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

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

7617:   if (output) {
7618:     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);
7619:   }
7620:   PetscFree2(J,invJ);

7622:   DMGetCoarseDM(dm,&dmCoarse);
7623:   if (dmCoarse) {
7624:     PetscBool isplex;

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

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

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

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

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

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

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

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

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

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

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

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

7717:   Input Parameter:
7718: . dm - The DMPlex object

7720:   Output Parameter:
7721: . regular - The flag

7723:   Level: intermediate

7725: .seealso: DMPlexSetRegularRefinement()
7726: @*/
7727: PetscErrorCode DMPlexGetRegularRefinement(DM dm, PetscBool *regular)
7728: {
7732:   *regular = ((DM_Plex *) dm->data)->regularRefinement;
7733:   return(0);
7734: }

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

7739:   Input Parameters:
7740: + dm - The DMPlex object
7741: - regular - The flag

7743:   Level: intermediate

7745: .seealso: DMPlexGetRegularRefinement()
7746: @*/
7747: PetscErrorCode DMPlexSetRegularRefinement(DM dm, PetscBool regular)
7748: {
7751:   ((DM_Plex *) dm->data)->regularRefinement = regular;
7752:   return(0);
7753: }

7755: /*@
7756:   DMPlexGetCellRefinerType - Get the strategy for refining a cell

7758:   Input Parameter:
7759: . dm - The DMPlex object

7761:   Output Parameter:
7762: . cr - The strategy number

7764:   Level: intermediate

7766: .seealso: DMPlexSetCellRefinerType(), DMPlexSetRegularRefinement()
7767: @*/
7768: PetscErrorCode DMPlexGetCellRefinerType(DM dm, DMPlexCellRefinerType *cr)
7769: {
7773:   *cr = ((DM_Plex *) dm->data)->cellRefiner;
7774:   return(0);
7775: }

7777: /*@
7778:   DMPlexSetCellRefinerType - Set the strategy for refining a cell

7780:   Input Parameters:
7781: + dm - The DMPlex object
7782: - cr - The strategy number

7784:   Level: intermediate

7786: .seealso: DMPlexGetCellRefinerType(), DMPlexGetRegularRefinement()
7787: @*/
7788: PetscErrorCode DMPlexSetCellRefinerType(DM dm, DMPlexCellRefinerType cr)
7789: {
7792:   ((DM_Plex *) dm->data)->cellRefiner = cr;
7793:   return(0);
7794: }

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

7801:   not collective

7803:   Input Parameters:
7804: . dm - The DMPlex object

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


7811:   Level: intermediate

7813: .seealso: DMPlexSetAnchors(), DMGetConstraints(), DMSetConstraints()
7814: @*/
7815: PetscErrorCode DMPlexGetAnchors(DM dm, PetscSection *anchorSection, IS *anchorIS)
7816: {
7817:   DM_Plex *plex = (DM_Plex *)dm->data;

7822:   if (!plex->anchorSection && !plex->anchorIS && plex->createanchors) {(*plex->createanchors)(dm);}
7823:   if (anchorSection) *anchorSection = plex->anchorSection;
7824:   if (anchorIS) *anchorIS = plex->anchorIS;
7825:   return(0);
7826: }

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

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

7836:   collective on dm

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

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

7845:   Level: intermediate

7847: .seealso: DMPlexGetAnchors(), DMGetConstraints(), DMSetConstraints()
7848: @*/
7849: PetscErrorCode DMPlexSetAnchors(DM dm, PetscSection anchorSection, IS anchorIS)
7850: {
7851:   DM_Plex        *plex = (DM_Plex *)dm->data;
7852:   PetscMPIInt    result;

7857:   if (anchorSection) {
7859:     MPI_Comm_compare(PETSC_COMM_SELF,PetscObjectComm((PetscObject)anchorSection),&result);
7860:     if (result != MPI_CONGRUENT && result != MPI_IDENT) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_NOTSAMECOMM,"anchor section must have local communicator");
7861:   }
7862:   if (anchorIS) {
7864:     MPI_Comm_compare(PETSC_COMM_SELF,PetscObjectComm((PetscObject)anchorIS),&result);
7865:     if (result != MPI_CONGRUENT && result != MPI_IDENT) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_NOTSAMECOMM,"anchor IS must have local communicator");
7866:   }

7868:   PetscObjectReference((PetscObject)anchorSection);
7869:   PetscSectionDestroy(&plex->anchorSection);
7870:   plex->anchorSection = anchorSection;

7872:   PetscObjectReference((PetscObject)anchorIS);
7873:   ISDestroy(&plex->anchorIS);
7874:   plex->anchorIS = anchorIS;

7876: #if defined(PETSC_USE_DEBUG)
7877:   if (anchorIS && anchorSection) {
7878:     PetscInt size, a, pStart, pEnd;
7879:     const PetscInt *anchors;

7881:     PetscSectionGetChart(anchorSection,&pStart,&pEnd);
7882:     ISGetLocalSize(anchorIS,&size);
7883:     ISGetIndices(anchorIS,&anchors);
7884:     for (a = 0; a < size; a++) {
7885:       PetscInt p;

7887:       p = anchors[a];
7888:       if (p >= pStart && p < pEnd) {
7889:         PetscInt dof;

7891:         PetscSectionGetDof(anchorSection,p,&dof);
7892:         if (dof) {
7893:           PetscErrorCode ierr2;

7895:           ierr2 = ISRestoreIndices(anchorIS,&anchors);CHKERRQ(ierr2);
7896:           SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_ARG_INCOMP,"Point %D cannot be constrained and an anchor",p);
7897:         }
7898:       }
7899:     }
7900:     ISRestoreIndices(anchorIS,&anchors);
7901:   }
7902: #endif
7903:   /* reset the generic constraints */
7904:   DMSetDefaultConstraints(dm,NULL,NULL);
7905:   return(0);
7906: }

7908: static PetscErrorCode DMPlexCreateConstraintSection_Anchors(DM dm, PetscSection section, PetscSection *cSec)
7909: {
7910:   PetscSection anchorSection;
7911:   PetscInt pStart, pEnd, sStart, sEnd, p, dof, numFields, f;

7916:   DMPlexGetAnchors(dm,&anchorSection,NULL);
7917:   PetscSectionCreate(PETSC_COMM_SELF,cSec);
7918:   PetscSectionGetNumFields(section,&numFields);
7919:   if (numFields) {
7920:     PetscInt f;
7921:     PetscSectionSetNumFields(*cSec,numFields);

7923:     for (f = 0; f < numFields; f++) {
7924:       PetscInt numComp;

7926:       PetscSectionGetFieldComponents(section,f,&numComp);
7927:       PetscSectionSetFieldComponents(*cSec,f,numComp);
7928:     }
7929:   }
7930:   PetscSectionGetChart(anchorSection,&pStart,&pEnd);
7931:   PetscSectionGetChart(section,&sStart,&sEnd);
7932:   pStart = PetscMax(pStart,sStart);
7933:   pEnd   = PetscMin(pEnd,sEnd);
7934:   pEnd   = PetscMax(pStart,pEnd);
7935:   PetscSectionSetChart(*cSec,pStart,pEnd);
7936:   for (p = pStart; p < pEnd; p++) {
7937:     PetscSectionGetDof(anchorSection,p,&dof);
7938:     if (dof) {
7939:       PetscSectionGetDof(section,p,&dof);
7940:       PetscSectionSetDof(*cSec,p,dof);
7941:       for (f = 0; f < numFields; f++) {
7942:         PetscSectionGetFieldDof(section,p,f,&dof);
7943:         PetscSectionSetFieldDof(*cSec,p,f,dof);
7944:       }
7945:     }
7946:   }
7947:   PetscSectionSetUp(*cSec);
7948:   return(0);
7949: }

7951: static PetscErrorCode DMPlexCreateConstraintMatrix_Anchors(DM dm, PetscSection section, PetscSection cSec, Mat *cMat)
7952: {
7953:   PetscSection aSec;
7954:   PetscInt pStart, pEnd, p, dof, aDof, aOff, off, nnz, annz, m, n, q, a, offset, *i, *j;
7955:   const PetscInt *anchors;
7956:   PetscInt numFields, f;
7957:   IS aIS;

7962:   PetscSectionGetStorageSize(cSec, &m);
7963:   PetscSectionGetStorageSize(section, &n);
7964:   MatCreate(PETSC_COMM_SELF,cMat);
7965:   MatSetSizes(*cMat,m,n,m,n);
7966:   MatSetType(*cMat,MATSEQAIJ);
7967:   DMPlexGetAnchors(dm,&aSec,&aIS);
7968:   ISGetIndices(aIS,&anchors);
7969:   /* cSec will be a subset of aSec and section */
7970:   PetscSectionGetChart(cSec,&pStart,&pEnd);
7971:   PetscMalloc1(m+1,&i);
7972:   i[0] = 0;
7973:   PetscSectionGetNumFields(section,&numFields);
7974:   for (p = pStart; p < pEnd; p++) {
7975:     PetscInt rDof, rOff, r;

7977:     PetscSectionGetDof(aSec,p,&rDof);
7978:     if (!rDof) continue;
7979:     PetscSectionGetOffset(aSec,p,&rOff);
7980:     if (numFields) {
7981:       for (f = 0; f < numFields; f++) {
7982:         annz = 0;
7983:         for (r = 0; r < rDof; r++) {
7984:           a = anchors[rOff + r];
7985:           PetscSectionGetFieldDof(section,a,f,&aDof);
7986:           annz += aDof;
7987:         }
7988:         PetscSectionGetFieldDof(cSec,p,f,&dof);
7989:         PetscSectionGetFieldOffset(cSec,p,f,&off);
7990:         for (q = 0; q < dof; q++) {
7991:           i[off + q + 1] = i[off + q] + annz;
7992:         }
7993:       }
7994:     }
7995:     else {
7996:       annz = 0;
7997:       for (q = 0; q < dof; q++) {
7998:         a = anchors[off + q];
7999:         PetscSectionGetDof(section,a,&aDof);
8000:         annz += aDof;
8001:       }
8002:       PetscSectionGetDof(cSec,p,&dof);
8003:       PetscSectionGetOffset(cSec,p,&off);
8004:       for (q = 0; q < dof; q++) {
8005:         i[off + q + 1] = i[off + q] + annz;
8006:       }
8007:     }
8008:   }
8009:   nnz = i[m];
8010:   PetscMalloc1(nnz,&j);
8011:   offset = 0;
8012:   for (p = pStart; p < pEnd; p++) {
8013:     if (numFields) {
8014:       for (f = 0; f < numFields; f++) {
8015:         PetscSectionGetFieldDof(cSec,p,f,&dof);
8016:         for (q = 0; q < dof; q++) {
8017:           PetscInt rDof, rOff, r;
8018:           PetscSectionGetDof(aSec,p,&rDof);
8019:           PetscSectionGetOffset(aSec,p,&rOff);
8020:           for (r = 0; r < rDof; r++) {
8021:             PetscInt s;

8023:             a = anchors[rOff + r];
8024:             PetscSectionGetFieldDof(section,a,f,&aDof);
8025:             PetscSectionGetFieldOffset(section,a,f,&aOff);
8026:             for (s = 0; s < aDof; s++) {
8027:               j[offset++] = aOff + s;
8028:             }
8029:           }
8030:         }
8031:       }
8032:     }
8033:     else {
8034:       PetscSectionGetDof(cSec,p,&dof);
8035:       for (q = 0; q < dof; q++) {
8036:         PetscInt rDof, rOff, r;
8037:         PetscSectionGetDof(aSec,p,&rDof);
8038:         PetscSectionGetOffset(aSec,p,&rOff);
8039:         for (r = 0; r < rDof; r++) {
8040:           PetscInt s;

8042:           a = anchors[rOff + r];
8043:           PetscSectionGetDof(section,a,&aDof);
8044:           PetscSectionGetOffset(section,a,&aOff);
8045:           for (s = 0; s < aDof; s++) {
8046:             j[offset++] = aOff + s;
8047:           }
8048:         }
8049:       }
8050:     }
8051:   }
8052:   MatSeqAIJSetPreallocationCSR(*cMat,i,j,NULL);
8053:   PetscFree(i);
8054:   PetscFree(j);
8055:   ISRestoreIndices(aIS,&anchors);
8056:   return(0);
8057: }

8059: PetscErrorCode DMCreateDefaultConstraints_Plex(DM dm)
8060: {
8061:   DM_Plex        *plex = (DM_Plex *)dm->data;
8062:   PetscSection   anchorSection, section, cSec;
8063:   Mat            cMat;

8068:   DMPlexGetAnchors(dm,&anchorSection,NULL);
8069:   if (anchorSection) {
8070:     PetscInt Nf;

8072:     DMGetLocalSection(dm,&section);
8073:     DMPlexCreateConstraintSection_Anchors(dm,section,&cSec);
8074:     DMPlexCreateConstraintMatrix_Anchors(dm,section,cSec,&cMat);
8075:     DMGetNumFields(dm,&Nf);
8076:     if (Nf && plex->computeanchormatrix) {(*plex->computeanchormatrix)(dm,section,cSec,cMat);}
8077:     DMSetDefaultConstraints(dm,cSec,cMat);
8078:     PetscSectionDestroy(&cSec);
8079:     MatDestroy(&cMat);
8080:   }
8081:   return(0);
8082: }

8084: PetscErrorCode DMCreateSubDomainDM_Plex(DM dm, DMLabel label, PetscInt value, IS *is, DM *subdm)
8085: {
8086:   IS             subis;
8087:   PetscSection   section, subsection;

8091:   DMGetLocalSection(dm, &section);
8092:   if (!section) SETERRQ(PetscObjectComm((PetscObject) dm), PETSC_ERR_ARG_WRONG, "Must set default section for DM before splitting subdomain");
8093:   if (!subdm)   SETERRQ(PetscObjectComm((PetscObject) dm), PETSC_ERR_ARG_WRONG, "Must set output subDM for splitting subdomain");
8094:   /* Create subdomain */
8095:   DMPlexFilter(dm, label, value, subdm);
8096:   /* Create submodel */
8097:   DMPlexCreateSubpointIS(*subdm, &subis);
8098:   PetscSectionCreateSubmeshSection(section, subis, &subsection);
8099:   ISDestroy(&subis);
8100:   DMSetLocalSection(*subdm, subsection);
8101:   PetscSectionDestroy(&subsection);
8102:   DMCopyDisc(dm, *subdm);
8103:   /* Create map from submodel to global model */
8104:   if (is) {
8105:     PetscSection    sectionGlobal, subsectionGlobal;
8106:     IS              spIS;
8107:     const PetscInt *spmap;
8108:     PetscInt       *subIndices;
8109:     PetscInt        subSize = 0, subOff = 0, pStart, pEnd, p;
8110:     PetscInt        Nf, f, bs = -1, bsLocal[2], bsMinMax[2];

8112:     DMPlexCreateSubpointIS(*subdm, &spIS);
8113:     ISGetIndices(spIS, &spmap);
8114:     PetscSectionGetNumFields(section, &Nf);
8115:     DMGetGlobalSection(dm, &sectionGlobal);
8116:     DMGetGlobalSection(*subdm, &subsectionGlobal);
8117:     PetscSectionGetChart(subsection, &pStart, &pEnd);
8118:     for (p = pStart; p < pEnd; ++p) {
8119:       PetscInt gdof, pSubSize  = 0;

8121:       PetscSectionGetDof(sectionGlobal, p, &gdof);
8122:       if (gdof > 0) {
8123:         for (f = 0; f < Nf; ++f) {
8124:           PetscInt fdof, fcdof;

8126:           PetscSectionGetFieldDof(subsection, p, f, &fdof);
8127:           PetscSectionGetFieldConstraintDof(subsection, p, f, &fcdof);
8128:           pSubSize += fdof-fcdof;
8129:         }
8130:         subSize += pSubSize;
8131:         if (pSubSize) {
8132:           if (bs < 0) {
8133:             bs = pSubSize;
8134:           } else if (bs != pSubSize) {
8135:             /* Layout does not admit a pointwise block size */
8136:             bs = 1;
8137:           }
8138:         }
8139:       }
8140:     }
8141:     /* Must have same blocksize on all procs (some might have no points) */
8142:     bsLocal[0] = bs < 0 ? PETSC_MAX_INT : bs; bsLocal[1] = bs;
8143:     PetscGlobalMinMaxInt(PetscObjectComm((PetscObject) dm), bsLocal, bsMinMax);
8144:     if (bsMinMax[0] != bsMinMax[1]) {bs = 1;}
8145:     else                            {bs = bsMinMax[0];}
8146:     PetscMalloc1(subSize, &subIndices);
8147:     for (p = pStart; p < pEnd; ++p) {
8148:       PetscInt gdof, goff;

8150:       PetscSectionGetDof(subsectionGlobal, p, &gdof);
8151:       if (gdof > 0) {
8152:         const PetscInt point = spmap[p];

8154:         PetscSectionGetOffset(sectionGlobal, point, &goff);
8155:         for (f = 0; f < Nf; ++f) {
8156:           PetscInt fdof, fcdof, fc, f2, poff = 0;

8158:           /* Can get rid of this loop by storing field information in the global section */
8159:           for (f2 = 0; f2 < f; ++f2) {
8160:             PetscSectionGetFieldDof(section, p, f2, &fdof);
8161:             PetscSectionGetFieldConstraintDof(section, p, f2, &fcdof);
8162:             poff += fdof-fcdof;
8163:           }
8164:           PetscSectionGetFieldDof(section, p, f, &fdof);
8165:           PetscSectionGetFieldConstraintDof(section, p, f, &fcdof);
8166:           for (fc = 0; fc < fdof-fcdof; ++fc, ++subOff) {
8167:             subIndices[subOff] = goff+poff+fc;
8168:           }
8169:         }
8170:       }
8171:     }
8172:     ISRestoreIndices(spIS, &spmap);
8173:     ISDestroy(&spIS);
8174:     ISCreateGeneral(PetscObjectComm((PetscObject)dm), subSize, subIndices, PETSC_OWN_POINTER, is);
8175:     if (bs > 1) {
8176:       /* We need to check that the block size does not come from non-contiguous fields */
8177:       PetscInt i, j, set = 1;
8178:       for (i = 0; i < subSize; i += bs) {
8179:         for (j = 0; j < bs; ++j) {
8180:           if (subIndices[i+j] != subIndices[i]+j) {set = 0; break;}
8181:         }
8182:       }
8183:       if (set) {ISSetBlockSize(*is, bs);}
8184:     }
8185:     /* Attach nullspace */
8186:     for (f = 0; f < Nf; ++f) {
8187:       (*subdm)->nullspaceConstructors[f] = dm->nullspaceConstructors[f];
8188:       if ((*subdm)->nullspaceConstructors[f]) break;
8189:     }
8190:     if (f < Nf) {
8191:       MatNullSpace nullSpace;

8193:       (*(*subdm)->nullspaceConstructors[f])(*subdm, f, &nullSpace);
8194:       PetscObjectCompose((PetscObject) *is, "nullspace", (PetscObject) nullSpace);
8195:       MatNullSpaceDestroy(&nullSpace);
8196:     }
8197:   }
8198:   return(0);
8199: }

8201: /*@
8202:   DMPlexMonitorThroughput - Report the cell throughput of FE integration

8204:   Input Parameter:
8205: - dm - The DM

8207:   Level: developer

8209:   Options Database Keys:
8210: . -dm_plex_monitor_throughput - Activate the monitor

8212: .seealso: DMSetFromOptions(), DMPlexCreate()
8213: @*/
8214: PetscErrorCode DMPlexMonitorThroughput(DM dm, void *dummy)
8215: {
8216:   PetscStageLog      stageLog;
8217:   PetscLogEvent      event;
8218:   PetscLogStage      stage;
8219:   PetscEventPerfInfo eventInfo;
8220:   PetscReal          cellRate, flopRate;
8221:   PetscInt           cStart, cEnd, Nf, N;
8222:   const char        *name;
8223:   PetscErrorCode     ierr;

8227: #if defined(PETSC_USE_LOG)
8228:   PetscObjectGetName((PetscObject) dm, &name);
8229:   DMPlexGetHeightStratum(dm, 0, &cStart, &cEnd);
8230:   DMGetNumFields(dm, &Nf);
8231:   PetscLogGetStageLog(&stageLog);
8232:   PetscStageLogGetCurrent(stageLog, &stage);
8233:   PetscLogEventGetId("DMPlexResidualFE", &event);
8234:   PetscLogEventGetPerfInfo(stage, event, &eventInfo);
8235:   N        = (cEnd - cStart)*Nf*eventInfo.count;
8236:   flopRate = eventInfo.flops/eventInfo.time;
8237:   cellRate = N/eventInfo.time;
8238:   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));
8239: #else
8240:   SETERRQ(PetscObjectComm((PetscObject) dm), PETSC_ERR_SUP, "Plex Throughput Monitor is not supported if logging is turned off. Reconfigure using --with-log.");
8241: #endif
8242:   return(0);
8243: }