Actual source code: dm.c

  1: #include <petscvec.h>
  2: #include <petsc/private/dmimpl.h>
  3: #include <petsc/private/dmlabelimpl.h>
  4: #include <petsc/private/petscdsimpl.h>
  5: #include <petscdmplex.h>
  6: #include <petscdmceed.h>
  7: #include <petscdmfield.h>
  8: #include <petscsf.h>
  9: #include <petscds.h>

 11: #ifdef PETSC_HAVE_LIBCEED
 12: #include <petscfeceed.h>
 13: #endif

 15: PetscClassId DM_CLASSID;
 16: PetscClassId DMLABEL_CLASSID;
 17: PetscLogEvent DM_Convert, DM_GlobalToLocal, DM_LocalToGlobal, DM_LocalToLocal, DM_LocatePoints, DM_Coarsen, DM_Refine, DM_CreateInterpolation, DM_CreateRestriction, DM_CreateInjection, DM_CreateMatrix, DM_CreateMassMatrix, DM_Load, DM_View, DM_AdaptInterpolator, DM_ProjectFunction;

 19: const char *const DMBoundaryTypes[]          = {"NONE", "GHOSTED", "MIRROR", "PERIODIC", "TWIST", "DMBoundaryType", "DM_BOUNDARY_", NULL};
 20: const char *const DMBoundaryConditionTypes[] = {"INVALID", "ESSENTIAL", "NATURAL", "INVALID", "LOWER_BOUND", "ESSENTIAL_FIELD", "NATURAL_FIELD", "INVALID", "UPPER_BOUND", "ESSENTIAL_BD_FIELD", "NATURAL_RIEMANN", "DMBoundaryConditionType",
 21:                                                 "DM_BC_",  NULL};
 22: const char *const DMBlockingTypes[]          = {"TOPOLOGICAL_POINT", "FIELD_NODE", "DMBlockingType", "DM_BLOCKING_", NULL};
 23: const char *const DMPolytopeTypes[] =
 24:   {"vertex",  "segment",      "tensor_segment", "triangle", "quadrilateral",  "tensor_quad",  "tetrahedron", "hexahedron", "triangular_prism", "tensor_triangular_prism", "tensor_quadrilateral_prism", "pyramid", "FV_ghost_cell", "interior_ghost_cell",
 25:    "unknown", "unknown_cell", "unknown_face",   "invalid",  "DMPolytopeType", "DM_POLYTOPE_", NULL};
 26: const char *const DMCopyLabelsModes[] = {"replace", "keep", "fail", "DMCopyLabelsMode", "DM_COPY_LABELS_", NULL};

 28: /*@
 29:   DMCreate - Creates an empty `DM` object. `DM`s are the abstract objects in PETSc that mediate between meshes and discretizations and the
 30:   algebraic solvers, time integrators, and optimization algorithms in PETSc.

 32:   Collective

 34:   Input Parameter:
 35: . comm - The communicator for the `DM` object

 37:   Output Parameter:
 38: . dm - The `DM` object

 40:   Level: beginner

 42:   Notes:
 43:   See `DMType` for a brief summary of available `DM`.

 45:   The type must then be set with `DMSetType()`. If you never call `DMSetType()` it will generate an
 46:   error when you try to use the `dm`.

 48:   `DM` is an orphan initialism or orphan acronym, the letters have no meaning and never did.

 50: .seealso: [](ch_dmbase), `DM`, `DMSetType()`, `DMType`, `DMDACreate()`, `DMDA`, `DMSLICED`, `DMCOMPOSITE`, `DMPLEX`, `DMMOAB`, `DMNETWORK`
 51: @*/
 52: PetscErrorCode DMCreate(MPI_Comm comm, DM *dm)
 53: {
 54:   DM      v;
 55:   PetscDS ds;

 57:   PetscFunctionBegin;
 58:   PetscAssertPointer(dm, 2);

 60:   PetscCall(DMInitializePackage());
 61:   PetscCall(PetscHeaderCreate(v, DM_CLASSID, "DM", "Distribution Manager", "DM", comm, DMDestroy, DMView));
 62:   ((PetscObject)v)->non_cyclic_references = &DMCountNonCyclicReferences;
 63:   v->setupcalled                          = PETSC_FALSE;
 64:   v->setfromoptionscalled                 = PETSC_FALSE;
 65:   v->ltogmap                              = NULL;
 66:   v->bind_below                           = 0;
 67:   v->bs                                   = 1;
 68:   v->coloringtype                         = IS_COLORING_GLOBAL;
 69:   PetscCall(PetscSFCreate(comm, &v->sf));
 70:   PetscCall(PetscSFCreate(comm, &v->sectionSF));
 71:   v->labels                    = NULL;
 72:   v->adjacency[0]              = PETSC_FALSE;
 73:   v->adjacency[1]              = PETSC_TRUE;
 74:   v->depthLabel                = NULL;
 75:   v->celltypeLabel             = NULL;
 76:   v->localSection              = NULL;
 77:   v->globalSection             = NULL;
 78:   v->defaultConstraint.section = NULL;
 79:   v->defaultConstraint.mat     = NULL;
 80:   v->defaultConstraint.bias    = NULL;
 81:   v->coordinates[0].dim        = PETSC_DEFAULT;
 82:   v->coordinates[1].dim        = PETSC_DEFAULT;
 83:   v->sparseLocalize            = PETSC_TRUE;
 84:   v->dim                       = PETSC_DETERMINE;
 85:   PetscCall(PetscDSCreate(PETSC_COMM_SELF, &ds));
 86:   PetscCall(DMSetRegionDS(v, NULL, NULL, ds, NULL));
 87:   PetscCall(PetscDSDestroy(&ds));
 88:   PetscCall(PetscHMapAuxCreate(&v->auxData));
 89:   v->dmBC              = NULL;
 90:   v->coarseMesh        = NULL;
 91:   v->outputSequenceNum = -1;
 92:   v->outputSequenceVal = 0.0;
 93:   PetscCall(DMSetVecType(v, VECSTANDARD));
 94:   PetscCall(DMSetMatType(v, MATAIJ));

 96:   *dm = v;
 97:   PetscFunctionReturn(PETSC_SUCCESS);
 98: }

100: /*@
101:   DMClone - Creates a `DM` object with the same topology as the original.

103:   Collective

105:   Input Parameter:
106: . dm - The original `DM` object

108:   Output Parameter:
109: . newdm - The new `DM` object

111:   Level: beginner

113:   Notes:
114:   For some `DM` implementations this is a shallow clone, the result of which may share (reference counted) information with its parent. For example,
115:   `DMClone()` applied to a `DMPLEX` object will result in a new `DMPLEX` that shares the topology with the original `DMPLEX`. It does not
116:   share the `PetscSection` of the original `DM`.

118:   The clone is considered set up if the original has been set up.

120:   Use `DMConvert()` for a general way to create new `DM` from a given `DM`

122: .seealso: [](ch_dmbase), `DM`, `DMDestroy()`, `DMCreate()`, `DMSetType()`, `DMSetLocalSection()`, `DMSetGlobalSection()`, `DMPLEX`, `DMConvert()`
123: @*/
124: PetscErrorCode DMClone(DM dm, DM *newdm)
125: {
126:   PetscSF              sf;
127:   Vec                  coords;
128:   void                *ctx;
129:   MatOrderingType      otype;
130:   DMReorderDefaultFlag flg;
131:   PetscInt             dim, cdim, i;
132:   PetscBool            sparse;

134:   PetscFunctionBegin;
136:   PetscAssertPointer(newdm, 2);
137:   PetscCall(DMCreate(PetscObjectComm((PetscObject)dm), newdm));
138:   PetscCall(DMCopyLabels(dm, *newdm, PETSC_COPY_VALUES, PETSC_TRUE, DM_COPY_LABELS_FAIL));
139:   (*newdm)->leveldown     = dm->leveldown;
140:   (*newdm)->levelup       = dm->levelup;
141:   (*newdm)->prealloc_only = dm->prealloc_only;
142:   (*newdm)->prealloc_skip = dm->prealloc_skip;
143:   PetscCall(PetscFree((*newdm)->vectype));
144:   PetscCall(PetscStrallocpy(dm->vectype, (char **)&(*newdm)->vectype));
145:   PetscCall(PetscFree((*newdm)->mattype));
146:   PetscCall(PetscStrallocpy(dm->mattype, (char **)&(*newdm)->mattype));
147:   PetscCall(DMGetDimension(dm, &dim));
148:   PetscCall(DMSetDimension(*newdm, dim));
149:   PetscTryTypeMethod(dm, clone, newdm);
150:   (*newdm)->setupcalled = dm->setupcalled;
151:   PetscCall(DMGetPointSF(dm, &sf));
152:   PetscCall(DMSetPointSF(*newdm, sf));
153:   PetscCall(DMGetApplicationContext(dm, &ctx));
154:   PetscCall(DMSetApplicationContext(*newdm, ctx));
155:   PetscCall(DMReorderSectionGetDefault(dm, &flg));
156:   PetscCall(DMReorderSectionSetDefault(*newdm, flg));
157:   PetscCall(DMReorderSectionGetType(dm, &otype));
158:   PetscCall(DMReorderSectionSetType(*newdm, otype));
159:   for (i = 0; i < 2; ++i) {
160:     if (dm->coordinates[i].dm) {
161:       DM           ncdm;
162:       PetscSection cs;
163:       PetscInt     pEnd = -1, pEndMax = -1;

165:       PetscCall(DMGetLocalSection(dm->coordinates[i].dm, &cs));
166:       if (cs) PetscCall(PetscSectionGetChart(cs, NULL, &pEnd));
167:       PetscCallMPI(MPIU_Allreduce(&pEnd, &pEndMax, 1, MPIU_INT, MPI_MAX, PetscObjectComm((PetscObject)dm)));
168:       if (pEndMax >= 0) {
169:         PetscCall(DMClone(dm->coordinates[i].dm, &ncdm));
170:         PetscCall(DMCopyDisc(dm->coordinates[i].dm, ncdm));
171:         PetscCall(DMSetLocalSection(ncdm, cs));
172:         if (dm->coordinates[i].dm->periodic.setup) {
173:           ncdm->periodic.setup = dm->coordinates[i].dm->periodic.setup;
174:           PetscCall(ncdm->periodic.setup(ncdm));
175:         }
176:         if (i) PetscCall(DMSetCellCoordinateDM(*newdm, ncdm));
177:         else PetscCall(DMSetCoordinateDM(*newdm, ncdm));
178:         PetscCall(DMDestroy(&ncdm));
179:       }
180:     }
181:   }
182:   PetscCall(DMGetCoordinateDim(dm, &cdim));
183:   PetscCall(DMSetCoordinateDim(*newdm, cdim));
184:   PetscCall(DMGetCoordinatesLocal(dm, &coords));
185:   if (coords) {
186:     PetscCall(DMSetCoordinatesLocal(*newdm, coords));
187:   } else {
188:     PetscCall(DMGetCoordinates(dm, &coords));
189:     if (coords) PetscCall(DMSetCoordinates(*newdm, coords));
190:   }
191:   PetscCall(DMGetSparseLocalize(dm, &sparse));
192:   PetscCall(DMSetSparseLocalize(*newdm, sparse));
193:   PetscCall(DMGetCellCoordinatesLocal(dm, &coords));
194:   if (coords) {
195:     PetscCall(DMSetCellCoordinatesLocal(*newdm, coords));
196:   } else {
197:     PetscCall(DMGetCellCoordinates(dm, &coords));
198:     if (coords) PetscCall(DMSetCellCoordinates(*newdm, coords));
199:   }
200:   {
201:     const PetscReal *maxCell, *Lstart, *L;

203:     PetscCall(DMGetPeriodicity(dm, &maxCell, &Lstart, &L));
204:     PetscCall(DMSetPeriodicity(*newdm, maxCell, Lstart, L));
205:   }
206:   {
207:     PetscBool useCone, useClosure;

209:     PetscCall(DMGetAdjacency(dm, PETSC_DEFAULT, &useCone, &useClosure));
210:     PetscCall(DMSetAdjacency(*newdm, PETSC_DEFAULT, useCone, useClosure));
211:   }
212:   PetscFunctionReturn(PETSC_SUCCESS);
213: }

215: /*@
216:   DMSetVecType - Sets the type of vector to be created with `DMCreateLocalVector()` and `DMCreateGlobalVector()`

218:   Logically Collective

220:   Input Parameters:
221: + dm    - initial distributed array
222: - ctype - the vector type, for example `VECSTANDARD`, `VECCUDA`, or `VECVIENNACL`

224:   Options Database Key:
225: . -dm_vec_type ctype - the type of vector to create

227:   Level: intermediate

229: .seealso: [](ch_dmbase), `DM`, `DMCreate()`, `DMDestroy()`, `DMDAInterpolationType`, `VecType`, `DMGetVecType()`, `DMSetMatType()`, `DMGetMatType()`,
230:           `VECSTANDARD`, `VECCUDA`, `VECVIENNACL`, `DMCreateLocalVector()`, `DMCreateGlobalVector()`
231: @*/
232: PetscErrorCode DMSetVecType(DM dm, VecType ctype)
233: {
234:   char *tmp;

236:   PetscFunctionBegin;
238:   PetscAssertPointer(ctype, 2);
239:   tmp = (char *)dm->vectype;
240:   PetscCall(PetscStrallocpy(ctype, (char **)&dm->vectype));
241:   PetscCall(PetscFree(tmp));
242:   PetscFunctionReturn(PETSC_SUCCESS);
243: }

245: /*@
246:   DMGetVecType - Gets the type of vector created with `DMCreateLocalVector()` and `DMCreateGlobalVector()`

248:   Logically Collective

250:   Input Parameter:
251: . da - initial distributed array

253:   Output Parameter:
254: . ctype - the vector type

256:   Level: intermediate

258: .seealso: [](ch_dmbase), `DM`, `DMCreate()`, `DMDestroy()`, `DMDAInterpolationType`, `VecType`, `DMSetMatType()`, `DMGetMatType()`, `DMSetVecType()`
259: @*/
260: PetscErrorCode DMGetVecType(DM da, VecType *ctype)
261: {
262:   PetscFunctionBegin;
264:   *ctype = da->vectype;
265:   PetscFunctionReturn(PETSC_SUCCESS);
266: }

268: /*@
269:   VecGetDM - Gets the `DM` defining the data layout of the vector

271:   Not Collective

273:   Input Parameter:
274: . v - The `Vec`

276:   Output Parameter:
277: . dm - The `DM`

279:   Level: intermediate

281:   Note:
282:   A `Vec` may not have a `DM` associated with it.

284: .seealso: [](ch_dmbase), `DM`, `VecSetDM()`, `DMGetLocalVector()`, `DMGetGlobalVector()`, `DMSetVecType()`
285: @*/
286: PetscErrorCode VecGetDM(Vec v, DM *dm)
287: {
288:   PetscFunctionBegin;
290:   PetscAssertPointer(dm, 2);
291:   PetscCall(PetscObjectQuery((PetscObject)v, "__PETSc_dm", (PetscObject *)dm));
292:   PetscFunctionReturn(PETSC_SUCCESS);
293: }

295: /*@
296:   VecSetDM - Sets the `DM` defining the data layout of the vector.

298:   Not Collective

300:   Input Parameters:
301: + v  - The `Vec`
302: - dm - The `DM`

304:   Level: developer

306:   Notes:
307:   This is rarely used, generally one uses `DMGetLocalVector()` or  `DMGetGlobalVector()` to create a vector associated with a given `DM`

309:   This is NOT the same as `DMCreateGlobalVector()` since it does not change the view methods or perform other customization, but merely sets the `DM` member.

311: .seealso: [](ch_dmbase), `DM`, `VecGetDM()`, `DMGetLocalVector()`, `DMGetGlobalVector()`, `DMSetVecType()`
312: @*/
313: PetscErrorCode VecSetDM(Vec v, DM dm)
314: {
315:   PetscFunctionBegin;
318:   PetscCall(PetscObjectCompose((PetscObject)v, "__PETSc_dm", (PetscObject)dm));
319:   PetscFunctionReturn(PETSC_SUCCESS);
320: }

322: /*@
323:   DMSetISColoringType - Sets the type of coloring, `IS_COLORING_GLOBAL` or `IS_COLORING_LOCAL` that is created by the `DM`

325:   Logically Collective

327:   Input Parameters:
328: + dm    - the `DM` context
329: - ctype - the matrix type

331:   Options Database Key:
332: . -dm_is_coloring_type (global|local) - see `ISColoringType`

334:   Level: intermediate

336: .seealso: [](ch_dmbase), `DM`, `DMDACreate1d()`, `DMDACreate2d()`, `DMDACreate3d()`, `DMCreateMatrix()`, `DMCreateMassMatrix()`, `DMSetMatrixPreallocateOnly()`, `MatType`, `DMGetMatType()`,
337:           `DMGetISColoringType()`, `ISColoringType`, `IS_COLORING_GLOBAL`, `IS_COLORING_LOCAL`
338: @*/
339: PetscErrorCode DMSetISColoringType(DM dm, ISColoringType ctype)
340: {
341:   PetscFunctionBegin;
343:   dm->coloringtype = ctype;
344:   PetscFunctionReturn(PETSC_SUCCESS);
345: }

347: /*@
348:   DMGetISColoringType - Gets the type of coloring, `IS_COLORING_GLOBAL` or `IS_COLORING_LOCAL` that is created by the `DM`

350:   Logically Collective

352:   Input Parameter:
353: . dm - the `DM` context

355:   Output Parameter:
356: . ctype - the matrix type

358:   Level: intermediate

360: .seealso: [](ch_dmbase), `DM`, `DMDACreate1d()`, `DMDACreate2d()`, `DMDACreate3d()`, `DMCreateMatrix()`, `DMCreateMassMatrix()`, `DMSetMatrixPreallocateOnly()`, `MatType`, `DMGetMatType()`,
361:           `ISColoringType`, `IS_COLORING_GLOBAL`, `IS_COLORING_LOCAL`
362: @*/
363: PetscErrorCode DMGetISColoringType(DM dm, ISColoringType *ctype)
364: {
365:   PetscFunctionBegin;
367:   *ctype = dm->coloringtype;
368:   PetscFunctionReturn(PETSC_SUCCESS);
369: }

371: /*@
372:   DMSetMatType - Sets the type of matrix created with `DMCreateMatrix()`

374:   Logically Collective

376:   Input Parameters:
377: + dm    - the `DM` context
378: - ctype - the matrix type, for example `MATMPIAIJ`

380:   Options Database Key:
381: . -dm_mat_type ctype - the type of the matrix to create, see `MatType`

383:   Level: intermediate

385: .seealso: [](ch_dmbase), `DM`, `MatType`, `DMDACreate1d()`, `DMDACreate2d()`, `DMDACreate3d()`, `DMCreateMatrix()`, `DMCreateMassMatrix()`, `DMSetMatrixPreallocateOnly()`, `DMGetMatType()`, `DMCreateGlobalVector()`, `DMCreateLocalVector()`
386: @*/
387: PetscErrorCode DMSetMatType(DM dm, MatType ctype)
388: {
389:   char *tmp;

391:   PetscFunctionBegin;
393:   PetscAssertPointer(ctype, 2);
394:   tmp = (char *)dm->mattype;
395:   PetscCall(PetscStrallocpy(ctype, (char **)&dm->mattype));
396:   PetscCall(PetscFree(tmp));
397:   PetscFunctionReturn(PETSC_SUCCESS);
398: }

400: /*@
401:   DMGetMatType - Gets the type of matrix that would be created with `DMCreateMatrix()`

403:   Logically Collective

405:   Input Parameter:
406: . dm - the `DM` context

408:   Output Parameter:
409: . ctype - the matrix type

411:   Level: intermediate

413: .seealso: [](ch_dmbase), `DM`, `DMDACreate1d()`, `DMDACreate2d()`, `DMDACreate3d()`, `DMCreateMatrix()`, `DMCreateMassMatrix()`, `DMSetMatrixPreallocateOnly()`, `MatType`, `DMSetMatType()`
414: @*/
415: PetscErrorCode DMGetMatType(DM dm, MatType *ctype)
416: {
417:   PetscFunctionBegin;
419:   *ctype = dm->mattype;
420:   PetscFunctionReturn(PETSC_SUCCESS);
421: }

423: /*@
424:   MatGetDM - Gets the `DM` defining the data layout of the matrix

426:   Not Collective

428:   Input Parameter:
429: . A - The `Mat`

431:   Output Parameter:
432: . dm - The `DM`

434:   Level: intermediate

436:   Note:
437:   A matrix may not have a `DM` associated with it

439:   Developer Note:
440:   Since the `Mat` class doesn't know about the `DM` class the `DM` object is associated with the `Mat` through a `PetscObjectCompose()` operation

442: .seealso: [](ch_dmbase), `DM`, `MatSetDM()`, `DMCreateMatrix()`, `DMSetMatType()`
443: @*/
444: PetscErrorCode MatGetDM(Mat A, DM *dm)
445: {
446:   PetscFunctionBegin;
448:   PetscAssertPointer(dm, 2);
449:   PetscCall(PetscObjectQuery((PetscObject)A, "__PETSc_dm", (PetscObject *)dm));
450:   PetscFunctionReturn(PETSC_SUCCESS);
451: }

453: /*@
454:   MatSetDM - Sets the `DM` defining the data layout of the matrix

456:   Not Collective

458:   Input Parameters:
459: + A  - The `Mat`
460: - dm - The `DM`

462:   Level: developer

464:   Note:
465:   This is rarely used in practice, rather `DMCreateMatrix()` is used to create a matrix associated with a particular `DM`

467:   Developer Note:
468:   Since the `Mat` class doesn't know about the `DM` class the `DM` object is associated with
469:   the `Mat` through a `PetscObjectCompose()` operation

471: .seealso: [](ch_dmbase), `DM`, `MatGetDM()`, `DMCreateMatrix()`, `DMSetMatType()`
472: @*/
473: PetscErrorCode MatSetDM(Mat A, DM dm)
474: {
475:   PetscFunctionBegin;
478:   PetscCall(PetscObjectCompose((PetscObject)A, "__PETSc_dm", (PetscObject)dm));
479:   PetscFunctionReturn(PETSC_SUCCESS);
480: }

482: /*@
483:   DMSetOptionsPrefix - Sets the prefix prepended to all option names when searching through the options database

485:   Logically Collective

487:   Input Parameters:
488: + dm     - the `DM` context
489: - prefix - the prefix to prepend

491:   Level: advanced

493:   Note:
494:   A hyphen (-) must NOT be given at the beginning of the prefix name.
495:   The first character of all runtime options is AUTOMATICALLY the hyphen.

497: .seealso: [](ch_dmbase), `DM`, `PetscObjectSetOptionsPrefix()`, `DMSetFromOptions()`
498: @*/
499: PetscErrorCode DMSetOptionsPrefix(DM dm, const char prefix[])
500: {
501:   PetscFunctionBegin;
503:   PetscCall(PetscObjectSetOptionsPrefix((PetscObject)dm, prefix));
504:   if (dm->sf) PetscCall(PetscObjectSetOptionsPrefix((PetscObject)dm->sf, prefix));
505:   if (dm->sectionSF) PetscCall(PetscObjectSetOptionsPrefix((PetscObject)dm->sectionSF, prefix));
506:   PetscFunctionReturn(PETSC_SUCCESS);
507: }

509: /*@
510:   DMAppendOptionsPrefix - Appends an additional string to an already existing prefix used for searching for
511:   `DM` options in the options database.

513:   Logically Collective

515:   Input Parameters:
516: + dm     - the `DM` context
517: - prefix - the string to append to the current prefix

519:   Level: advanced

521:   Note:
522:   If the `DM` does not currently have an options prefix then this value is used alone as the prefix as if `DMSetOptionsPrefix()` had been called.
523:   A hyphen (-) must NOT be given at the beginning of the prefix name.
524:   The first character of all runtime options is AUTOMATICALLY the hyphen.

526: .seealso: [](ch_dmbase), `DM`, `DMSetOptionsPrefix()`, `DMGetOptionsPrefix()`, `PetscObjectAppendOptionsPrefix()`, `DMSetFromOptions()`
527: @*/
528: PetscErrorCode DMAppendOptionsPrefix(DM dm, const char prefix[])
529: {
530:   PetscFunctionBegin;
532:   PetscCall(PetscObjectAppendOptionsPrefix((PetscObject)dm, prefix));
533:   PetscFunctionReturn(PETSC_SUCCESS);
534: }

536: /*@
537:   DMGetOptionsPrefix - Gets the prefix used for searching for all
538:   DM options in the options database.

540:   Not Collective

542:   Input Parameter:
543: . dm - the `DM` context

545:   Output Parameter:
546: . prefix - pointer to the prefix string used is returned

548:   Level: advanced

550: .seealso: [](ch_dmbase), `DM`, `DMSetOptionsPrefix()`, `DMAppendOptionsPrefix()`, `DMSetFromOptions()`
551: @*/
552: PetscErrorCode DMGetOptionsPrefix(DM dm, const char *prefix[])
553: {
554:   PetscFunctionBegin;
556:   PetscCall(PetscObjectGetOptionsPrefix((PetscObject)dm, prefix));
557:   PetscFunctionReturn(PETSC_SUCCESS);
558: }

560: static PetscErrorCode DMCountNonCyclicReferences_Internal(DM dm, PetscBool recurseCoarse, PetscBool recurseFine, PetscInt *ncrefct)
561: {
562:   PetscInt refct = ((PetscObject)dm)->refct;

564:   PetscFunctionBegin;
565:   *ncrefct = 0;
566:   if (dm->coarseMesh && dm->coarseMesh->fineMesh == dm) {
567:     refct--;
568:     if (recurseCoarse) {
569:       PetscInt coarseCount;

571:       PetscCall(DMCountNonCyclicReferences_Internal(dm->coarseMesh, PETSC_TRUE, PETSC_FALSE, &coarseCount));
572:       refct += coarseCount;
573:     }
574:   }
575:   if (dm->fineMesh && dm->fineMesh->coarseMesh == dm) {
576:     refct--;
577:     if (recurseFine) {
578:       PetscInt fineCount;

580:       PetscCall(DMCountNonCyclicReferences_Internal(dm->fineMesh, PETSC_FALSE, PETSC_TRUE, &fineCount));
581:       refct += fineCount;
582:     }
583:   }
584:   *ncrefct = refct;
585:   PetscFunctionReturn(PETSC_SUCCESS);
586: }

588: /* Generic wrapper for DMCountNonCyclicReferences_Internal() */
589: PetscErrorCode DMCountNonCyclicReferences(PetscObject dm, PetscInt *ncrefct)
590: {
591:   PetscFunctionBegin;
592:   PetscCall(DMCountNonCyclicReferences_Internal((DM)dm, PETSC_TRUE, PETSC_TRUE, ncrefct));
593:   PetscFunctionReturn(PETSC_SUCCESS);
594: }

596: PetscErrorCode DMDestroyLabelLinkList_Internal(DM dm)
597: {
598:   DMLabelLink next = dm->labels;

600:   PetscFunctionBegin;
601:   /* destroy the labels */
602:   while (next) {
603:     DMLabelLink tmp = next->next;

605:     if (next->label == dm->depthLabel) dm->depthLabel = NULL;
606:     if (next->label == dm->celltypeLabel) dm->celltypeLabel = NULL;
607:     PetscCall(DMLabelDestroy(&next->label));
608:     PetscCall(PetscFree(next));
609:     next = tmp;
610:   }
611:   dm->labels = NULL;
612:   PetscFunctionReturn(PETSC_SUCCESS);
613: }

615: PetscErrorCode DMDestroyCoordinates_Internal(DMCoordinates *c)
616: {
617:   PetscFunctionBegin;
618:   c->dim = PETSC_DEFAULT;
619:   PetscCall(DMDestroy(&c->dm));
620:   PetscCall(VecDestroy(&c->x));
621:   PetscCall(VecDestroy(&c->xl));
622:   PetscCall(DMFieldDestroy(&c->field));
623:   PetscFunctionReturn(PETSC_SUCCESS);
624: }

626: /*@
627:   DMDestroy - Destroys a `DM`.

629:   Collective

631:   Input Parameter:
632: . dm - the `DM` object to destroy

634:   Level: developer

636: .seealso: [](ch_dmbase), `DM`, `DMCreate()`, `DMType`, `DMSetType()`, `DMView()`, `DMCreateGlobalVector()`, `DMCreateInterpolation()`, `DMCreateColoring()`, `DMCreateMatrix()`
637: @*/
638: PetscErrorCode DMDestroy(DM *dm)
639: {
640:   PetscInt cnt;

642:   PetscFunctionBegin;
643:   if (!*dm) PetscFunctionReturn(PETSC_SUCCESS);

646:   /* count all non-cyclic references in the doubly-linked list of coarse<->fine meshes */
647:   PetscCall(DMCountNonCyclicReferences_Internal(*dm, PETSC_TRUE, PETSC_TRUE, &cnt));
648:   --((PetscObject)*dm)->refct;
649:   if (--cnt > 0) {
650:     *dm = NULL;
651:     PetscFunctionReturn(PETSC_SUCCESS);
652:   }
653:   if (((PetscObject)*dm)->refct < 0) PetscFunctionReturn(PETSC_SUCCESS);
654:   ((PetscObject)*dm)->refct = 0;

656:   PetscCall(DMClearGlobalVectors(*dm));
657:   PetscCall(DMClearLocalVectors(*dm));
658:   PetscCall(DMClearNamedGlobalVectors(*dm));
659:   PetscCall(DMClearNamedLocalVectors(*dm));

661:   /* Destroy the list of hooks */
662:   {
663:     DMCoarsenHookLink link, next;
664:     for (link = (*dm)->coarsenhook; link; link = next) {
665:       next = link->next;
666:       PetscCall(PetscFree(link));
667:     }
668:     (*dm)->coarsenhook = NULL;
669:   }
670:   {
671:     DMRefineHookLink link, next;
672:     for (link = (*dm)->refinehook; link; link = next) {
673:       next = link->next;
674:       PetscCall(PetscFree(link));
675:     }
676:     (*dm)->refinehook = NULL;
677:   }
678:   {
679:     DMSubDomainHookLink link, next;
680:     for (link = (*dm)->subdomainhook; link; link = next) {
681:       next = link->next;
682:       PetscCall(PetscFree(link));
683:     }
684:     (*dm)->subdomainhook = NULL;
685:   }
686:   {
687:     DMGlobalToLocalHookLink link, next;
688:     for (link = (*dm)->gtolhook; link; link = next) {
689:       next = link->next;
690:       PetscCall(PetscFree(link));
691:     }
692:     (*dm)->gtolhook = NULL;
693:   }
694:   {
695:     DMLocalToGlobalHookLink link, next;
696:     for (link = (*dm)->ltoghook; link; link = next) {
697:       next = link->next;
698:       PetscCall(PetscFree(link));
699:     }
700:     (*dm)->ltoghook = NULL;
701:   }
702:   /* Destroy the work arrays */
703:   {
704:     DMWorkLink link, next;
705:     PetscCheck(!(*dm)->workout, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Work array still checked out %p %p", (void *)(*dm)->workout, (*dm)->workout->mem);
706:     for (link = (*dm)->workin; link; link = next) {
707:       next = link->next;
708:       PetscCall(PetscFree(link->mem));
709:       PetscCall(PetscFree(link));
710:     }
711:     (*dm)->workin = NULL;
712:   }
713:   /* destroy the labels */
714:   PetscCall(DMDestroyLabelLinkList_Internal(*dm));
715:   /* destroy the fields */
716:   PetscCall(DMClearFields(*dm));
717:   /* destroy the boundaries */
718:   {
719:     DMBoundary next = (*dm)->boundary;
720:     while (next) {
721:       DMBoundary b = next;

723:       next = b->next;
724:       PetscCall(PetscFree(b));
725:     }
726:   }

728:   PetscCall(PetscObjectDestroy(&(*dm)->dmksp));
729:   PetscCall(PetscObjectDestroy(&(*dm)->dmsnes));
730:   PetscCall(PetscObjectDestroy(&(*dm)->dmts));

732:   if ((*dm)->ctx && (*dm)->ctxdestroy) PetscCall((*(*dm)->ctxdestroy)(&(*dm)->ctx));
733:   PetscCall(MatFDColoringDestroy(&(*dm)->fd));
734:   PetscCall(ISLocalToGlobalMappingDestroy(&(*dm)->ltogmap));
735:   PetscCall(PetscFree((*dm)->vectype));
736:   PetscCall(PetscFree((*dm)->mattype));

738:   PetscCall(PetscSectionDestroy(&(*dm)->localSection));
739:   PetscCall(PetscSectionDestroy(&(*dm)->globalSection));
740:   PetscCall(PetscFree((*dm)->reorderSectionType));
741:   PetscCall(PetscLayoutDestroy(&(*dm)->map));
742:   PetscCall(PetscSectionDestroy(&(*dm)->defaultConstraint.section));
743:   PetscCall(MatDestroy(&(*dm)->defaultConstraint.mat));
744:   PetscCall(PetscSFDestroy(&(*dm)->sf));
745:   PetscCall(PetscSFDestroy(&(*dm)->sectionSF));
746:   PetscCall(PetscSFDestroy(&(*dm)->sfNatural));
747:   PetscCall(PetscObjectDereference((PetscObject)(*dm)->sfMigration));
748:   PetscCall(DMClearAuxiliaryVec(*dm));
749:   PetscCall(PetscHMapAuxDestroy(&(*dm)->auxData));
750:   if ((*dm)->coarseMesh && (*dm)->coarseMesh->fineMesh == *dm) PetscCall(DMSetFineDM((*dm)->coarseMesh, NULL));

752:   PetscCall(DMDestroy(&(*dm)->coarseMesh));
753:   if ((*dm)->fineMesh && (*dm)->fineMesh->coarseMesh == *dm) PetscCall(DMSetCoarseDM((*dm)->fineMesh, NULL));
754:   PetscCall(DMDestroy(&(*dm)->fineMesh));
755:   PetscCall(PetscFree((*dm)->Lstart));
756:   PetscCall(PetscFree((*dm)->L));
757:   PetscCall(PetscFree((*dm)->maxCell));
758:   PetscCall(PetscFree2((*dm)->nullspaceConstructors, (*dm)->nearnullspaceConstructors));
759:   PetscCall(DMDestroyCoordinates_Internal(&(*dm)->coordinates[0]));
760:   PetscCall(DMDestroyCoordinates_Internal(&(*dm)->coordinates[1]));
761:   if ((*dm)->transformDestroy) PetscCall((*(*dm)->transformDestroy)(*dm, (*dm)->transformCtx));
762:   PetscCall(DMDestroy(&(*dm)->transformDM));
763:   PetscCall(VecDestroy(&(*dm)->transform));
764:   for (PetscInt i = 0; i < (*dm)->periodic.num_affines; i++) {
765:     PetscCall(VecScatterDestroy(&(*dm)->periodic.affine_to_local[i]));
766:     PetscCall(VecDestroy(&(*dm)->periodic.affine[i]));
767:   }
768:   if ((*dm)->periodic.num_affines > 0) PetscCall(PetscFree2((*dm)->periodic.affine_to_local, (*dm)->periodic.affine));

770:   PetscCall(DMClearDS(*dm));
771:   PetscCall(DMDestroy(&(*dm)->dmBC));
772:   /* if memory was published with SAWs then destroy it */
773:   PetscCall(PetscObjectSAWsViewOff((PetscObject)*dm));

775:   PetscTryTypeMethod(*dm, destroy);
776:   PetscCall(DMMonitorCancel(*dm));
777:   PetscCall(DMCeedDestroy(&(*dm)->dmceed));
778: #ifdef PETSC_HAVE_LIBCEED
779:   PetscCallCEED(CeedElemRestrictionDestroy(&(*dm)->ceedERestrict));
780:   PetscCallCEED(CeedDestroy(&(*dm)->ceed));
781: #endif
782:   /* We do not destroy (*dm)->data here so that we can reference count backend objects */
783:   PetscCall(PetscHeaderDestroy(dm));
784:   PetscFunctionReturn(PETSC_SUCCESS);
785: }

787: /*@
788:   DMSetUp - sets up the data structures inside a `DM` object

790:   Collective

792:   Input Parameter:
793: . dm - the `DM` object to setup

795:   Level: intermediate

797:   Note:
798:   This is usually called after various parameter setting operations and `DMSetFromOptions()` are called on the `DM`

800: .seealso: [](ch_dmbase), `DM`, `DMCreate()`, `DMSetType()`, `DMView()`, `DMCreateGlobalVector()`, `DMCreateInterpolation()`, `DMCreateColoring()`, `DMCreateMatrix()`
801: @*/
802: PetscErrorCode DMSetUp(DM dm)
803: {
804:   PetscFunctionBegin;
806:   if (dm->setupcalled) PetscFunctionReturn(PETSC_SUCCESS);
807:   PetscTryTypeMethod(dm, setup);
808:   dm->setupcalled = PETSC_TRUE;
809:   PetscFunctionReturn(PETSC_SUCCESS);
810: }

812: /*@
813:   DMSetFromOptions - sets parameters in a `DM` from the options database

815:   Collective

817:   Input Parameter:
818: . dm - the `DM` object to set options for

820:   Options Database Keys:
821: + -dm_preallocate_only (true|false)                  - Only preallocate the matrix for `DMCreateMatrix()` and `DMCreateMassMatrix()`, but do not fill it with zeros
822: . -dm_vec_type type                                  - type of vector to create inside `DM`
823: . -dm_mat_type type                                  - type of matrix to create inside `DM`
824: . -dm_is_coloring_type (global|local)                - see `ISColoringType`
825: . -dm_bind_below n                                   - bind (force execution on CPU) for `Vec` and `Mat` objects with local size (number of vector entries or matrix rows) below n; currently only supported for `DMDA`
826: . -dm_plex_option_phases ph0_, ph1_, ...             - List of prefixes for option processing phases
827: . -dm_plex_filename str                              - File containing a mesh
828: . -dm_plex_boundary_filename str                     - File containing a mesh boundary
829: . -dm_plex_name str                                  - Name of the mesh in the file
830: . -dm_plex_shape shape                               - The domain shape, such as `BOX`, `SPHERE`, etc.
831: . -dm_plex_cell ct                                   - Cell shape
832: . -dm_plex_reference_cell_domain (true|false)        - Use a reference cell domain
833: . -dm_plex_dim dim                                   - Set the topological dimension
834: . -dm_plex_simplex (true|false)                      - `PETSC_TRUE` for simplex elements, `PETSC_FALSE` for tensor elements
835: . -dm_plex_interpolate (true|false)                  - `PETSC_TRUE` turns on topological interpolation (creating edges and faces)
836: . -dm_plex_orient (true|false)                       - `PETSC_TRUE` turns on topological orientation (flipping edges and faces)
837: . -dm_plex_scale sc                                  - Scale factor for mesh coordinates
838: . -dm_coord_remap (true|false)                       - Map coordinates using a function
839: . -dm_plex_coordinate_dim dim                        - Change the coordinate dimension of a mesh (usually given with cdm_ prefix)
840: . -dm_coord_map mapname                              - Select a builtin coordinate map
841: . -dm_coord_map_params p0,p1,p2,...                  - Set coordinate mapping parameters
842: . -dm_plex_box_faces m,n,p                           - Number of faces along each dimension
843: . -dm_plex_box_lower x,y,z                           - Specify lower-left-bottom coordinates for the box
844: . -dm_plex_box_upper x,y,z                           - Specify upper-right-top coordinates for the box
845: . -dm_plex_box_bd bx,by,bz                           - Specify the `DMBoundaryType` for each direction
846: . -dm_plex_sphere_radius r                           - The sphere radius
847: . -dm_plex_ball_radius r                             - Radius of the ball
848: . -dm_plex_cylinder_bd bz                            - Boundary type in the z direction
849: . -dm_plex_cylinder_num_wedges n                     - Number of wedges around the cylinder
850: . -dm_plex_reorder order                             - Reorder the mesh using the specified algorithm
851: . -dm_refine_pre n                                   - The number of refinements before distribution
852: . -dm_refine_uniform_pre (true|false)                - Flag for uniform refinement before distribution
853: . -dm_refine_volume_limit_pre v                      - The maximum cell volume after refinement before distribution
854: . -dm_refine n                                       - The number of refinements after distribution
855: . -dm_extrude l                                      - Activate extrusion and specify the number of layers to extrude
856: . -dm_plex_save_transform (true|false)               - Save the `DMPlexTransform` that produced this mesh
857: . -dm_plex_transform_extrude_thickness t             - The total thickness of extruded layers
858: . -dm_plex_transform_extrude_use_tensor (true|false) - Use tensor cells when extruding
859: . -dm_plex_transform_extrude_symmetric (true|false)  - Extrude layers symmetrically about the surface
860: . -dm_plex_transform_extrude_normal n0,...,nd        - Specify the extrusion direction
861: . -dm_plex_transform_extrude_thicknesses t0,...,tl   - Specify thickness of each layer
862: . -dm_plex_create_fv_ghost_cells                     - Flag to create finite volume ghost cells on the boundary
863: . -dm_plex_fv_ghost_cells_label name                 - Label name for ghost cells boundary
864: . -dm_distribute (true|false)                        - Flag to redistribute a mesh among processes
865: . -dm_distribute_overlap n                           - The size of the overlap halo
866: . -dm_plex_adj_cone (true|false)                     - Set adjacency direction
867: . -dm_plex_adj_closure (true|false)                  - Set adjacency size
868: . -dm_plex_use_ceed (true|false)                     - Use LibCEED as the FEM backend
869: . -dm_plex_check_symmetry (true|false)               - Check that the adjacency information in the mesh is symmetric - `DMPlexCheckSymmetry()`
870: . -dm_plex_check_skeleton (true|false)               - Check that each cell has the correct number of vertices (only for homogeneous simplex or tensor meshes) - `DMPlexCheckSkeleton()`
871: . -dm_plex_check_faces (true|false)                  - Check that the faces of each cell give a vertex order this is consistent with what we expect from the cell type - `DMPlexCheckFaces()`
872: . -dm_plex_check_geometry (true|false)               - Check that cells have positive volume - `DMPlexCheckGeometry()`
873: . -dm_plex_check_pointsf (true|false)                - Check some necessary conditions for `PointSF` - `DMPlexCheckPointSF()`
874: . -dm_plex_check_interface_cones (true|false)        - Check points on inter-partition interfaces have conforming order of cone points - `DMPlexCheckInterfaceCones()`
875: - -dm_plex_check_all (true|false)                    - Perform all the checks above

877:   Level: intermediate

879:   Note:
880:   For some `DMType` such as `DMDA` this cannot be called after `DMSetUp()` has been called.

882: .seealso: [](ch_dmbase), `DM`, `DMView()`, `DMCreateGlobalVector()`, `DMCreateInterpolation()`, `DMCreateColoring()`, `DMCreateMatrix()`,
883:          `DMPlexCheckSymmetry()`, `DMPlexCheckSkeleton()`, `DMPlexCheckFaces()`, `DMPlexCheckGeometry()`, `DMPlexCheckPointSF()`, `DMPlexCheckInterfaceCones()`,
884:          `DMSetOptionsPrefix()`, `DMType`, `DMPLEX`, `DMDA`, `DMSetUp()`
885: @*/
886: PetscErrorCode DMSetFromOptions(DM dm)
887: {
888:   char      typeName[256];
889:   PetscBool flg;

891:   PetscFunctionBegin;
893:   dm->setfromoptionscalled = PETSC_TRUE;
894:   if (dm->sf) PetscCall(PetscSFSetFromOptions(dm->sf));
895:   if (dm->sectionSF) PetscCall(PetscSFSetFromOptions(dm->sectionSF));
896:   if (dm->coordinates[0].dm) PetscCall(DMSetFromOptions(dm->coordinates[0].dm));
897:   PetscObjectOptionsBegin((PetscObject)dm);
898:   PetscCall(PetscOptionsBool("-dm_preallocate_only", "only preallocate matrix, but do not set column indices", "DMSetMatrixPreallocateOnly", dm->prealloc_only, &dm->prealloc_only, NULL));
899:   PetscCall(PetscOptionsFList("-dm_vec_type", "Vector type used for created vectors", "DMSetVecType", VecList, dm->vectype, typeName, 256, &flg));
900:   if (flg) PetscCall(DMSetVecType(dm, typeName));
901:   PetscCall(PetscOptionsFList("-dm_mat_type", "Matrix type used for created matrices", "DMSetMatType", MatList, dm->mattype ? dm->mattype : typeName, typeName, sizeof(typeName), &flg));
902:   if (flg) PetscCall(DMSetMatType(dm, typeName));
903:   PetscCall(PetscOptionsEnum("-dm_blocking_type", "Topological point or field node blocking", "DMSetBlockingType", DMBlockingTypes, (PetscEnum)dm->blocking_type, (PetscEnum *)&dm->blocking_type, NULL));
904:   PetscCall(PetscOptionsEnum("-dm_is_coloring_type", "Global or local coloring of Jacobian", "DMSetISColoringType", ISColoringTypes, (PetscEnum)dm->coloringtype, (PetscEnum *)&dm->coloringtype, NULL));
905:   PetscCall(PetscOptionsInt("-dm_bind_below", "Set the size threshold (in entries) below which the Vec is bound to the CPU", "VecBindToCPU", dm->bind_below, &dm->bind_below, &flg));
906:   PetscCall(PetscOptionsBool("-dm_ignore_perm_output", "Ignore the local section permutation on output", "DMGetOutputDM", dm->ignorePermOutput, &dm->ignorePermOutput, NULL));
907:   PetscTryTypeMethod(dm, setfromoptions, PetscOptionsObject);
908:   /* process any options handlers added with PetscObjectAddOptionsHandler() */
909:   PetscCall(PetscObjectProcessOptionsHandlers((PetscObject)dm, PetscOptionsObject));
910:   PetscOptionsEnd();
911:   PetscFunctionReturn(PETSC_SUCCESS);
912: }

914: /*@
915:   DMViewFromOptions - View a `DM` in a particular way based on a request in the options database

917:   Collective

919:   Input Parameters:
920: + dm   - the `DM` object
921: . obj  - optional object that provides the prefix for the options database (if `NULL` then the prefix in `obj` is used)
922: - name - option string that is used to activate viewing

924:   Options Database Key:
925: . -name [viewertype][:...] - option name and values. See `PetscObjectViewFromOptions()` for the possible arguments

927:   Level: intermediate

929: .seealso: [](ch_dmbase), `DM`, `DMView()`, `PetscObjectViewFromOptions()`, `DMCreate()`
930: @*/
931: PetscErrorCode DMViewFromOptions(DM dm, PeOp PetscObject obj, const char name[])
932: {
933:   PetscFunctionBegin;
935:   PetscCall(PetscObjectViewFromOptions((PetscObject)dm, obj, name));
936:   PetscFunctionReturn(PETSC_SUCCESS);
937: }

939: /*@
940:   DMView - Views a `DM`. Depending on the `PetscViewer` and its `PetscViewerFormat` it may print some ASCII information about the `DM` to the screen or a file or
941:   save the `DM` in a binary file to be loaded later or create a visualization of the `DM`

943:   Collective

945:   Input Parameters:
946: + dm - the `DM` object to view
947: - v  - the viewer

949:   Options Database Keys:
950: + -view_pyvista_warp f                 - Warps the mesh by the active scalar with factor f
951: . -view_pyvista_clip xl,xu,yl,yu,zl,zu - Defines the clipping box
952: . -dm_view_draw_line_color color       - Specify the X-window color for cell borders
953: . -dm_view_draw_cell_color color       - Specify the X-window color for cells
954: - -dm_view_draw_affine (true|false)    - Flag to ignore high-order edges

956:   Level: beginner

958:   Notes:

960:   `PetscViewer` = `PETSCVIEWERHDF5` i.e. HDF5 format can be used with `PETSC_VIEWER_HDF5_PETSC` as the `PetscViewerFormat` to save multiple `DMPLEX`
961:   meshes in a single HDF5 file. This in turn requires one to name the `DMPLEX` object with `PetscObjectSetName()`
962:   before saving it with `DMView()` and before loading it with `DMLoad()` for identification of the mesh object.

964:   `PetscViewer` = `PETSCVIEWEREXODUSII` i.e. ExodusII format assumes that element blocks (mapped to "Cell sets" labels)
965:   consists of sequentially numbered cells.

967:   If `dm` has been distributed, only the part of the `DM` on MPI rank 0 (including "ghost" cells and vertices) will be written.

969:   Only TRI, TET, QUAD, and HEX cells are supported in ExodusII.

971:   `DMPLEX` only represents geometry while most post-processing software expect that a mesh also provides information on the discretization space. This function assumes that the file represents Lagrange finite elements of order 1 or 2.
972:   The order of the mesh shall be set using `PetscViewerExodusIISetOrder()`

974:   Variable names can be set and queried using `PetscViewerExodusII[Set/Get][Nodal/Zonal]VariableNames[s]`.

976: .seealso: [](ch_dmbase), `DM`, `PetscViewer`, `PetscViewerFormat`, `PetscViewerSetFormat()`, `DMDestroy()`, `DMCreateGlobalVector()`, `DMCreateInterpolation()`, `DMCreateColoring()`, `DMCreateMatrix()`, `DMCreateMassMatrix()`, `DMLoad()`, `PetscObjectSetName()`
977: @*/
978: PetscErrorCode DMView(DM dm, PetscViewer v)
979: {
980:   PetscBool         isbinary;
981:   PetscMPIInt       size;
982:   PetscViewerFormat format;

984:   PetscFunctionBegin;
986:   if (!v) PetscCall(PetscViewerASCIIGetStdout(PetscObjectComm((PetscObject)dm), &v));
988:   /* Ideally, we would like to have this test on.
989:      However, it currently breaks socket viz via GLVis.
990:      During DMView(parallel_mesh,glvis_viewer), each
991:      process opens a sequential ASCII socket to visualize
992:      the local mesh, and PetscObjectView(dm,local_socket)
993:      is internally called inside VecView_GLVis, incurring
994:      in an error here */
995:   /* PetscCheckSameComm(dm,1,v,2); */
996:   PetscCall(PetscViewerCheckWritable(v));

998:   PetscCall(PetscLogEventBegin(DM_View, v, 0, 0, 0));
999:   PetscCall(PetscViewerGetFormat(v, &format));
1000:   PetscCallMPI(MPI_Comm_size(PetscObjectComm((PetscObject)dm), &size));
1001:   if (size == 1 && format == PETSC_VIEWER_LOAD_BALANCE) PetscFunctionReturn(PETSC_SUCCESS);
1002:   PetscCall(PetscObjectPrintClassNamePrefixType((PetscObject)dm, v));
1003:   PetscCall(PetscObjectTypeCompare((PetscObject)v, PETSCVIEWERBINARY, &isbinary));
1004:   if (isbinary) {
1005:     PetscInt classid = DM_FILE_CLASSID;
1006:     char     type[256];

1008:     PetscCall(PetscViewerBinaryWrite(v, &classid, 1, PETSC_INT));
1009:     PetscCall(PetscStrncpy(type, ((PetscObject)dm)->type_name, sizeof(type)));
1010:     PetscCall(PetscViewerBinaryWrite(v, type, 256, PETSC_CHAR));
1011:   }
1012:   PetscTryTypeMethod(dm, view, v);
1013:   PetscCall(PetscLogEventEnd(DM_View, v, 0, 0, 0));
1014:   PetscFunctionReturn(PETSC_SUCCESS);
1015: }

1017: /*@
1018:   DMCreateGlobalVector - Creates a global vector from a `DM` object. A global vector is a parallel vector that has no duplicate values shared between MPI ranks,
1019:   that is it has no ghost locations.

1021:   Collective

1023:   Input Parameter:
1024: . dm - the `DM` object

1026:   Output Parameter:
1027: . vec - the global vector

1029:   Level: beginner

1031:   Note:
1032:   PETSc `Vec` always have all zero entries when created with `DMCreateGlobalVector()` until routines such as `VecSet()` or `VecSetValues()`
1033:   are used to change the values. There is no reason to call `VecZeroEntries()` after creation.

1035: .seealso: [](ch_dmbase), `DM`, `Vec`, `DMCreateLocalVector()`, `DMGetGlobalVector()`, `DMDestroy()`, `DMView()`, `DMCreateInterpolation()`, `DMCreateColoring()`, `DMCreateMatrix()`,
1036:          `DMGlobalToLocalBegin()`, `DMGlobalToLocalEnd()`
1037: @*/
1038: PetscErrorCode DMCreateGlobalVector(DM dm, Vec *vec)
1039: {
1040:   PetscFunctionBegin;
1042:   PetscAssertPointer(vec, 2);
1043:   PetscUseTypeMethod(dm, createglobalvector, vec);
1044:   if (PetscDefined(USE_DEBUG)) {
1045:     DM vdm;

1047:     PetscCall(VecGetDM(*vec, &vdm));
1048:     PetscCheck(vdm, PETSC_COMM_SELF, PETSC_ERR_PLIB, "DM type '%s' did not attach the DM to the vector", ((PetscObject)dm)->type_name);
1049:   }
1050:   PetscFunctionReturn(PETSC_SUCCESS);
1051: }

1053: /*@
1054:   DMCreateLocalVector - Creates a local vector from a `DM` object.

1056:   Not Collective

1058:   Input Parameter:
1059: . dm - the `DM` object

1061:   Output Parameter:
1062: . vec - the local vector

1064:   Level: beginner

1066:   Notes:
1067:   A local vector usually has ghost locations that contain values that are owned by different MPI ranks. A global vector has no ghost locations.

1069:   PETSc `Vec` always have all zero entries when created with `DMCreateLocalVector()` until routines such as `VecSet()` or `VecSetValues()`
1070:   are used to change the values. There is no reason to call `VecZeroEntries()` after creation.

1072: .seealso: [](ch_dmbase), `DM`, `Vec`, `DMCreateGlobalVector()`, `DMGetLocalVector()`, `DMDestroy()`, `DMView()`, `DMCreateInterpolation()`, `DMCreateColoring()`, `DMCreateMatrix()`,
1073:          `DMGlobalToLocalBegin()`, `DMGlobalToLocalEnd()`
1074: @*/
1075: PetscErrorCode DMCreateLocalVector(DM dm, Vec *vec)
1076: {
1077:   PetscFunctionBegin;
1079:   PetscAssertPointer(vec, 2);
1080:   PetscUseTypeMethod(dm, createlocalvector, vec);
1081:   if (PetscDefined(USE_DEBUG)) {
1082:     DM vdm;

1084:     PetscCall(VecGetDM(*vec, &vdm));
1085:     PetscCheck(vdm, PETSC_COMM_SELF, PETSC_ERR_LIB, "DM type '%s' did not attach the DM to the vector", ((PetscObject)dm)->type_name);
1086:   }
1087:   PetscFunctionReturn(PETSC_SUCCESS);
1088: }

1090: /*@
1091:   DMGetLocalToGlobalMapping - Accesses the local-to-global mapping in a `DM`.

1093:   Collective

1095:   Input Parameter:
1096: . dm - the `DM` that provides the mapping

1098:   Output Parameter:
1099: . ltog - the mapping

1101:   Level: advanced

1103:   Notes:
1104:   The global to local mapping allows one to set values into the global vector or matrix using `VecSetValuesLocal()` and `MatSetValuesLocal()`

1106:   Vectors obtained with  `DMCreateGlobalVector()` and matrices obtained with `DMCreateMatrix()` already contain the global mapping so you do
1107:   need to use this function with those objects.

1109:   This mapping can then be used by `VecSetLocalToGlobalMapping()` or `MatSetLocalToGlobalMapping()`.

1111: .seealso: [](ch_dmbase), `DM`, `DMCreateLocalVector()`, `DMCreateGlobalVector()`, `VecSetLocalToGlobalMapping()`, `MatSetLocalToGlobalMapping()`,
1112:           `DMCreateMatrix()`
1113: @*/
1114: PetscErrorCode DMGetLocalToGlobalMapping(DM dm, ISLocalToGlobalMapping *ltog)
1115: {
1116:   PetscInt bs = -1, bsLocal[2], bsMinMax[2];

1118:   PetscFunctionBegin;
1120:   PetscAssertPointer(ltog, 2);
1121:   if (!dm->ltogmap) {
1122:     PetscSection section, sectionGlobal;

1124:     PetscCall(DMGetLocalSection(dm, &section));
1125:     if (section) {
1126:       const PetscInt *cdofs;
1127:       PetscInt       *ltog;
1128:       PetscInt        pStart, pEnd, n, p, k, l;

1130:       PetscCall(DMGetGlobalSection(dm, &sectionGlobal));
1131:       PetscCall(PetscSectionGetChart(section, &pStart, &pEnd));
1132:       PetscCall(PetscSectionGetStorageSize(section, &n));
1133:       PetscCall(PetscMalloc1(n, &ltog)); /* We want the local+overlap size */
1134:       for (p = pStart, l = 0; p < pEnd; ++p) {
1135:         PetscInt bdof, cdof, dof, off, c, cind;

1137:         /* Should probably use constrained dofs */
1138:         PetscCall(PetscSectionGetDof(section, p, &dof));
1139:         PetscCall(PetscSectionGetConstraintDof(section, p, &cdof));
1140:         PetscCall(PetscSectionGetConstraintIndices(section, p, &cdofs));
1141:         PetscCall(PetscSectionGetOffset(sectionGlobal, p, &off));
1142:         /* If you have dofs, and constraints, and they are unequal, we set the blocksize to 1 */
1143:         bdof = cdof && (dof - cdof) ? 1 : dof;
1144:         if (dof) bs = bs < 0 ? bdof : PetscGCD(bs, bdof);

1146:         for (c = 0, cind = 0; c < dof; ++c, ++l) {
1147:           if (cind < cdof && c == cdofs[cind]) {
1148:             ltog[l] = off < 0 ? off - c : -(off + c + 1);
1149:             cind++;
1150:           } else {
1151:             ltog[l] = (off < 0 ? -(off + 1) : off) + c - cind;
1152:           }
1153:         }
1154:       }
1155:       /* Must have same blocksize on all procs (some might have no points) */
1156:       bsLocal[0] = bs < 0 ? PETSC_INT_MAX : bs;
1157:       bsLocal[1] = bs;
1158:       PetscCall(PetscGlobalMinMaxInt(PetscObjectComm((PetscObject)dm), bsLocal, bsMinMax));
1159:       if (bsMinMax[0] != bsMinMax[1]) {
1160:         bs = 1;
1161:       } else {
1162:         bs = bsMinMax[0];
1163:       }
1164:       bs = bs < 0 ? 1 : bs;
1165:       /* Must reduce indices by blocksize */
1166:       if (bs > 1) {
1167:         for (l = 0, k = 0; l < n; l += bs, ++k) {
1168:           // Integer division of negative values truncates toward zero(!), not toward negative infinity
1169:           ltog[k] = ltog[l] >= 0 ? ltog[l] / bs : -(-(ltog[l] + 1) / bs + 1);
1170:         }
1171:         n /= bs;
1172:       }
1173:       PetscCall(ISLocalToGlobalMappingCreate(PetscObjectComm((PetscObject)dm), bs, n, ltog, PETSC_OWN_POINTER, &dm->ltogmap));
1174:     } else PetscUseTypeMethod(dm, getlocaltoglobalmapping);
1175:   }
1176:   *ltog = dm->ltogmap;
1177:   PetscFunctionReturn(PETSC_SUCCESS);
1178: }

1180: /*@
1181:   DMGetBlockSize - Gets the inherent block size associated with a `DM`

1183:   Not Collective

1185:   Input Parameter:
1186: . dm - the `DM` with block structure

1188:   Output Parameter:
1189: . bs - the block size, 1 implies no exploitable block structure

1191:   Level: intermediate

1193:   Notes:
1194:   This might be the number of degrees of freedom at each grid point for a structured grid.

1196:   Complex `DM` that represent multiphysics or staggered grids or mixed-methods do not generally have a single inherent block size, but
1197:   rather different locations in the vectors may have a different block size.

1199: .seealso: [](ch_dmbase), `DM`, `ISCreateBlock()`, `VecSetBlockSize()`, `MatSetBlockSize()`, `DMGetLocalToGlobalMapping()`
1200: @*/
1201: PetscErrorCode DMGetBlockSize(DM dm, PetscInt *bs)
1202: {
1203:   PetscFunctionBegin;
1205:   PetscAssertPointer(bs, 2);
1206:   PetscCheck(dm->bs >= 1, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "DM does not have enough information to provide a block size yet");
1207:   *bs = dm->bs;
1208:   PetscFunctionReturn(PETSC_SUCCESS);
1209: }

1211: /*@
1212:   DMCreateInterpolation - Gets the interpolation matrix between two `DM` objects. The resulting matrix map degrees of freedom in the vector obtained by
1213:   `DMCreateGlobalVector()` on the coarse `DM` to similar vectors on the fine grid `DM`.

1215:   Collective

1217:   Input Parameters:
1218: + dmc - the `DM` object
1219: - dmf - the second, finer `DM` object

1221:   Output Parameters:
1222: + mat - the interpolation
1223: - vec - the scaling (optional, pass `NULL` if not needed), see `DMCreateInterpolationScale()`

1225:   Level: developer

1227:   Notes:
1228:   For `DMDA` objects this only works for "uniform refinement", that is the refined mesh was obtained `DMRefine()` or the coarse mesh was obtained by
1229:   DMCoarsen(). The coordinates set into the `DMDA` are completely ignored in computing the interpolation.

1231:   For `DMDA` objects you can use this interpolation (more precisely the interpolation from the `DMGetCoordinateDM()`) to interpolate the mesh coordinate
1232:   vectors EXCEPT in the periodic case where it does not make sense since the coordinate vectors are not periodic.

1234: .seealso: [](ch_dmbase), `DM`, `DMDestroy()`, `DMView()`, `DMCreateGlobalVector()`, `DMCreateColoring()`, `DMCreateMatrix()`, `DMCreateMassMatrix()`, `DMRefine()`, `DMCoarsen()`, `DMCreateRestriction()`, `DMCreateInterpolationScale()`
1235: @*/
1236: PetscErrorCode DMCreateInterpolation(DM dmc, DM dmf, Mat *mat, Vec *vec)
1237: {
1238:   PetscFunctionBegin;
1241:   PetscAssertPointer(mat, 3);
1242:   PetscCall(PetscLogEventBegin(DM_CreateInterpolation, dmc, dmf, 0, 0));
1243:   PetscUseTypeMethod(dmc, createinterpolation, dmf, mat, vec);
1244:   PetscCall(PetscLogEventEnd(DM_CreateInterpolation, dmc, dmf, 0, 0));
1245:   PetscFunctionReturn(PETSC_SUCCESS);
1246: }

1248: /*@
1249:   DMCreateInterpolationScale - Forms L = 1/(R*1) where 1 is the vector of all ones, and R is
1250:   the transpose of the interpolation between the `DM`.

1252:   Input Parameters:
1253: + dac - `DM` that defines a coarse mesh
1254: . daf - `DM` that defines a fine mesh
1255: - mat - the restriction (or interpolation operator) from fine to coarse

1257:   Output Parameter:
1258: . scale - the scaled vector

1260:   Level: advanced

1262:   Note:
1263:   xcoarse = diag(L)*R*xfine preserves scale and is thus suitable for state (versus residual)
1264:   restriction. In other words xcoarse is the coarse representation of xfine.

1266:   Developer Note:
1267:   If the fine-scale `DMDA` has the -dm_bind_below option set to true, then `DMCreateInterpolationScale()` calls `MatSetBindingPropagates()`
1268:   on the restriction/interpolation operator to set the bindingpropagates flag to true.

1270: .seealso: [](ch_dmbase), `DM`, `MatRestrict()`, `MatInterpolate()`, `DMCreateInterpolation()`, `DMCreateRestriction()`, `DMCreateGlobalVector()`
1271: @*/
1272: PetscErrorCode DMCreateInterpolationScale(DM dac, DM daf, Mat mat, Vec *scale)
1273: {
1274:   Vec         fine;
1275:   PetscScalar one = 1.0;
1276: #if defined(PETSC_HAVE_CUDA)
1277:   PetscBool bindingpropagates, isbound;
1278: #endif

1280:   PetscFunctionBegin;
1281:   PetscCall(DMCreateGlobalVector(daf, &fine));
1282:   PetscCall(DMCreateGlobalVector(dac, scale));
1283:   PetscCall(VecSet(fine, one));
1284: #if defined(PETSC_HAVE_CUDA)
1285:   /* If the 'fine' Vec is bound to the CPU, it makes sense to bind 'mat' as well.
1286:    * Note that we only do this for the CUDA case, right now, but if we add support for MatMultTranspose() via ViennaCL,
1287:    * we'll need to do it for that case, too.*/
1288:   PetscCall(VecGetBindingPropagates(fine, &bindingpropagates));
1289:   if (bindingpropagates) {
1290:     PetscCall(MatSetBindingPropagates(mat, PETSC_TRUE));
1291:     PetscCall(VecBoundToCPU(fine, &isbound));
1292:     PetscCall(MatBindToCPU(mat, isbound));
1293:   }
1294: #endif
1295:   PetscCall(MatRestrict(mat, fine, *scale));
1296:   PetscCall(VecDestroy(&fine));
1297:   PetscCall(VecReciprocal(*scale));
1298:   PetscFunctionReturn(PETSC_SUCCESS);
1299: }

1301: /*@
1302:   DMCreateRestriction - Gets restriction matrix between two `DM` objects. The resulting matrix map degrees of freedom in the vector obtained by
1303:   `DMCreateGlobalVector()` on the fine `DM` to similar vectors on the coarse grid `DM`.

1305:   Collective

1307:   Input Parameters:
1308: + dmc - the `DM` object
1309: - dmf - the second, finer `DM` object

1311:   Output Parameter:
1312: . mat - the restriction

1314:   Level: developer

1316:   Note:
1317:   This only works for `DMSTAG`. For many situations either the transpose of the operator obtained with `DMCreateInterpolation()` or that
1318:   matrix multiplied by the vector obtained with `DMCreateInterpolationScale()` provides the desired object.

1320: .seealso: [](ch_dmbase), `DM`, `DMRestrict()`, `DMInterpolate()`, `DMDestroy()`, `DMView()`, `DMCreateGlobalVector()`, `DMCreateColoring()`, `DMCreateMatrix()`, `DMCreateMassMatrix()`, `DMRefine()`, `DMCoarsen()`, `DMCreateInterpolation()`
1321: @*/
1322: PetscErrorCode DMCreateRestriction(DM dmc, DM dmf, Mat *mat)
1323: {
1324:   PetscFunctionBegin;
1327:   PetscAssertPointer(mat, 3);
1328:   PetscCall(PetscLogEventBegin(DM_CreateRestriction, dmc, dmf, 0, 0));
1329:   PetscUseTypeMethod(dmc, createrestriction, dmf, mat);
1330:   PetscCall(PetscLogEventEnd(DM_CreateRestriction, dmc, dmf, 0, 0));
1331:   PetscFunctionReturn(PETSC_SUCCESS);
1332: }

1334: /*@
1335:   DMCreateInjection - Gets injection matrix between two `DM` objects.

1337:   Collective

1339:   Input Parameters:
1340: + dac - the `DM` object
1341: - daf - the second, finer `DM` object

1343:   Output Parameter:
1344: . mat - the injection

1346:   Level: developer

1348:   Notes:
1349:   This is an operator that applied to a vector obtained with `DMCreateGlobalVector()` on the
1350:   fine grid maps the values to a vector on the vector on the coarse `DM` by simply selecting
1351:   the values on the coarse grid points. This compares to the operator obtained by
1352:   `DMCreateRestriction()` or the transpose of the operator obtained by
1353:   `DMCreateInterpolation()` that uses a "local weighted average" of the values around the
1354:   coarse grid point as the coarse grid value.

1356:   For `DMDA` objects this only works for "uniform refinement", that is the refined mesh was obtained `DMRefine()` or the coarse mesh was obtained by
1357:   `DMCoarsen()`. The coordinates set into the `DMDA` are completely ignored in computing the injection.

1359: .seealso: [](ch_dmbase), `DM`, `DMDestroy()`, `DMView()`, `DMCreateGlobalVector()`, `DMCreateColoring()`, `DMCreateMatrix()`, `DMCreateMassMatrix()`, `DMCreateInterpolation()`,
1360:           `DMCreateRestriction()`, `MatRestrict()`, `MatInterpolate()`
1361: @*/
1362: PetscErrorCode DMCreateInjection(DM dac, DM daf, Mat *mat)
1363: {
1364:   PetscFunctionBegin;
1367:   PetscAssertPointer(mat, 3);
1368:   PetscCall(PetscLogEventBegin(DM_CreateInjection, dac, daf, 0, 0));
1369:   PetscUseTypeMethod(dac, createinjection, daf, mat);
1370:   PetscCall(PetscLogEventEnd(DM_CreateInjection, dac, daf, 0, 0));
1371:   PetscFunctionReturn(PETSC_SUCCESS);
1372: }

1374: /*@
1375:   DMCreateMassMatrix - Gets the mass matrix between two `DM` objects, M_ij = \int \phi_i \psi_j where the \phi are Galerkin basis functions for a
1376:   a Galerkin finite element model on the `DM`

1378:   Collective

1380:   Input Parameters:
1381: + dmc - the target `DM` object
1382: - dmf - the source `DM` object, can be `NULL`

1384:   Output Parameter:
1385: . mat - the mass matrix

1387:   Level: developer

1389:   Notes:
1390:   For `DMPLEX` the finite element model for the `DM` must have been already provided.

1392:   if `dmc` is `dmf` or `NULL`, then x^t M x is an approximation to the L2 norm of the vector x which is obtained by `DMCreateGlobalVector()`

1394: .seealso: [](ch_dmbase), `DM`, `DMCreateMassMatrixLumped()`, `DMCreateMatrix()`, `DMRefine()`, `DMCoarsen()`, `DMCreateRestriction()`, `DMCreateInterpolation()`, `DMCreateInjection()`
1395: @*/
1396: PetscErrorCode DMCreateMassMatrix(DM dmc, DM dmf, Mat *mat)
1397: {
1398:   PetscFunctionBegin;
1400:   if (!dmf) dmf = dmc;
1402:   PetscAssertPointer(mat, 3);
1403:   PetscCall(PetscLogEventBegin(DM_CreateMassMatrix, dmc, dmf, 0, 0));
1404:   PetscUseTypeMethod(dmc, createmassmatrix, dmf, mat);
1405:   PetscCall(PetscLogEventEnd(DM_CreateMassMatrix, dmc, dmf, 0, 0));
1406:   PetscFunctionReturn(PETSC_SUCCESS);
1407: }

1409: /*@
1410:   DMCreateMassMatrixLumped - Gets the lumped mass matrix for a given `DM`

1412:   Collective

1414:   Input Parameter:
1415: . dm - the `DM` object

1417:   Output Parameters:
1418: + llm - the local lumped mass matrix, which is a diagonal matrix, represented as a vector
1419: - lm  - the global lumped mass matrix, which is a diagonal matrix, represented as a vector

1421:   Level: developer

1423:   Note:
1424:   See `DMCreateMassMatrix()` for how to create the non-lumped version of the mass matrix.

1426: .seealso: [](ch_dmbase), `DM`, `DMCreateMassMatrix()`, `DMCreateMatrix()`, `DMRefine()`, `DMCoarsen()`, `DMCreateRestriction()`, `DMCreateInterpolation()`, `DMCreateInjection()`
1427: @*/
1428: PetscErrorCode DMCreateMassMatrixLumped(DM dm, Vec *llm, Vec *lm)
1429: {
1430:   PetscFunctionBegin;
1432:   if (llm) PetscAssertPointer(llm, 2);
1433:   if (lm) PetscAssertPointer(lm, 3);
1434:   if (llm || lm) PetscUseTypeMethod(dm, createmassmatrixlumped, llm, lm);
1435:   PetscFunctionReturn(PETSC_SUCCESS);
1436: }

1438: /*@
1439:   DMCreateGradientMatrix - Gets the gradient matrix between two `DM` objects, M_(ic)j = \int \partial_c \phi_i \psi_j where the \phi are Galerkin basis functions for a Galerkin finite element model on the `DM`

1441:   Collective

1443:   Input Parameters:
1444: + dmc - the target `DM` object
1445: - dmf - the source `DM` object, can be `NULL`

1447:   Output Parameter:
1448: . mat - the gradient matrix

1450:   Level: developer

1452:   Notes:
1453:   For `DMPLEX` the finite element model for the `DM` must have been already provided.

1455: .seealso: [](ch_dmbase), `DM`, `DMCreateMassMatrix()`, `DMCreateMassMatrixLumped()`, `DMCreateMatrix()`, `DMRefine()`, `DMCoarsen()`, `DMCreateRestriction()`, `DMCreateInterpolation()`, `DMCreateInjection()`
1456: @*/
1457: PetscErrorCode DMCreateGradientMatrix(DM dmc, DM dmf, Mat *mat)
1458: {
1459:   PetscFunctionBegin;
1461:   if (!dmf) dmf = dmc;
1463:   PetscAssertPointer(mat, 3);
1464:   PetscUseTypeMethod(dmc, creategradientmatrix, dmf, mat);
1465:   PetscFunctionReturn(PETSC_SUCCESS);
1466: }

1468: /*@
1469:   DMCreateColoring - Gets coloring of a graph associated with the `DM`. Often the graph represents the operator matrix associated with the discretization
1470:   of a PDE on the `DM`.

1472:   Collective

1474:   Input Parameters:
1475: + dm    - the `DM` object
1476: - ctype - `IS_COLORING_LOCAL` or `IS_COLORING_GLOBAL`

1478:   Output Parameter:
1479: . coloring - the coloring

1481:   Level: developer

1483:   Notes:
1484:   Coloring of matrices can also be computed directly from the sparse matrix nonzero structure via the `MatColoring` object or from the mesh from which the
1485:   matrix comes from (what this function provides). In general using the mesh produces a more optimal coloring (fewer colors).

1487:   This produces a coloring with the distance of 2, see `MatSetColoringDistance()` which can be used for efficiently computing Jacobians with `MatFDColoringCreate()`
1488:   For `DMDA` in three dimensions with periodic boundary conditions the number of grid points in each dimension must be divisible by 2*stencil_width + 1,
1489:   otherwise an error will be generated.

1491: .seealso: [](ch_dmbase), `DM`, `ISColoring`, `DMDestroy()`, `DMView()`, `DMCreateGlobalVector()`, `DMCreateInterpolation()`, `DMCreateMatrix()`, `DMCreateMassMatrix()`, `DMSetMatType()`, `MatColoring`, `MatFDColoringCreate()`
1492: @*/
1493: PetscErrorCode DMCreateColoring(DM dm, ISColoringType ctype, ISColoring *coloring)
1494: {
1495:   PetscFunctionBegin;
1497:   PetscAssertPointer(coloring, 3);
1498:   PetscUseTypeMethod(dm, getcoloring, ctype, coloring);
1499:   PetscFunctionReturn(PETSC_SUCCESS);
1500: }

1502: /*@
1503:   DMCreateMatrix - Gets an empty matrix for a `DM` that is most commonly used to store the Jacobian of a discrete PDE operator.

1505:   Collective

1507:   Input Parameter:
1508: . dm - the `DM` object

1510:   Output Parameter:
1511: . mat - the empty Jacobian

1513:   Options Database Key:
1514: . -dm_preallocate_only - Only preallocate the matrix for `DMCreateMatrix()` and `DMCreateMassMatrix()`, but do not fill it with zeros

1516:   Level: beginner

1518:   Notes:
1519:   This properly preallocates the number of nonzeros in the sparse matrix so you
1520:   do not need to do it yourself.

1522:   By default it also sets the nonzero structure and puts in the zero entries. To prevent setting
1523:   the nonzero pattern call `DMSetMatrixPreallocateOnly()`

1525:   For `DMDA`, when you call `MatView()` on this matrix it is displayed using the global natural ordering, NOT in the ordering used
1526:   internally by PETSc.

1528:   For `DMDA`, in general it is easiest to use `MatSetValuesStencil()` or `MatSetValuesLocal()` to put values into the matrix because
1529:   `MatSetValues()` requires the indices for the global numbering for the `DMDA` which is complic`ated to compute

1531: .seealso: [](ch_dmbase), `DM`, `DMDestroy()`, `DMView()`, `DMCreateGlobalVector()`, `DMCreateInterpolation()`, `DMSetMatType()`, `DMCreateMassMatrix()`
1532: @*/
1533: PetscErrorCode DMCreateMatrix(DM dm, Mat *mat)
1534: {
1535:   PetscFunctionBegin;
1537:   PetscAssertPointer(mat, 2);
1538:   PetscCall(MatInitializePackage());
1539:   PetscCall(PetscLogEventBegin(DM_CreateMatrix, 0, 0, 0, 0));
1540:   PetscUseTypeMethod(dm, creatematrix, mat);
1541:   if (PetscDefined(USE_DEBUG)) {
1542:     DM mdm;

1544:     PetscCall(MatGetDM(*mat, &mdm));
1545:     PetscCheck(mdm, PETSC_COMM_SELF, PETSC_ERR_PLIB, "DM type '%s' did not attach the DM to the matrix", ((PetscObject)dm)->type_name);
1546:   }
1547:   /* Handle nullspace and near nullspace */
1548:   if (dm->Nf) {
1549:     MatNullSpace nullSpace;
1550:     PetscInt     Nf, f;

1552:     PetscCall(DMGetNumFields(dm, &Nf));
1553:     for (f = 0; f < Nf; ++f) {
1554:       if (dm->nullspaceConstructors && dm->nullspaceConstructors[f]) {
1555:         PetscCall((*dm->nullspaceConstructors[f])(dm, f, f, &nullSpace));
1556:         PetscCall(MatSetNullSpace(*mat, nullSpace));
1557:         PetscCall(MatNullSpaceDestroy(&nullSpace));
1558:         break;
1559:       }
1560:     }
1561:     for (f = 0; f < Nf; ++f) {
1562:       if (dm->nearnullspaceConstructors && dm->nearnullspaceConstructors[f]) {
1563:         PetscCall((*dm->nearnullspaceConstructors[f])(dm, f, f, &nullSpace));
1564:         PetscCall(MatSetNearNullSpace(*mat, nullSpace));
1565:         PetscCall(MatNullSpaceDestroy(&nullSpace));
1566:       }
1567:     }
1568:   }
1569:   PetscCall(PetscLogEventEnd(DM_CreateMatrix, 0, 0, 0, 0));
1570:   PetscFunctionReturn(PETSC_SUCCESS);
1571: }

1573: /*@
1574:   DMSetMatrixPreallocateSkip - When `DMCreateMatrix()` is called the matrix sizes and
1575:   `ISLocalToGlobalMapping` will be properly set, but the data structures to store values in the
1576:   matrices will not be preallocated.

1578:   Logically Collective

1580:   Input Parameters:
1581: + dm   - the `DM`
1582: - skip - `PETSC_TRUE` to skip preallocation

1584:   Level: developer

1586:   Note:
1587:   This is most useful to reduce initialization costs when `MatSetPreallocationCOO()` and
1588:   `MatSetValuesCOO()` will be used.

1590: .seealso: [](ch_dmbase), `DM`, `DMCreateMatrix()`, `DMSetMatrixStructureOnly()`, `DMSetMatrixPreallocateOnly()`
1591: @*/
1592: PetscErrorCode DMSetMatrixPreallocateSkip(DM dm, PetscBool skip)
1593: {
1594:   PetscFunctionBegin;
1596:   dm->prealloc_skip = skip;
1597:   PetscFunctionReturn(PETSC_SUCCESS);
1598: }

1600: /*@
1601:   DMSetMatrixPreallocateOnly - When `DMCreateMatrix()` is called the matrix will be properly
1602:   preallocated but the nonzero structure and zero values will not be set.

1604:   Logically Collective

1606:   Input Parameters:
1607: + dm   - the `DM`
1608: - only - `PETSC_TRUE` if only want preallocation

1610:   Options Database Key:
1611: . -dm_preallocate_only - Only preallocate the matrix for `DMCreateMatrix()`, `DMCreateMassMatrix()`, but do not fill it with zeros

1613:   Level: developer

1615: .seealso: [](ch_dmbase), `DM`, `DMCreateMatrix()`, `DMCreateMassMatrix()`, `DMSetMatrixStructureOnly()`, `DMSetMatrixPreallocateSkip()`
1616: @*/
1617: PetscErrorCode DMSetMatrixPreallocateOnly(DM dm, PetscBool only)
1618: {
1619:   PetscFunctionBegin;
1621:   dm->prealloc_only = only;
1622:   PetscFunctionReturn(PETSC_SUCCESS);
1623: }

1625: /*@
1626:   DMSetMatrixStructureOnly - When `DMCreateMatrix()` is called, the matrix nonzero structure will be created
1627:   but the array for numerical values will not be allocated.

1629:   Logically Collective

1631:   Input Parameters:
1632: + dm   - the `DM`
1633: - only - `PETSC_TRUE` if you only want matrix nonzero structure

1635:   Level: developer

1637: .seealso: [](ch_dmbase), `DM`, `DMCreateMatrix()`, `DMSetMatrixPreallocateOnly()`, `DMSetMatrixPreallocateSkip()`
1638: @*/
1639: PetscErrorCode DMSetMatrixStructureOnly(DM dm, PetscBool only)
1640: {
1641:   PetscFunctionBegin;
1643:   dm->structure_only = only;
1644:   PetscFunctionReturn(PETSC_SUCCESS);
1645: }

1647: /*@
1648:   DMSetBlockingType - set the blocking granularity to be used for variable block size `DMCreateMatrix()` is called

1650:   Logically Collective

1652:   Input Parameters:
1653: + dm    - the `DM`
1654: - btype - block by topological point or field node

1656:   Options Database Key:
1657: . -dm_blocking_type (topological_point|field_node) - use topological point blocking or field node blocking

1659:   Level: advanced

1661: .seealso: [](ch_dmbase), `DM`, `DMCreateMatrix()`, `MatSetVariableBlockSizes()`
1662: @*/
1663: PetscErrorCode DMSetBlockingType(DM dm, DMBlockingType btype)
1664: {
1665:   PetscFunctionBegin;
1667:   dm->blocking_type = btype;
1668:   PetscFunctionReturn(PETSC_SUCCESS);
1669: }

1671: /*@
1672:   DMGetBlockingType - get the blocking granularity to be used for variable block size `DMCreateMatrix()` is called

1674:   Not Collective

1676:   Input Parameter:
1677: . dm - the `DM`

1679:   Output Parameter:
1680: . btype - block by topological point or field node

1682:   Level: advanced

1684: .seealso: [](ch_dmbase), `DM`, `DMCreateMatrix()`, `MatSetVariableBlockSizes()`
1685: @*/
1686: PetscErrorCode DMGetBlockingType(DM dm, DMBlockingType *btype)
1687: {
1688:   PetscFunctionBegin;
1690:   PetscAssertPointer(btype, 2);
1691:   *btype = dm->blocking_type;
1692:   PetscFunctionReturn(PETSC_SUCCESS);
1693: }

1695: /*@C
1696:   DMGetWorkArray - Gets a work array guaranteed to be at least the input size, restore with `DMRestoreWorkArray()`

1698:   Not Collective

1700:   Input Parameters:
1701: + dm    - the `DM` object
1702: . count - The minimum size
1703: - dtype - MPI data type, often `MPIU_REAL`, `MPIU_SCALAR`, or `MPIU_INT`)

1705:   Output Parameter:
1706: . mem - the work array

1708:   Level: developer

1710:   Notes:
1711:   A `DM` may stash the array between instantiations so using this routine may be more efficient than calling `PetscMalloc()`

1713:   The array may contain nonzero values

1715: .seealso: [](ch_dmbase), `DM`, `DMDestroy()`, `DMCreate()`, `DMRestoreWorkArray()`, `PetscMalloc()`
1716: @*/
1717: PetscErrorCode DMGetWorkArray(DM dm, PetscInt count, MPI_Datatype dtype, void *mem)
1718: {
1719:   DMWorkLink  link;
1720:   PetscMPIInt dsize;

1722:   PetscFunctionBegin;
1724:   PetscAssertPointer(mem, 4);
1725:   if (!count) {
1726:     *(void **)mem = NULL;
1727:     PetscFunctionReturn(PETSC_SUCCESS);
1728:   }
1729:   if (dm->workin) {
1730:     link       = dm->workin;
1731:     dm->workin = dm->workin->next;
1732:   } else {
1733:     PetscCall(PetscNew(&link));
1734:   }
1735:   /* Avoid MPI_Type_size for most used datatypes
1736:      Get size directly */
1737:   if (dtype == MPIU_INT) dsize = sizeof(PetscInt);
1738:   else if (dtype == MPIU_REAL) dsize = sizeof(PetscReal);
1739: #if defined(PETSC_USE_64BIT_INDICES)
1740:   else if (dtype == MPI_INT) dsize = sizeof(int);
1741: #endif
1742: #if defined(PETSC_USE_COMPLEX)
1743:   else if (dtype == MPIU_SCALAR) dsize = sizeof(PetscScalar);
1744: #endif
1745:   else PetscCallMPI(MPI_Type_size(dtype, &dsize));

1747:   if (((size_t)dsize * count) > link->bytes) {
1748:     PetscCall(PetscFree(link->mem));
1749:     PetscCall(PetscMalloc(dsize * count, &link->mem));
1750:     link->bytes = dsize * count;
1751:   }
1752:   link->next    = dm->workout;
1753:   dm->workout   = link;
1754:   *(void **)mem = link->mem;
1755:   PetscFunctionReturn(PETSC_SUCCESS);
1756: }

1758: /*@C
1759:   DMRestoreWorkArray - Restores a work array obtained with `DMCreateWorkArray()`

1761:   Not Collective

1763:   Input Parameters:
1764: + dm    - the `DM` object
1765: . count - The minimum size
1766: - dtype - MPI data type, often `MPIU_REAL`, `MPIU_SCALAR`, `MPIU_INT`

1768:   Output Parameter:
1769: . mem - the work array

1771:   Level: developer

1773:   Developer Note:
1774:   count and dtype are ignored, they are only needed for `DMGetWorkArray()`

1776: .seealso: [](ch_dmbase), `DM`, `DMDestroy()`, `DMCreate()`, `DMGetWorkArray()`
1777: @*/
1778: PetscErrorCode DMRestoreWorkArray(DM dm, PetscInt count, MPI_Datatype dtype, void *mem)
1779: {
1780:   DMWorkLink *p, link;

1782:   PetscFunctionBegin;
1783:   PetscAssertPointer(mem, 4);
1784:   (void)count;
1785:   (void)dtype;
1786:   if (!*(void **)mem) PetscFunctionReturn(PETSC_SUCCESS);
1787:   for (p = &dm->workout; (link = *p); p = &link->next) {
1788:     if (link->mem == *(void **)mem) {
1789:       *p            = link->next;
1790:       link->next    = dm->workin;
1791:       dm->workin    = link;
1792:       *(void **)mem = NULL;
1793:       PetscFunctionReturn(PETSC_SUCCESS);
1794:     }
1795:   }
1796:   SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Array was not checked out");
1797: }

1799: /*@C
1800:   DMSetNullSpaceConstructor - Provide a callback function which constructs the nullspace for a given field, defined with `DMAddField()`, when function spaces
1801:   are joined or split, such as in `DMCreateSubDM()`

1803:   Logically Collective; No Fortran Support

1805:   Input Parameters:
1806: + dm     - The `DM`
1807: . field  - The field number for the nullspace
1808: - nullsp - A callback to create the nullspace

1810:   Calling sequence of `nullsp`:
1811: + dm        - The present `DM`
1812: . origField - The field number given above, in the original `DM`
1813: . field     - The field number in dm
1814: - nullSpace - The nullspace for the given field

1816:   Level: intermediate

1818: .seealso: [](ch_dmbase), `DM`, `DMAddField()`, `DMGetNullSpaceConstructor()`, `DMSetNearNullSpaceConstructor()`, `DMGetNearNullSpaceConstructor()`, `DMCreateSubDM()`, `DMCreateSuperDM()`
1819: @*/
1820: PetscErrorCode DMSetNullSpaceConstructor(DM dm, PetscInt field, PetscErrorCode (*nullsp)(DM dm, PetscInt origField, PetscInt field, MatNullSpace *nullSpace))
1821: {
1822:   PetscFunctionBegin;
1824:   PetscCheck(field < dm->Nf, PetscObjectComm((PetscObject)dm), PETSC_ERR_ARG_OUTOFRANGE, "Cannot handle %" PetscInt_FMT " >= %" PetscInt_FMT " fields", field, dm->Nf);
1825:   PetscCheck(dm->nullspaceConstructors, PetscObjectComm((PetscObject)dm), PETSC_ERR_ARG_WRONG, "Must call DMCreateDS() to setup nullspaces");
1826:   dm->nullspaceConstructors[field] = nullsp;
1827:   PetscFunctionReturn(PETSC_SUCCESS);
1828: }

1830: /*@C
1831:   DMGetNullSpaceConstructor - Return the callback function which constructs the nullspace for a given field, defined with `DMAddField()`

1833:   Not Collective; No Fortran Support

1835:   Input Parameters:
1836: + dm    - The `DM`
1837: - field - The field number for the nullspace

1839:   Output Parameter:
1840: . nullsp - A callback to create the nullspace

1842:   Calling sequence of `nullsp`:
1843: + dm        - The present DM
1844: . origField - The field number given above, in the original DM
1845: . field     - The field number in dm
1846: - nullSpace - The nullspace for the given field

1848:   Level: intermediate

1850: .seealso: [](ch_dmbase), `DM`, `DMAddField()`, `DMGetField()`, `DMSetNullSpaceConstructor()`, `DMSetNearNullSpaceConstructor()`, `DMGetNearNullSpaceConstructor()`, `DMCreateSubDM()`, `DMCreateSuperDM()`
1851: @*/
1852: PetscErrorCode DMGetNullSpaceConstructor(DM dm, PetscInt field, PetscErrorCode (**nullsp)(DM dm, PetscInt origField, PetscInt field, MatNullSpace *nullSpace))
1853: {
1854:   PetscFunctionBegin;
1856:   PetscAssertPointer(nullsp, 3);
1857:   PetscCheck(field < dm->Nf, PetscObjectComm((PetscObject)dm), PETSC_ERR_ARG_OUTOFRANGE, "Cannot handle %" PetscInt_FMT " >= %" PetscInt_FMT " fields", field, dm->Nf);
1858:   PetscCheck(dm->nullspaceConstructors, PetscObjectComm((PetscObject)dm), PETSC_ERR_ARG_WRONG, "Must call DMCreateDS() to setup nullspaces");
1859:   *nullsp = dm->nullspaceConstructors[field];
1860:   PetscFunctionReturn(PETSC_SUCCESS);
1861: }

1863: /*@C
1864:   DMSetNearNullSpaceConstructor - Provide a callback function which constructs the near-nullspace for a given field, defined with `DMAddField()`

1866:   Logically Collective; No Fortran Support

1868:   Input Parameters:
1869: + dm     - The `DM`
1870: . field  - The field number for the nullspace
1871: - nullsp - A callback to create the near-nullspace

1873:   Calling sequence of `nullsp`:
1874: + dm        - The present `DM`
1875: . origField - The field number given above, in the original `DM`
1876: . field     - The field number in dm
1877: - nullSpace - The nullspace for the given field

1879:   Level: intermediate

1881: .seealso: [](ch_dmbase), `DM`, `DMAddField()`, `DMGetNearNullSpaceConstructor()`, `DMSetNullSpaceConstructor()`, `DMGetNullSpaceConstructor()`, `DMCreateSubDM()`, `DMCreateSuperDM()`,
1882:           `MatNullSpace`
1883: @*/
1884: PetscErrorCode DMSetNearNullSpaceConstructor(DM dm, PetscInt field, PetscErrorCode (*nullsp)(DM dm, PetscInt origField, PetscInt field, MatNullSpace *nullSpace))
1885: {
1886:   PetscFunctionBegin;
1888:   PetscCheck(field < dm->Nf, PetscObjectComm((PetscObject)dm), PETSC_ERR_ARG_OUTOFRANGE, "Cannot handle %" PetscInt_FMT " >= %" PetscInt_FMT " fields", field, dm->Nf);
1889:   PetscCheck(dm->nearnullspaceConstructors, PetscObjectComm((PetscObject)dm), PETSC_ERR_ARG_WRONG, "Must call DMCreateDS() to setup nullspaces");
1890:   dm->nearnullspaceConstructors[field] = nullsp;
1891:   PetscFunctionReturn(PETSC_SUCCESS);
1892: }

1894: /*@C
1895:   DMGetNearNullSpaceConstructor - Return the callback function which constructs the near-nullspace for a given field, defined with `DMAddField()`

1897:   Not Collective; No Fortran Support

1899:   Input Parameters:
1900: + dm    - The `DM`
1901: - field - The field number for the nullspace

1903:   Output Parameter:
1904: . nullsp - A callback to create the near-nullspace

1906:   Calling sequence of `nullsp`:
1907: + dm        - The present `DM`
1908: . origField - The field number given above, in the original `DM`
1909: . field     - The field number in dm
1910: - nullSpace - The nullspace for the given field

1912:   Level: intermediate

1914: .seealso: [](ch_dmbase), `DM`, `DMAddField()`, `DMGetField()`, `DMSetNearNullSpaceConstructor()`, `DMSetNullSpaceConstructor()`, `DMGetNullSpaceConstructor()`, `DMCreateSubDM()`,
1915:           `MatNullSpace`, `DMCreateSuperDM()`
1916: @*/
1917: PetscErrorCode DMGetNearNullSpaceConstructor(DM dm, PetscInt field, PetscErrorCode (**nullsp)(DM dm, PetscInt origField, PetscInt field, MatNullSpace *nullSpace))
1918: {
1919:   PetscFunctionBegin;
1921:   PetscAssertPointer(nullsp, 3);
1922:   PetscCheck(field < dm->Nf, PetscObjectComm((PetscObject)dm), PETSC_ERR_ARG_OUTOFRANGE, "Cannot handle %" PetscInt_FMT " >= %" PetscInt_FMT " fields", field, dm->Nf);
1923:   PetscCheck(dm->nearnullspaceConstructors, PetscObjectComm((PetscObject)dm), PETSC_ERR_ARG_WRONG, "Must call DMCreateDS() to setup nullspaces");
1924:   *nullsp = dm->nearnullspaceConstructors[field];
1925:   PetscFunctionReturn(PETSC_SUCCESS);
1926: }

1928: /*@C
1929:   DMCreateFieldIS - Creates a set of `IS` objects with the global indices of dofs for each field defined with `DMAddField()`

1931:   Not Collective; No Fortran Support

1933:   Input Parameter:
1934: . dm - the `DM` object

1936:   Output Parameters:
1937: + numFields  - The number of fields (or `NULL` if not requested)
1938: . fieldNames - The name of each field (or `NULL` if not requested)
1939: - fields     - The global indices for each field (or `NULL` if not requested)

1941:   Level: intermediate

1943:   Note:
1944:   The user is responsible for freeing all requested arrays. In particular, every entry of `fieldNames` should be freed with
1945:   `PetscFree()`, every entry of `fields` should be destroyed with `ISDestroy()`, and both arrays should be freed with
1946:   `PetscFree()`.

1948:   Developer Note:
1949:   It is not clear why both this function and `DMCreateFieldDecomposition()` exist. Having two seems redundant and confusing. This function should
1950:   likely be removed.

1952: .seealso: [](ch_dmbase), `DM`, `DMAddField()`, `DMGetField()`, `DMDestroy()`, `DMView()`, `DMCreateInterpolation()`, `DMCreateColoring()`, `DMCreateMatrix()`,
1953:           `DMCreateFieldDecomposition()`
1954: @*/
1955: PetscErrorCode DMCreateFieldIS(DM dm, PetscInt *numFields, char ***fieldNames, IS *fields[])
1956: {
1957:   PetscSection section, sectionGlobal;

1959:   PetscFunctionBegin;
1961:   if (numFields) {
1962:     PetscAssertPointer(numFields, 2);
1963:     *numFields = 0;
1964:   }
1965:   if (fieldNames) {
1966:     PetscAssertPointer(fieldNames, 3);
1967:     *fieldNames = NULL;
1968:   }
1969:   if (fields) {
1970:     PetscAssertPointer(fields, 4);
1971:     *fields = NULL;
1972:   }
1973:   PetscCall(DMGetLocalSection(dm, &section));
1974:   if (section) {
1975:     PetscInt *fieldSizes, *fieldNc, **fieldIndices;
1976:     PetscInt  nF, f, pStart, pEnd, p;

1978:     PetscCall(DMGetGlobalSection(dm, &sectionGlobal));
1979:     PetscCall(PetscSectionGetNumFields(section, &nF));
1980:     PetscCall(PetscMalloc3(nF, &fieldSizes, nF, &fieldNc, nF, &fieldIndices));
1981:     PetscCall(PetscSectionGetChart(sectionGlobal, &pStart, &pEnd));
1982:     for (f = 0; f < nF; ++f) {
1983:       fieldSizes[f] = 0;
1984:       PetscCall(PetscSectionGetFieldComponents(section, f, &fieldNc[f]));
1985:     }
1986:     for (p = pStart; p < pEnd; ++p) {
1987:       PetscInt gdof;

1989:       PetscCall(PetscSectionGetDof(sectionGlobal, p, &gdof));
1990:       if (gdof > 0) {
1991:         for (f = 0; f < nF; ++f) {
1992:           PetscInt fdof, fcdof, fpdof;

1994:           PetscCall(PetscSectionGetFieldDof(section, p, f, &fdof));
1995:           PetscCall(PetscSectionGetFieldConstraintDof(section, p, f, &fcdof));
1996:           fpdof = fdof - fcdof;
1997:           if (fpdof && fpdof != fieldNc[f]) {
1998:             /* Layout does not admit a pointwise block size */
1999:             fieldNc[f] = 1;
2000:           }
2001:           fieldSizes[f] += fpdof;
2002:         }
2003:       }
2004:     }
2005:     for (f = 0; f < nF; ++f) {
2006:       PetscCall(PetscMalloc1(fieldSizes[f], &fieldIndices[f]));
2007:       fieldSizes[f] = 0;
2008:     }
2009:     for (p = pStart; p < pEnd; ++p) {
2010:       PetscInt gdof, goff;

2012:       PetscCall(PetscSectionGetDof(sectionGlobal, p, &gdof));
2013:       if (gdof > 0) {
2014:         PetscCall(PetscSectionGetOffset(sectionGlobal, p, &goff));
2015:         for (f = 0; f < nF; ++f) {
2016:           PetscInt fdof, fcdof, fc;

2018:           PetscCall(PetscSectionGetFieldDof(section, p, f, &fdof));
2019:           PetscCall(PetscSectionGetFieldConstraintDof(section, p, f, &fcdof));
2020:           for (fc = 0; fc < fdof - fcdof; ++fc, ++fieldSizes[f]) fieldIndices[f][fieldSizes[f]] = goff++;
2021:         }
2022:       }
2023:     }
2024:     if (numFields) *numFields = nF;
2025:     if (fieldNames) {
2026:       PetscCall(PetscMalloc1(nF, fieldNames));
2027:       for (f = 0; f < nF; ++f) {
2028:         const char *fieldName;

2030:         PetscCall(PetscSectionGetFieldName(section, f, &fieldName));
2031:         PetscCall(PetscStrallocpy(fieldName, &(*fieldNames)[f]));
2032:       }
2033:     }
2034:     if (fields) {
2035:       PetscCall(PetscMalloc1(nF, fields));
2036:       for (f = 0; f < nF; ++f) {
2037:         PetscInt bs, in[2], out[2];

2039:         PetscCall(ISCreateGeneral(PetscObjectComm((PetscObject)dm), fieldSizes[f], fieldIndices[f], PETSC_OWN_POINTER, &(*fields)[f]));
2040:         in[0] = -fieldNc[f];
2041:         in[1] = fieldNc[f];
2042:         PetscCallMPI(MPIU_Allreduce(in, out, 2, MPIU_INT, MPI_MAX, PetscObjectComm((PetscObject)dm)));
2043:         bs = (-out[0] == out[1]) ? out[1] : 1;
2044:         PetscCall(ISSetBlockSize((*fields)[f], bs));
2045:       }
2046:     }
2047:     PetscCall(PetscFree3(fieldSizes, fieldNc, fieldIndices));
2048:   } else PetscTryTypeMethod(dm, createfieldis, numFields, fieldNames, fields);
2049:   PetscFunctionReturn(PETSC_SUCCESS);
2050: }

2052: /*@C
2053:   DMCreateFieldDecomposition - Returns a list of `IS` objects defining a decomposition of a problem into subproblems
2054:   corresponding to different fields.

2056:   Not Collective; No Fortran Support

2058:   Input Parameter:
2059: . dm - the `DM` object

2061:   Output Parameters:
2062: + len      - The number of fields (or `NULL` if not requested)
2063: . namelist - The name for each field (or `NULL` if not requested)
2064: . islist   - The global indices for each field (or `NULL` if not requested)
2065: - dmlist   - The `DM`s for each field subproblem (or `NULL`, if not requested; if `NULL` is returned, no `DM`s are defined)

2067:   Level: intermediate

2069:   Notes:
2070:   Each `IS` contains the global indices of the dofs of the corresponding field, defined by
2071:   `DMAddField()`. The optional list of `DM`s define the `DM` for each subproblem.

2073:   The same as `DMCreateFieldIS()` but also returns a `DM` for each field.

2075:   The user is responsible for freeing all requested arrays. In particular, every entry of `namelist` should be freed with
2076:   `PetscFree()`, every entry of `islist` should be destroyed with `ISDestroy()`, every entry of `dmlist` should be destroyed with `DMDestroy()`,
2077:   and all of the arrays should be freed with `PetscFree()`.

2079:   Fortran Notes:
2080:   Use the declarations
2081: .vb
2082:   character(80), pointer :: namelist(:)
2083:   IS, pointer :: islist(:)
2084:   DM, pointer :: dmlist(:)
2085: .ve

2087:   `namelist` must be provided, `islist` may be `PETSC_NULL_IS_POINTER` and `dmlist` may be `PETSC_NULL_DM_POINTER`

2089:   Use `DMDestroyFieldDecomposition()` to free the returned objects

2091:   Developer Notes:
2092:   It is not clear why this function and `DMCreateFieldIS()` exist. Having two seems redundant and confusing.

2094:   Unlike  `DMRefine()`, `DMCoarsen()`, and `DMCreateDomainDecomposition()` this provides no mechanism to provide hooks that are called after the
2095:   decomposition is computed.

2097: .seealso: [](ch_dmbase), `DM`, `DMAddField()`, `DMCreateFieldIS()`, `DMCreateSubDM()`, `DMCreateDomainDecomposition()`, `DMDestroy()`, `DMView()`, `DMCreateInterpolation()`, `DMCreateColoring()`, `DMCreateMatrix()`, `DMCreateMassMatrix()`, `DMRefine()`, `DMCoarsen()`
2098: @*/
2099: PetscErrorCode DMCreateFieldDecomposition(DM dm, PetscInt *len, char ***namelist, IS *islist[], DM *dmlist[])
2100: {
2101:   PetscFunctionBegin;
2103:   if (len) {
2104:     PetscAssertPointer(len, 2);
2105:     *len = 0;
2106:   }
2107:   if (namelist) {
2108:     PetscAssertPointer(namelist, 3);
2109:     *namelist = NULL;
2110:   }
2111:   if (islist) {
2112:     PetscAssertPointer(islist, 4);
2113:     *islist = NULL;
2114:   }
2115:   if (dmlist) {
2116:     PetscAssertPointer(dmlist, 5);
2117:     *dmlist = NULL;
2118:   }
2119:   /*
2120:    Is it a good idea to apply the following check across all impls?
2121:    Perhaps some impls can have a well-defined decomposition before DMSetUp?
2122:    This, however, follows the general principle that accessors are not well-behaved until the object is set up.
2123:    */
2124:   PetscCheck(dm->setupcalled, PetscObjectComm((PetscObject)dm), PETSC_ERR_ARG_WRONGSTATE, "Decomposition defined only after DMSetUp");
2125:   if (!dm->ops->createfielddecomposition) {
2126:     PetscSection section;
2127:     PetscInt     numFields, f;

2129:     PetscCall(DMGetLocalSection(dm, &section));
2130:     if (section) PetscCall(PetscSectionGetNumFields(section, &numFields));
2131:     if (section && numFields && dm->ops->createsubdm) {
2132:       if (len) *len = numFields;
2133:       if (namelist) PetscCall(PetscMalloc1(numFields, namelist));
2134:       if (islist) PetscCall(PetscMalloc1(numFields, islist));
2135:       if (dmlist) PetscCall(PetscMalloc1(numFields, dmlist));
2136:       for (f = 0; f < numFields; ++f) {
2137:         const char *fieldName;

2139:         PetscCall(DMCreateSubDM(dm, 1, &f, islist ? &(*islist)[f] : NULL, dmlist ? &(*dmlist)[f] : NULL));
2140:         if (namelist) {
2141:           PetscCall(PetscSectionGetFieldName(section, f, &fieldName));
2142:           PetscCall(PetscStrallocpy(fieldName, &(*namelist)[f]));
2143:         }
2144:       }
2145:     } else {
2146:       PetscCall(DMCreateFieldIS(dm, len, namelist, islist));
2147:       /* By default there are no DMs associated with subproblems. */
2148:       if (dmlist) *dmlist = NULL;
2149:     }
2150:   } else PetscUseTypeMethod(dm, createfielddecomposition, len, namelist, islist, dmlist);
2151:   PetscFunctionReturn(PETSC_SUCCESS);
2152: }

2154: /*@
2155:   DMCreateSubDM - Returns an `IS` and `DM` encapsulating a subproblem defined by the fields passed in.
2156:   The fields are defined by `DMCreateFieldIS()`.

2158:   Not collective

2160:   Input Parameters:
2161: + dm        - The `DM` object
2162: . numFields - The number of fields to select
2163: - fields    - The field numbers of the selected fields

2165:   Output Parameters:
2166: + is    - The global indices for all the degrees of freedom in the new sub `DM`, use `NULL` if not needed
2167: - subdm - The `DM` for the subproblem, use `NULL` if not needed

2169:   Level: intermediate

2171:   Note:
2172:   You need to call `DMPlexSetMigrationSF()` on the original `DM` if you want the Global-To-Natural map to be automatically constructed

2174: .seealso: [](ch_dmbase), `DM`, `DMCreateFieldIS()`, `DMCreateFieldDecomposition()`, `DMAddField()`, `DMCreateSuperDM()`, `IS`, `VecISCopy()`, `DMPlexSetMigrationSF()`, `DMDestroy()`, `DMView()`, `DMCreateInterpolation()`, `DMCreateColoring()`, `DMCreateMatrix()`, `DMCreateMassMatrix()`
2175: @*/
2176: PetscErrorCode DMCreateSubDM(DM dm, PetscInt numFields, const PetscInt fields[], IS *is, DM *subdm)
2177: {
2178:   PetscFunctionBegin;
2180:   PetscAssertPointer(fields, 3);
2181:   if (is) PetscAssertPointer(is, 4);
2182:   if (subdm) PetscAssertPointer(subdm, 5);
2183:   PetscUseTypeMethod(dm, createsubdm, numFields, fields, is, subdm);
2184:   PetscFunctionReturn(PETSC_SUCCESS);
2185: }

2187: /*@C
2188:   DMCreateSuperDM - Returns an arrays of `IS` and a single `DM` encapsulating a superproblem defined by multiple `DM`s passed in.

2190:   Not collective

2192:   Input Parameters:
2193: + dms - The `DM` objects
2194: - n   - The number of `DM`s

2196:   Output Parameters:
2197: + is      - The global indices for each of subproblem within the super `DM`, or `NULL`, its length is `n`
2198: - superdm - The `DM` for the superproblem

2200:   Level: intermediate

2202:   Note:
2203:   You need to call `DMPlexSetMigrationSF()` on the original `DM` if you want the Global-To-Natural map to be automatically constructed

2205: .seealso: [](ch_dmbase), `DM`, `DMCreateSubDM()`, `DMPlexSetMigrationSF()`, `DMDestroy()`, `DMView()`, `DMCreateInterpolation()`, `DMCreateColoring()`, `DMCreateMatrix()`, `DMCreateMassMatrix()`, `DMCreateFieldIS()`, `DMCreateDomainDecomposition()`
2206: @*/
2207: PetscErrorCode DMCreateSuperDM(DM dms[], PetscInt n, IS *is[], DM *superdm)
2208: {
2209:   PetscInt i;

2211:   PetscFunctionBegin;
2212:   PetscAssertPointer(dms, 1);
2214:   if (is) PetscAssertPointer(is, 3);
2215:   PetscAssertPointer(superdm, 4);
2216:   PetscCheck(n >= 0, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Number of DMs must be nonnegative: %" PetscInt_FMT, n);
2217:   if (n) {
2218:     DM dm = dms[0];
2219:     PetscCheck(dm->ops->createsuperdm, PetscObjectComm((PetscObject)dm), PETSC_ERR_SUP, "No method createsuperdm for DM of type %s", ((PetscObject)dm)->type_name);
2220:     PetscCall((*dm->ops->createsuperdm)(dms, n, is, superdm));
2221:   }
2222:   PetscFunctionReturn(PETSC_SUCCESS);
2223: }

2225: /*@C
2226:   DMCreateDomainDecomposition - Returns lists of `IS` objects defining a decomposition of a
2227:   problem into subproblems corresponding to restrictions to pairs of nested subdomains.

2229:   Not Collective

2231:   Input Parameter:
2232: . dm - the `DM` object

2234:   Output Parameters:
2235: + n           - The number of subproblems in the domain decomposition (or `NULL` if not requested), also the length of the four arrays below
2236: . namelist    - The name for each subdomain (or `NULL` if not requested)
2237: . innerislist - The global indices for each inner subdomain (or `NULL`, if not requested)
2238: . outerislist - The global indices for each outer subdomain (or `NULL`, if not requested)
2239: - dmlist      - The `DM`s for each subdomain subproblem (or `NULL`, if not requested; if `NULL` is returned, no `DM`s are defined)

2241:   Level: intermediate

2243:   Notes:
2244:   Each `IS` contains the global indices of the dofs of the corresponding subdomains with in the
2245:   dofs of the original `DM`. The inner subdomains conceptually define a nonoverlapping
2246:   covering, while outer subdomains can overlap.

2248:   The optional list of `DM`s define a `DM` for each subproblem.

2250:   The user is responsible for freeing all requested arrays. In particular, every entry of `namelist` should be freed with
2251:   `PetscFree()`, every entry of `innerislist` and `outerislist` should be destroyed with `ISDestroy()`, every entry of `dmlist` should be destroyed with `DMDestroy()`,
2252:   and all of the arrays should be freed with `PetscFree()`.

2254:   Developer Notes:
2255:   The `dmlist` is for the inner subdomains or the outer subdomains or all subdomains?

2257:   The names are inconsistent, the hooks use `DMSubDomainHook` which is nothing like `DMCreateDomainDecomposition()` while `DMRefineHook` is used for `DMRefine()`.

2259: .seealso: [](ch_dmbase), `DM`, `DMCreateFieldDecomposition()`, `DMDestroy()`, `DMCreateDomainDecompositionScatters()`, `DMView()`, `DMCreateInterpolation()`,
2260:           `DMSubDomainHookAdd()`, `DMSubDomainHookRemove()`, `DMCreateColoring()`, `DMCreateMatrix()`, `DMCreateMassMatrix()`, `DMRefine()`, `DMCoarsen()`
2261: @*/
2262: PetscErrorCode DMCreateDomainDecomposition(DM dm, PetscInt *n, char **namelist[], IS *innerislist[], IS *outerislist[], DM *dmlist[])
2263: {
2264:   DMSubDomainHookLink link;
2265:   PetscInt            i, l;

2267:   PetscFunctionBegin;
2269:   if (n) {
2270:     PetscAssertPointer(n, 2);
2271:     *n = 0;
2272:   }
2273:   if (namelist) {
2274:     PetscAssertPointer(namelist, 3);
2275:     *namelist = NULL;
2276:   }
2277:   if (innerislist) {
2278:     PetscAssertPointer(innerislist, 4);
2279:     *innerislist = NULL;
2280:   }
2281:   if (outerislist) {
2282:     PetscAssertPointer(outerislist, 5);
2283:     *outerislist = NULL;
2284:   }
2285:   if (dmlist) {
2286:     PetscAssertPointer(dmlist, 6);
2287:     *dmlist = NULL;
2288:   }
2289:   /*
2290:    Is it a good idea to apply the following check across all impls?
2291:    Perhaps some impls can have a well-defined decomposition before DMSetUp?
2292:    This, however, follows the general principle that accessors are not well-behaved until the object is set up.
2293:    */
2294:   PetscCheck(dm->setupcalled, PetscObjectComm((PetscObject)dm), PETSC_ERR_ARG_WRONGSTATE, "Decomposition defined only after DMSetUp");
2295:   if (dm->ops->createdomaindecomposition) {
2296:     PetscUseTypeMethod(dm, createdomaindecomposition, &l, namelist, innerislist, outerislist, dmlist);
2297:     /* copy subdomain hooks and context over to the subdomain DMs */
2298:     if (dmlist && *dmlist) {
2299:       for (i = 0; i < l; i++) {
2300:         for (link = dm->subdomainhook; link; link = link->next) {
2301:           if (link->ddhook) PetscCall((*link->ddhook)(dm, (*dmlist)[i], link->ctx));
2302:         }
2303:         if (dm->ctx) (*dmlist)[i]->ctx = dm->ctx;
2304:       }
2305:     }
2306:     if (n) *n = l;
2307:   }
2308:   PetscFunctionReturn(PETSC_SUCCESS);
2309: }

2311: /*@C
2312:   DMCreateDomainDecompositionScatters - Returns scatters to the subdomain vectors from the global vector for subdomains created with
2313:   `DMCreateDomainDecomposition()`

2315:   Not Collective

2317:   Input Parameters:
2318: + dm     - the `DM` object
2319: . n      - the number of subdomains
2320: - subdms - the local subdomains

2322:   Output Parameters:
2323: + iscat - scatter from global vector to nonoverlapping global vector entries on subdomain
2324: . oscat - scatter from global vector to overlapping global vector entries on subdomain
2325: - gscat - scatter from global vector to local vector on subdomain (fills in ghosts)

2327:   Level: developer

2329:   Note:
2330:   This is an alternative to the `iis` and `ois` arguments in `DMCreateDomainDecomposition()` that allow for the solution
2331:   of general nonlinear problems with overlapping subdomain methods.  While merely having index sets that enable subsets
2332:   of the residual equations to be created is fine for linear problems, nonlinear problems require local assembly of
2333:   solution and residual data.

2335:   Developer Note:
2336:   Can the `subdms` input be anything or are they exactly the `DM` obtained from
2337:   `DMCreateDomainDecomposition()`?

2339: .seealso: [](ch_dmbase), `DM`, `DMCreateDomainDecomposition()`, `DMDestroy()`, `DMView()`, `DMCreateInterpolation()`, `DMCreateColoring()`, `DMCreateMatrix()`, `DMCreateMassMatrix()`, `DMCreateFieldIS()`
2340: @*/
2341: PetscErrorCode DMCreateDomainDecompositionScatters(DM dm, PetscInt n, DM subdms[], VecScatter *iscat[], VecScatter *oscat[], VecScatter *gscat[])
2342: {
2343:   PetscFunctionBegin;
2345:   PetscAssertPointer(subdms, 3);
2346:   PetscUseTypeMethod(dm, createddscatters, n, subdms, iscat, oscat, gscat);
2347:   PetscFunctionReturn(PETSC_SUCCESS);
2348: }

2350: /*@
2351:   DMRefine - Refines a `DM` object using a standard nonadaptive refinement of the underlying mesh

2353:   Collective

2355:   Input Parameters:
2356: + dm   - the `DM` object
2357: - comm - the communicator to contain the new `DM` object (or `MPI_COMM_NULL`)

2359:   Output Parameter:
2360: . dmf - the refined `DM`, or `NULL`

2362:   Options Database Key:
2363: . -dm_plex_cell_refiner strategy - chooses the refinement strategy, e.g. regular, tohex

2365:   Level: developer

2367:   Note:
2368:   If no refinement was done, the return value is `NULL`

2370: .seealso: [](ch_dmbase), `DM`, `DMCoarsen()`, `DMDestroy()`, `DMView()`, `DMCreateGlobalVector()`, `DMCreateInterpolation()`, `DMCreateDomainDecomposition()`,
2371:           `DMRefineHookAdd()`, `DMRefineHookRemove()`
2372: @*/
2373: PetscErrorCode DMRefine(DM dm, MPI_Comm comm, DM *dmf)
2374: {
2375:   DMRefineHookLink link;

2377:   PetscFunctionBegin;
2379:   PetscCall(PetscLogEventBegin(DM_Refine, dm, 0, 0, 0));
2380:   PetscUseTypeMethod(dm, refine, comm, dmf);
2381:   if (*dmf) {
2382:     (*dmf)->ops->creatematrix = dm->ops->creatematrix;

2384:     PetscCall(PetscObjectCopyFortranFunctionPointers((PetscObject)dm, (PetscObject)*dmf));

2386:     (*dmf)->ctx       = dm->ctx;
2387:     (*dmf)->leveldown = dm->leveldown;
2388:     (*dmf)->levelup   = dm->levelup + 1;

2390:     PetscCall(DMSetMatType(*dmf, dm->mattype));
2391:     for (link = dm->refinehook; link; link = link->next) {
2392:       if (link->refinehook) PetscCall((*link->refinehook)(dm, *dmf, link->ctx));
2393:     }
2394:   }
2395:   PetscCall(PetscLogEventEnd(DM_Refine, dm, 0, 0, 0));
2396:   PetscFunctionReturn(PETSC_SUCCESS);
2397: }

2399: /*@C
2400:   DMRefineHookAdd - adds a callback to be run when interpolating a nonlinear problem to a finer grid

2402:   Logically Collective; No Fortran Support

2404:   Input Parameters:
2405: + coarse     - `DM` on which to run a hook when interpolating to a finer level
2406: . refinehook - function to run when setting up the finer level
2407: . interphook - function to run to update data on finer levels (once per `SNESSolve()`)
2408: - ctx        - [optional] context for provide data for the hooks (may be `NULL`)

2410:   Calling sequence of `refinehook`:
2411: + coarse - coarse level `DM`
2412: . fine   - fine level `DM` to interpolate problem to
2413: - ctx    - optional function context

2415:   Calling sequence of `interphook`:
2416: + coarse - coarse level `DM`
2417: . interp - matrix interpolating a coarse-level solution to the finer grid
2418: . fine   - fine level `DM` to update
2419: - ctx    - optional function context

2421:   Level: advanced

2423:   Notes:
2424:   This function is only needed if auxiliary data that is attached to the `DM`s via, for example, `PetscObjectCompose()`, needs to be
2425:   passed to fine grids while grid sequencing.

2427:   The actual interpolation is done when `DMInterpolate()` is called.

2429:   If this function is called multiple times, the hooks will be run in the order they are added.

2431: .seealso: [](ch_dmbase), `DM`, `DMCoarsenHookAdd()`, `DMInterpolate()`, `SNESFASGetInterpolation()`, `SNESFASGetInjection()`, `PetscObjectCompose()`, `PetscContainerCreate()`
2432: @*/
2433: PetscErrorCode DMRefineHookAdd(DM coarse, PetscErrorCode (*refinehook)(DM coarse, DM fine, PetscCtx ctx), PetscErrorCode (*interphook)(DM coarse, Mat interp, DM fine, PetscCtx ctx), PetscCtx ctx)
2434: {
2435:   DMRefineHookLink link, *p;

2437:   PetscFunctionBegin;
2439:   for (p = &coarse->refinehook; *p; p = &(*p)->next) { /* Scan to the end of the current list of hooks */
2440:     if ((*p)->refinehook == refinehook && (*p)->interphook == interphook && (*p)->ctx == ctx) PetscFunctionReturn(PETSC_SUCCESS);
2441:   }
2442:   PetscCall(PetscNew(&link));
2443:   link->refinehook = refinehook;
2444:   link->interphook = interphook;
2445:   link->ctx        = ctx;
2446:   link->next       = NULL;
2447:   *p               = link;
2448:   PetscFunctionReturn(PETSC_SUCCESS);
2449: }

2451: /*@C
2452:   DMRefineHookRemove - remove a callback from the list of hooks, that have been set with `DMRefineHookAdd()`, to be run when interpolating
2453:   a nonlinear problem to a finer grid

2455:   Logically Collective; No Fortran Support

2457:   Input Parameters:
2458: + coarse     - the `DM` on which to run a hook when restricting to a coarser level
2459: . refinehook - function to run when setting up a finer level
2460: . interphook - function to run to update data on finer levels
2461: - ctx        - [optional] application context for provide data for the hooks (may be `NULL`)

2463:   Calling sequence of refinehook:
2464: + coarse - the coarse `DM`
2465: . fine   - the fine `DM`
2466: - ctx    - context for the function

2468:   Calling sequence of interphook:
2469: + coarse - the coarse `DM`
2470: . interp - the interpolation `Mat` from coarse to fine
2471: . fine   - the fine `DM`
2472: - ctx    - context for the function

2474:   Level: advanced

2476:   Note:
2477:   This function does nothing if the hook is not in the list.

2479: .seealso: [](ch_dmbase), `DM`, `DMRefineHookAdd()`, `DMCoarsenHookRemove()`, `DMInterpolate()`, `SNESFASGetInterpolation()`, `SNESFASGetInjection()`, `PetscObjectCompose()`, `PetscContainerCreate()`
2480: @*/
2481: PetscErrorCode DMRefineHookRemove(DM coarse, PetscErrorCode (*refinehook)(DM coarse, DM fine, PetscCtx ctx), PetscErrorCode (*interphook)(DM coarse, Mat interp, DM fine, PetscCtx ctx), PetscCtx ctx)
2482: {
2483:   DMRefineHookLink link, *p;

2485:   PetscFunctionBegin;
2487:   for (p = &coarse->refinehook; *p; p = &(*p)->next) { /* Search the list of current hooks */
2488:     if ((*p)->refinehook == refinehook && (*p)->interphook == interphook && (*p)->ctx == ctx) {
2489:       link = *p;
2490:       *p   = link->next;
2491:       PetscCall(PetscFree(link));
2492:       break;
2493:     }
2494:   }
2495:   PetscFunctionReturn(PETSC_SUCCESS);
2496: }

2498: /*@
2499:   DMInterpolate - interpolates user-defined problem data attached to a `DM` to a finer `DM` by running hooks registered by `DMRefineHookAdd()`

2501:   Collective if any hooks are

2503:   Input Parameters:
2504: + coarse - coarser `DM` to use as a base
2505: . interp - interpolation matrix, apply using `MatInterpolate()`
2506: - fine   - finer `DM` to update

2508:   Level: developer

2510:   Developer Note:
2511:   This routine is called `DMInterpolate()` while the hook is called `DMRefineHookAdd()`. It would be better to have an
2512:   an API with consistent terminology.

2514: .seealso: [](ch_dmbase), `DM`, `DMRefineHookAdd()`, `MatInterpolate()`
2515: @*/
2516: PetscErrorCode DMInterpolate(DM coarse, Mat interp, DM fine)
2517: {
2518:   DMRefineHookLink link;

2520:   PetscFunctionBegin;
2521:   for (link = fine->refinehook; link; link = link->next) {
2522:     if (link->interphook) PetscCall((*link->interphook)(coarse, interp, fine, link->ctx));
2523:   }
2524:   PetscFunctionReturn(PETSC_SUCCESS);
2525: }

2527: /*@
2528:   DMInterpolateSolution - Interpolates a solution from a coarse mesh to a fine mesh.

2530:   Collective

2532:   Input Parameters:
2533: + coarse    - coarse `DM`
2534: . fine      - fine `DM`
2535: . interp    - (optional) the matrix computed by `DMCreateInterpolation()`.  Implementations may not need this, but if it
2536:             is available it can avoid some recomputation.  If it is provided, `MatInterpolate()` will be used if
2537:             the coarse `DM` does not have a specialized implementation.
2538: - coarseSol - solution on the coarse mesh

2540:   Output Parameter:
2541: . fineSol - the interpolation of coarseSol to the fine mesh

2543:   Level: developer

2545:   Note:
2546:   This function exists because the interpolation of a solution vector between meshes is not always a linear
2547:   map.  For example, if a boundary value problem has an inhomogeneous Dirichlet boundary condition that is compressed
2548:   out of the solution vector.  Or if interpolation is inherently a nonlinear operation, such as a method using
2549:   slope-limiting reconstruction.

2551:   Developer Note:
2552:   This doesn't just interpolate "solutions" so its API name is questionable.

2554: .seealso: [](ch_dmbase), `DM`, `DMInterpolate()`, `DMCreateInterpolation()`
2555: @*/
2556: PetscErrorCode DMInterpolateSolution(DM coarse, DM fine, Mat interp, Vec coarseSol, Vec fineSol)
2557: {
2558:   PetscErrorCode (*interpsol)(DM, DM, Mat, Vec, Vec) = NULL;

2560:   PetscFunctionBegin;

2566:   PetscCall(PetscObjectQueryFunction((PetscObject)coarse, "DMInterpolateSolution_C", &interpsol));
2567:   if (interpsol) {
2568:     PetscCall((*interpsol)(coarse, fine, interp, coarseSol, fineSol));
2569:   } else if (interp) {
2570:     PetscCall(MatInterpolate(interp, coarseSol, fineSol));
2571:   } else SETERRQ(PetscObjectComm((PetscObject)coarse), PETSC_ERR_SUP, "DM %s does not implement DMInterpolateSolution()", ((PetscObject)coarse)->type_name);
2572:   PetscFunctionReturn(PETSC_SUCCESS);
2573: }

2575: /*@
2576:   DMGetRefineLevel - Gets the number of refinements that have generated this `DM` from some initial `DM`.

2578:   Not Collective

2580:   Input Parameter:
2581: . dm - the `DM` object

2583:   Output Parameter:
2584: . level - number of refinements

2586:   Level: developer

2588:   Note:
2589:   This can be used, by example, to set the number of coarser levels associated with this `DM` for a multigrid solver.

2591: .seealso: [](ch_dmbase), `DM`, `DMRefine()`, `DMCoarsen()`, `DMGetCoarsenLevel()`, `DMDestroy()`, `DMView()`, `DMCreateGlobalVector()`, `DMCreateInterpolation()`
2592: @*/
2593: PetscErrorCode DMGetRefineLevel(DM dm, PetscInt *level)
2594: {
2595:   PetscFunctionBegin;
2597:   *level = dm->levelup;
2598:   PetscFunctionReturn(PETSC_SUCCESS);
2599: }

2601: /*@
2602:   DMSetRefineLevel - Sets the number of refinements that have generated this `DM`.

2604:   Not Collective

2606:   Input Parameters:
2607: + dm    - the `DM` object
2608: - level - number of refinements

2610:   Level: advanced

2612:   Notes:
2613:   This value is used by `PCMG` to determine how many multigrid levels to use

2615:   The values are usually set automatically by the process that is causing the refinements of an initial `DM` by calling this routine.

2617: .seealso: [](ch_dmbase), `DM`, `DMGetRefineLevel()`, `DMCoarsen()`, `DMGetCoarsenLevel()`, `DMDestroy()`, `DMView()`, `DMCreateGlobalVector()`, `DMCreateInterpolation()`
2618: @*/
2619: PetscErrorCode DMSetRefineLevel(DM dm, PetscInt level)
2620: {
2621:   PetscFunctionBegin;
2623:   dm->levelup = level;
2624:   PetscFunctionReturn(PETSC_SUCCESS);
2625: }

2627: /*@
2628:   DMExtrude - Extrude a `DM` object from a surface

2630:   Collective

2632:   Input Parameters:
2633: + dm     - the `DM` object
2634: - layers - the number of extruded cell layers

2636:   Output Parameter:
2637: . dme - the extruded `DM`, or `NULL`

2639:   Level: developer

2641:   Note:
2642:   If no extrusion was done, the return value is `NULL`

2644: .seealso: [](ch_dmbase), `DM`, `DMRefine()`, `DMCoarsen()`, `DMDestroy()`, `DMView()`, `DMCreateGlobalVector()`
2645: @*/
2646: PetscErrorCode DMExtrude(DM dm, PetscInt layers, DM *dme)
2647: {
2648:   PetscFunctionBegin;
2650:   PetscUseTypeMethod(dm, extrude, layers, dme);
2651:   if (*dme) {
2652:     (*dme)->ops->creatematrix = dm->ops->creatematrix;
2653:     PetscCall(PetscObjectCopyFortranFunctionPointers((PetscObject)dm, (PetscObject)*dme));
2654:     (*dme)->ctx = dm->ctx;
2655:     PetscCall(DMSetMatType(*dme, dm->mattype));
2656:   }
2657:   PetscFunctionReturn(PETSC_SUCCESS);
2658: }

2660: PetscErrorCode DMGetBasisTransformDM_Internal(DM dm, DM *tdm)
2661: {
2662:   PetscFunctionBegin;
2664:   PetscAssertPointer(tdm, 2);
2665:   *tdm = dm->transformDM;
2666:   PetscFunctionReturn(PETSC_SUCCESS);
2667: }

2669: PetscErrorCode DMGetBasisTransformVec_Internal(DM dm, Vec *tv)
2670: {
2671:   PetscFunctionBegin;
2673:   PetscAssertPointer(tv, 2);
2674:   *tv = dm->transform;
2675:   PetscFunctionReturn(PETSC_SUCCESS);
2676: }

2678: /*@
2679:   DMHasBasisTransform - Whether the `DM` employs a basis transformation from functions in global vectors to functions in local vectors

2681:   Input Parameter:
2682: . dm - The `DM`

2684:   Output Parameter:
2685: . flg - `PETSC_TRUE` if a basis transformation should be done

2687:   Level: developer

2689: .seealso: [](ch_dmbase), `DM`, `DMPlexGlobalToLocalBasis()`, `DMPlexLocalToGlobalBasis()`, `DMPlexCreateBasisRotation()`
2690: @*/
2691: PetscErrorCode DMHasBasisTransform(DM dm, PetscBool *flg)
2692: {
2693:   Vec tv;

2695:   PetscFunctionBegin;
2697:   PetscAssertPointer(flg, 2);
2698:   PetscCall(DMGetBasisTransformVec_Internal(dm, &tv));
2699:   *flg = tv ? PETSC_TRUE : PETSC_FALSE;
2700:   PetscFunctionReturn(PETSC_SUCCESS);
2701: }

2703: PetscErrorCode DMConstructBasisTransform_Internal(DM dm)
2704: {
2705:   PetscSection s, ts;
2706:   PetscScalar *ta;
2707:   PetscInt     cdim, pStart, pEnd, p, Nf, f, Nc, dof;

2709:   PetscFunctionBegin;
2710:   PetscCall(DMGetCoordinateDim(dm, &cdim));
2711:   PetscCall(DMGetLocalSection(dm, &s));
2712:   PetscCall(PetscSectionGetChart(s, &pStart, &pEnd));
2713:   PetscCall(PetscSectionGetNumFields(s, &Nf));
2714:   PetscCall(DMClone(dm, &dm->transformDM));
2715:   PetscCall(DMGetLocalSection(dm->transformDM, &ts));
2716:   PetscCall(PetscSectionSetNumFields(ts, Nf));
2717:   PetscCall(PetscSectionSetChart(ts, pStart, pEnd));
2718:   for (f = 0; f < Nf; ++f) {
2719:     PetscCall(PetscSectionGetFieldComponents(s, f, &Nc));
2720:     /* We could start to label fields by their transformation properties */
2721:     if (Nc != cdim) continue;
2722:     for (p = pStart; p < pEnd; ++p) {
2723:       PetscCall(PetscSectionGetFieldDof(s, p, f, &dof));
2724:       if (!dof) continue;
2725:       PetscCall(PetscSectionSetFieldDof(ts, p, f, PetscSqr(cdim)));
2726:       PetscCall(PetscSectionAddDof(ts, p, PetscSqr(cdim)));
2727:     }
2728:   }
2729:   PetscCall(PetscSectionSetUp(ts));
2730:   PetscCall(DMCreateLocalVector(dm->transformDM, &dm->transform));
2731:   PetscCall(VecGetArray(dm->transform, &ta));
2732:   for (p = pStart; p < pEnd; ++p) {
2733:     for (f = 0; f < Nf; ++f) {
2734:       PetscCall(PetscSectionGetFieldDof(ts, p, f, &dof));
2735:       if (dof) {
2736:         PetscReal          x[3] = {0.0, 0.0, 0.0};
2737:         PetscScalar       *tva;
2738:         const PetscScalar *A;

2740:         /* TODO Get quadrature point for this dual basis vector for coordinate */
2741:         PetscCall((*dm->transformGetMatrix)(dm, x, PETSC_TRUE, &A, dm->transformCtx));
2742:         PetscCall(DMPlexPointLocalFieldRef(dm->transformDM, p, f, ta, (void *)&tva));
2743:         PetscCall(PetscArraycpy(tva, A, PetscSqr(cdim)));
2744:       }
2745:     }
2746:   }
2747:   PetscCall(VecRestoreArray(dm->transform, &ta));
2748:   PetscFunctionReturn(PETSC_SUCCESS);
2749: }

2751: PetscErrorCode DMCopyTransform(DM dm, DM newdm)
2752: {
2753:   PetscFunctionBegin;
2756:   newdm->transformCtx       = dm->transformCtx;
2757:   newdm->transformSetUp     = dm->transformSetUp;
2758:   newdm->transformDestroy   = NULL;
2759:   newdm->transformGetMatrix = dm->transformGetMatrix;
2760:   if (newdm->transformSetUp) PetscCall(DMConstructBasisTransform_Internal(newdm));
2761:   PetscFunctionReturn(PETSC_SUCCESS);
2762: }

2764: /*@C
2765:   DMGlobalToLocalHookAdd - adds a callback to be run when `DMGlobalToLocal()` is called

2767:   Logically Collective

2769:   Input Parameters:
2770: + dm        - the `DM`
2771: . beginhook - function to run at the beginning of `DMGlobalToLocalBegin()`
2772: . endhook   - function to run after `DMGlobalToLocalEnd()` has completed
2773: - ctx       - [optional] context for provide data for the hooks (may be `NULL`)

2775:   Calling sequence of `beginhook`:
2776: + dm   - global `DM`
2777: . g    - global vector
2778: . mode - mode
2779: . l    - local vector
2780: - ctx  - optional function context

2782:   Calling sequence of `endhook`:
2783: + dm   - global `DM`
2784: . g    - global vector
2785: . mode - mode
2786: . l    - local vector
2787: - ctx  - optional function context

2789:   Level: advanced

2791:   Note:
2792:   The hook may be used to provide, for example, values that represent boundary conditions in the local vectors that do not exist on the global vector.

2794: .seealso: [](ch_dmbase), `DM`, `DMGlobalToLocal()`, `DMRefineHookAdd()`, `SNESFASGetInterpolation()`, `SNESFASGetInjection()`, `PetscObjectCompose()`, `PetscContainerCreate()`
2795: @*/
2796: PetscErrorCode DMGlobalToLocalHookAdd(DM dm, PetscErrorCode (*beginhook)(DM dm, Vec g, InsertMode mode, Vec l, PetscCtx ctx), PetscErrorCode (*endhook)(DM dm, Vec g, InsertMode mode, Vec l, PetscCtx ctx), PetscCtx ctx)
2797: {
2798:   DMGlobalToLocalHookLink link, *p;

2800:   PetscFunctionBegin;
2802:   for (p = &dm->gtolhook; *p; p = &(*p)->next) { } /* Scan to the end of the current list of hooks */
2803:   PetscCall(PetscNew(&link));
2804:   link->beginhook = beginhook;
2805:   link->endhook   = endhook;
2806:   link->ctx       = ctx;
2807:   link->next      = NULL;
2808:   *p              = link;
2809:   PetscFunctionReturn(PETSC_SUCCESS);
2810: }

2812: static PetscErrorCode DMGlobalToLocalHook_Constraints(DM dm, Vec g, InsertMode mode, Vec l, PetscCtx ctx)
2813: {
2814:   Mat          cMat;
2815:   Vec          cVec, cBias;
2816:   PetscSection section, cSec;
2817:   PetscInt     pStart, pEnd, p, dof;

2819:   PetscFunctionBegin;
2820:   (void)g;
2821:   (void)ctx;
2823:   PetscCall(DMGetDefaultConstraints(dm, &cSec, &cMat, &cBias));
2824:   if (cMat && (mode == INSERT_VALUES || mode == INSERT_ALL_VALUES || mode == INSERT_BC_VALUES)) {
2825:     PetscInt nRows;

2827:     PetscCall(MatGetSize(cMat, &nRows, NULL));
2828:     if (nRows <= 0) PetscFunctionReturn(PETSC_SUCCESS);
2829:     PetscCall(DMGetLocalSection(dm, &section));
2830:     PetscCall(MatCreateVecs(cMat, NULL, &cVec));
2831:     PetscCall(MatMult(cMat, l, cVec));
2832:     if (cBias) PetscCall(VecAXPY(cVec, 1., cBias));
2833:     PetscCall(PetscSectionGetChart(cSec, &pStart, &pEnd));
2834:     for (p = pStart; p < pEnd; p++) {
2835:       PetscCall(PetscSectionGetDof(cSec, p, &dof));
2836:       if (dof) {
2837:         PetscScalar *vals;
2838:         PetscCall(VecGetValuesSection(cVec, cSec, p, &vals));
2839:         PetscCall(VecSetValuesSection(l, section, p, vals, INSERT_ALL_VALUES));
2840:       }
2841:     }
2842:     PetscCall(VecDestroy(&cVec));
2843:   }
2844:   PetscFunctionReturn(PETSC_SUCCESS);
2845: }

2847: /*@
2848:   DMGlobalToLocal - update local vectors from global vector

2850:   Neighbor-wise Collective

2852:   Input Parameters:
2853: + dm   - the `DM` object
2854: . g    - the global vector
2855: . mode - `INSERT_VALUES` or `ADD_VALUES`
2856: - l    - the local vector

2858:   Level: beginner

2860:   Notes:
2861:   The communication involved in this update can be overlapped with computation by instead using
2862:   `DMGlobalToLocalBegin()` and `DMGlobalToLocalEnd()`.

2864:   `DMGlobalToLocalHookAdd()` may be used to provide additional operations that are performed during the update process.

2866: .seealso: [](ch_dmbase), `DM`, `DMGlobalToLocalHookAdd()`, `DMCoarsen()`, `DMDestroy()`, `DMView()`, `DMCreateGlobalVector()`, `DMCreateInterpolation()`,
2867:           `DMLocalToGlobalBegin()`, `DMLocalToGlobal()`, `DMLocalToGlobalEnd()`,
2868:           `DMGlobalToLocalBegin()`, `DMGlobalToLocalEnd()`
2869: @*/
2870: PetscErrorCode DMGlobalToLocal(DM dm, Vec g, InsertMode mode, Vec l)
2871: {
2872:   PetscFunctionBegin;
2873:   PetscCall(DMGlobalToLocalBegin(dm, g, mode, l));
2874:   PetscCall(DMGlobalToLocalEnd(dm, g, mode, l));
2875:   PetscFunctionReturn(PETSC_SUCCESS);
2876: }

2878: /*@
2879:   DMGlobalToLocalBegin - Begins updating local vectors from global vector

2881:   Neighbor-wise Collective

2883:   Input Parameters:
2884: + dm   - the `DM` object
2885: . g    - the global vector
2886: . mode - `INSERT_VALUES` or `ADD_VALUES`
2887: - l    - the local vector

2889:   Level: intermediate

2891:   Notes:
2892:   The operation is completed with `DMGlobalToLocalEnd()`

2894:   One can perform local computations between the `DMGlobalToLocalBegin()` and  `DMGlobalToLocalEnd()` to overlap communication and computation

2896:   `DMGlobalToLocal()` is a short form of  `DMGlobalToLocalBegin()` and  `DMGlobalToLocalEnd()`

2898:   `DMGlobalToLocalHookAdd()` may be used to provide additional operations that are performed during the update process.

2900: .seealso: [](ch_dmbase), `DM`, `DMCoarsen()`, `DMDestroy()`, `DMView()`, `DMCreateGlobalVector()`, `DMCreateInterpolation()`, `DMGlobalToLocal()`, `DMGlobalToLocalEnd()`, `DMLocalToGlobalBegin()`, `DMLocalToGlobal()`, `DMLocalToGlobalEnd()`
2901: @*/
2902: PetscErrorCode DMGlobalToLocalBegin(DM dm, Vec g, InsertMode mode, Vec l)
2903: {
2904:   PetscSF                 sf;
2905:   DMGlobalToLocalHookLink link;

2907:   PetscFunctionBegin;
2909:   for (link = dm->gtolhook; link; link = link->next) {
2910:     if (link->beginhook) PetscCall((*link->beginhook)(dm, g, mode, l, link->ctx));
2911:   }
2912:   PetscCall(DMGetSectionSF(dm, &sf));
2913:   if (sf) {
2914:     const PetscScalar *gArray;
2915:     PetscScalar       *lArray;
2916:     PetscMemType       lmtype, gmtype;

2918:     PetscCheck(mode != ADD_VALUES, PetscObjectComm((PetscObject)dm), PETSC_ERR_ARG_OUTOFRANGE, "Invalid insertion mode %d", (int)mode);
2919:     PetscCall(VecGetArrayAndMemType(l, &lArray, &lmtype));
2920:     PetscCall(VecGetArrayReadAndMemType(g, &gArray, &gmtype));
2921:     PetscCall(PetscSFBcastWithMemTypeBegin(sf, MPIU_SCALAR, gmtype, gArray, lmtype, lArray, MPI_REPLACE));
2922:     PetscCall(VecRestoreArrayAndMemType(l, &lArray));
2923:     PetscCall(VecRestoreArrayReadAndMemType(g, &gArray));
2924:   } else {
2925:     PetscUseTypeMethod(dm, globaltolocalbegin, g, mode == INSERT_ALL_VALUES ? INSERT_VALUES : (mode == ADD_ALL_VALUES ? ADD_VALUES : mode), l);
2926:   }
2927:   PetscFunctionReturn(PETSC_SUCCESS);
2928: }

2930: /*@
2931:   DMGlobalToLocalEnd - Ends updating local vectors from global vector

2933:   Neighbor-wise Collective

2935:   Input Parameters:
2936: + dm   - the `DM` object
2937: . g    - the global vector
2938: . mode - `INSERT_VALUES` or `ADD_VALUES`
2939: - l    - the local vector

2941:   Level: intermediate

2943:   Note:
2944:   See `DMGlobalToLocalBegin()` for details.

2946: .seealso: [](ch_dmbase), `DM`, `DMCoarsen()`, `DMDestroy()`, `DMView()`, `DMCreateGlobalVector()`, `DMCreateInterpolation()`, `DMGlobalToLocal()`, `DMLocalToGlobalBegin()`, `DMLocalToGlobal()`, `DMLocalToGlobalEnd()`
2947: @*/
2948: PetscErrorCode DMGlobalToLocalEnd(DM dm, Vec g, InsertMode mode, Vec l)
2949: {
2950:   PetscSF                 sf;
2951:   const PetscScalar      *gArray;
2952:   PetscScalar            *lArray;
2953:   PetscBool               transform;
2954:   DMGlobalToLocalHookLink link;
2955:   PetscMemType            lmtype, gmtype;

2957:   PetscFunctionBegin;
2959:   PetscCall(DMGetSectionSF(dm, &sf));
2960:   PetscCall(DMHasBasisTransform(dm, &transform));
2961:   if (sf) {
2962:     PetscCheck(mode != ADD_VALUES, PetscObjectComm((PetscObject)dm), PETSC_ERR_ARG_OUTOFRANGE, "Invalid insertion mode %d", (int)mode);

2964:     PetscCall(VecGetArrayAndMemType(l, &lArray, &lmtype));
2965:     PetscCall(VecGetArrayReadAndMemType(g, &gArray, &gmtype));
2966:     PetscCall(PetscSFBcastEnd(sf, MPIU_SCALAR, gArray, lArray, MPI_REPLACE));
2967:     PetscCall(VecRestoreArrayAndMemType(l, &lArray));
2968:     PetscCall(VecRestoreArrayReadAndMemType(g, &gArray));
2969:     if (transform) PetscCall(DMPlexGlobalToLocalBasis(dm, l));
2970:   } else {
2971:     PetscUseTypeMethod(dm, globaltolocalend, g, mode == INSERT_ALL_VALUES ? INSERT_VALUES : (mode == ADD_ALL_VALUES ? ADD_VALUES : mode), l);
2972:   }
2973:   PetscCall(DMGlobalToLocalHook_Constraints(dm, g, mode, l, NULL));
2974:   for (link = dm->gtolhook; link; link = link->next) {
2975:     if (link->endhook) PetscCall((*link->endhook)(dm, g, mode, l, link->ctx));
2976:   }
2977:   PetscFunctionReturn(PETSC_SUCCESS);
2978: }

2980: /*@C
2981:   DMLocalToGlobalHookAdd - adds a callback to be run when a local to global is called

2983:   Logically Collective

2985:   Input Parameters:
2986: + dm        - the `DM`
2987: . beginhook - function to run at the beginning of `DMLocalToGlobalBegin()`
2988: . endhook   - function to run after `DMLocalToGlobalEnd()` has completed
2989: - ctx       - [optional] context for provide data for the hooks (may be `NULL`)

2991:   Calling sequence of `beginhook`:
2992: + global - global `DM`
2993: . l      - local vector
2994: . mode   - mode
2995: . g      - global vector
2996: - ctx    - optional function context

2998:   Calling sequence of `endhook`:
2999: + global - global `DM`
3000: . l      - local vector
3001: . mode   - mode
3002: . g      - global vector
3003: - ctx    - optional function context

3005:   Level: advanced

3007: .seealso: [](ch_dmbase), `DM`, `DMLocalToGlobal()`, `DMRefineHookAdd()`, `DMGlobalToLocalHookAdd()`, `SNESFASGetInterpolation()`, `SNESFASGetInjection()`, `PetscObjectCompose()`, `PetscContainerCreate()`
3008: @*/
3009: PetscErrorCode DMLocalToGlobalHookAdd(DM dm, PetscErrorCode (*beginhook)(DM global, Vec l, InsertMode mode, Vec g, PetscCtx ctx), PetscErrorCode (*endhook)(DM global, Vec l, InsertMode mode, Vec g, PetscCtx ctx), PetscCtx ctx)
3010: {
3011:   DMLocalToGlobalHookLink link, *p;

3013:   PetscFunctionBegin;
3015:   for (p = &dm->ltoghook; *p; p = &(*p)->next) { } /* Scan to the end of the current list of hooks */
3016:   PetscCall(PetscNew(&link));
3017:   link->beginhook = beginhook;
3018:   link->endhook   = endhook;
3019:   link->ctx       = ctx;
3020:   link->next      = NULL;
3021:   *p              = link;
3022:   PetscFunctionReturn(PETSC_SUCCESS);
3023: }

3025: static PetscErrorCode DMLocalToGlobalHook_Constraints(DM dm, Vec l, InsertMode mode, Vec g, PetscCtx ctx)
3026: {
3027:   PetscFunctionBegin;
3028:   (void)g;
3029:   (void)ctx;
3031:   if (mode == ADD_VALUES || mode == ADD_ALL_VALUES || mode == ADD_BC_VALUES) {
3032:     Mat          cMat;
3033:     Vec          cVec;
3034:     PetscInt     nRows;
3035:     PetscSection section, cSec;
3036:     PetscInt     pStart, pEnd, p, dof;

3038:     PetscCall(DMGetDefaultConstraints(dm, &cSec, &cMat, NULL));
3039:     if (!cMat) PetscFunctionReturn(PETSC_SUCCESS);

3041:     PetscCall(MatGetSize(cMat, &nRows, NULL));
3042:     if (nRows <= 0) PetscFunctionReturn(PETSC_SUCCESS);
3043:     PetscCall(DMGetLocalSection(dm, &section));
3044:     PetscCall(MatCreateVecs(cMat, NULL, &cVec));
3045:     PetscCall(PetscSectionGetChart(cSec, &pStart, &pEnd));
3046:     for (p = pStart; p < pEnd; p++) {
3047:       PetscCall(PetscSectionGetDof(cSec, p, &dof));
3048:       if (dof) {
3049:         PetscInt     d;
3050:         PetscScalar *vals;
3051:         PetscCall(VecGetValuesSection(l, section, p, &vals));
3052:         PetscCall(VecSetValuesSection(cVec, cSec, p, vals, mode));
3053:         /* for this to be the true transpose, we have to zero the values that
3054:          * we just extracted */
3055:         for (d = 0; d < dof; d++) vals[d] = 0.;
3056:       }
3057:     }
3058:     PetscCall(MatMultTransposeAdd(cMat, cVec, l, l));
3059:     PetscCall(VecDestroy(&cVec));
3060:   }
3061:   PetscFunctionReturn(PETSC_SUCCESS);
3062: }
3063: /*@
3064:   DMLocalToGlobal - updates global vectors from local vectors

3066:   Neighbor-wise Collective

3068:   Input Parameters:
3069: + dm   - the `DM` object
3070: . l    - the local vector
3071: . mode - if `INSERT_VALUES` then no parallel communication is used, if `ADD_VALUES` then all ghost points from the same base point accumulate into that base point.
3072: - g    - the global vector

3074:   Level: beginner

3076:   Notes:
3077:   The communication involved in this update can be overlapped with computation by using
3078:   `DMLocalToGlobalBegin()` and `DMLocalToGlobalEnd()`.

3080:   In the `ADD_VALUES` case you normally would zero the receiving vector before beginning this operation.

3082:   `INSERT_VALUES` is not supported for `DMDA`; in that case simply compute the values directly into a global vector instead of a local one.

3084:   Use `DMLocalToGlobalHookAdd()` to add additional operations that are performed on the data during the update process

3086: .seealso: [](ch_dmbase), `DM`, `DMLocalToGlobalBegin()`, `DMLocalToGlobalEnd()`, `DMCoarsen()`, `DMDestroy()`, `DMView()`, `DMCreateGlobalVector()`, `DMCreateInterpolation()`, `DMGlobalToLocal()`, `DMGlobalToLocalEnd()`, `DMGlobalToLocalBegin()`, `DMLocalToGlobalHookAdd()`, `DMGlobaToLocallHookAdd()`
3087: @*/
3088: PetscErrorCode DMLocalToGlobal(DM dm, Vec l, InsertMode mode, Vec g)
3089: {
3090:   PetscFunctionBegin;
3091:   PetscCall(DMLocalToGlobalBegin(dm, l, mode, g));
3092:   PetscCall(DMLocalToGlobalEnd(dm, l, mode, g));
3093:   PetscFunctionReturn(PETSC_SUCCESS);
3094: }

3096: /*@
3097:   DMLocalToGlobalBegin - begins updating global vectors from local vectors

3099:   Neighbor-wise Collective

3101:   Input Parameters:
3102: + dm   - the `DM` object
3103: . l    - the local vector
3104: . mode - if `INSERT_VALUES` then no parallel communication is used, if `ADD_VALUES` then all ghost points from the same base point accumulate into that base point.
3105: - g    - the global vector

3107:   Level: intermediate

3109:   Notes:
3110:   In the `ADD_VALUES` case you normally would zero the receiving vector before beginning this operation.

3112:   `INSERT_VALUES is` not supported for `DMDA`, in that case simply compute the values directly into a global vector instead of a local one.

3114:   Use `DMLocalToGlobalEnd()` to complete the communication process.

3116:   `DMLocalToGlobal()` is a short form of  `DMLocalToGlobalBegin()` and  `DMLocalToGlobalEnd()`

3118:   `DMLocalToGlobalHookAdd()` may be used to provide additional operations that are performed during the update process.

3120: .seealso: [](ch_dmbase), `DM`, `DMLocalToGlobal()`, `DMLocalToGlobalEnd()`, `DMCoarsen()`, `DMDestroy()`, `DMView()`, `DMCreateGlobalVector()`, `DMCreateInterpolation()`, `DMGlobalToLocal()`, `DMGlobalToLocalEnd()`, `DMGlobalToLocalBegin()`
3121: @*/
3122: PetscErrorCode DMLocalToGlobalBegin(DM dm, Vec l, InsertMode mode, Vec g)
3123: {
3124:   PetscSF                 sf;
3125:   PetscSection            s, gs;
3126:   DMLocalToGlobalHookLink link;
3127:   Vec                     tmpl;
3128:   const PetscScalar      *lArray;
3129:   PetscScalar            *gArray;
3130:   PetscBool               isInsert, transform, l_inplace = PETSC_FALSE, g_inplace = PETSC_FALSE;
3131:   PetscMemType            lmtype = PETSC_MEMTYPE_HOST, gmtype = PETSC_MEMTYPE_HOST;

3133:   PetscFunctionBegin;
3135:   for (link = dm->ltoghook; link; link = link->next) {
3136:     if (link->beginhook) PetscCall((*link->beginhook)(dm, l, mode, g, link->ctx));
3137:   }
3138:   PetscCall(DMLocalToGlobalHook_Constraints(dm, l, mode, g, NULL));
3139:   PetscCall(DMGetSectionSF(dm, &sf));
3140:   PetscCall(DMGetLocalSection(dm, &s));
3141:   switch (mode) {
3142:   case INSERT_VALUES:
3143:   case INSERT_ALL_VALUES:
3144:   case INSERT_BC_VALUES:
3145:     isInsert = PETSC_TRUE;
3146:     break;
3147:   case ADD_VALUES:
3148:   case ADD_ALL_VALUES:
3149:   case ADD_BC_VALUES:
3150:     isInsert = PETSC_FALSE;
3151:     break;
3152:   default:
3153:     SETERRQ(PetscObjectComm((PetscObject)dm), PETSC_ERR_ARG_OUTOFRANGE, "Invalid insertion mode %d", mode);
3154:   }
3155:   if ((sf && !isInsert) || (s && isInsert)) {
3156:     PetscCall(DMHasBasisTransform(dm, &transform));
3157:     if (transform) {
3158:       PetscCall(DMGetNamedLocalVector(dm, "__petsc_dm_transform_local_copy", &tmpl));
3159:       PetscCall(VecCopy(l, tmpl));
3160:       PetscCall(DMPlexLocalToGlobalBasis(dm, tmpl));
3161:       PetscCall(VecGetArrayRead(tmpl, &lArray));
3162:     } else if (isInsert) {
3163:       PetscCall(VecGetArrayRead(l, &lArray));
3164:     } else {
3165:       PetscCall(VecGetArrayReadAndMemType(l, &lArray, &lmtype));
3166:       l_inplace = PETSC_TRUE;
3167:     }
3168:     if (s && isInsert) {
3169:       PetscCall(VecGetArray(g, &gArray));
3170:     } else {
3171:       PetscCall(VecGetArrayAndMemType(g, &gArray, &gmtype));
3172:       g_inplace = PETSC_TRUE;
3173:     }
3174:     if (sf && !isInsert) {
3175:       PetscCall(PetscSFReduceWithMemTypeBegin(sf, MPIU_SCALAR, lmtype, lArray, gmtype, gArray, MPIU_SUM));
3176:     } else if (s && isInsert) {
3177:       PetscInt gStart, pStart, pEnd, p;

3179:       PetscCall(DMGetGlobalSection(dm, &gs));
3180:       PetscCall(PetscSectionGetChart(s, &pStart, &pEnd));
3181:       PetscCall(VecGetOwnershipRange(g, &gStart, NULL));
3182:       for (p = pStart; p < pEnd; ++p) {
3183:         PetscInt dof, gdof, cdof, gcdof, off, goff, d, e;

3185:         PetscCall(PetscSectionGetDof(s, p, &dof));
3186:         PetscCall(PetscSectionGetDof(gs, p, &gdof));
3187:         PetscCall(PetscSectionGetConstraintDof(s, p, &cdof));
3188:         PetscCall(PetscSectionGetConstraintDof(gs, p, &gcdof));
3189:         PetscCall(PetscSectionGetOffset(s, p, &off));
3190:         PetscCall(PetscSectionGetOffset(gs, p, &goff));
3191:         /* Ignore off-process data and points with no global data */
3192:         if (!gdof || goff < 0) continue;
3193:         PetscCheck(dof == gdof, PETSC_COMM_SELF, PETSC_ERR_ARG_SIZ, "Inconsistent sizes, p: %" PetscInt_FMT " dof: %" PetscInt_FMT " gdof: %" PetscInt_FMT " cdof: %" PetscInt_FMT " gcdof: %" PetscInt_FMT, p, dof, gdof, cdof, gcdof);
3194:         /* If no constraints are enforced in the global vector */
3195:         if (!gcdof) {
3196:           for (d = 0; d < dof; ++d) gArray[goff - gStart + d] = lArray[off + d];
3197:           /* If constraints are enforced in the global vector */
3198:         } else if (cdof == gcdof) {
3199:           const PetscInt *cdofs;
3200:           PetscInt        cind = 0;

3202:           PetscCall(PetscSectionGetConstraintIndices(s, p, &cdofs));
3203:           for (d = 0, e = 0; d < dof; ++d) {
3204:             if ((cind < cdof) && (d == cdofs[cind])) {
3205:               ++cind;
3206:               continue;
3207:             }
3208:             gArray[goff - gStart + e++] = lArray[off + d];
3209:           }
3210:         } else SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_SIZ, "Inconsistent sizes, p: %" PetscInt_FMT " dof: %" PetscInt_FMT " gdof: %" PetscInt_FMT " cdof: %" PetscInt_FMT " gcdof: %" PetscInt_FMT, p, dof, gdof, cdof, gcdof);
3211:       }
3212:     }
3213:     if (g_inplace) {
3214:       PetscCall(VecRestoreArrayAndMemType(g, &gArray));
3215:     } else {
3216:       PetscCall(VecRestoreArray(g, &gArray));
3217:     }
3218:     if (transform) {
3219:       PetscCall(VecRestoreArrayRead(tmpl, &lArray));
3220:       PetscCall(DMRestoreNamedLocalVector(dm, "__petsc_dm_transform_local_copy", &tmpl));
3221:     } else if (l_inplace) {
3222:       PetscCall(VecRestoreArrayReadAndMemType(l, &lArray));
3223:     } else {
3224:       PetscCall(VecRestoreArrayRead(l, &lArray));
3225:     }
3226:   } else {
3227:     PetscUseTypeMethod(dm, localtoglobalbegin, l, mode == INSERT_ALL_VALUES ? INSERT_VALUES : (mode == ADD_ALL_VALUES ? ADD_VALUES : mode), g);
3228:   }
3229:   PetscFunctionReturn(PETSC_SUCCESS);
3230: }

3232: /*@
3233:   DMLocalToGlobalEnd - updates global vectors from local vectors

3235:   Neighbor-wise Collective

3237:   Input Parameters:
3238: + dm   - the `DM` object
3239: . l    - the local vector
3240: . mode - `INSERT_VALUES` or `ADD_VALUES`
3241: - g    - the global vector

3243:   Level: intermediate

3245:   Note:
3246:   See `DMLocalToGlobalBegin()` for full details

3248: .seealso: [](ch_dmbase), `DM`, `DMLocalToGlobalBegin()`, `DMCoarsen()`, `DMDestroy()`, `DMView()`, `DMCreateGlobalVector()`, `DMCreateInterpolation()`, `DMGlobalToLocalEnd()`
3249: @*/
3250: PetscErrorCode DMLocalToGlobalEnd(DM dm, Vec l, InsertMode mode, Vec g)
3251: {
3252:   PetscSF                 sf;
3253:   PetscSection            s;
3254:   DMLocalToGlobalHookLink link;
3255:   PetscBool               isInsert, transform;

3257:   PetscFunctionBegin;
3259:   PetscCall(DMGetSectionSF(dm, &sf));
3260:   PetscCall(DMGetLocalSection(dm, &s));
3261:   switch (mode) {
3262:   case INSERT_VALUES:
3263:   case INSERT_ALL_VALUES:
3264:     isInsert = PETSC_TRUE;
3265:     break;
3266:   case ADD_VALUES:
3267:   case ADD_ALL_VALUES:
3268:     isInsert = PETSC_FALSE;
3269:     break;
3270:   default:
3271:     SETERRQ(PetscObjectComm((PetscObject)dm), PETSC_ERR_ARG_OUTOFRANGE, "Invalid insertion mode %d", mode);
3272:   }
3273:   if (sf && !isInsert) {
3274:     const PetscScalar *lArray;
3275:     PetscScalar       *gArray;
3276:     Vec                tmpl;

3278:     PetscCall(DMHasBasisTransform(dm, &transform));
3279:     if (transform) {
3280:       PetscCall(DMGetNamedLocalVector(dm, "__petsc_dm_transform_local_copy", &tmpl));
3281:       PetscCall(VecGetArrayRead(tmpl, &lArray));
3282:     } else {
3283:       PetscCall(VecGetArrayReadAndMemType(l, &lArray, NULL));
3284:     }
3285:     PetscCall(VecGetArrayAndMemType(g, &gArray, NULL));
3286:     PetscCall(PetscSFReduceEnd(sf, MPIU_SCALAR, lArray, gArray, MPIU_SUM));
3287:     if (transform) {
3288:       PetscCall(VecRestoreArrayRead(tmpl, &lArray));
3289:       PetscCall(DMRestoreNamedLocalVector(dm, "__petsc_dm_transform_local_copy", &tmpl));
3290:     } else {
3291:       PetscCall(VecRestoreArrayReadAndMemType(l, &lArray));
3292:     }
3293:     PetscCall(VecRestoreArrayAndMemType(g, &gArray));
3294:   } else if (s && isInsert) {
3295:   } else {
3296:     PetscUseTypeMethod(dm, localtoglobalend, l, mode == INSERT_ALL_VALUES ? INSERT_VALUES : (mode == ADD_ALL_VALUES ? ADD_VALUES : mode), g);
3297:   }
3298:   for (link = dm->ltoghook; link; link = link->next) {
3299:     if (link->endhook) PetscCall((*link->endhook)(dm, g, mode, l, link->ctx));
3300:   }
3301:   PetscFunctionReturn(PETSC_SUCCESS);
3302: }

3304: /*@
3305:   DMLocalToLocalBegin - Begins the process of mapping values from a local vector (that include
3306:   ghost points that contain irrelevant values) to another local vector where the ghost points
3307:   in the second are set correctly from values on other MPI ranks.

3309:   Neighbor-wise Collective

3311:   Input Parameters:
3312: + dm   - the `DM` object
3313: . g    - the original local vector
3314: - mode - one of `INSERT_VALUES` or `ADD_VALUES`

3316:   Output Parameter:
3317: . l - the local vector with correct ghost values

3319:   Level: intermediate

3321:   Note:
3322:   Must be followed by `DMLocalToLocalEnd()`.

3324: .seealso: [](ch_dmbase), `DM`, `DMLocalToLocalEnd()`, `DMCoarsen()`, `DMDestroy()`, `DMView()`, `DMCreateLocalVector()`, `DMCreateGlobalVector()`, `DMCreateInterpolation()`, `DMGlobalToLocalEnd()`, `DMLocalToGlobalBegin()`
3325: @*/
3326: PetscErrorCode DMLocalToLocalBegin(DM dm, Vec g, InsertMode mode, Vec l)
3327: {
3328:   PetscFunctionBegin;
3332:   PetscUseTypeMethod(dm, localtolocalbegin, g, mode == INSERT_ALL_VALUES ? INSERT_VALUES : (mode == ADD_ALL_VALUES ? ADD_VALUES : mode), l);
3333:   PetscFunctionReturn(PETSC_SUCCESS);
3334: }

3336: /*@
3337:   DMLocalToLocalEnd - Maps from a local vector to another local vector where the ghost
3338:   points in the second are set correctly. Must be preceded by `DMLocalToLocalBegin()`.

3340:   Neighbor-wise Collective

3342:   Input Parameters:
3343: + dm   - the `DM` object
3344: . g    - the original local vector
3345: - mode - one of `INSERT_VALUES` or `ADD_VALUES`

3347:   Output Parameter:
3348: . l - the local vector with correct ghost values

3350:   Level: intermediate

3352: .seealso: [](ch_dmbase), `DM`, `DMLocalToLocalBegin()`, `DMCoarsen()`, `DMDestroy()`, `DMView()`, `DMCreateLocalVector()`, `DMCreateGlobalVector()`, `DMCreateInterpolation()`, `DMGlobalToLocalEnd()`, `DMLocalToGlobalBegin()`
3353: @*/
3354: PetscErrorCode DMLocalToLocalEnd(DM dm, Vec g, InsertMode mode, Vec l)
3355: {
3356:   PetscFunctionBegin;
3360:   PetscUseTypeMethod(dm, localtolocalend, g, mode == INSERT_ALL_VALUES ? INSERT_VALUES : (mode == ADD_ALL_VALUES ? ADD_VALUES : mode), l);
3361:   PetscFunctionReturn(PETSC_SUCCESS);
3362: }

3364: /*@
3365:   DMCoarsen - Coarsens a `DM` object using a standard, non-adaptive coarsening of the underlying mesh

3367:   Collective

3369:   Input Parameters:
3370: + dm   - the `DM` object
3371: - comm - the communicator to contain the new `DM` object (or `MPI_COMM_NULL`)

3373:   Output Parameter:
3374: . dmc - the coarsened `DM`

3376:   Level: developer

3378: .seealso: [](ch_dmbase), `DM`, `DMRefine()`, `DMDestroy()`, `DMView()`, `DMCreateGlobalVector()`, `DMCreateInterpolation()`, `DMCreateDomainDecomposition()`,
3379:           `DMCoarsenHookAdd()`, `DMCoarsenHookRemove()`
3380: @*/
3381: PetscErrorCode DMCoarsen(DM dm, MPI_Comm comm, DM *dmc)
3382: {
3383:   DMCoarsenHookLink link;

3385:   PetscFunctionBegin;
3387:   PetscCall(PetscLogEventBegin(DM_Coarsen, dm, 0, 0, 0));
3388:   PetscUseTypeMethod(dm, coarsen, comm, dmc);
3389:   if (*dmc) {
3390:     (*dmc)->bind_below = dm->bind_below; /* Propagate this from parent DM; otherwise -dm_bind_below will be useless for multigrid cases. */
3391:     PetscCall(DMSetCoarseDM(dm, *dmc));
3392:     (*dmc)->ops->creatematrix = dm->ops->creatematrix;
3393:     PetscCall(PetscObjectCopyFortranFunctionPointers((PetscObject)dm, (PetscObject)*dmc));
3394:     (*dmc)->ctx       = dm->ctx;
3395:     (*dmc)->levelup   = dm->levelup;
3396:     (*dmc)->leveldown = dm->leveldown + 1;
3397:     PetscCall(DMSetMatType(*dmc, dm->mattype));
3398:     for (link = dm->coarsenhook; link; link = link->next) {
3399:       if (link->coarsenhook) PetscCall((*link->coarsenhook)(dm, *dmc, link->ctx));
3400:     }
3401:   }
3402:   PetscCall(PetscLogEventEnd(DM_Coarsen, dm, 0, 0, 0));
3403:   PetscCheck(*dmc, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "NULL coarse mesh produced");
3404:   PetscFunctionReturn(PETSC_SUCCESS);
3405: }

3407: /*@C
3408:   DMCoarsenHookAdd - adds a callback to be run when restricting a nonlinear problem to the coarse grid

3410:   Logically Collective; No Fortran Support

3412:   Input Parameters:
3413: + fine         - `DM` on which to run a hook when restricting to a coarser level
3414: . coarsenhook  - function to run when setting up a coarser level
3415: . restricthook - function to run to update data on coarser levels (called once per `SNESSolve()`)
3416: - ctx          - [optional] application context for provide data for the hooks (may be `NULL`)

3418:   Calling sequence of `coarsenhook`:
3419: + fine   - fine level `DM`
3420: . coarse - coarse level `DM` to restrict problem to
3421: - ctx    - optional application function context

3423:   Calling sequence of `restricthook`:
3424: + fine      - fine level `DM`
3425: . mrestrict - matrix restricting a fine-level solution to the coarse grid, usually the transpose of the interpolation
3426: . rscale    - scaling vector for restriction
3427: . inject    - matrix restricting by injection
3428: . coarse    - coarse level DM to update
3429: - ctx       - optional application function context

3431:   Level: advanced

3433:   Notes:
3434:   This function is only needed if auxiliary data, attached to the `DM` with `PetscObjectCompose()`, needs to be set up or passed from the fine `DM` to the coarse `DM`.

3436:   If this function is called multiple times, the hooks will be run in the order they are added.

3438:   In order to compose with nonlinear preconditioning without duplicating storage, the hook should be implemented to
3439:   extract the finest level information from its context (instead of from the `SNES`).

3441:   The hooks are automatically called by `DMRestrict()`

3443: .seealso: [](ch_dmbase), `DM`, `DMCoarsenHookRemove()`, `DMRefineHookAdd()`, `SNESFASGetInterpolation()`, `SNESFASGetInjection()`, `PetscObjectCompose()`, `PetscContainerCreate()`
3444: @*/
3445: PetscErrorCode DMCoarsenHookAdd(DM fine, PetscErrorCode (*coarsenhook)(DM fine, DM coarse, PetscCtx ctx), PetscErrorCode (*restricthook)(DM fine, Mat mrestrict, Vec rscale, Mat inject, DM coarse, PetscCtx ctx), PetscCtx ctx)
3446: {
3447:   DMCoarsenHookLink link, *p;

3449:   PetscFunctionBegin;
3451:   for (p = &fine->coarsenhook; *p; p = &(*p)->next) { /* Scan to the end of the current list of hooks */
3452:     if ((*p)->coarsenhook == coarsenhook && (*p)->restricthook == restricthook && (*p)->ctx == ctx) PetscFunctionReturn(PETSC_SUCCESS);
3453:   }
3454:   PetscCall(PetscNew(&link));
3455:   link->coarsenhook  = coarsenhook;
3456:   link->restricthook = restricthook;
3457:   link->ctx          = ctx;
3458:   link->next         = NULL;
3459:   *p                 = link;
3460:   PetscFunctionReturn(PETSC_SUCCESS);
3461: }

3463: /*@C
3464:   DMCoarsenHookRemove - remove a callback set with `DMCoarsenHookAdd()`

3466:   Logically Collective; No Fortran Support

3468:   Input Parameters:
3469: + fine         - `DM` on which to run a hook when restricting to a coarser level
3470: . coarsenhook  - function to run when setting up a coarser level
3471: . restricthook - function to run to update data on coarser levels
3472: - ctx          - [optional] application context for provide data for the hooks (may be `NULL`)

3474:   Calling sequence of `coarsenhook`:
3475: + fine   - fine level `DM`
3476: . coarse - coarse level `DM` to restrict problem to
3477: - ctx    - optional application function context

3479:   Calling sequence of `restricthook`:
3480: + fine    - fine level `DM`
3481: . rstrict - matrix restricting a fine-level solution to the coarse grid, usually the transpose of the interpolation
3482: . rscale  - scaling vector for restriction
3483: . inject  - matrix restricting by injection
3484: . coarse  - coarse level DM to update
3485: - ctx     - optional application function context

3487:   Level: advanced

3489:   Notes:
3490:   This function does nothing if the `coarsenhook` is not in the list.

3492:   See `DMCoarsenHookAdd()` for the calling sequence of `coarsenhook` and `restricthook`

3494: .seealso: [](ch_dmbase), `DM`, `DMCoarsenHookAdd()`, `DMRefineHookAdd()`, `SNESFASGetInterpolation()`, `SNESFASGetInjection()`, `PetscObjectCompose()`, `PetscContainerCreate()`
3495: @*/
3496: PetscErrorCode DMCoarsenHookRemove(DM fine, PetscErrorCode (*coarsenhook)(DM fine, DM coarse, PetscCtx ctx), PetscErrorCode (*restricthook)(DM fine, Mat rstrict, Vec rscale, Mat inject, DM coarse, PetscCtx ctx), PetscCtx ctx)
3497: {
3498:   DMCoarsenHookLink link, *p;

3500:   PetscFunctionBegin;
3502:   for (p = &fine->coarsenhook; *p; p = &(*p)->next) { /* Search the list of current hooks */
3503:     if ((*p)->coarsenhook == coarsenhook && (*p)->restricthook == restricthook && (*p)->ctx == ctx) {
3504:       link = *p;
3505:       *p   = link->next;
3506:       PetscCall(PetscFree(link));
3507:       break;
3508:     }
3509:   }
3510:   PetscFunctionReturn(PETSC_SUCCESS);
3511: }

3513: /*@
3514:   DMRestrict - restricts user-defined problem data to a coarser `DM` by running hooks registered by `DMCoarsenHookAdd()`

3516:   Collective if any hooks are

3518:   Input Parameters:
3519: + fine    - finer `DM` from which the data is obtained
3520: . restrct - restriction matrix, apply using `MatRestrict()`, usually the transpose of the interpolation
3521: . rscale  - scaling vector for restriction
3522: . inject  - injection matrix, also use `MatRestrict()`
3523: - coarse  - coarser `DM` to update

3525:   Level: developer

3527:   Developer Note:
3528:   Though this routine is called `DMRestrict()` the hooks are added with `DMCoarsenHookAdd()`, a consistent terminology would be better

3530: .seealso: [](ch_dmbase), `DM`, `DMCoarsenHookAdd()`, `MatRestrict()`, `DMInterpolate()`, `DMRefineHookAdd()`
3531: @*/
3532: PetscErrorCode DMRestrict(DM fine, Mat restrct, Vec rscale, Mat inject, DM coarse)
3533: {
3534:   DMCoarsenHookLink link;

3536:   PetscFunctionBegin;
3537:   for (link = fine->coarsenhook; link; link = link->next) {
3538:     if (link->restricthook) PetscCall((*link->restricthook)(fine, restrct, rscale, inject, coarse, link->ctx));
3539:   }
3540:   PetscFunctionReturn(PETSC_SUCCESS);
3541: }

3543: /*@C
3544:   DMSubDomainHookAdd - adds a callback to be run when restricting a problem to subdomain `DM`s with `DMCreateDomainDecomposition()`

3546:   Logically Collective; No Fortran Support

3548:   Input Parameters:
3549: + global       - global `DM`
3550: . ddhook       - function to run to pass data to the decomposition `DM` upon its creation
3551: . restricthook - function to run to update data on block solve (at the beginning of the block solve)
3552: - ctx          - [optional] application context for provide data for the hooks (may be `NULL`)

3554:   Calling sequence of `ddhook`:
3555: + global - global `DM`
3556: . block  - subdomain `DM`
3557: - ctx    - optional application function context

3559:   Calling sequence of `restricthook`:
3560: + global - global `DM`
3561: . out    - scatter to the outer (with ghost and overlap points) sub vector
3562: . in     - scatter to sub vector values only owned locally
3563: . block  - subdomain `DM`
3564: - ctx    - optional application function context

3566:   Level: advanced

3568:   Notes:
3569:   This function can be used if auxiliary data needs to be set up on subdomain `DM`s.

3571:   If this function is called multiple times, the hooks will be run in the order they are added.

3573:   In order to compose with nonlinear preconditioning without duplicating storage, the hook should be implemented to
3574:   extract the global information from its context (instead of from the `SNES`).

3576:   Developer Note:
3577:   It is unclear what "block solve" means within the definition of `restricthook`

3579: .seealso: [](ch_dmbase), `DM`, `DMSubDomainHookRemove()`, `DMRefineHookAdd()`, `SNESFASGetInterpolation()`, `SNESFASGetInjection()`, `PetscObjectCompose()`, `PetscContainerCreate()`, `DMCreateDomainDecomposition()`
3580: @*/
3581: PetscErrorCode DMSubDomainHookAdd(DM global, PetscErrorCode (*ddhook)(DM global, DM block, PetscCtx ctx), PetscErrorCode (*restricthook)(DM global, VecScatter out, VecScatter in, DM block, PetscCtx ctx), PetscCtx ctx)
3582: {
3583:   DMSubDomainHookLink link, *p;

3585:   PetscFunctionBegin;
3587:   for (p = &global->subdomainhook; *p; p = &(*p)->next) { /* Scan to the end of the current list of hooks */
3588:     if ((*p)->ddhook == ddhook && (*p)->restricthook == restricthook && (*p)->ctx == ctx) PetscFunctionReturn(PETSC_SUCCESS);
3589:   }
3590:   PetscCall(PetscNew(&link));
3591:   link->restricthook = restricthook;
3592:   link->ddhook       = ddhook;
3593:   link->ctx          = ctx;
3594:   link->next         = NULL;
3595:   *p                 = link;
3596:   PetscFunctionReturn(PETSC_SUCCESS);
3597: }

3599: /*@C
3600:   DMSubDomainHookRemove - remove a callback from the list to be run when restricting a problem to subdomain `DM`s with `DMCreateDomainDecomposition()`

3602:   Logically Collective; No Fortran Support

3604:   Input Parameters:
3605: + global       - global `DM`
3606: . ddhook       - function to run to pass data to the decomposition `DM` upon its creation
3607: . restricthook - function to run to update data on block solve (at the beginning of the block solve)
3608: - ctx          - [optional] application context for provide data for the hooks (may be `NULL`)

3610:   Calling sequence of `ddhook`:
3611: + dm    - global `DM`
3612: . block - subdomain `DM`
3613: - ctx   - optional application function context

3615:   Calling sequence of `restricthook`:
3616: + dm       - global `DM`
3617: . oscatter - scatter to the outer (with ghost and overlap points) sub vector
3618: . gscatter - scatter to sub vector values only owned locally
3619: . block    - subdomain `DM`
3620: - ctx      - optional application function context

3622:   Level: advanced

3624: .seealso: [](ch_dmbase), `DM`, `DMSubDomainHookAdd()`, `SNESFASGetInterpolation()`, `SNESFASGetInjection()`, `PetscObjectCompose()`, `PetscContainerCreate()`,
3625:           `DMCreateDomainDecomposition()`
3626: @*/
3627: PetscErrorCode DMSubDomainHookRemove(DM global, PetscErrorCode (*ddhook)(DM dm, DM block, PetscCtx ctx), PetscErrorCode (*restricthook)(DM dm, VecScatter oscatter, VecScatter gscatter, DM block, PetscCtx ctx), PetscCtx ctx)
3628: {
3629:   DMSubDomainHookLink link, *p;

3631:   PetscFunctionBegin;
3633:   for (p = &global->subdomainhook; *p; p = &(*p)->next) { /* Search the list of current hooks */
3634:     if ((*p)->ddhook == ddhook && (*p)->restricthook == restricthook && (*p)->ctx == ctx) {
3635:       link = *p;
3636:       *p   = link->next;
3637:       PetscCall(PetscFree(link));
3638:       break;
3639:     }
3640:   }
3641:   PetscFunctionReturn(PETSC_SUCCESS);
3642: }

3644: /*@
3645:   DMSubDomainRestrict - restricts user-defined problem data to a subdomain `DM` by running hooks registered by `DMSubDomainHookAdd()`

3647:   Collective if any hooks are

3649:   Input Parameters:
3650: + global   - The global `DM` to use as a base
3651: . oscatter - The scatter from domain global vector filling subdomain global vector with overlap
3652: . gscatter - The scatter from domain global vector filling subdomain local vector with ghosts
3653: - subdm    - The subdomain `DM` to update

3655:   Level: developer

3657: .seealso: [](ch_dmbase), `DM`, `DMCoarsenHookAdd()`, `MatRestrict()`, `DMCreateDomainDecomposition()`
3658: @*/
3659: PetscErrorCode DMSubDomainRestrict(DM global, VecScatter oscatter, VecScatter gscatter, DM subdm)
3660: {
3661:   DMSubDomainHookLink link;

3663:   PetscFunctionBegin;
3664:   for (link = global->subdomainhook; link; link = link->next) {
3665:     if (link->restricthook) PetscCall((*link->restricthook)(global, oscatter, gscatter, subdm, link->ctx));
3666:   }
3667:   PetscFunctionReturn(PETSC_SUCCESS);
3668: }

3670: /*@
3671:   DMGetCoarsenLevel - Gets the number of coarsenings that have generated this `DM`.

3673:   Not Collective

3675:   Input Parameter:
3676: . dm - the `DM` object

3678:   Output Parameter:
3679: . level - number of coarsenings

3681:   Level: developer

3683: .seealso: [](ch_dmbase), `DM`, `DMCoarsen()`, `DMSetCoarsenLevel()`, `DMGetRefineLevel()`, `DMDestroy()`, `DMView()`, `DMCreateGlobalVector()`, `DMCreateInterpolation()`
3684: @*/
3685: PetscErrorCode DMGetCoarsenLevel(DM dm, PetscInt *level)
3686: {
3687:   PetscFunctionBegin;
3689:   PetscAssertPointer(level, 2);
3690:   *level = dm->leveldown;
3691:   PetscFunctionReturn(PETSC_SUCCESS);
3692: }

3694: /*@
3695:   DMSetCoarsenLevel - Sets the number of coarsenings that have generated this `DM`.

3697:   Collective

3699:   Input Parameters:
3700: + dm    - the `DM` object
3701: - level - number of coarsenings

3703:   Level: developer

3705:   Note:
3706:   This is rarely used directly, the information is automatically set when a `DM` is created with `DMCoarsen()`

3708: .seealso: [](ch_dmbase), `DM`, `DMCoarsen()`, `DMGetCoarsenLevel()`, `DMGetRefineLevel()`, `DMDestroy()`, `DMView()`, `DMCreateGlobalVector()`, `DMCreateInterpolation()`
3709: @*/
3710: PetscErrorCode DMSetCoarsenLevel(DM dm, PetscInt level)
3711: {
3712:   PetscFunctionBegin;
3714:   dm->leveldown = level;
3715:   PetscFunctionReturn(PETSC_SUCCESS);
3716: }

3718: /*@
3719:   DMRefineHierarchy - Refines a `DM` object, all levels at once

3721:   Collective

3723:   Input Parameters:
3724: + dm      - the `DM` object
3725: - nlevels - the number of levels of refinement

3727:   Output Parameter:
3728: . dmf - the refined `DM` hierarchy

3730:   Level: developer

3732: .seealso: [](ch_dmbase), `DM`, `DMCoarsen()`, `DMCoarsenHierarchy()`, `DMDestroy()`, `DMView()`, `DMCreateGlobalVector()`, `DMCreateInterpolation()`
3733: @*/
3734: PetscErrorCode DMRefineHierarchy(DM dm, PetscInt nlevels, DM dmf[])
3735: {
3736:   PetscFunctionBegin;
3738:   PetscCheck(nlevels >= 0, PetscObjectComm((PetscObject)dm), PETSC_ERR_ARG_OUTOFRANGE, "nlevels cannot be negative");
3739:   if (nlevels == 0) PetscFunctionReturn(PETSC_SUCCESS);
3740:   PetscAssertPointer(dmf, 3);
3741:   if (dm->ops->refine && !dm->ops->refinehierarchy) {
3742:     PetscInt i;

3744:     PetscCall(DMRefine(dm, PetscObjectComm((PetscObject)dm), &dmf[0]));
3745:     for (i = 1; i < nlevels; i++) PetscCall(DMRefine(dmf[i - 1], PetscObjectComm((PetscObject)dm), &dmf[i]));
3746:   } else PetscUseTypeMethod(dm, refinehierarchy, nlevels, dmf);
3747:   PetscFunctionReturn(PETSC_SUCCESS);
3748: }

3750: /*@
3751:   DMCoarsenHierarchy - Coarsens a `DM` object, all levels at once

3753:   Collective

3755:   Input Parameters:
3756: + dm      - the `DM` object
3757: - nlevels - the number of levels of coarsening

3759:   Output Parameter:
3760: . dmc - the coarsened `DM` hierarchy

3762:   Level: developer

3764: .seealso: [](ch_dmbase), `DM`, `DMCoarsen()`, `DMRefineHierarchy()`, `DMDestroy()`, `DMView()`, `DMCreateGlobalVector()`, `DMCreateInterpolation()`
3765: @*/
3766: PetscErrorCode DMCoarsenHierarchy(DM dm, PetscInt nlevels, DM dmc[])
3767: {
3768:   PetscFunctionBegin;
3770:   PetscCheck(nlevels >= 0, PetscObjectComm((PetscObject)dm), PETSC_ERR_ARG_OUTOFRANGE, "nlevels cannot be negative");
3771:   if (nlevels == 0) PetscFunctionReturn(PETSC_SUCCESS);
3772:   PetscAssertPointer(dmc, 3);
3773:   if (dm->ops->coarsen && !dm->ops->coarsenhierarchy) {
3774:     PetscInt i;

3776:     PetscCall(DMCoarsen(dm, PetscObjectComm((PetscObject)dm), &dmc[0]));
3777:     for (i = 1; i < nlevels; i++) PetscCall(DMCoarsen(dmc[i - 1], PetscObjectComm((PetscObject)dm), &dmc[i]));
3778:   } else PetscUseTypeMethod(dm, coarsenhierarchy, nlevels, dmc);
3779:   PetscFunctionReturn(PETSC_SUCCESS);
3780: }

3782: /*@C
3783:   DMSetApplicationContextDestroy - Sets a user function that will be called to destroy the application context when the `DM` is destroyed

3785:   Logically Collective if the function is collective

3787:   Input Parameters:
3788: + dm      - the `DM` object
3789: - destroy - the destroy function, see `PetscCtxDestroyFn` for the calling sequence

3791:   Level: intermediate

3793: .seealso: [](ch_dmbase), `DM`, `DMSetApplicationContext()`, `DMView()`, `DMCreateGlobalVector()`, `DMCreateInterpolation()`, `DMCreateColoring()`, `DMCreateMatrix()`, `DMCreateMassMatrix()`,
3794:           `DMGetApplicationContext()`, `PetscCtxDestroyFn`
3795: @*/
3796: PetscErrorCode DMSetApplicationContextDestroy(DM dm, PetscCtxDestroyFn *destroy)
3797: {
3798:   PetscFunctionBegin;
3800:   dm->ctxdestroy = destroy;
3801:   PetscFunctionReturn(PETSC_SUCCESS);
3802: }

3804: /*@
3805:   DMSetApplicationContext - Set a user context into a `DM` object

3807:   Not Collective

3809:   Input Parameters:
3810: + dm  - the `DM` object
3811: - ctx - the user context

3813:   Level: intermediate

3815:   Note:
3816:   A user context is a way to pass problem specific information that is accessible whenever the `DM` is available
3817:   In a multilevel solver, the user context is shared by all the `DM` in the hierarchy; it is thus not advisable
3818:   to store objects that represent discretized quantities inside the context.

3820:   Fortran Notes:
3821:   This only works when the context is a Fortran derived type or a `PetscObject`. Declare `ctx` with
3822: .vb
3823:   type(tUsertype), pointer :: ctx
3824: .ve

3826: .seealso: [](ch_dmbase), `DM`, `DMGetApplicationContext()`, `DMView()`, `DMCreateGlobalVector()`, `DMCreateInterpolation()`, `DMCreateColoring()`, `DMCreateMatrix()`, `DMCreateMassMatrix()`
3827: @*/
3828: PetscErrorCode DMSetApplicationContext(DM dm, PetscCtx ctx)
3829: {
3830:   PetscFunctionBegin;
3832:   dm->ctx = ctx;
3833:   PetscFunctionReturn(PETSC_SUCCESS);
3834: }

3836: /*@
3837:   DMGetApplicationContext - Gets a user context from a `DM` object provided with `DMSetApplicationContext()`

3839:   Not Collective

3841:   Input Parameter:
3842: . dm - the `DM` object

3844:   Output Parameter:
3845: . ctx - a pointer to the user context

3847:   Level: intermediate

3849:   Note:
3850:   A user context is a way to pass problem specific information that is accessible whenever the `DM` is available

3852:   Fortran Notes:
3853:   This only works when the context is a Fortran derived type (it cannot be a `PetscObject`) and you **must** write a Fortran interface definition for this
3854:   function that tells the Fortran compiler the derived data type that is returned as the `ctx` argument. For example,
3855: .vb
3856:   Interface DMGetApplicationContext
3857:     Subroutine DMGetApplicationContext(dm,ctx,ierr)
3858:   #include <petsc/finclude/petscdm.h>
3859:       use petscdm
3860:       DM dm
3861:       type(tUsertype), pointer :: ctx
3862:       PetscErrorCode ierr
3863:     End Subroutine
3864:   End Interface DMGetApplicationContext
3865: .ve

3867:   The prototype for `ctx` must be
3868: .vb
3869:   type(tUsertype), pointer :: ctx
3870: .ve

3872: .seealso: [](ch_dmbase), `DM`, `DMView()`, `DMCreateGlobalVector()`, `DMCreateInterpolation()`, `DMCreateColoring()`, `DMCreateMatrix()`, `DMCreateMassMatrix()`
3873: @*/
3874: PetscErrorCode DMGetApplicationContext(DM dm, PetscCtxRt ctx)
3875: {
3876:   PetscFunctionBegin;
3878:   *(void **)ctx = dm->ctx;
3879:   PetscFunctionReturn(PETSC_SUCCESS);
3880: }

3882: /*@C
3883:   DMSetVariableBounds - sets a function to compute the lower and upper bound vectors for `SNESVI`.

3885:   Logically Collective

3887:   Input Parameters:
3888: + dm - the `DM` object
3889: - f  - the function that computes variable bounds used by `SNESVI` (use `NULL` to cancel a previous function that was set)

3891:   Calling sequence of f:
3892: + dm    - the `DM`
3893: . lower - the vector to hold the lower bounds
3894: - upper - the vector to hold the upper bounds

3896:   Level: intermediate

3898:   Developer Note:
3899:   Should be called `DMSetComputeVIBounds()` or something similar

3901: .seealso: [](ch_dmbase), `DM`, `DMComputeVariableBounds()`, `DMHasVariableBounds()`, `DMView()`, `DMCreateGlobalVector()`, `DMCreateInterpolation()`, `DMCreateColoring()`, `DMCreateMatrix()`, `DMCreateMassMatrix()`, `DMGetApplicationContext()`,
3902:          `DMSetJacobian()`
3903: @*/
3904: PetscErrorCode DMSetVariableBounds(DM dm, PetscErrorCode (*f)(DM dm, Vec lower, Vec upper))
3905: {
3906:   PetscFunctionBegin;
3908:   dm->ops->computevariablebounds = f;
3909:   PetscFunctionReturn(PETSC_SUCCESS);
3910: }

3912: /*@
3913:   DMHasVariableBounds - does the `DM` object have a variable bounds function?

3915:   Not Collective

3917:   Input Parameter:
3918: . dm - the `DM` object to destroy

3920:   Output Parameter:
3921: . flg - `PETSC_TRUE` if the variable bounds function exists

3923:   Level: developer

3925: .seealso: [](ch_dmbase), `DM`, `DMComputeVariableBounds()`, `DMView()`, `DMCreateGlobalVector()`, `DMCreateInterpolation()`, `DMCreateColoring()`, `DMCreateMatrix()`, `DMCreateMassMatrix()`, `DMGetApplicationContext()`
3926: @*/
3927: PetscErrorCode DMHasVariableBounds(DM dm, PetscBool *flg)
3928: {
3929:   PetscFunctionBegin;
3931:   PetscAssertPointer(flg, 2);
3932:   *flg = (dm->ops->computevariablebounds) ? PETSC_TRUE : PETSC_FALSE;
3933:   PetscFunctionReturn(PETSC_SUCCESS);
3934: }

3936: /*@
3937:   DMComputeVariableBounds - compute variable bounds used by `SNESVI`.

3939:   Logically Collective

3941:   Input Parameter:
3942: . dm - the `DM` object

3944:   Output Parameters:
3945: + xl - lower bound
3946: - xu - upper bound

3948:   Level: advanced

3950:   Note:
3951:   This is generally not called by users. It calls the function provided by the user with DMSetVariableBounds()

3953: .seealso: [](ch_dmbase), `DM`, `DMHasVariableBounds()`, `DMView()`, `DMCreateGlobalVector()`, `DMCreateInterpolation()`, `DMCreateColoring()`, `DMCreateMatrix()`, `DMCreateMassMatrix()`, `DMGetApplicationContext()`
3954: @*/
3955: PetscErrorCode DMComputeVariableBounds(DM dm, Vec xl, Vec xu)
3956: {
3957:   PetscFunctionBegin;
3961:   PetscUseTypeMethod(dm, computevariablebounds, xl, xu);
3962:   PetscFunctionReturn(PETSC_SUCCESS);
3963: }

3965: /*@
3966:   DMHasColoring - does the `DM` object have a method of providing a coloring?

3968:   Not Collective

3970:   Input Parameter:
3971: . dm - the DM object

3973:   Output Parameter:
3974: . flg - `PETSC_TRUE` if the `DM` has facilities for `DMCreateColoring()`.

3976:   Level: developer

3978: .seealso: [](ch_dmbase), `DM`, `DMCreateColoring()`
3979: @*/
3980: PetscErrorCode DMHasColoring(DM dm, PetscBool *flg)
3981: {
3982:   PetscFunctionBegin;
3984:   PetscAssertPointer(flg, 2);
3985:   *flg = (dm->ops->getcoloring) ? PETSC_TRUE : PETSC_FALSE;
3986:   PetscFunctionReturn(PETSC_SUCCESS);
3987: }

3989: /*@
3990:   DMHasCreateRestriction - does the `DM` object have a method of providing a restriction?

3992:   Not Collective

3994:   Input Parameter:
3995: . dm - the `DM` object

3997:   Output Parameter:
3998: . flg - `PETSC_TRUE` if the `DM` has facilities for `DMCreateRestriction()`.

4000:   Level: developer

4002: .seealso: [](ch_dmbase), `DM`, `DMCreateRestriction()`, `DMHasCreateInterpolation()`, `DMHasCreateInjection()`
4003: @*/
4004: PetscErrorCode DMHasCreateRestriction(DM dm, PetscBool *flg)
4005: {
4006:   PetscFunctionBegin;
4008:   PetscAssertPointer(flg, 2);
4009:   *flg = (dm->ops->createrestriction) ? PETSC_TRUE : PETSC_FALSE;
4010:   PetscFunctionReturn(PETSC_SUCCESS);
4011: }

4013: /*@
4014:   DMHasCreateInjection - does the `DM` object have a method of providing an injection?

4016:   Not Collective

4018:   Input Parameter:
4019: . dm - the `DM` object

4021:   Output Parameter:
4022: . flg - `PETSC_TRUE` if the `DM` has facilities for `DMCreateInjection()`.

4024:   Level: developer

4026: .seealso: [](ch_dmbase), `DM`, `DMCreateInjection()`, `DMHasCreateRestriction()`, `DMHasCreateInterpolation()`
4027: @*/
4028: PetscErrorCode DMHasCreateInjection(DM dm, PetscBool *flg)
4029: {
4030:   PetscFunctionBegin;
4032:   PetscAssertPointer(flg, 2);
4033:   if (dm->ops->hascreateinjection) PetscUseTypeMethod(dm, hascreateinjection, flg);
4034:   else *flg = (dm->ops->createinjection) ? PETSC_TRUE : PETSC_FALSE;
4035:   PetscFunctionReturn(PETSC_SUCCESS);
4036: }

4038: PetscFunctionList DMList              = NULL;
4039: PetscBool         DMRegisterAllCalled = PETSC_FALSE;

4041: /*@
4042:   DMSetType - Builds a `DM`, for a particular `DM` implementation.

4044:   Collective

4046:   Input Parameters:
4047: + dm     - The `DM` object
4048: - method - The name of the `DMType`, for example `DMDA`, `DMPLEX`

4050:   Options Database Key:
4051: . -dm_type type - Sets the `DM` type; use -help for a list of available types

4053:   Level: intermediate

4055:   Note:
4056:   Of the `DM` is constructed by directly calling a function to construct a particular `DM`, for example, `DMDACreate2d()` or `DMPlexCreateBoxMesh()`

4058: .seealso: [](ch_dmbase), `DM`, `DMType`, `DMDA`, `DMPLEX`, `DMGetType()`, `DMCreate()`, `DMDACreate2d()`
4059: @*/
4060: PetscErrorCode DMSetType(DM dm, DMType method)
4061: {
4062:   PetscErrorCode (*r)(DM);
4063:   PetscBool match;

4065:   PetscFunctionBegin;
4067:   PetscCall(PetscObjectTypeCompare((PetscObject)dm, method, &match));
4068:   if (match) PetscFunctionReturn(PETSC_SUCCESS);

4070:   PetscCall(DMRegisterAll());
4071:   PetscCall(PetscFunctionListFind(DMList, method, &r));
4072:   PetscCheck(r, PetscObjectComm((PetscObject)dm), PETSC_ERR_ARG_UNKNOWN_TYPE, "Unknown DM type: %s", method);

4074:   PetscTryTypeMethod(dm, destroy);
4075:   PetscCall(PetscMemzero(dm->ops, sizeof(*dm->ops)));
4076:   PetscCall(PetscObjectChangeTypeName((PetscObject)dm, method));
4077:   PetscCall((*r)(dm));
4078:   PetscFunctionReturn(PETSC_SUCCESS);
4079: }

4081: /*@
4082:   DMGetType - Gets the `DM` type name (as a string) from the `DM`.

4084:   Not Collective

4086:   Input Parameter:
4087: . dm - The `DM`

4089:   Output Parameter:
4090: . type - The `DMType` name

4092:   Level: intermediate

4094: .seealso: [](ch_dmbase), `DM`, `DMType`, `DMDA`, `DMPLEX`, `DMSetType()`, `DMCreate()`
4095: @*/
4096: PetscErrorCode DMGetType(DM dm, DMType *type)
4097: {
4098:   PetscFunctionBegin;
4100:   PetscAssertPointer(type, 2);
4101:   PetscCall(DMRegisterAll());
4102:   *type = ((PetscObject)dm)->type_name;
4103:   PetscFunctionReturn(PETSC_SUCCESS);
4104: }

4106: /*@
4107:   DMConvert - Converts a `DM` to another `DM`, either of the same or different type.

4109:   Collective

4111:   Input Parameters:
4112: + dm      - the `DM`
4113: - newtype - new `DM` type (use "same" for the same type)

4115:   Output Parameter:
4116: . M - pointer to new `DM`

4118:   Level: intermediate

4120:   Note:
4121:   Cannot be used to convert a sequential `DM` to a parallel or a parallel to sequential,
4122:   the MPI communicator of the generated `DM` is always the same as the communicator
4123:   of the input `DM`.

4125: .seealso: [](ch_dmbase), `DM`, `DMSetType()`, `DMCreate()`, `DMClone()`
4126: @*/
4127: PetscErrorCode DMConvert(DM dm, DMType newtype, DM *M)
4128: {
4129:   DM        B;
4130:   char      convname[256];
4131:   PetscBool sametype /*, issame */;

4133:   PetscFunctionBegin;
4136:   PetscAssertPointer(M, 3);
4137:   PetscCall(PetscObjectTypeCompare((PetscObject)dm, newtype, &sametype));
4138:   /* PetscCall(PetscStrcmp(newtype, "same", &issame)); */
4139:   if (sametype) {
4140:     *M = dm;
4141:     PetscCall(PetscObjectReference((PetscObject)dm));
4142:     PetscFunctionReturn(PETSC_SUCCESS);
4143:   } else {
4144:     PetscErrorCode (*conv)(DM, DMType, DM *) = NULL;

4146:     /*
4147:        Order of precedence:
4148:        1) See if a specialized converter is known to the current DM.
4149:        2) See if a specialized converter is known to the desired DM class.
4150:        3) See if a good general converter is registered for the desired class
4151:        4) See if a good general converter is known for the current matrix.
4152:        5) Use a really basic converter.
4153:     */

4155:     /* 1) See if a specialized converter is known to the current DM and the desired class */
4156:     PetscCall(PetscStrncpy(convname, "DMConvert_", sizeof(convname)));
4157:     PetscCall(PetscStrlcat(convname, ((PetscObject)dm)->type_name, sizeof(convname)));
4158:     PetscCall(PetscStrlcat(convname, "_", sizeof(convname)));
4159:     PetscCall(PetscStrlcat(convname, newtype, sizeof(convname)));
4160:     PetscCall(PetscStrlcat(convname, "_C", sizeof(convname)));
4161:     PetscCall(PetscObjectQueryFunction((PetscObject)dm, convname, &conv));
4162:     if (conv) goto foundconv;

4164:     /* 2)  See if a specialized converter is known to the desired DM class. */
4165:     PetscCall(DMCreate(PetscObjectComm((PetscObject)dm), &B));
4166:     PetscCall(DMSetType(B, newtype));
4167:     PetscCall(PetscStrncpy(convname, "DMConvert_", sizeof(convname)));
4168:     PetscCall(PetscStrlcat(convname, ((PetscObject)dm)->type_name, sizeof(convname)));
4169:     PetscCall(PetscStrlcat(convname, "_", sizeof(convname)));
4170:     PetscCall(PetscStrlcat(convname, newtype, sizeof(convname)));
4171:     PetscCall(PetscStrlcat(convname, "_C", sizeof(convname)));
4172:     PetscCall(PetscObjectQueryFunction((PetscObject)B, convname, &conv));
4173:     if (conv) {
4174:       PetscCall(DMDestroy(&B));
4175:       goto foundconv;
4176:     }

4178: #if 0
4179:     /* 3) See if a good general converter is registered for the desired class */
4180:     conv = B->ops->convertfrom;
4181:     PetscCall(DMDestroy(&B));
4182:     if (conv) goto foundconv;

4184:     /* 4) See if a good general converter is known for the current matrix */
4185:     if (dm->ops->convert) conv = dm->ops->convert;
4186:     if (conv) goto foundconv;
4187: #endif

4189:     /* 5) Use a really basic converter. */
4190:     SETERRQ(PetscObjectComm((PetscObject)dm), PETSC_ERR_SUP, "No conversion possible between DM types %s and %s", ((PetscObject)dm)->type_name, newtype);

4192:   foundconv:
4193:     PetscCall(PetscLogEventBegin(DM_Convert, dm, 0, 0, 0));
4194:     PetscCall((*conv)(dm, newtype, M));
4195:     /* Things that are independent of DM type: We should consult DMClone() here */
4196:     {
4197:       const PetscReal *maxCell, *Lstart, *L;

4199:       PetscCall(DMGetPeriodicity(dm, &maxCell, &Lstart, &L));
4200:       PetscCall(DMSetPeriodicity(*M, maxCell, Lstart, L));
4201:       (*M)->prealloc_only = dm->prealloc_only;
4202:       PetscCall(PetscFree((*M)->vectype));
4203:       PetscCall(PetscStrallocpy(dm->vectype, (char **)&(*M)->vectype));
4204:       PetscCall(PetscFree((*M)->mattype));
4205:       PetscCall(PetscStrallocpy(dm->mattype, (char **)&(*M)->mattype));
4206:     }
4207:     PetscCall(PetscLogEventEnd(DM_Convert, dm, 0, 0, 0));
4208:   }
4209:   PetscCall(PetscObjectStateIncrease((PetscObject)*M));
4210:   PetscFunctionReturn(PETSC_SUCCESS);
4211: }

4213: /*@C
4214:   DMRegister -  Adds a new `DM` type implementation

4216:   Not Collective, No Fortran Support

4218:   Input Parameters:
4219: + sname    - The name of a new user-defined creation routine
4220: - function - The creation routine itself

4222:   Calling sequence of function:
4223: . dm - the new `DM` that is being created

4225:   Level: advanced

4227:   Note:
4228:   `DMRegister()` may be called multiple times to add several user-defined `DM`s

4230:   Example Usage:
4231: .vb
4232:     DMRegister("my_da", MyDMCreate);
4233: .ve

4235:   Then, your `DM` type can be chosen with the procedural interface via
4236: .vb
4237:     DMCreate(MPI_Comm, DM *);
4238:     DMSetType(DM,"my_da");
4239: .ve
4240:   or at runtime via the option
4241: .vb
4242:     -da_type my_da
4243: .ve

4245: .seealso: [](ch_dmbase), `DM`, `DMType`, `DMSetType()`, `DMRegisterAll()`, `DMRegisterDestroy()`
4246: @*/
4247: PetscErrorCode DMRegister(const char sname[], PetscErrorCode (*function)(DM dm))
4248: {
4249:   PetscFunctionBegin;
4250:   PetscCall(DMInitializePackage());
4251:   PetscCall(PetscFunctionListAdd(&DMList, sname, function));
4252:   PetscFunctionReturn(PETSC_SUCCESS);
4253: }

4255: /*@
4256:   DMLoad - Loads a DM that has been stored in binary  with `DMView()`.

4258:   Collective

4260:   Input Parameters:
4261: + newdm  - the newly loaded `DM`, this needs to have been created with `DMCreate()` or
4262:            some related function before a call to `DMLoad()`.
4263: - viewer - binary file viewer, obtained from `PetscViewerBinaryOpen()` or
4264:            `PETSCVIEWERHDF5` file viewer, obtained from `PetscViewerHDF5Open()`

4266:   Level: intermediate

4268:   Notes:
4269:   The type is determined by the data in the file, any type set into the DM before this call is ignored.

4271:   Using `PETSCVIEWERHDF5` type with `PETSC_VIEWER_HDF5_PETSC` format, one can save multiple `DMPLEX`
4272:   meshes in a single HDF5 file. This in turn requires one to name the `DMPLEX` object with `PetscObjectSetName()`
4273:   before saving it with `DMView()` and before loading it with `DMLoad()` for identification of the mesh object.

4275: .seealso: [](ch_dmbase), `DM`, `PetscViewerBinaryOpen()`, `DMView()`, `MatLoad()`, `VecLoad()`
4276: @*/
4277: PetscErrorCode DMLoad(DM newdm, PetscViewer viewer)
4278: {
4279:   PetscBool isbinary, ishdf5;

4281:   PetscFunctionBegin;
4284:   PetscCall(PetscViewerCheckReadable(viewer));
4285:   PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERBINARY, &isbinary));
4286:   PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERHDF5, &ishdf5));
4287:   PetscCall(PetscLogEventBegin(DM_Load, viewer, 0, 0, 0));
4288:   if (isbinary) {
4289:     PetscInt classid;
4290:     char     type[256];

4292:     PetscCall(PetscViewerBinaryRead(viewer, &classid, 1, NULL, PETSC_INT));
4293:     PetscCheck(classid == DM_FILE_CLASSID, PetscObjectComm((PetscObject)newdm), PETSC_ERR_ARG_WRONG, "Not DM next in file, classid found %" PetscInt_FMT, classid);
4294:     PetscCall(PetscViewerBinaryRead(viewer, type, 256, NULL, PETSC_CHAR));
4295:     PetscCall(DMSetType(newdm, type));
4296:     PetscTryTypeMethod(newdm, load, viewer);
4297:   } else if (ishdf5) {
4298:     PetscTryTypeMethod(newdm, load, viewer);
4299:   } else SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Invalid viewer; open viewer with PetscViewerBinaryOpen() or PetscViewerHDF5Open()");
4300:   PetscCall(PetscLogEventEnd(DM_Load, viewer, 0, 0, 0));
4301:   PetscFunctionReturn(PETSC_SUCCESS);
4302: }

4304: /* FEM Support */

4306: PetscErrorCode DMPrintCellIndices(PetscInt c, const char name[], PetscInt len, const PetscInt x[])
4307: {
4308:   PetscInt f;

4310:   PetscFunctionBegin;
4311:   PetscCall(PetscPrintf(PETSC_COMM_SELF, "Cell %" PetscInt_FMT " Element %s\n", c, name));
4312:   for (f = 0; f < len; ++f) PetscCall(PetscPrintf(PETSC_COMM_SELF, "  | %" PetscInt_FMT " |\n", x[f]));
4313:   PetscFunctionReturn(PETSC_SUCCESS);
4314: }

4316: PetscErrorCode DMPrintCellVector(PetscInt c, const char name[], PetscInt len, const PetscScalar x[])
4317: {
4318:   PetscInt f;

4320:   PetscFunctionBegin;
4321:   PetscCall(PetscPrintf(PETSC_COMM_SELF, "Cell %" PetscInt_FMT " Element %s\n", c, name));
4322:   for (f = 0; f < len; ++f) PetscCall(PetscPrintf(PETSC_COMM_SELF, "  | %g |\n", (double)PetscRealPart(x[f])));
4323:   PetscFunctionReturn(PETSC_SUCCESS);
4324: }

4326: PetscErrorCode DMPrintCellVectorReal(PetscInt c, const char name[], PetscInt len, const PetscReal x[])
4327: {
4328:   PetscInt f;

4330:   PetscFunctionBegin;
4331:   PetscCall(PetscPrintf(PETSC_COMM_SELF, "Cell %" PetscInt_FMT " Element %s\n", c, name));
4332:   for (f = 0; f < len; ++f) PetscCall(PetscPrintf(PETSC_COMM_SELF, "  | %g |\n", (double)x[f]));
4333:   PetscFunctionReturn(PETSC_SUCCESS);
4334: }

4336: PetscErrorCode DMPrintCellMatrix(PetscInt c, const char name[], PetscInt rows, PetscInt cols, const PetscScalar A[])
4337: {
4338:   PetscInt f, g;

4340:   PetscFunctionBegin;
4341:   PetscCall(PetscPrintf(PETSC_COMM_SELF, "Cell %" PetscInt_FMT " Element %s\n", c, name));
4342:   for (f = 0; f < rows; ++f) {
4343:     PetscCall(PetscPrintf(PETSC_COMM_SELF, "  |"));
4344:     for (g = 0; g < cols; ++g) PetscCall(PetscPrintf(PETSC_COMM_SELF, " % 9.5g", (double)PetscRealPart(A[f * cols + g])));
4345:     PetscCall(PetscPrintf(PETSC_COMM_SELF, " |\n"));
4346:   }
4347:   PetscFunctionReturn(PETSC_SUCCESS);
4348: }

4350: PetscErrorCode DMPrintLocalVec(DM dm, const char name[], PetscReal tol, Vec X)
4351: {
4352:   PetscInt           localSize, bs;
4353:   PetscMPIInt        size;
4354:   Vec                x, xglob;
4355:   const PetscScalar *xarray;

4357:   PetscFunctionBegin;
4358:   PetscCallMPI(MPI_Comm_size(PetscObjectComm((PetscObject)dm), &size));
4359:   PetscCall(VecDuplicate(X, &x));
4360:   PetscCall(VecCopy(X, x));
4361:   PetscCall(VecFilter(x, tol));
4362:   PetscCall(PetscPrintf(PetscObjectComm((PetscObject)dm), "%s:\n", name));
4363:   if (size > 1) {
4364:     PetscCall(VecGetLocalSize(x, &localSize));
4365:     PetscCall(VecGetArrayRead(x, &xarray));
4366:     PetscCall(VecGetBlockSize(x, &bs));
4367:     PetscCall(VecCreateMPIWithArray(PetscObjectComm((PetscObject)dm), bs, localSize, PETSC_DETERMINE, xarray, &xglob));
4368:   } else {
4369:     xglob = x;
4370:   }
4371:   PetscCall(VecView(xglob, PETSC_VIEWER_STDOUT_(PetscObjectComm((PetscObject)dm))));
4372:   if (size > 1) {
4373:     PetscCall(VecDestroy(&xglob));
4374:     PetscCall(VecRestoreArrayRead(x, &xarray));
4375:   }
4376:   PetscCall(VecDestroy(&x));
4377:   PetscFunctionReturn(PETSC_SUCCESS);
4378: }

4380: /*@
4381:   DMGetLocalSection - Get the `PetscSection` encoding the local data layout for the `DM`.

4383:   Input Parameter:
4384: . dm - The `DM`

4386:   Output Parameter:
4387: . section - The `PetscSection`

4389:   Options Database Key:
4390: . -dm_petscsection_view - View the section created by the `DM`

4392:   Level: intermediate

4394:   Note:
4395:   This gets a borrowed reference, so the user should not destroy this `PetscSection`.

4397: .seealso: [](ch_dmbase), `DM`, `DMSetLocalSection()`, `DMGetGlobalSection()`
4398: @*/
4399: PetscErrorCode DMGetLocalSection(DM dm, PetscSection *section)
4400: {
4401:   PetscFunctionBegin;
4403:   PetscAssertPointer(section, 2);
4404:   if (!dm->localSection && dm->ops->createlocalsection) {
4405:     PetscInt d;

4407:     if (dm->setfromoptionscalled) {
4408:       PetscObject       obj = (PetscObject)dm;
4409:       PetscViewer       viewer;
4410:       PetscViewerFormat format;
4411:       PetscBool         flg;

4413:       PetscCall(PetscOptionsCreateViewer(PetscObjectComm(obj), obj->options, obj->prefix, "-dm_petscds_view", &viewer, &format, &flg));
4414:       if (flg) PetscCall(PetscViewerPushFormat(viewer, format));
4415:       for (d = 0; d < dm->Nds; ++d) {
4416:         PetscCall(PetscDSSetFromOptions(dm->probs[d].ds));
4417:         if (flg) PetscCall(PetscDSView(dm->probs[d].ds, viewer));
4418:       }
4419:       if (flg) {
4420:         PetscCall(PetscViewerFlush(viewer));
4421:         PetscCall(PetscViewerPopFormat(viewer));
4422:         PetscCall(PetscViewerDestroy(&viewer));
4423:       }
4424:     }
4425:     PetscUseTypeMethod(dm, createlocalsection);
4426:     if (dm->localSection) PetscCall(PetscObjectViewFromOptions((PetscObject)dm->localSection, NULL, "-dm_petscsection_view"));
4427:   }
4428:   *section = dm->localSection;
4429:   PetscFunctionReturn(PETSC_SUCCESS);
4430: }

4432: /*@
4433:   DMSetLocalSection - Set the `PetscSection` encoding the local data layout for the `DM`.

4435:   Input Parameters:
4436: + dm      - The `DM`
4437: - section - The `PetscSection`

4439:   Level: intermediate

4441:   Note:
4442:   Any existing Section will be destroyed

4444: .seealso: [](ch_dmbase), `DM`, `PetscSection`, `DMGetLocalSection()`, `DMSetGlobalSection()`
4445: @*/
4446: PetscErrorCode DMSetLocalSection(DM dm, PetscSection section)
4447: {
4448:   PetscInt numFields = 0;
4449:   PetscInt f;

4451:   PetscFunctionBegin;
4454:   PetscCall(PetscObjectReference((PetscObject)section));
4455:   PetscCall(PetscSectionDestroy(&dm->localSection));
4456:   dm->localSection = section;
4457:   if (section) PetscCall(PetscSectionGetNumFields(dm->localSection, &numFields));
4458:   if (numFields) {
4459:     PetscCall(DMSetNumFields(dm, numFields));
4460:     for (f = 0; f < numFields; ++f) {
4461:       PetscObject disc;
4462:       const char *name;

4464:       PetscCall(PetscSectionGetFieldName(dm->localSection, f, &name));
4465:       PetscCall(DMGetField(dm, f, NULL, &disc));
4466:       PetscCall(PetscObjectSetName(disc, name));
4467:     }
4468:   }
4469:   /* The global section and the SectionSF will be rebuilt
4470:      in the next call to DMGetGlobalSection() and DMGetSectionSF(). */
4471:   PetscCall(PetscSectionDestroy(&dm->globalSection));
4472:   PetscCall(PetscSFDestroy(&dm->sectionSF));
4473:   PetscCall(PetscSFCreate(PetscObjectComm((PetscObject)dm), &dm->sectionSF));

4475:   /* Clear scratch vectors */
4476:   PetscCall(DMClearGlobalVectors(dm));
4477:   PetscCall(DMClearLocalVectors(dm));
4478:   PetscCall(DMClearNamedGlobalVectors(dm));
4479:   PetscCall(DMClearNamedLocalVectors(dm));
4480:   PetscFunctionReturn(PETSC_SUCCESS);
4481: }

4483: /*@C
4484:   DMCreateSectionPermutation - Create a permutation of the `PetscSection` chart and optionally a block structure.

4486:   Input Parameter:
4487: . dm - The `DM`

4489:   Output Parameters:
4490: + perm        - A permutation of the mesh points in the chart
4491: - blockStarts - A high bit is set for the point that begins every block, or `NULL` for default blocking

4493:   Level: developer

4495: .seealso: [](ch_dmbase), `DM`, `PetscSection`, `DMGetLocalSection()`, `DMGetGlobalSection()`
4496: @*/
4497: PetscErrorCode DMCreateSectionPermutation(DM dm, IS *perm, PetscBT *blockStarts)
4498: {
4499:   PetscFunctionBegin;
4500:   *perm        = NULL;
4501:   *blockStarts = NULL;
4502:   PetscTryTypeMethod(dm, createsectionpermutation, perm, blockStarts);
4503:   PetscFunctionReturn(PETSC_SUCCESS);
4504: }

4506: /*@
4507:   DMGetDefaultConstraints - Get the `PetscSection` and `Mat` that specify the local constraint interpolation. See `DMSetDefaultConstraints()` for a description of the purpose of constraint interpolation.

4509:   not Collective

4511:   Input Parameter:
4512: . dm - The `DM`

4514:   Output Parameters:
4515: + section - The `PetscSection` describing the range of the constraint matrix: relates rows of the constraint matrix to dofs of the default section.  Returns `NULL` if there are no local constraints.
4516: . mat     - The `Mat` that interpolates local constraints: its width should be the layout size of the default section.  Returns `NULL` if there are no local constraints.
4517: - bias    - Vector containing bias to be added to constrained dofs

4519:   Level: advanced

4521:   Note:
4522:   This gets borrowed references, so the user should not destroy the `PetscSection`, `Mat`, or `Vec`.

4524: .seealso: [](ch_dmbase), `DM`, `DMSetDefaultConstraints()`
4525: @*/
4526: PetscErrorCode DMGetDefaultConstraints(DM dm, PetscSection *section, Mat *mat, Vec *bias)
4527: {
4528:   PetscFunctionBegin;
4530:   if (!dm->defaultConstraint.section && !dm->defaultConstraint.mat && dm->ops->createdefaultconstraints) PetscUseTypeMethod(dm, createdefaultconstraints);
4531:   if (section) *section = dm->defaultConstraint.section;
4532:   if (mat) *mat = dm->defaultConstraint.mat;
4533:   if (bias) *bias = dm->defaultConstraint.bias;
4534:   PetscFunctionReturn(PETSC_SUCCESS);
4535: }

4537: /*@
4538:   DMSetDefaultConstraints - Set the `PetscSection` and `Mat` that specify the local constraint interpolation.

4540:   Collective

4542:   Input Parameters:
4543: + dm      - The `DM`
4544: . section - The `PetscSection` describing the range of the constraint matrix: relates rows of the constraint matrix to dofs of the default section.  Must have a local communicator (`PETSC_COMM_SELF` or derivative).
4545: . mat     - The `Mat` that interpolates local constraints: its width should be the layout size of the default section:  `NULL` indicates no constraints.  Must have a local communicator (`PETSC_COMM_SELF` or derivative).
4546: - bias    - A bias vector to be added to constrained values in the local vector.  `NULL` indicates no bias.  Must have a local communicator (`PETSC_COMM_SELF` or derivative).

4548:   Level: advanced

4550:   Notes:
4551:   If a constraint matrix is specified, then it is applied during `DMGlobalToLocalEnd()` when mode is `INSERT_VALUES`, `INSERT_BC_VALUES`, or `INSERT_ALL_VALUES`.  Without a constraint matrix, the local vector l returned by `DMGlobalToLocalEnd()` contains values that have been scattered from a global vector without modification; with a constraint matrix A, l is modified by computing c = A * l + bias, l[s[i]] = c[i], where the scatter s is defined by the `PetscSection` returned by `DMGetDefaultConstraints()`.

4553:   If a constraint matrix is specified, then its adjoint is applied during `DMLocalToGlobalBegin()` when mode is `ADD_VALUES`, `ADD_BC_VALUES`, or `ADD_ALL_VALUES`.  Without a constraint matrix, the local vector l is accumulated into a global vector without modification; with a constraint matrix A, l is first modified by computing c[i] = l[s[i]], l[s[i]] = 0, l = l + A'*c, which is the adjoint of the operation described above.  Any bias, if specified, is ignored when accumulating.

4555:   This increments the references of the `PetscSection`, `Mat`, and `Vec`, so they user can destroy them.

4557: .seealso: [](ch_dmbase), `DM`, `DMGetDefaultConstraints()`
4558: @*/
4559: PetscErrorCode DMSetDefaultConstraints(DM dm, PetscSection section, Mat mat, Vec bias)
4560: {
4561:   PetscMPIInt result;

4563:   PetscFunctionBegin;
4565:   if (section) {
4567:     PetscCallMPI(MPI_Comm_compare(PETSC_COMM_SELF, PetscObjectComm((PetscObject)section), &result));
4568:     PetscCheck(result == MPI_CONGRUENT || result == MPI_IDENT, PETSC_COMM_SELF, PETSC_ERR_ARG_NOTSAMECOMM, "constraint section must have local communicator");
4569:   }
4570:   if (mat) {
4572:     PetscCallMPI(MPI_Comm_compare(PETSC_COMM_SELF, PetscObjectComm((PetscObject)mat), &result));
4573:     PetscCheck(result == MPI_CONGRUENT || result == MPI_IDENT, PETSC_COMM_SELF, PETSC_ERR_ARG_NOTSAMECOMM, "constraint matrix must have local communicator");
4574:   }
4575:   if (bias) {
4577:     PetscCallMPI(MPI_Comm_compare(PETSC_COMM_SELF, PetscObjectComm((PetscObject)bias), &result));
4578:     PetscCheck(result == MPI_CONGRUENT || result == MPI_IDENT, PETSC_COMM_SELF, PETSC_ERR_ARG_NOTSAMECOMM, "constraint bias must have local communicator");
4579:   }
4580:   PetscCall(PetscObjectReference((PetscObject)section));
4581:   PetscCall(PetscSectionDestroy(&dm->defaultConstraint.section));
4582:   dm->defaultConstraint.section = section;
4583:   PetscCall(PetscObjectReference((PetscObject)mat));
4584:   PetscCall(MatDestroy(&dm->defaultConstraint.mat));
4585:   dm->defaultConstraint.mat = mat;
4586:   PetscCall(PetscObjectReference((PetscObject)bias));
4587:   PetscCall(VecDestroy(&dm->defaultConstraint.bias));
4588:   dm->defaultConstraint.bias = bias;
4589:   PetscFunctionReturn(PETSC_SUCCESS);
4590: }

4592: #if defined(PETSC_USE_DEBUG)
4593: /*
4594:   DMDefaultSectionCheckConsistency - Check the consistentcy of the global and local sections. Generates and error if they are not consistent.

4596:   Input Parameters:
4597: + dm - The `DM`
4598: . localSection - `PetscSection` describing the local data layout
4599: - globalSection - `PetscSection` describing the global data layout

4601:   Level: intermediate

4603: .seealso: [](ch_dmbase), `DM`, `DMGetSectionSF()`, `DMSetSectionSF()`
4604: */
4605: static PetscErrorCode DMDefaultSectionCheckConsistency_Internal(DM dm, PetscSection localSection, PetscSection globalSection)
4606: {
4607:   MPI_Comm        comm;
4608:   PetscLayout     layout;
4609:   const PetscInt *ranges;
4610:   PetscInt        pStart, pEnd, p, nroots;
4611:   PetscMPIInt     size, rank;
4612:   PetscBool       valid = PETSC_TRUE, gvalid;

4614:   PetscFunctionBegin;
4615:   PetscCall(PetscObjectGetComm((PetscObject)dm, &comm));
4617:   PetscCallMPI(MPI_Comm_size(comm, &size));
4618:   PetscCallMPI(MPI_Comm_rank(comm, &rank));
4619:   PetscCall(PetscSectionGetChart(globalSection, &pStart, &pEnd));
4620:   PetscCall(PetscSectionGetConstrainedStorageSize(globalSection, &nroots));
4621:   PetscCall(PetscLayoutCreate(comm, &layout));
4622:   PetscCall(PetscLayoutSetBlockSize(layout, 1));
4623:   PetscCall(PetscLayoutSetLocalSize(layout, nroots));
4624:   PetscCall(PetscLayoutSetUp(layout));
4625:   PetscCall(PetscLayoutGetRanges(layout, &ranges));
4626:   for (p = pStart; p < pEnd; ++p) {
4627:     PetscInt dof, cdof, off, gdof, gcdof, goff, gsize, d;

4629:     PetscCall(PetscSectionGetDof(localSection, p, &dof));
4630:     PetscCall(PetscSectionGetOffset(localSection, p, &off));
4631:     PetscCall(PetscSectionGetConstraintDof(localSection, p, &cdof));
4632:     PetscCall(PetscSectionGetDof(globalSection, p, &gdof));
4633:     PetscCall(PetscSectionGetConstraintDof(globalSection, p, &gcdof));
4634:     PetscCall(PetscSectionGetOffset(globalSection, p, &goff));
4635:     if (!gdof) continue; /* Censored point */
4636:     if ((gdof < 0 ? -(gdof + 1) : gdof) != dof) {
4637:       PetscCall(PetscSynchronizedPrintf(comm, "[%d]Global dof %" PetscInt_FMT " for point %" PetscInt_FMT " not equal to local dof %" PetscInt_FMT "\n", rank, gdof, p, dof));
4638:       valid = PETSC_FALSE;
4639:     }
4640:     if (gcdof && (gcdof != cdof)) {
4641:       PetscCall(PetscSynchronizedPrintf(comm, "[%d]Global constraints %" PetscInt_FMT " for point %" PetscInt_FMT " not equal to local constraints %" PetscInt_FMT "\n", rank, gcdof, p, cdof));
4642:       valid = PETSC_FALSE;
4643:     }
4644:     if (gdof < 0) {
4645:       gsize = gdof < 0 ? -(gdof + 1) - gcdof : gdof - gcdof;
4646:       for (d = 0; d < gsize; ++d) {
4647:         PetscInt offset = -(goff + 1) + d, r;

4649:         PetscCall(PetscFindInt(offset, size + 1, ranges, &r));
4650:         if (r < 0) r = -(r + 2);
4651:         if ((r < 0) || (r >= size)) {
4652:           PetscCall(PetscSynchronizedPrintf(comm, "[%d]Point %" PetscInt_FMT " mapped to invalid process %" PetscInt_FMT " (%" PetscInt_FMT ", %" PetscInt_FMT ")\n", rank, p, r, gdof, goff));
4653:           valid = PETSC_FALSE;
4654:           break;
4655:         }
4656:       }
4657:     }
4658:   }
4659:   PetscCall(PetscLayoutDestroy(&layout));
4660:   PetscCall(PetscSynchronizedFlush(comm, NULL));
4661:   PetscCallMPI(MPIU_Allreduce(&valid, &gvalid, 1, MPI_C_BOOL, MPI_LAND, comm));
4662:   if (!gvalid) {
4663:     PetscCall(DMView(dm, NULL));
4664:     SETERRQ(comm, PETSC_ERR_ARG_WRONG, "Inconsistent local and global sections");
4665:   }
4666:   PetscFunctionReturn(PETSC_SUCCESS);
4667: }
4668: #endif

4670: PetscErrorCode DMGetIsoperiodicPointSF_Internal(DM dm, PetscSF *sf)
4671: {
4672:   PetscErrorCode (*f)(DM, PetscSF *);

4674:   PetscFunctionBegin;
4676:   PetscAssertPointer(sf, 2);
4677:   PetscCall(PetscObjectQueryFunction((PetscObject)dm, "DMGetIsoperiodicPointSF_C", &f));
4678:   if (f) PetscCall(f(dm, sf));
4679:   else *sf = dm->sf;
4680:   PetscFunctionReturn(PETSC_SUCCESS);
4681: }

4683: /*@
4684:   DMGetGlobalSection - Get the `PetscSection` encoding the global data layout for the `DM`.

4686:   Collective

4688:   Input Parameter:
4689: . dm - The `DM`

4691:   Output Parameter:
4692: . section - The `PetscSection`

4694:   Level: intermediate

4696:   Note:
4697:   This gets a borrowed reference, so the user should not destroy this `PetscSection`.

4699: .seealso: [](ch_dmbase), `DM`, `DMSetLocalSection()`, `DMGetLocalSection()`
4700: @*/
4701: PetscErrorCode DMGetGlobalSection(DM dm, PetscSection *section)
4702: {
4703:   PetscFunctionBegin;
4705:   PetscAssertPointer(section, 2);
4706:   if (!dm->globalSection) {
4707:     PetscSection s;
4708:     PetscSF      sf;

4710:     PetscCall(DMGetLocalSection(dm, &s));
4711:     PetscCheck(s, PetscObjectComm((PetscObject)dm), PETSC_ERR_ARG_WRONGSTATE, "DM must have a default PetscSection in order to create a global PetscSection");
4712:     PetscCheck(dm->sf, PetscObjectComm((PetscObject)dm), PETSC_ERR_ARG_WRONGSTATE, "DM must have a point PetscSF in order to create a global PetscSection");
4713:     PetscCall(DMGetIsoperiodicPointSF_Internal(dm, &sf));
4714:     PetscCall(PetscSectionCreateGlobalSection(s, sf, PETSC_TRUE, PETSC_FALSE, PETSC_FALSE, &dm->globalSection));
4715:     PetscCall(PetscLayoutDestroy(&dm->map));
4716:     PetscCall(PetscSectionGetValueLayout(PetscObjectComm((PetscObject)dm), dm->globalSection, &dm->map));
4717:     PetscCall(PetscSectionViewFromOptions(dm->globalSection, NULL, "-global_section_view"));
4718:   }
4719:   *section = dm->globalSection;
4720:   PetscFunctionReturn(PETSC_SUCCESS);
4721: }

4723: /*@
4724:   DMSetGlobalSection - Set the `PetscSection` encoding the global data layout for the `DM`.

4726:   Input Parameters:
4727: + dm      - The `DM`
4728: - section - The PetscSection, or `NULL`

4730:   Level: intermediate

4732:   Note:
4733:   Any existing `PetscSection` will be destroyed

4735: .seealso: [](ch_dmbase), `DM`, `DMGetGlobalSection()`, `DMSetLocalSection()`
4736: @*/
4737: PetscErrorCode DMSetGlobalSection(DM dm, PetscSection section)
4738: {
4739:   PetscFunctionBegin;
4742:   PetscCall(PetscObjectReference((PetscObject)section));
4743:   PetscCall(PetscSectionDestroy(&dm->globalSection));
4744:   dm->globalSection = section;
4745: #if defined(PETSC_USE_DEBUG)
4746:   if (section) PetscCall(DMDefaultSectionCheckConsistency_Internal(dm, dm->localSection, section));
4747: #endif
4748:   /* Clear global scratch vectors and sectionSF */
4749:   PetscCall(PetscSFDestroy(&dm->sectionSF));
4750:   PetscCall(PetscSFCreate(PetscObjectComm((PetscObject)dm), &dm->sectionSF));
4751:   PetscCall(DMClearGlobalVectors(dm));
4752:   PetscCall(DMClearNamedGlobalVectors(dm));
4753:   PetscFunctionReturn(PETSC_SUCCESS);
4754: }

4756: /*@
4757:   DMGetSectionSF - Get the `PetscSF` encoding the parallel dof overlap for the `DM`. If it has not been set,
4758:   it is created from the default `PetscSection` layouts in the `DM`.

4760:   Input Parameter:
4761: . dm - The `DM`

4763:   Output Parameter:
4764: . sf - The `PetscSF`

4766:   Level: intermediate

4768:   Note:
4769:   This gets a borrowed reference, so the user should not destroy this `PetscSF`.

4771: .seealso: [](ch_dmbase), `DM`, `DMSetSectionSF()`, `DMCreateSectionSF()`
4772: @*/
4773: PetscErrorCode DMGetSectionSF(DM dm, PetscSF *sf)
4774: {
4775:   PetscInt nroots;

4777:   PetscFunctionBegin;
4779:   PetscAssertPointer(sf, 2);
4780:   if (!dm->sectionSF) PetscCall(PetscSFCreate(PetscObjectComm((PetscObject)dm), &dm->sectionSF));
4781:   PetscCall(PetscSFGetGraph(dm->sectionSF, &nroots, NULL, NULL, NULL));
4782:   if (nroots < 0) {
4783:     PetscSection section, gSection;

4785:     PetscCall(DMGetLocalSection(dm, &section));
4786:     if (section) {
4787:       PetscCall(DMGetGlobalSection(dm, &gSection));
4788:       PetscCall(DMCreateSectionSF(dm, section, gSection));
4789:     } else {
4790:       *sf = NULL;
4791:       PetscFunctionReturn(PETSC_SUCCESS);
4792:     }
4793:   }
4794:   *sf = dm->sectionSF;
4795:   PetscFunctionReturn(PETSC_SUCCESS);
4796: }

4798: /*@
4799:   DMSetSectionSF - Set the `PetscSF` encoding the parallel dof overlap for the `DM`

4801:   Input Parameters:
4802: + dm - The `DM`
4803: - sf - The `PetscSF`

4805:   Level: intermediate

4807:   Note:
4808:   Any previous `PetscSF` is destroyed

4810: .seealso: [](ch_dmbase), `DM`, `DMGetSectionSF()`, `DMCreateSectionSF()`
4811: @*/
4812: PetscErrorCode DMSetSectionSF(DM dm, PetscSF sf)
4813: {
4814:   PetscFunctionBegin;
4817:   PetscCall(PetscObjectReference((PetscObject)sf));
4818:   PetscCall(PetscSFDestroy(&dm->sectionSF));
4819:   dm->sectionSF = sf;
4820:   PetscFunctionReturn(PETSC_SUCCESS);
4821: }

4823: /*@
4824:   DMCreateSectionSF - Create the `PetscSF` encoding the parallel dof overlap for the `DM` based upon the `PetscSection`s
4825:   describing the data layout.

4827:   Input Parameters:
4828: + dm            - The `DM`
4829: . localSection  - `PetscSection` describing the local data layout
4830: - globalSection - `PetscSection` describing the global data layout

4832:   Level: developer

4834:   Note:
4835:   One usually uses `DMGetSectionSF()` to obtain the `PetscSF`

4837:   Developer Note:
4838:   Since this routine has for arguments the two sections from the `DM` and puts the resulting `PetscSF`
4839:   directly into the `DM`, perhaps this function should not take the local and global sections as
4840:   input and should just obtain them from the `DM`? Plus PETSc creation functions return the thing
4841:   they create, this returns nothing

4843: .seealso: [](ch_dmbase), `DM`, `DMGetSectionSF()`, `DMSetSectionSF()`, `DMGetLocalSection()`, `DMGetGlobalSection()`
4844: @*/
4845: PetscErrorCode DMCreateSectionSF(DM dm, PetscSection localSection, PetscSection globalSection)
4846: {
4847:   PetscFunctionBegin;
4849:   PetscCall(PetscSFSetGraphSection(dm->sectionSF, localSection, globalSection));
4850:   PetscFunctionReturn(PETSC_SUCCESS);
4851: }

4853: /*@
4854:   DMGetPointSF - Get the `PetscSF` encoding the parallel section point overlap for the `DM`.

4856:   Not collective but the resulting `PetscSF` is collective

4858:   Input Parameter:
4859: . dm - The `DM`

4861:   Output Parameter:
4862: . sf - The `PetscSF`

4864:   Level: intermediate

4866:   Note:
4867:   This gets a borrowed reference, so the user should not destroy this `PetscSF`.

4869: .seealso: [](ch_dmbase), `DM`, `DMSetPointSF()`, `DMGetSectionSF()`, `DMSetSectionSF()`, `DMCreateSectionSF()`
4870: @*/
4871: PetscErrorCode DMGetPointSF(DM dm, PetscSF *sf)
4872: {
4873:   PetscFunctionBegin;
4875:   PetscAssertPointer(sf, 2);
4876:   *sf = dm->sf;
4877:   PetscFunctionReturn(PETSC_SUCCESS);
4878: }

4880: /*@
4881:   DMSetPointSF - Set the `PetscSF` encoding the parallel section point overlap for the `DM`.

4883:   Collective

4885:   Input Parameters:
4886: + dm - The `DM`
4887: - sf - The `PetscSF`

4889:   Level: intermediate

4891: .seealso: [](ch_dmbase), `DM`, `DMGetPointSF()`, `DMGetSectionSF()`, `DMSetSectionSF()`, `DMCreateSectionSF()`
4892: @*/
4893: PetscErrorCode DMSetPointSF(DM dm, PetscSF sf)
4894: {
4895:   PetscFunctionBegin;
4898:   PetscCall(PetscObjectReference((PetscObject)sf));
4899:   PetscCall(PetscSFDestroy(&dm->sf));
4900:   dm->sf = sf;
4901:   PetscFunctionReturn(PETSC_SUCCESS);
4902: }

4904: /*@
4905:   DMGetNaturalSF - Get the `PetscSF` encoding the map back to the original mesh ordering

4907:   Input Parameter:
4908: . dm - The `DM`

4910:   Output Parameter:
4911: . sf - The `PetscSF`

4913:   Level: intermediate

4915:   Note:
4916:   This gets a borrowed reference, so the user should not destroy this `PetscSF`.

4918: .seealso: [](ch_dmbase), `DM`, `DMSetNaturalSF()`, `DMSetUseNatural()`, `DMGetUseNatural()`, `DMPlexCreateGlobalToNaturalSF()`, `DMPlexDistribute()`
4919: @*/
4920: PetscErrorCode DMGetNaturalSF(DM dm, PetscSF *sf)
4921: {
4922:   PetscFunctionBegin;
4924:   PetscAssertPointer(sf, 2);
4925:   *sf = dm->sfNatural;
4926:   PetscFunctionReturn(PETSC_SUCCESS);
4927: }

4929: /*@
4930:   DMSetNaturalSF - Set the PetscSF encoding the map back to the original mesh ordering

4932:   Input Parameters:
4933: + dm - The DM
4934: - sf - The PetscSF

4936:   Level: intermediate

4938: .seealso: [](ch_dmbase), `DM`, `DMGetNaturalSF()`, `DMSetUseNatural()`, `DMGetUseNatural()`, `DMPlexCreateGlobalToNaturalSF()`, `DMPlexDistribute()`
4939: @*/
4940: PetscErrorCode DMSetNaturalSF(DM dm, PetscSF sf)
4941: {
4942:   PetscFunctionBegin;
4945:   PetscCall(PetscObjectReference((PetscObject)sf));
4946:   PetscCall(PetscSFDestroy(&dm->sfNatural));
4947:   dm->sfNatural = sf;
4948:   PetscFunctionReturn(PETSC_SUCCESS);
4949: }

4951: static PetscErrorCode DMSetDefaultAdjacency_Private(DM dm, PetscInt f, PetscObject disc)
4952: {
4953:   PetscClassId id;

4955:   PetscFunctionBegin;
4956:   PetscCall(PetscObjectGetClassId(disc, &id));
4957:   if (id == PETSCFE_CLASSID) PetscCall(DMSetAdjacency(dm, f, PETSC_FALSE, PETSC_TRUE));
4958:   else if (id == PETSCFV_CLASSID) PetscCall(DMSetAdjacency(dm, f, PETSC_TRUE, PETSC_FALSE));
4959:   else PetscCall(DMSetAdjacency(dm, f, PETSC_FALSE, PETSC_TRUE));
4960:   PetscFunctionReturn(PETSC_SUCCESS);
4961: }

4963: static PetscErrorCode DMFieldEnlarge_Static(DM dm, PetscInt NfNew)
4964: {
4965:   RegionField *tmpr;
4966:   PetscInt     Nf = dm->Nf, f;

4968:   PetscFunctionBegin;
4969:   if (Nf >= NfNew) PetscFunctionReturn(PETSC_SUCCESS);
4970:   PetscCall(PetscMalloc1(NfNew, &tmpr));
4971:   for (f = 0; f < Nf; ++f) tmpr[f] = dm->fields[f];
4972:   for (f = Nf; f < NfNew; ++f) {
4973:     tmpr[f].disc        = NULL;
4974:     tmpr[f].label       = NULL;
4975:     tmpr[f].avoidTensor = PETSC_FALSE;
4976:   }
4977:   PetscCall(PetscFree(dm->fields));
4978:   dm->Nf     = NfNew;
4979:   dm->fields = tmpr;
4980:   PetscFunctionReturn(PETSC_SUCCESS);
4981: }

4983: /*@
4984:   DMClearFields - Remove all fields from the `DM`

4986:   Logically Collective

4988:   Input Parameter:
4989: . dm - The `DM`

4991:   Level: intermediate

4993: .seealso: [](ch_dmbase), `DM`, `DMGetNumFields()`, `DMSetNumFields()`, `DMSetField()`
4994: @*/
4995: PetscErrorCode DMClearFields(DM dm)
4996: {
4997:   PetscInt f;

4999:   PetscFunctionBegin;
5001:   if (!dm->fields) PetscFunctionReturn(PETSC_SUCCESS); // DMDA does not use fields field in DM
5002:   for (f = 0; f < dm->Nf; ++f) {
5003:     PetscCall(PetscObjectDestroy(&dm->fields[f].disc));
5004:     PetscCall(DMLabelDestroy(&dm->fields[f].label));
5005:   }
5006:   PetscCall(PetscFree(dm->fields));
5007:   dm->fields = NULL;
5008:   dm->Nf     = 0;
5009:   PetscFunctionReturn(PETSC_SUCCESS);
5010: }

5012: /*@
5013:   DMGetNumFields - Get the number of fields in the `DM`

5015:   Not Collective

5017:   Input Parameter:
5018: . dm - The `DM`

5020:   Output Parameter:
5021: . numFields - The number of fields

5023:   Level: intermediate

5025: .seealso: [](ch_dmbase), `DM`, `DMSetNumFields()`, `DMSetField()`
5026: @*/
5027: PetscErrorCode DMGetNumFields(DM dm, PetscInt *numFields)
5028: {
5029:   PetscFunctionBegin;
5031:   PetscAssertPointer(numFields, 2);
5032:   *numFields = dm->Nf;
5033:   PetscFunctionReturn(PETSC_SUCCESS);
5034: }

5036: /*@
5037:   DMSetNumFields - Set the number of fields in the `DM`

5039:   Logically Collective

5041:   Input Parameters:
5042: + dm        - The `DM`
5043: - numFields - The number of fields

5045:   Level: intermediate

5047: .seealso: [](ch_dmbase), `DM`, `DMGetNumFields()`, `DMSetField()`
5048: @*/
5049: PetscErrorCode DMSetNumFields(DM dm, PetscInt numFields)
5050: {
5051:   PetscInt Nf, f;

5053:   PetscFunctionBegin;
5055:   PetscCall(DMGetNumFields(dm, &Nf));
5056:   for (f = Nf; f < numFields; ++f) {
5057:     PetscContainer obj;

5059:     PetscCall(PetscContainerCreate(PetscObjectComm((PetscObject)dm), &obj));
5060:     PetscCall(DMAddField(dm, NULL, (PetscObject)obj));
5061:     PetscCall(PetscContainerDestroy(&obj));
5062:   }
5063:   PetscFunctionReturn(PETSC_SUCCESS);
5064: }

5066: /*@
5067:   DMGetField - Return the `DMLabel` and discretization object for a given `DM` field

5069:   Not Collective

5071:   Input Parameters:
5072: + dm - The `DM`
5073: - f  - The field number

5075:   Output Parameters:
5076: + label - The label indicating the support of the field, or `NULL` for the entire mesh (pass in `NULL` if not needed)
5077: - disc  - The discretization object (pass in `NULL` if not needed)

5079:   Level: intermediate

5081: .seealso: [](ch_dmbase), `DM`, `DMAddField()`, `DMSetField()`
5082: @*/
5083: PetscErrorCode DMGetField(DM dm, PetscInt f, DMLabel *label, PetscObject *disc)
5084: {
5085:   PetscFunctionBegin;
5087:   PetscAssertPointer(disc, 4);
5088:   PetscCheck((f >= 0) && (f < dm->Nf), PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Field number %" PetscInt_FMT " must be in [0, %" PetscInt_FMT ")", f, dm->Nf);
5089:   if (!dm->fields) {
5090:     if (label) *label = NULL;
5091:     if (disc) *disc = NULL;
5092:   } else { // some DM such as DMDA do not have dm->fields
5093:     if (label) *label = dm->fields[f].label;
5094:     if (disc) *disc = dm->fields[f].disc;
5095:   }
5096:   PetscFunctionReturn(PETSC_SUCCESS);
5097: }

5099: /* Does not clear the DS */
5100: PetscErrorCode DMSetField_Internal(DM dm, PetscInt f, DMLabel label, PetscObject disc)
5101: {
5102:   PetscFunctionBegin;
5103:   PetscCall(DMFieldEnlarge_Static(dm, f + 1));
5104:   PetscCall(DMLabelDestroy(&dm->fields[f].label));
5105:   PetscCall(PetscObjectDestroy(&dm->fields[f].disc));
5106:   dm->fields[f].label = label;
5107:   dm->fields[f].disc  = disc;
5108:   PetscCall(PetscObjectReference((PetscObject)label));
5109:   PetscCall(PetscObjectReference(disc));
5110:   PetscFunctionReturn(PETSC_SUCCESS);
5111: }

5113: /*@
5114:   DMSetField - Set the discretization object for a given `DM` field. Usually one would call `DMAddField()` which automatically handles
5115:   the field numbering.

5117:   Logically Collective

5119:   Input Parameters:
5120: + dm    - The `DM`
5121: . f     - The field number
5122: . label - The label indicating the support of the field, or `NULL` for the entire mesh
5123: - disc  - The discretization object

5125:   Level: intermediate

5127: .seealso: [](ch_dmbase), `DM`, `DMAddField()`, `DMGetField()`
5128: @*/
5129: PetscErrorCode DMSetField(DM dm, PetscInt f, DMLabel label, PetscObject disc)
5130: {
5131:   PetscFunctionBegin;
5135:   PetscCheck(f >= 0, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Field number %" PetscInt_FMT " must be non-negative", f);
5136:   PetscCall(DMSetField_Internal(dm, f, label, disc));
5137:   PetscCall(DMSetDefaultAdjacency_Private(dm, f, disc));
5138:   PetscCall(DMClearDS(dm));
5139:   PetscFunctionReturn(PETSC_SUCCESS);
5140: }

5142: /*@
5143:   DMAddField - Add a field to a `DM` object. A field is a function space defined by of a set of discretization points (geometric entities)
5144:   and a discretization object that defines the function space associated with those points.

5146:   Logically Collective

5148:   Input Parameters:
5149: + dm    - The `DM`
5150: . label - The label indicating the support of the field, or `NULL` for the entire mesh
5151: - disc  - The discretization object

5153:   Level: intermediate

5155:   Notes:
5156:   The label already exists or will be added to the `DM` with `DMSetLabel()`.

5158:   For example, a piecewise continuous pressure field can be defined by coefficients at the cell centers of a mesh and piecewise constant functions
5159:   within each cell. Thus a specific function in the space is defined by the combination of a `Vec` containing the coefficients, a `DM` defining the
5160:   geometry entities, a `DMLabel` indicating a subset of those geometric entities, and a discretization object, such as a `PetscFE`.

5162:   Fortran Note:
5163:   Use the argument `PetscObjectCast(disc)` as the second argument

5165: .seealso: [](ch_dmbase), `DM`, `DMSetLabel()`, `DMSetField()`, `DMGetField()`, `PetscFE`
5166: @*/
5167: PetscErrorCode DMAddField(DM dm, DMLabel label, PetscObject disc)
5168: {
5169:   PetscInt Nf = dm->Nf;

5171:   PetscFunctionBegin;
5175:   PetscCall(DMFieldEnlarge_Static(dm, Nf + 1));
5176:   dm->fields[Nf].label = label;
5177:   dm->fields[Nf].disc  = disc;
5178:   PetscCall(PetscObjectReference((PetscObject)label));
5179:   PetscCall(PetscObjectReference(disc));
5180:   PetscCall(DMSetDefaultAdjacency_Private(dm, Nf, disc));
5181:   PetscCall(DMClearDS(dm));
5182:   PetscFunctionReturn(PETSC_SUCCESS);
5183: }

5185: /*@
5186:   DMSetFieldAvoidTensor - Set flag to avoid defining the field on tensor cells

5188:   Logically Collective

5190:   Input Parameters:
5191: + dm          - The `DM`
5192: . f           - The field index
5193: - avoidTensor - `PETSC_TRUE` to skip defining the field on tensor cells

5195:   Level: intermediate

5197: .seealso: [](ch_dmbase), `DM`, `DMGetFieldAvoidTensor()`, `DMSetField()`, `DMGetField()`
5198: @*/
5199: PetscErrorCode DMSetFieldAvoidTensor(DM dm, PetscInt f, PetscBool avoidTensor)
5200: {
5201:   PetscFunctionBegin;
5202:   PetscCheck((f >= 0) && (f < dm->Nf), PetscObjectComm((PetscObject)dm), PETSC_ERR_ARG_OUTOFRANGE, "Field %" PetscInt_FMT " is not in [0, %" PetscInt_FMT ")", f, dm->Nf);
5203:   dm->fields[f].avoidTensor = avoidTensor;
5204:   PetscFunctionReturn(PETSC_SUCCESS);
5205: }

5207: /*@
5208:   DMGetFieldAvoidTensor - Get flag to avoid defining the field on tensor cells

5210:   Not Collective

5212:   Input Parameters:
5213: + dm - The `DM`
5214: - f  - The field index

5216:   Output Parameter:
5217: . avoidTensor - The flag to avoid defining the field on tensor cells

5219:   Level: intermediate

5221: .seealso: [](ch_dmbase), `DM`, `DMAddField()`, `DMSetField()`, `DMGetField()`, `DMSetFieldAvoidTensor()`
5222: @*/
5223: PetscErrorCode DMGetFieldAvoidTensor(DM dm, PetscInt f, PetscBool *avoidTensor)
5224: {
5225:   PetscFunctionBegin;
5226:   PetscCheck((f >= 0) && (f < dm->Nf), PetscObjectComm((PetscObject)dm), PETSC_ERR_ARG_OUTOFRANGE, "Field %" PetscInt_FMT " is not in [0, %" PetscInt_FMT ")", f, dm->Nf);
5227:   *avoidTensor = dm->fields[f].avoidTensor;
5228:   PetscFunctionReturn(PETSC_SUCCESS);
5229: }

5231: /*@
5232:   DMCopyFields - Copy the discretizations for the `DM` into another `DM`

5234:   Collective

5236:   Input Parameters:
5237: + dm        - The `DM`
5238: . minDegree - Minimum degree for a discretization, or `PETSC_DETERMINE` for no limit
5239: - maxDegree - Maximum degree for a discretization, or `PETSC_DETERMINE` for no limit

5241:   Output Parameter:
5242: . newdm - The `DM`

5244:   Level: advanced

5246: .seealso: [](ch_dmbase), `DM`, `DMGetField()`, `DMSetField()`, `DMAddField()`, `DMCopyDS()`, `DMGetDS()`, `DMGetCellDS()`
5247: @*/
5248: PetscErrorCode DMCopyFields(DM dm, PetscInt minDegree, PetscInt maxDegree, DM newdm)
5249: {
5250:   PetscInt Nf, f;

5252:   PetscFunctionBegin;
5253:   if (dm == newdm) PetscFunctionReturn(PETSC_SUCCESS);
5254:   PetscCall(DMGetNumFields(dm, &Nf));
5255:   PetscCall(DMClearFields(newdm));
5256:   for (f = 0; f < Nf; ++f) {
5257:     DMLabel      label;
5258:     PetscObject  field;
5259:     PetscClassId id;
5260:     PetscBool    useCone, useClosure;

5262:     PetscCall(DMGetField(dm, f, &label, &field));
5263:     PetscCall(PetscObjectGetClassId(field, &id));
5264:     if (id == PETSCFE_CLASSID) {
5265:       PetscFE newfe;

5267:       PetscCall(PetscFELimitDegree((PetscFE)field, minDegree, maxDegree, &newfe));
5268:       PetscCall(DMSetField(newdm, f, label, (PetscObject)newfe));
5269:       PetscCall(PetscFEDestroy(&newfe));
5270:     } else {
5271:       PetscCall(DMSetField(newdm, f, label, field));
5272:     }
5273:     PetscCall(DMGetAdjacency(dm, f, &useCone, &useClosure));
5274:     PetscCall(DMSetAdjacency(newdm, f, useCone, useClosure));
5275:   }
5276:   // Create nullspace constructor slots
5277:   if (dm->nullspaceConstructors) {
5278:     PetscCall(PetscFree2(newdm->nullspaceConstructors, newdm->nearnullspaceConstructors));
5279:     PetscCall(PetscCalloc2(Nf, &newdm->nullspaceConstructors, Nf, &newdm->nearnullspaceConstructors));
5280:   }
5281:   PetscFunctionReturn(PETSC_SUCCESS);
5282: }

5284: /*@
5285:   DMGetAdjacency - Returns the flags for determining variable influence

5287:   Not Collective

5289:   Input Parameters:
5290: + dm - The `DM` object
5291: - f  - The field number, or `PETSC_DEFAULT` for the default adjacency

5293:   Output Parameters:
5294: + useCone    - Flag for variable influence starting with the cone operation
5295: - useClosure - Flag for variable influence using transitive closure

5297:   Level: developer

5299:   Notes:
5300: .vb
5301:      FEM:   Two points p and q are adjacent if q \in closure(star(p)),   useCone = PETSC_FALSE, useClosure = PETSC_TRUE
5302:      FVM:   Two points p and q are adjacent if q \in support(p+cone(p)), useCone = PETSC_TRUE,  useClosure = PETSC_FALSE
5303:      FVM++: Two points p and q are adjacent if q \in star(closure(p)),   useCone = PETSC_TRUE,  useClosure = PETSC_TRUE
5304: .ve
5305:   Further explanation can be found in the User's Manual Section on the Influence of Variables on One Another.

5307: .seealso: [](ch_dmbase), `DM`, `DMSetAdjacency()`, `DMGetField()`, `DMSetField()`
5308: @*/
5309: PetscErrorCode DMGetAdjacency(DM dm, PetscInt f, PetscBool *useCone, PetscBool *useClosure)
5310: {
5311:   PetscFunctionBegin;
5313:   if (useCone) PetscAssertPointer(useCone, 3);
5314:   if (useClosure) PetscAssertPointer(useClosure, 4);
5315:   if (f < 0) {
5316:     if (useCone) *useCone = dm->adjacency[0];
5317:     if (useClosure) *useClosure = dm->adjacency[1];
5318:   } else {
5319:     PetscInt Nf;

5321:     PetscCall(DMGetNumFields(dm, &Nf));
5322:     PetscCheck(f < Nf, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Field number %" PetscInt_FMT " must be in [0, %" PetscInt_FMT ")", f, Nf);
5323:     if (useCone) *useCone = dm->fields[f].adjacency[0];
5324:     if (useClosure) *useClosure = dm->fields[f].adjacency[1];
5325:   }
5326:   PetscFunctionReturn(PETSC_SUCCESS);
5327: }

5329: /*@
5330:   DMSetAdjacency - Set the flags for determining variable influence

5332:   Not Collective

5334:   Input Parameters:
5335: + dm         - The `DM` object
5336: . f          - The field number
5337: . useCone    - Flag for variable influence starting with the cone operation
5338: - useClosure - Flag for variable influence using transitive closure

5340:   Level: developer

5342:   Notes:
5343: .vb
5344:      FEM:   Two points p and q are adjacent if q \in closure(star(p)),   useCone = PETSC_FALSE, useClosure = PETSC_TRUE
5345:      FVM:   Two points p and q are adjacent if q \in support(p+cone(p)), useCone = PETSC_TRUE,  useClosure = PETSC_FALSE
5346:      FVM++: Two points p and q are adjacent if q \in star(closure(p)),   useCone = PETSC_TRUE,  useClosure = PETSC_TRUE
5347: .ve
5348:   Further explanation can be found in the User's Manual Section on the Influence of Variables on One Another.

5350: .seealso: [](ch_dmbase), `DM`, `DMGetAdjacency()`, `DMGetField()`, `DMSetField()`
5351: @*/
5352: PetscErrorCode DMSetAdjacency(DM dm, PetscInt f, PetscBool useCone, PetscBool useClosure)
5353: {
5354:   PetscFunctionBegin;
5356:   if (f < 0) {
5357:     dm->adjacency[0] = useCone;
5358:     dm->adjacency[1] = useClosure;
5359:   } else {
5360:     PetscInt Nf;

5362:     PetscCall(DMGetNumFields(dm, &Nf));
5363:     PetscCheck(f < Nf, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Field number %" PetscInt_FMT " must be in [0, %" PetscInt_FMT ")", f, Nf);
5364:     dm->fields[f].adjacency[0] = useCone;
5365:     dm->fields[f].adjacency[1] = useClosure;
5366:   }
5367:   PetscFunctionReturn(PETSC_SUCCESS);
5368: }

5370: /*@
5371:   DMGetBasicAdjacency - Returns the flags for determining variable influence, using either the default or field 0 if it is defined

5373:   Not collective

5375:   Input Parameter:
5376: . dm - The `DM` object

5378:   Output Parameters:
5379: + useCone    - Flag for variable influence starting with the cone operation
5380: - useClosure - Flag for variable influence using transitive closure

5382:   Level: developer

5384:   Notes:
5385: .vb
5386:      FEM:   Two points p and q are adjacent if q \in closure(star(p)),   useCone = PETSC_FALSE, useClosure = PETSC_TRUE
5387:      FVM:   Two points p and q are adjacent if q \in support(p+cone(p)), useCone = PETSC_TRUE,  useClosure = PETSC_FALSE
5388:      FVM++: Two points p and q are adjacent if q \in star(closure(p)),   useCone = PETSC_TRUE,  useClosure = PETSC_TRUE
5389: .ve

5391: .seealso: [](ch_dmbase), `DM`, `DMSetBasicAdjacency()`, `DMGetField()`, `DMSetField()`
5392: @*/
5393: PetscErrorCode DMGetBasicAdjacency(DM dm, PetscBool *useCone, PetscBool *useClosure)
5394: {
5395:   PetscInt Nf;

5397:   PetscFunctionBegin;
5399:   if (useCone) PetscAssertPointer(useCone, 2);
5400:   if (useClosure) PetscAssertPointer(useClosure, 3);
5401:   PetscCall(DMGetNumFields(dm, &Nf));
5402:   if (!Nf) {
5403:     PetscCall(DMGetAdjacency(dm, PETSC_DEFAULT, useCone, useClosure));
5404:   } else {
5405:     PetscCall(DMGetAdjacency(dm, 0, useCone, useClosure));
5406:   }
5407:   PetscFunctionReturn(PETSC_SUCCESS);
5408: }

5410: /*@
5411:   DMSetBasicAdjacency - Set the flags for determining variable influence, using either the default or field 0 if it is defined

5413:   Not Collective

5415:   Input Parameters:
5416: + dm         - The `DM` object
5417: . useCone    - Flag for variable influence starting with the cone operation
5418: - useClosure - Flag for variable influence using transitive closure

5420:   Level: developer

5422:   Notes:
5423: .vb
5424:      FEM:   Two points p and q are adjacent if q \in closure(star(p)),   useCone = PETSC_FALSE, useClosure = PETSC_TRUE
5425:      FVM:   Two points p and q are adjacent if q \in support(p+cone(p)), useCone = PETSC_TRUE,  useClosure = PETSC_FALSE
5426:      FVM++: Two points p and q are adjacent if q \in star(closure(p)),   useCone = PETSC_TRUE,  useClosure = PETSC_TRUE
5427: .ve

5429: .seealso: [](ch_dmbase), `DM`, `DMGetBasicAdjacency()`, `DMGetField()`, `DMSetField()`
5430: @*/
5431: PetscErrorCode DMSetBasicAdjacency(DM dm, PetscBool useCone, PetscBool useClosure)
5432: {
5433:   PetscInt Nf;

5435:   PetscFunctionBegin;
5437:   PetscCall(DMGetNumFields(dm, &Nf));
5438:   if (!Nf) {
5439:     PetscCall(DMSetAdjacency(dm, PETSC_DEFAULT, useCone, useClosure));
5440:   } else {
5441:     PetscCall(DMSetAdjacency(dm, 0, useCone, useClosure));
5442:   }
5443:   PetscFunctionReturn(PETSC_SUCCESS);
5444: }

5446: PetscErrorCode DMCompleteBCLabels_Internal(DM dm)
5447: {
5448:   DM           plex;
5449:   DMLabel     *labels, *glabels;
5450:   const char **names;
5451:   char        *sendNames, *recvNames;
5452:   PetscInt     Nds, s, maxLabels = 0, maxLen = 0, gmaxLen, Nl = 0, gNl, l, gl, m;
5453:   size_t       len;
5454:   MPI_Comm     comm;
5455:   PetscMPIInt  rank, size, p, *counts, *displs;

5457:   PetscFunctionBegin;
5458:   PetscCall(PetscObjectGetComm((PetscObject)dm, &comm));
5459:   PetscCallMPI(MPI_Comm_size(comm, &size));
5460:   PetscCallMPI(MPI_Comm_rank(comm, &rank));
5461:   PetscCall(DMGetNumDS(dm, &Nds));
5462:   for (s = 0; s < Nds; ++s) {
5463:     PetscDS  dsBC;
5464:     PetscInt numBd;

5466:     PetscCall(DMGetRegionNumDS(dm, s, NULL, NULL, &dsBC, NULL));
5467:     PetscCall(PetscDSGetNumBoundary(dsBC, &numBd));
5468:     maxLabels += numBd;
5469:   }
5470:   PetscCall(PetscCalloc1(maxLabels, &labels));
5471:   /* Get list of labels to be completed */
5472:   for (s = 0; s < Nds; ++s) {
5473:     PetscDS  dsBC;
5474:     PetscInt numBd, bd;

5476:     PetscCall(DMGetRegionNumDS(dm, s, NULL, NULL, &dsBC, NULL));
5477:     PetscCall(PetscDSGetNumBoundary(dsBC, &numBd));
5478:     for (bd = 0; bd < numBd; ++bd) {
5479:       DMLabel      label;
5480:       PetscInt     field;
5481:       PetscObject  obj;
5482:       PetscClassId id;

5484:       PetscCall(PetscDSGetBoundary(dsBC, bd, NULL, NULL, NULL, &label, NULL, NULL, &field, NULL, NULL, NULL, NULL, NULL));
5485:       PetscCall(DMGetField(dm, field, NULL, &obj));
5486:       PetscCall(PetscObjectGetClassId(obj, &id));
5487:       if (id != PETSCFE_CLASSID || !label) continue;
5488:       for (l = 0; l < Nl; ++l)
5489:         if (labels[l] == label) break;
5490:       if (l == Nl) labels[Nl++] = label;
5491:     }
5492:   }
5493:   /* Get label names */
5494:   PetscCall(PetscMalloc1(Nl, &names));
5495:   for (l = 0; l < Nl; ++l) PetscCall(PetscObjectGetName((PetscObject)labels[l], &names[l]));
5496:   for (l = 0; l < Nl; ++l) {
5497:     PetscCall(PetscStrlen(names[l], &len));
5498:     maxLen = PetscMax(maxLen, (PetscInt)len + 2);
5499:   }
5500:   PetscCall(PetscFree(labels));
5501:   PetscCallMPI(MPIU_Allreduce(&maxLen, &gmaxLen, 1, MPIU_INT, MPI_MAX, comm));
5502:   PetscCall(PetscCalloc1(Nl * gmaxLen, &sendNames));
5503:   for (l = 0; l < Nl; ++l) PetscCall(PetscStrncpy(&sendNames[gmaxLen * l], names[l], gmaxLen));
5504:   PetscCall(PetscFree(names));
5505:   /* Put all names on all processes */
5506:   PetscCall(PetscCalloc2(size, &counts, size + 1, &displs));
5507:   PetscCallMPI(MPI_Allgather(&Nl, 1, MPI_INT, counts, 1, MPI_INT, comm));
5508:   for (p = 0; p < size; ++p) displs[p + 1] = displs[p] + counts[p];
5509:   gNl = displs[size];
5510:   for (p = 0; p < size; ++p) {
5511:     counts[p] *= gmaxLen;
5512:     displs[p] *= gmaxLen;
5513:   }
5514:   PetscCall(PetscCalloc2(gNl * gmaxLen, &recvNames, gNl, &glabels));
5515:   PetscCallMPI(MPI_Allgatherv(sendNames, counts[rank], MPI_CHAR, recvNames, counts, displs, MPI_CHAR, comm));
5516:   PetscCall(PetscFree2(counts, displs));
5517:   PetscCall(PetscFree(sendNames));
5518:   for (l = 0, gl = 0; l < gNl; ++l) {
5519:     PetscCall(DMGetLabel(dm, &recvNames[l * gmaxLen], &glabels[gl]));
5520:     PetscCheck(glabels[gl], PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Label %s missing on rank %d", &recvNames[l * gmaxLen], rank);
5521:     for (m = 0; m < gl; ++m)
5522:       if (glabels[m] == glabels[gl]) goto next_label;
5523:     PetscCall(DMConvert(dm, DMPLEX, &plex));
5524:     PetscCall(DMPlexLabelComplete(plex, glabels[gl]));
5525:     PetscCall(DMDestroy(&plex));
5526:     ++gl;
5527:   next_label:
5528:     continue;
5529:   }
5530:   PetscCall(PetscFree2(recvNames, glabels));
5531:   PetscFunctionReturn(PETSC_SUCCESS);
5532: }

5534: static PetscErrorCode DMDSEnlarge_Static(DM dm, PetscInt NdsNew)
5535: {
5536:   DMSpace *tmpd;
5537:   PetscInt Nds = dm->Nds, s;

5539:   PetscFunctionBegin;
5540:   if (Nds >= NdsNew) PetscFunctionReturn(PETSC_SUCCESS);
5541:   PetscCall(PetscMalloc1(NdsNew, &tmpd));
5542:   for (s = 0; s < Nds; ++s) tmpd[s] = dm->probs[s];
5543:   for (s = Nds; s < NdsNew; ++s) {
5544:     tmpd[s].ds     = NULL;
5545:     tmpd[s].label  = NULL;
5546:     tmpd[s].fields = NULL;
5547:   }
5548:   PetscCall(PetscFree(dm->probs));
5549:   dm->Nds   = NdsNew;
5550:   dm->probs = tmpd;
5551:   PetscFunctionReturn(PETSC_SUCCESS);
5552: }

5554: /*@
5555:   DMGetNumDS - Get the number of discrete systems in the `DM`

5557:   Not Collective

5559:   Input Parameter:
5560: . dm - The `DM`

5562:   Output Parameter:
5563: . Nds - The number of `PetscDS` objects

5565:   Level: intermediate

5567: .seealso: [](ch_dmbase), `DM`, `DMGetDS()`, `DMGetCellDS()`
5568: @*/
5569: PetscErrorCode DMGetNumDS(DM dm, PetscInt *Nds)
5570: {
5571:   PetscFunctionBegin;
5573:   PetscAssertPointer(Nds, 2);
5574:   *Nds = dm->Nds;
5575:   PetscFunctionReturn(PETSC_SUCCESS);
5576: }

5578: /*@
5579:   DMClearDS - Remove all discrete systems from the `DM`

5581:   Logically Collective

5583:   Input Parameter:
5584: . dm - The `DM`

5586:   Level: intermediate

5588: .seealso: [](ch_dmbase), `DM`, `DMGetNumDS()`, `DMGetDS()`, `DMSetField()`
5589: @*/
5590: PetscErrorCode DMClearDS(DM dm)
5591: {
5592:   PetscInt s;

5594:   PetscFunctionBegin;
5596:   for (s = 0; s < dm->Nds; ++s) {
5597:     PetscCall(PetscDSDestroy(&dm->probs[s].ds));
5598:     PetscCall(PetscDSDestroy(&dm->probs[s].dsIn));
5599:     PetscCall(DMLabelDestroy(&dm->probs[s].label));
5600:     PetscCall(ISDestroy(&dm->probs[s].fields));
5601:   }
5602:   PetscCall(PetscFree(dm->probs));
5603:   dm->probs = NULL;
5604:   dm->Nds   = 0;
5605:   PetscFunctionReturn(PETSC_SUCCESS);
5606: }

5608: /*@
5609:   DMGetDS - Get the default `PetscDS`

5611:   Not Collective

5613:   Input Parameter:
5614: . dm - The `DM`

5616:   Output Parameter:
5617: . ds - The default `PetscDS`

5619:   Level: intermediate

5621:   Note:
5622:   The `ds` is owned by the `dm` and should not be destroyed directly.

5624: .seealso: [](ch_dmbase), `DM`, `DMGetCellDS()`, `DMGetRegionDS()`
5625: @*/
5626: PetscErrorCode DMGetDS(DM dm, PetscDS *ds)
5627: {
5628:   PetscFunctionBeginHot;
5630:   PetscAssertPointer(ds, 2);
5631:   PetscCheck(dm->Nds > 0, PetscObjectComm((PetscObject)dm), PETSC_ERR_ARG_WRONGSTATE, "Need to call DMCreateDS() before calling DMGetDS()");
5632:   *ds = dm->probs[0].ds;
5633:   PetscFunctionReturn(PETSC_SUCCESS);
5634: }

5636: /*@
5637:   DMGetCellDS - Get the `PetscDS` defined on a given cell

5639:   Not Collective

5641:   Input Parameters:
5642: + dm    - The `DM`
5643: - point - Cell for the `PetscDS`

5645:   Output Parameters:
5646: + ds   - The `PetscDS` defined on the given cell
5647: - dsIn - The `PetscDS` for input on the given cell, or `NULL` if the same ds

5649:   Level: developer

5651: .seealso: [](ch_dmbase), `DM`, `DMGetDS()`, `DMSetRegionDS()`
5652: @*/
5653: PetscErrorCode DMGetCellDS(DM dm, PetscInt point, PetscDS *ds, PetscDS *dsIn)
5654: {
5655:   PetscDS  dsDef = NULL;
5656:   PetscInt s;

5658:   PetscFunctionBeginHot;
5660:   if (ds) PetscAssertPointer(ds, 3);
5661:   if (dsIn) PetscAssertPointer(dsIn, 4);
5662:   PetscCheck(point >= 0, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Mesh point cannot be negative: %" PetscInt_FMT, point);
5663:   if (ds) *ds = NULL;
5664:   if (dsIn) *dsIn = NULL;
5665:   for (s = 0; s < dm->Nds; ++s) {
5666:     PetscInt val;

5668:     if (!dm->probs[s].label) {
5669:       dsDef = dm->probs[s].ds;
5670:     } else {
5671:       PetscCall(DMLabelGetValue(dm->probs[s].label, point, &val));
5672:       if (val >= 0) {
5673:         if (ds) *ds = dm->probs[s].ds;
5674:         if (dsIn) *dsIn = dm->probs[s].dsIn;
5675:         break;
5676:       }
5677:     }
5678:   }
5679:   if (ds && !*ds) *ds = dsDef;
5680:   PetscFunctionReturn(PETSC_SUCCESS);
5681: }

5683: /*@
5684:   DMGetRegionDS - Get the `PetscDS` for a given mesh region, defined by a `DMLabel`

5686:   Not Collective

5688:   Input Parameters:
5689: + dm    - The `DM`
5690: - label - The `DMLabel` defining the mesh region, or `NULL` for the entire mesh

5692:   Output Parameters:
5693: + fields - The `IS` containing the `DM` field numbers for the fields in this `PetscDS`, or `NULL`
5694: . ds     - The `PetscDS` defined on the given region, or `NULL`
5695: - dsIn   - The `PetscDS` for input in the given region, or `NULL`

5697:   Level: advanced

5699:   Note:
5700:   If a non-`NULL` label is given, but there is no `PetscDS` on that specific label,
5701:   the `PetscDS` for the full domain (if present) is returned. Returns with
5702:   fields = `NULL` and ds = `NULL` if there is no `PetscDS` for the full domain.

5704: .seealso: [](ch_dmbase), `DM`, `DMGetRegionNumDS()`, `DMSetRegionDS()`, `DMGetDS()`, `DMGetCellDS()`
5705: @*/
5706: PetscErrorCode DMGetRegionDS(DM dm, DMLabel label, IS *fields, PetscDS *ds, PetscDS *dsIn)
5707: {
5708:   PetscInt Nds = dm->Nds, s;

5710:   PetscFunctionBegin;
5713:   if (fields) {
5714:     PetscAssertPointer(fields, 3);
5715:     *fields = NULL;
5716:   }
5717:   if (ds) {
5718:     PetscAssertPointer(ds, 4);
5719:     *ds = NULL;
5720:   }
5721:   if (dsIn) {
5722:     PetscAssertPointer(dsIn, 5);
5723:     *dsIn = NULL;
5724:   }
5725:   for (s = 0; s < Nds; ++s) {
5726:     if (dm->probs[s].label == label || !dm->probs[s].label) {
5727:       if (fields) *fields = dm->probs[s].fields;
5728:       if (ds) *ds = dm->probs[s].ds;
5729:       if (dsIn) *dsIn = dm->probs[s].dsIn;
5730:       if (dm->probs[s].label) PetscFunctionReturn(PETSC_SUCCESS);
5731:     }
5732:   }
5733:   PetscFunctionReturn(PETSC_SUCCESS);
5734: }

5736: /*@
5737:   DMSetRegionDS - Set the `PetscDS` for a given mesh region, defined by a `DMLabel`

5739:   Collective

5741:   Input Parameters:
5742: + dm     - The `DM`
5743: . label  - The `DMLabel` defining the mesh region, or `NULL` for the entire mesh
5744: . fields - The `IS` containing the `DM` field numbers for the fields in this `PetscDS`, or `NULL` for all fields
5745: . ds     - The `PetscDS` defined on the given region
5746: - dsIn   - The `PetscDS` for input on the given cell, or `NULL` if it is the same `PetscDS`

5748:   Level: advanced

5750:   Note:
5751:   If the label has a `PetscDS` defined, it will be replaced. Otherwise, it will be added to the `DM`. If the `PetscDS` is replaced,
5752:   the fields argument is ignored.

5754: .seealso: [](ch_dmbase), `DM`, `DMGetRegionDS()`, `DMSetRegionNumDS()`, `DMGetDS()`, `DMGetCellDS()`
5755: @*/
5756: PetscErrorCode DMSetRegionDS(DM dm, DMLabel label, IS fields, PetscDS ds, PetscDS dsIn)
5757: {
5758:   PetscInt Nds = dm->Nds, s;

5760:   PetscFunctionBegin;
5766:   for (s = 0; s < Nds; ++s) {
5767:     if (dm->probs[s].label == label) {
5768:       PetscCall(PetscDSDestroy(&dm->probs[s].ds));
5769:       PetscCall(PetscDSDestroy(&dm->probs[s].dsIn));
5770:       dm->probs[s].ds   = ds;
5771:       dm->probs[s].dsIn = dsIn;
5772:       PetscFunctionReturn(PETSC_SUCCESS);
5773:     }
5774:   }
5775:   PetscCall(DMDSEnlarge_Static(dm, Nds + 1));
5776:   PetscCall(PetscObjectReference((PetscObject)label));
5777:   PetscCall(PetscObjectReference((PetscObject)fields));
5778:   PetscCall(PetscObjectReference((PetscObject)ds));
5779:   PetscCall(PetscObjectReference((PetscObject)dsIn));
5780:   if (!label) {
5781:     /* Put the NULL label at the front, so it is returned as the default */
5782:     for (s = Nds - 1; s >= 0; --s) dm->probs[s + 1] = dm->probs[s];
5783:     Nds = 0;
5784:   }
5785:   dm->probs[Nds].label  = label;
5786:   dm->probs[Nds].fields = fields;
5787:   dm->probs[Nds].ds     = ds;
5788:   dm->probs[Nds].dsIn   = dsIn;
5789:   PetscFunctionReturn(PETSC_SUCCESS);
5790: }

5792: /*@
5793:   DMGetRegionNumDS - Get the `PetscDS` for a given mesh region, defined by the region number

5795:   Not Collective

5797:   Input Parameters:
5798: + dm  - The `DM`
5799: - num - The region number, in [0, Nds)

5801:   Output Parameters:
5802: + label  - The region label, or `NULL`
5803: . fields - The `IS` containing the `DM` field numbers for the fields in this `PetscDS`, or `NULL`
5804: . ds     - The `PetscDS` defined on the given region, or `NULL`
5805: - dsIn   - The `PetscDS` for input in the given region, or `NULL`

5807:   Level: advanced

5809: .seealso: [](ch_dmbase), `DM`, `DMGetRegionDS()`, `DMSetRegionDS()`, `DMGetDS()`, `DMGetCellDS()`
5810: @*/
5811: PetscErrorCode DMGetRegionNumDS(DM dm, PetscInt num, DMLabel *label, IS *fields, PetscDS *ds, PetscDS *dsIn)
5812: {
5813:   PetscInt Nds;

5815:   PetscFunctionBegin;
5817:   PetscCall(DMGetNumDS(dm, &Nds));
5818:   PetscCheck((num >= 0) && (num < Nds), PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Region number %" PetscInt_FMT " is not in [0, %" PetscInt_FMT ")", num, Nds);
5819:   if (label) {
5820:     PetscAssertPointer(label, 3);
5821:     *label = dm->probs[num].label;
5822:   }
5823:   if (fields) {
5824:     PetscAssertPointer(fields, 4);
5825:     *fields = dm->probs[num].fields;
5826:   }
5827:   if (ds) {
5828:     PetscAssertPointer(ds, 5);
5829:     *ds = dm->probs[num].ds;
5830:   }
5831:   if (dsIn) {
5832:     PetscAssertPointer(dsIn, 6);
5833:     *dsIn = dm->probs[num].dsIn;
5834:   }
5835:   PetscFunctionReturn(PETSC_SUCCESS);
5836: }

5838: /*@
5839:   DMSetRegionNumDS - Set the `PetscDS` for a given mesh region, defined by the region number

5841:   Not Collective

5843:   Input Parameters:
5844: + dm     - The `DM`
5845: . num    - The region number, in [0, Nds)
5846: . label  - The region label, or `NULL`
5847: . fields - The `IS` containing the `DM` field numbers for the fields in this `PetscDS`, or `NULL` to prevent setting
5848: . ds     - The `PetscDS` defined on the given region, or `NULL` to prevent setting
5849: - dsIn   - The `PetscDS` for input on the given cell, or `NULL` if it is the same `PetscDS`

5851:   Level: advanced

5853: .seealso: [](ch_dmbase), `DM`, `DMGetRegionDS()`, `DMSetRegionDS()`, `DMGetDS()`, `DMGetCellDS()`
5854: @*/
5855: PetscErrorCode DMSetRegionNumDS(DM dm, PetscInt num, DMLabel label, IS fields, PetscDS ds, PetscDS dsIn)
5856: {
5857:   PetscInt Nds;

5859:   PetscFunctionBegin;
5862:   PetscCall(DMGetNumDS(dm, &Nds));
5863:   PetscCheck((num >= 0) && (num < Nds), PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Region number %" PetscInt_FMT " is not in [0, %" PetscInt_FMT ")", num, Nds);
5864:   PetscCall(PetscObjectReference((PetscObject)label));
5865:   PetscCall(DMLabelDestroy(&dm->probs[num].label));
5866:   dm->probs[num].label = label;
5867:   if (fields) {
5869:     PetscCall(PetscObjectReference((PetscObject)fields));
5870:     PetscCall(ISDestroy(&dm->probs[num].fields));
5871:     dm->probs[num].fields = fields;
5872:   }
5873:   if (ds) {
5875:     PetscCall(PetscObjectReference((PetscObject)ds));
5876:     PetscCall(PetscDSDestroy(&dm->probs[num].ds));
5877:     dm->probs[num].ds = ds;
5878:   }
5879:   if (dsIn) {
5881:     PetscCall(PetscObjectReference((PetscObject)dsIn));
5882:     PetscCall(PetscDSDestroy(&dm->probs[num].dsIn));
5883:     dm->probs[num].dsIn = dsIn;
5884:   }
5885:   PetscFunctionReturn(PETSC_SUCCESS);
5886: }

5888: /*@
5889:   DMFindRegionNum - Find the region number for a given `PetscDS`, or -1 if it is not found.

5891:   Not Collective

5893:   Input Parameters:
5894: + dm - The `DM`
5895: - ds - The `PetscDS` defined on the given region

5897:   Output Parameter:
5898: . num - The region number, in [0, Nds), or -1 if not found

5900:   Level: advanced

5902: .seealso: [](ch_dmbase), `DM`, `DMGetRegionNumDS()`, `DMGetRegionDS()`, `DMSetRegionDS()`, `DMGetDS()`, `DMGetCellDS()`
5903: @*/
5904: PetscErrorCode DMFindRegionNum(DM dm, PetscDS ds, PetscInt *num)
5905: {
5906:   PetscInt Nds, n;

5908:   PetscFunctionBegin;
5911:   PetscAssertPointer(num, 3);
5912:   PetscCall(DMGetNumDS(dm, &Nds));
5913:   for (n = 0; n < Nds; ++n)
5914:     if (ds == dm->probs[n].ds) break;
5915:   if (n >= Nds) *num = -1;
5916:   else *num = n;
5917:   PetscFunctionReturn(PETSC_SUCCESS);
5918: }

5920: /*@
5921:   DMCreateFEDefault - Create a `PetscFE` based on the celltype for the mesh

5923:   Not Collective

5925:   Input Parameters:
5926: + dm     - The `DM`
5927: . Nc     - The number of components for the field
5928: . prefix - The options prefix for the output `PetscFE`, or `NULL`
5929: - qorder - The quadrature order or `PETSC_DETERMINE` to use `PetscSpace` polynomial degree

5931:   Output Parameter:
5932: . fem - The `PetscFE`

5934:   Level: intermediate

5936:   Note:
5937:   This is a convenience method that just calls `PetscFECreateByCell()` underneath.

5939: .seealso: [](ch_dmbase), `DM`, `PetscFECreateByCell()`, `DMAddField()`, `DMCreateDS()`, `DMGetCellDS()`, `DMGetRegionDS()`
5940: @*/
5941: PetscErrorCode DMCreateFEDefault(DM dm, PetscInt Nc, const char prefix[], PetscInt qorder, PetscFE *fem)
5942: {
5943:   DMPolytopeType ct;
5944:   PetscInt       dim, cStart;

5946:   PetscFunctionBegin;
5949:   if (prefix) PetscAssertPointer(prefix, 3);
5951:   PetscAssertPointer(fem, 5);
5952:   PetscCall(DMGetDimension(dm, &dim));
5953:   PetscCall(DMPlexGetHeightStratum(dm, 0, &cStart, NULL));
5954:   PetscCall(DMPlexGetCellType(dm, cStart, &ct));
5955:   PetscCall(PetscFECreateByCell(PETSC_COMM_SELF, dim, Nc, ct, prefix, qorder, fem));
5956:   PetscFunctionReturn(PETSC_SUCCESS);
5957: }

5959: /*@
5960:   DMCreateDS - Create the discrete systems for the `DM` based upon the fields added to the `DM`

5962:   Collective

5964:   Input Parameter:
5965: . dm - The `DM`

5967:   Options Database Key:
5968: . -dm_petscds_view - View all the `PetscDS` objects in this `DM`

5970:   Level: intermediate

5972:   Developer Note:
5973:   The name of this function is wrong. Create functions always return the created object as one of the arguments.

5975: .seealso: [](ch_dmbase), `DM`, `DMSetField`, `DMAddField()`, `DMGetDS()`, `DMGetCellDS()`, `DMGetRegionDS()`, `DMSetRegionDS()`
5976: @*/
5977: PetscErrorCode DMCreateDS(DM dm)
5978: {
5979:   MPI_Comm  comm;
5980:   PetscDS   dsDef;
5981:   DMLabel  *labelSet;
5982:   PetscInt  dE, Nf = dm->Nf, f, s, Nl, l, Ndef, k;
5983:   PetscBool doSetup = PETSC_TRUE, flg;

5985:   PetscFunctionBegin;
5987:   if (!dm->fields) PetscFunctionReturn(PETSC_SUCCESS);
5988:   PetscCall(PetscObjectGetComm((PetscObject)dm, &comm));
5989:   PetscCall(DMGetCoordinateDim(dm, &dE));
5990:   // Create nullspace constructor slots
5991:   PetscCall(PetscFree2(dm->nullspaceConstructors, dm->nearnullspaceConstructors));
5992:   PetscCall(PetscCalloc2(Nf, &dm->nullspaceConstructors, Nf, &dm->nearnullspaceConstructors));
5993:   /* Determine how many regions we have */
5994:   PetscCall(PetscMalloc1(Nf, &labelSet));
5995:   Nl   = 0;
5996:   Ndef = 0;
5997:   for (f = 0; f < Nf; ++f) {
5998:     DMLabel  label = dm->fields[f].label;
5999:     PetscInt l;

6001: #ifdef PETSC_HAVE_LIBCEED
6002:     /* Move CEED context to discretizations */
6003:     {
6004:       PetscClassId id;

6006:       PetscCall(PetscObjectGetClassId(dm->fields[f].disc, &id));
6007:       if (id == PETSCFE_CLASSID) {
6008:         Ceed ceed;

6010:         PetscCall(DMGetCeed(dm, &ceed));
6011:         PetscCall(PetscFESetCeed((PetscFE)dm->fields[f].disc, ceed));
6012:       }
6013:     }
6014: #endif
6015:     if (!label) {
6016:       ++Ndef;
6017:       continue;
6018:     }
6019:     for (l = 0; l < Nl; ++l)
6020:       if (label == labelSet[l]) break;
6021:     if (l < Nl) continue;
6022:     labelSet[Nl++] = label;
6023:   }
6024:   /* Create default DS if there are no labels to intersect with */
6025:   PetscCall(DMGetRegionDS(dm, NULL, NULL, &dsDef, NULL));
6026:   if (!dsDef && Ndef && !Nl) {
6027:     IS        fields;
6028:     PetscInt *fld, nf;

6030:     for (f = 0, nf = 0; f < Nf; ++f)
6031:       if (!dm->fields[f].label) ++nf;
6032:     PetscCheck(nf, comm, PETSC_ERR_PLIB, "All fields have labels, but we are trying to create a default DS");
6033:     PetscCall(PetscMalloc1(nf, &fld));
6034:     for (f = 0, nf = 0; f < Nf; ++f)
6035:       if (!dm->fields[f].label) fld[nf++] = f;
6036:     PetscCall(ISCreate(PETSC_COMM_SELF, &fields));
6037:     PetscCall(PetscObjectSetOptionsPrefix((PetscObject)fields, "dm_fields_"));
6038:     PetscCall(ISSetType(fields, ISGENERAL));
6039:     PetscCall(ISGeneralSetIndices(fields, nf, fld, PETSC_OWN_POINTER));

6041:     PetscCall(PetscDSCreate(PETSC_COMM_SELF, &dsDef));
6042:     PetscCall(DMSetRegionDS(dm, NULL, fields, dsDef, NULL));
6043:     PetscCall(PetscDSDestroy(&dsDef));
6044:     PetscCall(ISDestroy(&fields));
6045:   }
6046:   PetscCall(DMGetRegionDS(dm, NULL, NULL, &dsDef, NULL));
6047:   if (dsDef) PetscCall(PetscDSSetCoordinateDimension(dsDef, dE));
6048:   /* Intersect labels with default fields */
6049:   if (Ndef && Nl) {
6050:     DM              plex;
6051:     DMLabel         cellLabel;
6052:     IS              fieldIS, allcellIS, defcellIS = NULL;
6053:     PetscInt       *fields;
6054:     const PetscInt *cells;
6055:     PetscInt        depth, nf = 0, n, c;

6057:     PetscCall(DMConvert(dm, DMPLEX, &plex));
6058:     PetscCall(DMPlexGetDepth(plex, &depth));
6059:     PetscCall(DMGetStratumIS(plex, "dim", depth, &allcellIS));
6060:     if (!allcellIS) PetscCall(DMGetStratumIS(plex, "depth", depth, &allcellIS));
6061:     /* TODO This looks like it only works for one label */
6062:     for (l = 0; l < Nl; ++l) {
6063:       DMLabel label = labelSet[l];
6064:       IS      pointIS;

6066:       PetscCall(ISDestroy(&defcellIS));
6067:       PetscCall(DMLabelGetStratumIS(label, 1, &pointIS));
6068:       PetscCall(ISDifference(allcellIS, pointIS, &defcellIS));
6069:       PetscCall(ISDestroy(&pointIS));
6070:     }
6071:     PetscCall(ISDestroy(&allcellIS));

6073:     PetscCall(DMLabelCreate(PETSC_COMM_SELF, "defaultCells", &cellLabel));
6074:     PetscCall(ISGetLocalSize(defcellIS, &n));
6075:     PetscCall(ISGetIndices(defcellIS, &cells));
6076:     for (c = 0; c < n; ++c) PetscCall(DMLabelSetValue(cellLabel, cells[c], 1));
6077:     PetscCall(ISRestoreIndices(defcellIS, &cells));
6078:     PetscCall(ISDestroy(&defcellIS));
6079:     PetscCall(DMPlexLabelComplete(plex, cellLabel));

6081:     PetscCall(PetscMalloc1(Ndef, &fields));
6082:     for (f = 0; f < Nf; ++f)
6083:       if (!dm->fields[f].label) fields[nf++] = f;
6084:     PetscCall(ISCreate(PETSC_COMM_SELF, &fieldIS));
6085:     PetscCall(PetscObjectSetOptionsPrefix((PetscObject)fieldIS, "dm_fields_"));
6086:     PetscCall(ISSetType(fieldIS, ISGENERAL));
6087:     PetscCall(ISGeneralSetIndices(fieldIS, nf, fields, PETSC_OWN_POINTER));

6089:     PetscCall(PetscDSCreate(PETSC_COMM_SELF, &dsDef));
6090:     PetscCall(DMSetRegionDS(dm, cellLabel, fieldIS, dsDef, NULL));
6091:     PetscCall(PetscDSSetCoordinateDimension(dsDef, dE));
6092:     PetscCall(DMLabelDestroy(&cellLabel));
6093:     PetscCall(PetscDSDestroy(&dsDef));
6094:     PetscCall(ISDestroy(&fieldIS));
6095:     PetscCall(DMDestroy(&plex));
6096:   }
6097:   /* Create label DSes
6098:      - WE ONLY SUPPORT IDENTICAL OR DISJOINT LABELS
6099:   */
6100:   /* TODO Should check that labels are disjoint */
6101:   for (l = 0; l < Nl; ++l) {
6102:     DMLabel   label = labelSet[l];
6103:     PetscDS   ds, dsIn = NULL;
6104:     IS        fields;
6105:     PetscInt *fld, nf;

6107:     PetscCall(PetscDSCreate(PETSC_COMM_SELF, &ds));
6108:     for (f = 0, nf = 0; f < Nf; ++f)
6109:       if (label == dm->fields[f].label || !dm->fields[f].label) ++nf;
6110:     PetscCall(PetscMalloc1(nf, &fld));
6111:     for (f = 0, nf = 0; f < Nf; ++f)
6112:       if (label == dm->fields[f].label || !dm->fields[f].label) fld[nf++] = f;
6113:     PetscCall(ISCreate(PETSC_COMM_SELF, &fields));
6114:     PetscCall(PetscObjectSetOptionsPrefix((PetscObject)fields, "dm_fields_"));
6115:     PetscCall(ISSetType(fields, ISGENERAL));
6116:     PetscCall(ISGeneralSetIndices(fields, nf, fld, PETSC_OWN_POINTER));
6117:     PetscCall(PetscDSSetCoordinateDimension(ds, dE));
6118:     {
6119:       DMPolytopeType ct;
6120:       PetscInt       lStart, lEnd;
6121:       PetscBool      isCohesiveLocal = PETSC_FALSE, isCohesive;

6123:       PetscCall(DMLabelGetBounds(label, &lStart, &lEnd));
6124:       if (lStart >= 0) {
6125:         PetscCall(DMPlexGetCellType(dm, lStart, &ct));
6126:         switch (ct) {
6127:         case DM_POLYTOPE_POINT_PRISM_TENSOR:
6128:         case DM_POLYTOPE_SEG_PRISM_TENSOR:
6129:         case DM_POLYTOPE_TRI_PRISM_TENSOR:
6130:         case DM_POLYTOPE_QUAD_PRISM_TENSOR:
6131:           isCohesiveLocal = PETSC_TRUE;
6132:           break;
6133:         default:
6134:           break;
6135:         }
6136:       }
6137:       PetscCallMPI(MPIU_Allreduce(&isCohesiveLocal, &isCohesive, 1, MPI_C_BOOL, MPI_LOR, comm));
6138:       if (isCohesive) {
6139:         PetscCall(PetscDSCreate(PETSC_COMM_SELF, &dsIn));
6140:         PetscCall(PetscDSSetCoordinateDimension(dsIn, dE));
6141:       }
6142:       for (f = 0, nf = 0; f < Nf; ++f) {
6143:         if (label == dm->fields[f].label || !dm->fields[f].label) {
6144:           if (label == dm->fields[f].label) {
6145:             PetscCall(PetscDSSetDiscretization(ds, nf, NULL));
6146:             PetscCall(PetscDSSetCohesive(ds, nf, isCohesive));
6147:             if (dsIn) {
6148:               PetscCall(PetscDSSetDiscretization(dsIn, nf, NULL));
6149:               PetscCall(PetscDSSetCohesive(dsIn, nf, isCohesive));
6150:             }
6151:           }
6152:           ++nf;
6153:         }
6154:       }
6155:     }
6156:     PetscCall(DMSetRegionDS(dm, label, fields, ds, dsIn));
6157:     PetscCall(ISDestroy(&fields));
6158:     PetscCall(PetscDSDestroy(&ds));
6159:     PetscCall(PetscDSDestroy(&dsIn));
6160:   }
6161:   PetscCall(PetscFree(labelSet));
6162:   /* Set fields in DSes */
6163:   for (s = 0; s < dm->Nds; ++s) {
6164:     PetscDS         ds     = dm->probs[s].ds;
6165:     PetscDS         dsIn   = dm->probs[s].dsIn;
6166:     IS              fields = dm->probs[s].fields;
6167:     const PetscInt *fld;
6168:     PetscInt        nf, dsnf;
6169:     PetscBool       isCohesive;

6171:     PetscCall(PetscDSGetNumFields(ds, &dsnf));
6172:     PetscCall(PetscDSIsCohesive(ds, &isCohesive));
6173:     PetscCall(ISGetLocalSize(fields, &nf));
6174:     PetscCall(ISGetIndices(fields, &fld));
6175:     for (f = 0; f < nf; ++f) {
6176:       PetscObject  disc = dm->fields[fld[f]].disc;
6177:       PetscBool    isCohesiveField;
6178:       PetscClassId id;

6180:       /* Handle DS with no fields */
6181:       if (dsnf) PetscCall(PetscDSGetCohesive(ds, f, &isCohesiveField));
6182:       /* If this is a cohesive cell, then regular fields need the lower dimensional discretization */
6183:       if (isCohesive) {
6184:         if (!isCohesiveField) {
6185:           PetscObject bdDisc;

6187:           PetscCall(PetscFEGetHeightSubspace((PetscFE)disc, 1, (PetscFE *)&bdDisc));
6188:           PetscCall(PetscDSSetDiscretization(ds, f, bdDisc));
6189:           PetscCall(PetscDSSetDiscretization(dsIn, f, disc));
6190:         } else {
6191:           PetscCall(PetscDSSetDiscretization(ds, f, disc));
6192:           PetscCall(PetscDSSetDiscretization(dsIn, f, disc));
6193:         }
6194:       } else {
6195:         PetscCall(PetscDSSetDiscretization(ds, f, disc));
6196:       }
6197:       /* We allow people to have placeholder fields and construct the Section by hand */
6198:       PetscCall(PetscObjectGetClassId(disc, &id));
6199:       if ((id != PETSCFE_CLASSID) && (id != PETSCFV_CLASSID)) doSetup = PETSC_FALSE;
6200:     }
6201:     PetscCall(ISRestoreIndices(fields, &fld));
6202:   }
6203:   /* Allow k-jet tabulation */
6204:   PetscCall(PetscOptionsGetInt(NULL, ((PetscObject)dm)->prefix, "-dm_ds_jet_degree", &k, &flg));
6205:   if (flg) {
6206:     for (s = 0; s < dm->Nds; ++s) {
6207:       PetscDS  ds   = dm->probs[s].ds;
6208:       PetscDS  dsIn = dm->probs[s].dsIn;
6209:       PetscInt Nf, f;

6211:       PetscCall(PetscDSGetNumFields(ds, &Nf));
6212:       for (f = 0; f < Nf; ++f) {
6213:         PetscCall(PetscDSSetJetDegree(ds, f, k));
6214:         if (dsIn) PetscCall(PetscDSSetJetDegree(dsIn, f, k));
6215:       }
6216:     }
6217:   }
6218:   /* Setup DSes */
6219:   if (doSetup) {
6220:     for (s = 0; s < dm->Nds; ++s) {
6221:       if (dm->setfromoptionscalled) {
6222:         PetscCall(PetscDSSetFromOptions(dm->probs[s].ds));
6223:         if (dm->probs[s].dsIn) PetscCall(PetscDSSetFromOptions(dm->probs[s].dsIn));
6224:       }
6225:       PetscCall(PetscDSSetUp(dm->probs[s].ds));
6226:       if (dm->probs[s].dsIn) PetscCall(PetscDSSetUp(dm->probs[s].dsIn));
6227:     }
6228:   }
6229:   PetscFunctionReturn(PETSC_SUCCESS);
6230: }

6232: /*@
6233:   DMUseTensorOrder - Use a tensor product closure ordering for the default section

6235:   Input Parameters:
6236: + dm     - The DM
6237: - tensor - Flag for tensor order

6239:   Level: developer

6241: .seealso: `DMPlexSetClosurePermutationTensor()`, `PetscSectionResetClosurePermutation()`
6242: @*/
6243: PetscErrorCode DMUseTensorOrder(DM dm, PetscBool tensor)
6244: {
6245:   PetscInt  Nf;
6246:   PetscBool reorder = PETSC_TRUE, isPlex;

6248:   PetscFunctionBegin;
6249:   PetscCall(PetscObjectTypeCompare((PetscObject)dm, DMPLEX, &isPlex));
6250:   PetscCall(DMGetNumFields(dm, &Nf));
6251:   for (PetscInt f = 0; f < Nf; ++f) {
6252:     PetscObject  obj;
6253:     PetscClassId id;

6255:     PetscCall(DMGetField(dm, f, NULL, &obj));
6256:     PetscCall(PetscObjectGetClassId(obj, &id));
6257:     if (id == PETSCFE_CLASSID) {
6258:       PetscSpace sp;
6259:       PetscBool  tensor;

6261:       PetscCall(PetscFEGetBasisSpace((PetscFE)obj, &sp));
6262:       PetscCall(PetscSpacePolynomialGetTensor(sp, &tensor));
6263:       reorder = reorder && tensor ? PETSC_TRUE : PETSC_FALSE;
6264:     } else reorder = PETSC_FALSE;
6265:   }
6266:   if (tensor) {
6267:     if (reorder && isPlex) PetscCall(DMPlexSetClosurePermutationTensor(dm, PETSC_DETERMINE, NULL));
6268:   } else {
6269:     PetscSection s;

6271:     PetscCall(DMGetLocalSection(dm, &s));
6272:     if (s) PetscCall(PetscSectionResetClosurePermutation(s));
6273:   }
6274:   PetscFunctionReturn(PETSC_SUCCESS);
6275: }

6277: /*@
6278:   DMComputeExactSolution - Compute the exact solution for a given `DM`, using the `PetscDS` information.

6280:   Collective

6282:   Input Parameters:
6283: + dm   - The `DM`
6284: - time - The time

6286:   Output Parameters:
6287: + u   - The vector will be filled with exact solution values, or `NULL`
6288: - u_t - The vector will be filled with the time derivative of exact solution values, or `NULL`

6290:   Level: developer

6292:   Note:
6293:   The user must call `PetscDSSetExactSolution()` before using this routine

6295: .seealso: [](ch_dmbase), `DM`, `PetscDSSetExactSolution()`
6296: @*/
6297: PetscErrorCode DMComputeExactSolution(DM dm, PetscReal time, Vec u, Vec u_t)
6298: {
6299:   PetscErrorCode (**exacts)(PetscInt, PetscReal, const PetscReal x[], PetscInt, PetscScalar *u, PetscCtx ctx);
6300:   void   **ectxs;
6301:   Vec      locu, locu_t;
6302:   PetscInt Nf, Nds, s;

6304:   PetscFunctionBegin;
6306:   if (u) {
6308:     PetscCall(DMGetLocalVector(dm, &locu));
6309:     PetscCall(VecSet(locu, 0.));
6310:   }
6311:   if (u_t) {
6313:     PetscCall(DMGetLocalVector(dm, &locu_t));
6314:     PetscCall(VecSet(locu_t, 0.));
6315:   }
6316:   PetscCall(DMGetNumFields(dm, &Nf));
6317:   PetscCall(PetscMalloc2(Nf, &exacts, Nf, &ectxs));
6318:   PetscCall(DMGetNumDS(dm, &Nds));
6319:   for (s = 0; s < Nds; ++s) {
6320:     PetscDS         ds;
6321:     DMLabel         label;
6322:     IS              fieldIS;
6323:     const PetscInt *fields, id = 1;
6324:     PetscInt        dsNf, f;

6326:     PetscCall(DMGetRegionNumDS(dm, s, &label, &fieldIS, &ds, NULL));
6327:     PetscCall(PetscDSGetNumFields(ds, &dsNf));
6328:     PetscCall(ISGetIndices(fieldIS, &fields));
6329:     PetscCall(PetscArrayzero(exacts, Nf));
6330:     PetscCall(PetscArrayzero(ectxs, Nf));
6331:     if (u) {
6332:       for (f = 0; f < dsNf; ++f) PetscCall(PetscDSGetExactSolution(ds, fields[f], &exacts[fields[f]], &ectxs[fields[f]]));
6333:       if (label) PetscCall(DMProjectFunctionLabelLocal(dm, time, label, 1, &id, 0, NULL, exacts, ectxs, INSERT_ALL_VALUES, locu));
6334:       else PetscCall(DMProjectFunctionLocal(dm, time, exacts, ectxs, INSERT_ALL_VALUES, locu));
6335:     }
6336:     if (u_t) {
6337:       PetscCall(PetscArrayzero(exacts, Nf));
6338:       PetscCall(PetscArrayzero(ectxs, Nf));
6339:       for (f = 0; f < dsNf; ++f) PetscCall(PetscDSGetExactSolutionTimeDerivative(ds, fields[f], &exacts[fields[f]], &ectxs[fields[f]]));
6340:       if (label) PetscCall(DMProjectFunctionLabelLocal(dm, time, label, 1, &id, 0, NULL, exacts, ectxs, INSERT_ALL_VALUES, locu_t));
6341:       else PetscCall(DMProjectFunctionLocal(dm, time, exacts, ectxs, INSERT_ALL_VALUES, locu_t));
6342:     }
6343:     PetscCall(ISRestoreIndices(fieldIS, &fields));
6344:   }
6345:   if (u) {
6346:     PetscCall(PetscObjectSetName((PetscObject)u, "Exact Solution"));
6347:     PetscCall(PetscObjectSetOptionsPrefix((PetscObject)u, "exact_"));
6348:   }
6349:   if (u_t) {
6350:     PetscCall(PetscObjectSetName((PetscObject)u, "Exact Solution Time Derivative"));
6351:     PetscCall(PetscObjectSetOptionsPrefix((PetscObject)u_t, "exact_t_"));
6352:   }
6353:   PetscCall(PetscFree2(exacts, ectxs));
6354:   if (u) {
6355:     PetscCall(DMLocalToGlobalBegin(dm, locu, INSERT_ALL_VALUES, u));
6356:     PetscCall(DMLocalToGlobalEnd(dm, locu, INSERT_ALL_VALUES, u));
6357:     PetscCall(DMRestoreLocalVector(dm, &locu));
6358:   }
6359:   if (u_t) {
6360:     PetscCall(DMLocalToGlobalBegin(dm, locu_t, INSERT_ALL_VALUES, u_t));
6361:     PetscCall(DMLocalToGlobalEnd(dm, locu_t, INSERT_ALL_VALUES, u_t));
6362:     PetscCall(DMRestoreLocalVector(dm, &locu_t));
6363:   }
6364:   PetscFunctionReturn(PETSC_SUCCESS);
6365: }

6367: static PetscErrorCode DMTransferDS_Internal(DM dm, DMLabel label, IS fields, PetscInt minDegree, PetscInt maxDegree, PetscDS ds, PetscDS dsIn)
6368: {
6369:   PetscDS dsNew, dsInNew = NULL;

6371:   PetscFunctionBegin;
6372:   PetscCall(PetscDSCreate(PetscObjectComm((PetscObject)ds), &dsNew));
6373:   PetscCall(PetscDSCopy(ds, minDegree, maxDegree, dm, dsNew));
6374:   if (dsIn) {
6375:     PetscCall(PetscDSCreate(PetscObjectComm((PetscObject)dsIn), &dsInNew));
6376:     PetscCall(PetscDSCopy(dsIn, minDegree, maxDegree, dm, dsInNew));
6377:   }
6378:   PetscCall(DMSetRegionDS(dm, label, fields, dsNew, dsInNew));
6379:   PetscCall(PetscDSDestroy(&dsNew));
6380:   PetscCall(PetscDSDestroy(&dsInNew));
6381:   PetscFunctionReturn(PETSC_SUCCESS);
6382: }

6384: /*@
6385:   DMCopyDS - Copy the discrete systems for the `DM` into another `DM`

6387:   Collective

6389:   Input Parameters:
6390: + dm        - The `DM`
6391: . minDegree - Minimum degree for a discretization, or `PETSC_DETERMINE` for no limit
6392: - maxDegree - Maximum degree for a discretization, or `PETSC_DETERMINE` for no limit

6394:   Output Parameter:
6395: . newdm - The `DM`

6397:   Level: advanced

6399: .seealso: [](ch_dmbase), `DM`, `DMCopyFields()`, `DMAddField()`, `DMGetDS()`, `DMGetCellDS()`, `DMGetRegionDS()`, `DMSetRegionDS()`
6400: @*/
6401: PetscErrorCode DMCopyDS(DM dm, PetscInt minDegree, PetscInt maxDegree, DM newdm)
6402: {
6403:   PetscInt Nds, s;

6405:   PetscFunctionBegin;
6406:   if (dm == newdm) PetscFunctionReturn(PETSC_SUCCESS);
6407:   PetscCall(DMGetNumDS(dm, &Nds));
6408:   PetscCall(DMClearDS(newdm));
6409:   for (s = 0; s < Nds; ++s) {
6410:     DMLabel  label;
6411:     IS       fields;
6412:     PetscDS  ds, dsIn, newds;
6413:     PetscInt Nbd, bd;

6415:     PetscCall(DMGetRegionNumDS(dm, s, &label, &fields, &ds, &dsIn));
6416:     /* TODO: We need to change all keys from labels in the old DM to labels in the new DM */
6417:     PetscCall(DMTransferDS_Internal(newdm, label, fields, minDegree, maxDegree, ds, dsIn));
6418:     /* Complete new labels in the new DS */
6419:     PetscCall(DMGetRegionDS(newdm, label, NULL, &newds, NULL));
6420:     PetscCall(PetscDSGetNumBoundary(newds, &Nbd));
6421:     for (bd = 0; bd < Nbd; ++bd) {
6422:       PetscWeakForm wf;
6423:       DMLabel       label;
6424:       PetscInt      field;

6426:       PetscCall(PetscDSGetBoundary(newds, bd, &wf, NULL, NULL, &label, NULL, NULL, &field, NULL, NULL, NULL, NULL, NULL));
6427:       PetscCall(PetscWeakFormReplaceLabel(wf, label));
6428:     }
6429:   }
6430:   PetscCall(DMCompleteBCLabels_Internal(newdm));
6431:   PetscFunctionReturn(PETSC_SUCCESS);
6432: }

6434: /*@
6435:   DMCopyDisc - Copy the fields and discrete systems for the `DM` into another `DM`

6437:   Collective

6439:   Input Parameter:
6440: . dm - The `DM`

6442:   Output Parameter:
6443: . newdm - The `DM`

6445:   Level: advanced

6447:   Developer Note:
6448:   Really ugly name, nothing in PETSc is called a `Disc` plus it is an ugly abbreviation

6450: .seealso: [](ch_dmbase), `DM`, `DMCopyFields()`, `DMCopyDS()`
6451: @*/
6452: PetscErrorCode DMCopyDisc(DM dm, DM newdm)
6453: {
6454:   PetscFunctionBegin;
6455:   PetscCall(DMCopyFields(dm, PETSC_DETERMINE, PETSC_DETERMINE, newdm));
6456:   PetscCall(DMCopyDS(dm, PETSC_DETERMINE, PETSC_DETERMINE, newdm));
6457:   PetscFunctionReturn(PETSC_SUCCESS);
6458: }

6460: /*@
6461:   DMGetDimension - Return the topological dimension of the `DM`

6463:   Not Collective

6465:   Input Parameter:
6466: . dm - The `DM`

6468:   Output Parameter:
6469: . dim - The topological dimension

6471:   Level: beginner

6473: .seealso: [](ch_dmbase), `DM`, `DMSetDimension()`, `DMCreate()`
6474: @*/
6475: PetscErrorCode DMGetDimension(DM dm, PetscInt *dim)
6476: {
6477:   PetscFunctionBegin;
6479:   PetscAssertPointer(dim, 2);
6480:   *dim = dm->dim;
6481:   PetscFunctionReturn(PETSC_SUCCESS);
6482: }

6484: /*@
6485:   DMSetDimension - Set the topological dimension of the `DM`

6487:   Collective

6489:   Input Parameters:
6490: + dm  - The `DM`
6491: - dim - The topological dimension

6493:   Level: beginner

6495: .seealso: [](ch_dmbase), `DM`, `DMGetDimension()`, `DMCreate()`
6496: @*/
6497: PetscErrorCode DMSetDimension(DM dm, PetscInt dim)
6498: {
6499:   PetscDS  ds;
6500:   PetscInt Nds, n;

6502:   PetscFunctionBegin;
6505:   if (dm->dim != dim) PetscCall(DMSetPeriodicity(dm, NULL, NULL, NULL));
6506:   dm->dim = dim;
6507:   if (dm->dim >= 0) {
6508:     PetscCall(DMGetNumDS(dm, &Nds));
6509:     for (n = 0; n < Nds; ++n) {
6510:       PetscCall(DMGetRegionNumDS(dm, n, NULL, NULL, &ds, NULL));
6511:       if (ds->dimEmbed < 0) PetscCall(PetscDSSetCoordinateDimension(ds, dim));
6512:     }
6513:   }
6514:   PetscFunctionReturn(PETSC_SUCCESS);
6515: }

6517: /*@
6518:   DMGetDimPoints - Get the half-open interval for all points of a given dimension

6520:   Collective

6522:   Input Parameters:
6523: + dm  - the `DM`
6524: - dim - the dimension

6526:   Output Parameters:
6527: + pStart - The first point of the given dimension
6528: - pEnd   - The first point following points of the given dimension

6530:   Level: intermediate

6532:   Note:
6533:   The points are vertices in the Hasse diagram encoding the topology. This is explained in
6534:   https://arxiv.org/abs/0908.4427. If no points exist of this dimension in the storage scheme,
6535:   then the interval is empty.

6537: .seealso: [](ch_dmbase), `DM`, `DMPLEX`, `DMPlexGetDepthStratum()`, `DMPlexGetHeightStratum()`
6538: @*/
6539: PetscErrorCode DMGetDimPoints(DM dm, PetscInt dim, PetscInt *pStart, PetscInt *pEnd)
6540: {
6541:   PetscInt d;

6543:   PetscFunctionBegin;
6545:   PetscCall(DMGetDimension(dm, &d));
6546:   PetscCheck((dim >= 0) && (dim <= d), PetscObjectComm((PetscObject)dm), PETSC_ERR_ARG_OUTOFRANGE, "Invalid dimension %" PetscInt_FMT, dim);
6547:   PetscUseTypeMethod(dm, getdimpoints, dim, pStart, pEnd);
6548:   PetscFunctionReturn(PETSC_SUCCESS);
6549: }

6551: /*@
6552:   DMGetOutputDM - Retrieve the `DM` associated with the layout for output

6554:   Collective

6556:   Input Parameter:
6557: . dm - The original `DM`

6559:   Output Parameter:
6560: . odm - The `DM` which provides the layout for output

6562:   Level: intermediate

6564:   Note:
6565:   In some situations the vector obtained with `DMCreateGlobalVector()` excludes points for degrees of freedom that are associated with fixed (Dirichelet) boundary
6566:   conditions since the algebraic solver does not solve for those variables. The output `DM` includes these excluded points and its global vector contains the
6567:   locations for those dof so that they can be output to a file or other viewer along with the unconstrained dof.

6569: .seealso: [](ch_dmbase), `DM`, `VecView()`, `DMGetGlobalSection()`, `DMCreateGlobalVector()`, `PetscSectionHasConstraints()`, `DMSetGlobalSection()`
6570: @*/
6571: PetscErrorCode DMGetOutputDM(DM dm, DM *odm)
6572: {
6573:   PetscSection section;
6574:   IS           perm;
6575:   PetscBool    hasConstraints, newDM, gnewDM;
6576:   PetscInt     num_face_sfs = 0;

6578:   PetscFunctionBegin;
6580:   PetscAssertPointer(odm, 2);
6581:   PetscCall(DMGetLocalSection(dm, &section));
6582:   PetscCall(PetscSectionHasConstraints(section, &hasConstraints));
6583:   PetscCall(PetscSectionGetPermutation(section, &perm));
6584:   PetscCall(DMPlexGetIsoperiodicFaceSF(dm, &num_face_sfs, NULL));
6585:   newDM = hasConstraints || perm || (num_face_sfs > 0) ? PETSC_TRUE : PETSC_FALSE;
6586:   PetscCallMPI(MPIU_Allreduce(&newDM, &gnewDM, 1, MPI_C_BOOL, MPI_LOR, PetscObjectComm((PetscObject)dm)));
6587:   if (!gnewDM) {
6588:     *odm = dm;
6589:     PetscFunctionReturn(PETSC_SUCCESS);
6590:   }
6591:   if (!dm->dmBC) {
6592:     PetscSection newSection, gsection;
6593:     PetscSF      sf, sfNatural;
6594:     PetscBool    usePerm = dm->ignorePermOutput ? PETSC_FALSE : PETSC_TRUE;

6596:     PetscCall(DMClone(dm, &dm->dmBC));
6597:     PetscCall(DMCopyDisc(dm, dm->dmBC));
6598:     PetscCall(PetscSectionClone(section, &newSection));
6599:     PetscCall(DMSetLocalSection(dm->dmBC, newSection));
6600:     PetscCall(PetscSectionDestroy(&newSection));
6601:     PetscCall(DMGetNaturalSF(dm, &sfNatural));
6602:     PetscCall(DMSetNaturalSF(dm->dmBC, sfNatural));
6603:     PetscCall(DMGetPointSF(dm->dmBC, &sf));
6604:     PetscCall(PetscSectionCreateGlobalSection(section, sf, usePerm, PETSC_TRUE, PETSC_FALSE, &gsection));
6605:     PetscCall(DMSetGlobalSection(dm->dmBC, gsection));
6606:     PetscCall(PetscSectionDestroy(&gsection));
6607:   }
6608:   *odm = dm->dmBC;
6609:   PetscFunctionReturn(PETSC_SUCCESS);
6610: }

6612: /*@
6613:   DMGetOutputSequenceNumber - Retrieve the sequence number/value for output

6615:   Input Parameter:
6616: . dm - The original `DM`

6618:   Output Parameters:
6619: + num - The output sequence number
6620: - val - The output sequence value

6622:   Level: intermediate

6624:   Note:
6625:   This is intended for output that should appear in sequence, for instance
6626:   a set of timesteps in an `PETSCVIEWERHDF5` file, or a set of realizations of a stochastic system.

6628:   Developer Note:
6629:   The `DM` serves as a convenient place to store the current iteration value. The iteration is not
6630:   not directly related to the `DM`.

6632: .seealso: [](ch_dmbase), `DM`, `VecView()`
6633: @*/
6634: PetscErrorCode DMGetOutputSequenceNumber(DM dm, PetscInt *num, PetscReal *val)
6635: {
6636:   PetscFunctionBegin;
6638:   if (num) {
6639:     PetscAssertPointer(num, 2);
6640:     *num = dm->outputSequenceNum;
6641:   }
6642:   if (val) {
6643:     PetscAssertPointer(val, 3);
6644:     *val = dm->outputSequenceVal;
6645:   }
6646:   PetscFunctionReturn(PETSC_SUCCESS);
6647: }

6649: /*@
6650:   DMSetOutputSequenceNumber - Set the sequence number/value for output

6652:   Input Parameters:
6653: + dm  - The original `DM`
6654: . num - The output sequence number
6655: - val - The output sequence value

6657:   Level: intermediate

6659:   Note:
6660:   This is intended for output that should appear in sequence, for instance
6661:   a set of timesteps in an `PETSCVIEWERHDF5` file, or a set of realizations of a stochastic system.

6663: .seealso: [](ch_dmbase), `DM`, `VecView()`
6664: @*/
6665: PetscErrorCode DMSetOutputSequenceNumber(DM dm, PetscInt num, PetscReal val)
6666: {
6667:   PetscFunctionBegin;
6669:   dm->outputSequenceNum = num;
6670:   dm->outputSequenceVal = val;
6671:   PetscFunctionReturn(PETSC_SUCCESS);
6672: }

6674: /*@
6675:   DMOutputSequenceLoad - Retrieve the sequence value from a `PetscViewer`

6677:   Input Parameters:
6678: + dm     - The original `DM`
6679: . viewer - The `PetscViewer` to get it from
6680: . name   - The sequence name
6681: - num    - The output sequence number

6683:   Output Parameter:
6684: . val - The output sequence value

6686:   Level: intermediate

6688:   Note:
6689:   This is intended for output that should appear in sequence, for instance
6690:   a set of timesteps in an `PETSCVIEWERHDF5` file, or a set of realizations of a stochastic system.

6692:   Developer Note:
6693:   It is unclear at the user API level why a `DM` is needed as input

6695: .seealso: [](ch_dmbase), `DM`, `DMGetOutputSequenceNumber()`, `DMSetOutputSequenceNumber()`, `VecView()`
6696: @*/
6697: PetscErrorCode DMOutputSequenceLoad(DM dm, PetscViewer viewer, const char name[], PetscInt num, PetscReal *val)
6698: {
6699:   PetscBool ishdf5;

6701:   PetscFunctionBegin;
6704:   PetscAssertPointer(name, 3);
6705:   PetscAssertPointer(val, 5);
6706:   PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERHDF5, &ishdf5));
6707:   PetscCheck(ishdf5, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Invalid viewer; open viewer with PetscViewerHDF5Open()");
6708: #if defined(PETSC_HAVE_HDF5)
6709:   PetscScalar value;

6711:   PetscCall(DMSequenceLoad_HDF5_Internal(dm, name, num, &value, viewer));
6712:   *val = PetscRealPart(value);
6713: #endif
6714:   PetscFunctionReturn(PETSC_SUCCESS);
6715: }

6717: /*@
6718:   DMGetOutputSequenceLength - Retrieve the number of sequence values from a `PetscViewer`

6720:   Input Parameters:
6721: + dm     - The original `DM`
6722: . viewer - The `PetscViewer` to get it from
6723: - name   - The sequence name

6725:   Output Parameter:
6726: . len - The length of the output sequence

6728:   Level: intermediate

6730:   Note:
6731:   This is intended for output that should appear in sequence, for instance
6732:   a set of timesteps in an `PETSCVIEWERHDF5` file, or a set of realizations of a stochastic system.

6734:   Developer Note:
6735:   It is unclear at the user API level why a `DM` is needed as input

6737: .seealso: [](ch_dmbase), `DM`, `DMGetOutputSequenceNumber()`, `DMSetOutputSequenceNumber()`, `VecView()`
6738: @*/
6739: PetscErrorCode DMGetOutputSequenceLength(DM dm, PetscViewer viewer, const char name[], PetscInt *len)
6740: {
6741:   PetscBool ishdf5;

6743:   PetscFunctionBegin;
6746:   PetscAssertPointer(name, 3);
6747:   PetscAssertPointer(len, 4);
6748:   PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERHDF5, &ishdf5));
6749:   PetscCheck(ishdf5, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Invalid viewer; open viewer with PetscViewerHDF5Open()");
6750: #if defined(PETSC_HAVE_HDF5)
6751:   PetscCall(DMSequenceGetLength_HDF5_Internal(dm, name, len, viewer));
6752: #endif
6753:   PetscFunctionReturn(PETSC_SUCCESS);
6754: }

6756: /*@
6757:   DMGetUseNatural - Get the flag for creating a mapping to the natural order when a `DM` is (re)distributed in parallel

6759:   Not Collective

6761:   Input Parameter:
6762: . dm - The `DM`

6764:   Output Parameter:
6765: . useNatural - `PETSC_TRUE` to build the mapping to a natural order during distribution

6767:   Level: beginner

6769: .seealso: [](ch_dmbase), `DM`, `DMSetUseNatural()`, `DMCreate()`
6770: @*/
6771: PetscErrorCode DMGetUseNatural(DM dm, PetscBool *useNatural)
6772: {
6773:   PetscFunctionBegin;
6775:   PetscAssertPointer(useNatural, 2);
6776:   *useNatural = dm->useNatural;
6777:   PetscFunctionReturn(PETSC_SUCCESS);
6778: }

6780: /*@
6781:   DMSetUseNatural - Set the flag for creating a mapping to the natural order when a `DM` is (re)distributed in parallel

6783:   Collective

6785:   Input Parameters:
6786: + dm         - The `DM`
6787: - useNatural - `PETSC_TRUE` to build the mapping to a natural order during distribution

6789:   Level: beginner

6791:   Note:
6792:   This also causes the map to be build after `DMCreateSubDM()` and `DMCreateSuperDM()`

6794: .seealso: [](ch_dmbase), `DM`, `DMGetUseNatural()`, `DMCreate()`, `DMPlexDistribute()`, `DMCreateSubDM()`, `DMCreateSuperDM()`
6795: @*/
6796: PetscErrorCode DMSetUseNatural(DM dm, PetscBool useNatural)
6797: {
6798:   PetscFunctionBegin;
6801:   dm->useNatural = useNatural;
6802:   PetscFunctionReturn(PETSC_SUCCESS);
6803: }

6805: /*@
6806:   DMCreateLabel - Create a label of the given name if it does not already exist in the `DM`

6808:   Not Collective

6810:   Input Parameters:
6811: + dm   - The `DM` object
6812: - name - The label name

6814:   Level: intermediate

6816: .seealso: [](ch_dmbase), `DM`, `DMLabelCreate()`, `DMHasLabel()`, `DMGetLabelValue()`, `DMSetLabelValue()`, `DMGetStratumIS()`
6817: @*/
6818: PetscErrorCode DMCreateLabel(DM dm, const char name[])
6819: {
6820:   PetscBool flg;
6821:   DMLabel   label;

6823:   PetscFunctionBegin;
6825:   PetscAssertPointer(name, 2);
6826:   PetscCall(DMHasLabel(dm, name, &flg));
6827:   if (!flg) {
6828:     PetscCall(DMLabelCreate(PETSC_COMM_SELF, name, &label));
6829:     PetscCall(DMAddLabel(dm, label));
6830:     PetscCall(DMLabelDestroy(&label));
6831:   }
6832:   PetscFunctionReturn(PETSC_SUCCESS);
6833: }

6835: /*@
6836:   DMCreateLabelAtIndex - Create a label of the given name at the given index. If it already exists in the `DM`, move it to this index.

6838:   Not Collective

6840:   Input Parameters:
6841: + dm   - The `DM` object
6842: . l    - The index for the label
6843: - name - The label name

6845:   Level: intermediate

6847: .seealso: [](ch_dmbase), `DM`, `DMCreateLabel()`, `DMLabelCreate()`, `DMHasLabel()`, `DMGetLabelValue()`, `DMSetLabelValue()`, `DMGetStratumIS()`
6848: @*/
6849: PetscErrorCode DMCreateLabelAtIndex(DM dm, PetscInt l, const char name[])
6850: {
6851:   DMLabelLink orig, prev = NULL;
6852:   DMLabel     label;
6853:   PetscInt    Nl, m;
6854:   PetscBool   flg, match;
6855:   const char *lname;

6857:   PetscFunctionBegin;
6859:   PetscAssertPointer(name, 3);
6860:   PetscCall(DMHasLabel(dm, name, &flg));
6861:   if (!flg) {
6862:     PetscCall(DMLabelCreate(PETSC_COMM_SELF, name, &label));
6863:     PetscCall(DMAddLabel(dm, label));
6864:     PetscCall(DMLabelDestroy(&label));
6865:   }
6866:   PetscCall(DMGetNumLabels(dm, &Nl));
6867:   PetscCheck(l < Nl, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Label index %" PetscInt_FMT " must be in [0, %" PetscInt_FMT ")", l, Nl);
6868:   for (m = 0, orig = dm->labels; m < Nl; ++m, prev = orig, orig = orig->next) {
6869:     PetscCall(PetscObjectGetName((PetscObject)orig->label, &lname));
6870:     PetscCall(PetscStrcmp(name, lname, &match));
6871:     if (match) break;
6872:   }
6873:   if (m == l) PetscFunctionReturn(PETSC_SUCCESS);
6874:   if (!m) dm->labels = orig->next;
6875:   else prev->next = orig->next;
6876:   if (!l) {
6877:     orig->next = dm->labels;
6878:     dm->labels = orig;
6879:   } else {
6880:     for (m = 0, prev = dm->labels; m < l - 1; ++m, prev = prev->next);
6881:     orig->next = prev->next;
6882:     prev->next = orig;
6883:   }
6884:   PetscFunctionReturn(PETSC_SUCCESS);
6885: }

6887: /*@
6888:   DMGetLabelValue - Get the value in a `DMLabel` for the given point, with -1 as the default

6890:   Not Collective

6892:   Input Parameters:
6893: + dm    - The `DM` object
6894: . name  - The label name
6895: - point - The mesh point

6897:   Output Parameter:
6898: . value - The label value for this point, or -1 if the point is not in the label

6900:   Level: beginner

6902: .seealso: [](ch_dmbase), `DM`, `DMLabelGetValue()`, `DMSetLabelValue()`, `DMGetStratumIS()`
6903: @*/
6904: PetscErrorCode DMGetLabelValue(DM dm, const char name[], PetscInt point, PetscInt *value)
6905: {
6906:   DMLabel label;

6908:   PetscFunctionBegin;
6910:   PetscAssertPointer(name, 2);
6911:   PetscCall(DMGetLabel(dm, name, &label));
6912:   PetscCheck(label, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "No label named %s was found", name);
6913:   PetscCall(DMLabelGetValue(label, point, value));
6914:   PetscFunctionReturn(PETSC_SUCCESS);
6915: }

6917: /*@
6918:   DMSetLabelValue - Add a point to a `DMLabel` with given value

6920:   Not Collective

6922:   Input Parameters:
6923: + dm    - The `DM` object
6924: . name  - The label name
6925: . point - The mesh point
6926: - value - The label value for this point

6928:   Output Parameter:

6930:   Level: beginner

6932: .seealso: [](ch_dmbase), `DM`, `DMLabelSetValue()`, `DMGetStratumIS()`, `DMClearLabelValue()`
6933: @*/
6934: PetscErrorCode DMSetLabelValue(DM dm, const char name[], PetscInt point, PetscInt value)
6935: {
6936:   DMLabel label;

6938:   PetscFunctionBegin;
6940:   PetscAssertPointer(name, 2);
6941:   PetscCall(DMGetLabel(dm, name, &label));
6942:   if (!label) {
6943:     PetscCall(DMCreateLabel(dm, name));
6944:     PetscCall(DMGetLabel(dm, name, &label));
6945:   }
6946:   PetscCall(DMLabelSetValue(label, point, value));
6947:   PetscFunctionReturn(PETSC_SUCCESS);
6948: }

6950: /*@
6951:   DMClearLabelValue - Remove a point from a `DMLabel` with given value

6953:   Not Collective

6955:   Input Parameters:
6956: + dm    - The `DM` object
6957: . name  - The label name
6958: . point - The mesh point
6959: - value - The label value for this point

6961:   Level: beginner

6963: .seealso: [](ch_dmbase), `DM`, `DMLabelClearValue()`, `DMSetLabelValue()`, `DMGetStratumIS()`
6964: @*/
6965: PetscErrorCode DMClearLabelValue(DM dm, const char name[], PetscInt point, PetscInt value)
6966: {
6967:   DMLabel label;

6969:   PetscFunctionBegin;
6971:   PetscAssertPointer(name, 2);
6972:   PetscCall(DMGetLabel(dm, name, &label));
6973:   if (!label) PetscFunctionReturn(PETSC_SUCCESS);
6974:   PetscCall(DMLabelClearValue(label, point, value));
6975:   PetscFunctionReturn(PETSC_SUCCESS);
6976: }

6978: /*@
6979:   DMGetLabelSize - Get the value of `DMLabelGetNumValues()` of a `DMLabel` in the `DM`

6981:   Not Collective

6983:   Input Parameters:
6984: + dm   - The `DM` object
6985: - name - The label name

6987:   Output Parameter:
6988: . size - The number of different integer ids, or 0 if the label does not exist

6990:   Level: beginner

6992:   Developer Note:
6993:   This should be renamed to something like `DMGetLabelNumValues()` or removed.

6995: .seealso: [](ch_dmbase), `DM`, `DMLabelGetNumValues()`, `DMSetLabelValue()`, `DMGetLabel()`
6996: @*/
6997: PetscErrorCode DMGetLabelSize(DM dm, const char name[], PetscInt *size)
6998: {
6999:   DMLabel label;

7001:   PetscFunctionBegin;
7003:   PetscAssertPointer(name, 2);
7004:   PetscAssertPointer(size, 3);
7005:   PetscCall(DMGetLabel(dm, name, &label));
7006:   *size = 0;
7007:   if (!label) PetscFunctionReturn(PETSC_SUCCESS);
7008:   PetscCall(DMLabelGetNumValues(label, size));
7009:   PetscFunctionReturn(PETSC_SUCCESS);
7010: }

7012: /*@
7013:   DMGetLabelIdIS - Get the `DMLabelGetValueIS()` from a `DMLabel` in the `DM`

7015:   Not Collective

7017:   Input Parameters:
7018: + dm   - The `DM` object
7019: - name - The label name

7021:   Output Parameter:
7022: . ids - The integer ids, or `NULL` if the label does not exist

7024:   Level: beginner

7026: .seealso: [](ch_dmbase), `DM`, `DMLabelGetValueIS()`, `DMGetLabelSize()`
7027: @*/
7028: PetscErrorCode DMGetLabelIdIS(DM dm, const char name[], IS *ids)
7029: {
7030:   DMLabel label;

7032:   PetscFunctionBegin;
7034:   PetscAssertPointer(name, 2);
7035:   PetscAssertPointer(ids, 3);
7036:   PetscCall(DMGetLabel(dm, name, &label));
7037:   *ids = NULL;
7038:   if (label) PetscCall(DMLabelGetValueIS(label, ids));
7039:   else {
7040:     /* returning an empty IS */
7041:     PetscCall(ISCreateGeneral(PETSC_COMM_SELF, 0, NULL, PETSC_USE_POINTER, ids));
7042:   }
7043:   PetscFunctionReturn(PETSC_SUCCESS);
7044: }

7046: /*@
7047:   DMGetStratumSize - Get the number of points in a label stratum

7049:   Not Collective

7051:   Input Parameters:
7052: + dm    - The `DM` object
7053: . name  - The label name of the stratum
7054: - value - The stratum value

7056:   Output Parameter:
7057: . size - The number of points, also called the stratum size

7059:   Level: beginner

7061: .seealso: [](ch_dmbase), `DM`, `DMLabelGetStratumSize()`, `DMGetLabelSize()`, `DMGetLabelIds()`
7062: @*/
7063: PetscErrorCode DMGetStratumSize(DM dm, const char name[], PetscInt value, PetscInt *size)
7064: {
7065:   DMLabel label;

7067:   PetscFunctionBegin;
7069:   PetscAssertPointer(name, 2);
7070:   PetscAssertPointer(size, 4);
7071:   PetscCall(DMGetLabel(dm, name, &label));
7072:   *size = 0;
7073:   if (!label) PetscFunctionReturn(PETSC_SUCCESS);
7074:   PetscCall(DMLabelGetStratumSize(label, value, size));
7075:   PetscFunctionReturn(PETSC_SUCCESS);
7076: }

7078: /*@
7079:   DMGetStratumIS - Get the points in a label stratum

7081:   Not Collective

7083:   Input Parameters:
7084: + dm    - The `DM` object
7085: . name  - The label name
7086: - value - The stratum value

7088:   Output Parameter:
7089: . points - The stratum points, or `NULL` if the label does not exist or does not have that value

7091:   Level: beginner

7093: .seealso: [](ch_dmbase), `DM`, `DMLabelGetStratumIS()`, `DMGetStratumSize()`
7094: @*/
7095: PetscErrorCode DMGetStratumIS(DM dm, const char name[], PetscInt value, IS *points)
7096: {
7097:   DMLabel label;

7099:   PetscFunctionBegin;
7101:   PetscAssertPointer(name, 2);
7102:   PetscAssertPointer(points, 4);
7103:   PetscCall(DMGetLabel(dm, name, &label));
7104:   *points = NULL;
7105:   if (!label) PetscFunctionReturn(PETSC_SUCCESS);
7106:   PetscCall(DMLabelGetStratumIS(label, value, points));
7107:   PetscFunctionReturn(PETSC_SUCCESS);
7108: }

7110: /*@
7111:   DMSetStratumIS - Set the points in a label stratum

7113:   Not Collective

7115:   Input Parameters:
7116: + dm     - The `DM` object
7117: . name   - The label name
7118: . value  - The stratum value
7119: - points - The stratum points

7121:   Level: beginner

7123: .seealso: [](ch_dmbase), `DM`, `DMLabel`, `DMClearLabelStratum()`, `DMLabelClearStratum()`, `DMLabelSetStratumIS()`, `DMGetStratumSize()`
7124: @*/
7125: PetscErrorCode DMSetStratumIS(DM dm, const char name[], PetscInt value, IS points)
7126: {
7127:   DMLabel label;

7129:   PetscFunctionBegin;
7131:   PetscAssertPointer(name, 2);
7133:   PetscCall(DMGetLabel(dm, name, &label));
7134:   if (!label) PetscFunctionReturn(PETSC_SUCCESS);
7135:   PetscCall(DMLabelSetStratumIS(label, value, points));
7136:   PetscFunctionReturn(PETSC_SUCCESS);
7137: }

7139: /*@
7140:   DMClearLabelStratum - Remove all points from a stratum from a `DMLabel`

7142:   Not Collective

7144:   Input Parameters:
7145: + dm    - The `DM` object
7146: . name  - The label name
7147: - value - The label value for this point

7149:   Output Parameter:

7151:   Level: beginner

7153: .seealso: [](ch_dmbase), `DM`, `DMLabel`, `DMLabelClearStratum()`, `DMSetLabelValue()`, `DMGetStratumIS()`, `DMClearLabelValue()`
7154: @*/
7155: PetscErrorCode DMClearLabelStratum(DM dm, const char name[], PetscInt value)
7156: {
7157:   DMLabel label;

7159:   PetscFunctionBegin;
7161:   PetscAssertPointer(name, 2);
7162:   PetscCall(DMGetLabel(dm, name, &label));
7163:   if (!label) PetscFunctionReturn(PETSC_SUCCESS);
7164:   PetscCall(DMLabelClearStratum(label, value));
7165:   PetscFunctionReturn(PETSC_SUCCESS);
7166: }

7168: /*@
7169:   DMGetNumLabels - Return the number of labels defined by on the `DM`

7171:   Not Collective

7173:   Input Parameter:
7174: . dm - The `DM` object

7176:   Output Parameter:
7177: . numLabels - the number of Labels

7179:   Level: intermediate

7181: .seealso: [](ch_dmbase), `DM`, `DMLabel`, `DMGetLabelByNum()`, `DMGetLabelName()`, `DMGetLabelValue()`, `DMSetLabelValue()`, `DMGetStratumIS()`
7182: @*/
7183: PetscErrorCode DMGetNumLabels(DM dm, PetscInt *numLabels)
7184: {
7185:   DMLabelLink next = dm->labels;
7186:   PetscInt    n    = 0;

7188:   PetscFunctionBegin;
7190:   PetscAssertPointer(numLabels, 2);
7191:   while (next) {
7192:     ++n;
7193:     next = next->next;
7194:   }
7195:   *numLabels = n;
7196:   PetscFunctionReturn(PETSC_SUCCESS);
7197: }

7199: /*@
7200:   DMGetLabelName - Return the name of nth label

7202:   Not Collective

7204:   Input Parameters:
7205: + dm - The `DM` object
7206: - n  - the label number

7208:   Output Parameter:
7209: . name - the label name

7211:   Level: intermediate

7213:   Developer Note:
7214:   Some of the functions that appropriate on labels using their number have the suffix ByNum, others do not.

7216: .seealso: [](ch_dmbase), `DM`, `DMLabel`, `DMGetLabelByNum()`, `DMGetLabel()`, `DMGetLabelValue()`, `DMSetLabelValue()`, `DMGetStratumIS()`
7217: @*/
7218: PetscErrorCode DMGetLabelName(DM dm, PetscInt n, const char *name[])
7219: {
7220:   DMLabelLink next = dm->labels;
7221:   PetscInt    l    = 0;

7223:   PetscFunctionBegin;
7225:   PetscAssertPointer(name, 3);
7226:   while (next) {
7227:     if (l == n) {
7228:       PetscCall(PetscObjectGetName((PetscObject)next->label, name));
7229:       PetscFunctionReturn(PETSC_SUCCESS);
7230:     }
7231:     ++l;
7232:     next = next->next;
7233:   }
7234:   SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Label %" PetscInt_FMT " does not exist in this DM", n);
7235: }

7237: /*@
7238:   DMHasLabel - Determine whether the `DM` has a label of a given name

7240:   Not Collective

7242:   Input Parameters:
7243: + dm   - The `DM` object
7244: - name - The label name

7246:   Output Parameter:
7247: . hasLabel - `PETSC_TRUE` if the label is present

7249:   Level: intermediate

7251: .seealso: [](ch_dmbase), `DM`, `DMLabel`, `DMGetLabel()`, `DMGetLabelByNum()`, `DMCreateLabel()`, `DMGetLabelValue()`, `DMSetLabelValue()`, `DMGetStratumIS()`
7252: @*/
7253: PetscErrorCode DMHasLabel(DM dm, const char name[], PetscBool *hasLabel)
7254: {
7255:   DMLabelLink next = dm->labels;
7256:   const char *lname;

7258:   PetscFunctionBegin;
7260:   PetscAssertPointer(name, 2);
7261:   PetscAssertPointer(hasLabel, 3);
7262:   *hasLabel = PETSC_FALSE;
7263:   while (next) {
7264:     PetscCall(PetscObjectGetName((PetscObject)next->label, &lname));
7265:     PetscCall(PetscStrcmp(name, lname, hasLabel));
7266:     if (*hasLabel) break;
7267:     next = next->next;
7268:   }
7269:   PetscFunctionReturn(PETSC_SUCCESS);
7270: }

7272: // PetscClangLinter pragma ignore: -fdoc-section-header-unknown
7273: /*@
7274:   DMGetLabel - Return the label of a given name, or `NULL`, from a `DM`

7276:   Not Collective

7278:   Input Parameters:
7279: + dm   - The `DM` object
7280: - name - The label name

7282:   Output Parameter:
7283: . label - The `DMLabel`, or `NULL` if the label is absent

7285:   Default labels in a `DMPLEX`:
7286: + "depth"       - Holds the depth (co-dimension) of each mesh point
7287: . "celltype"    - Holds the topological type of each cell
7288: . "ghost"       - If the DM is distributed with overlap, this marks the cells and faces in the overlap
7289: . "Cell Sets"   - Mirrors the cell sets defined by GMsh and ExodusII
7290: . "Face Sets"   - Mirrors the face sets defined by GMsh and ExodusII
7291: - "Vertex Sets" - Mirrors the vertex sets defined by GMsh

7293:   Level: intermediate

7295: .seealso: [](ch_dmbase), `DM`, `DMLabel`, `DMHasLabel()`, `DMGetLabelByNum()`, `DMAddLabel()`, `DMCreateLabel()`, `DMPlexGetDepthLabel()`, `DMPlexGetCellType()`
7296: @*/
7297: PetscErrorCode DMGetLabel(DM dm, const char name[], DMLabel *label)
7298: {
7299:   DMLabelLink next = dm->labels;
7300:   PetscBool   hasLabel;
7301:   const char *lname;

7303:   PetscFunctionBegin;
7305:   PetscAssertPointer(name, 2);
7306:   PetscAssertPointer(label, 3);
7307:   *label = NULL;
7308:   while (next) {
7309:     PetscCall(PetscObjectGetName((PetscObject)next->label, &lname));
7310:     PetscCall(PetscStrcmp(name, lname, &hasLabel));
7311:     if (hasLabel) {
7312:       *label = next->label;
7313:       break;
7314:     }
7315:     next = next->next;
7316:   }
7317:   PetscFunctionReturn(PETSC_SUCCESS);
7318: }

7320: /*@
7321:   DMGetLabelByNum - Return the nth label on a `DM`

7323:   Not Collective

7325:   Input Parameters:
7326: + dm - The `DM` object
7327: - n  - the label number

7329:   Output Parameter:
7330: . label - the label

7332:   Level: intermediate

7334: .seealso: [](ch_dmbase), `DM`, `DMLabel`, `DMAddLabel()`, `DMGetLabelValue()`, `DMSetLabelValue()`, `DMGetStratumIS()`
7335: @*/
7336: PetscErrorCode DMGetLabelByNum(DM dm, PetscInt n, DMLabel *label)
7337: {
7338:   DMLabelLink next = dm->labels;
7339:   PetscInt    l    = 0;

7341:   PetscFunctionBegin;
7343:   PetscAssertPointer(label, 3);
7344:   while (next) {
7345:     if (l == n) {
7346:       *label = next->label;
7347:       PetscFunctionReturn(PETSC_SUCCESS);
7348:     }
7349:     ++l;
7350:     next = next->next;
7351:   }
7352:   SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Label %" PetscInt_FMT " does not exist in this DM", n);
7353: }

7355: /*@
7356:   DMAddLabel - Add the label to this `DM`

7358:   Not Collective

7360:   Input Parameters:
7361: + dm    - The `DM` object
7362: - label - The `DMLabel`

7364:   Level: developer

7366: .seealso: [](ch_dmbase), `DM`, `DMLabel`, `DMCreateLabel()`, `DMHasLabel()`, `DMGetLabelValue()`, `DMSetLabelValue()`, `DMGetStratumIS()`
7367: @*/
7368: PetscErrorCode DMAddLabel(DM dm, DMLabel label)
7369: {
7370:   DMLabelLink l, *p, tmpLabel;
7371:   PetscBool   hasLabel;
7372:   const char *lname;
7373:   PetscBool   flg;

7375:   PetscFunctionBegin;
7377:   PetscCall(PetscObjectGetName((PetscObject)label, &lname));
7378:   PetscCall(DMHasLabel(dm, lname, &hasLabel));
7379:   PetscCheck(!hasLabel, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Label %s already exists in this DM", lname);
7380:   PetscCall(PetscCalloc1(1, &tmpLabel));
7381:   tmpLabel->label  = label;
7382:   tmpLabel->output = PETSC_TRUE;
7383:   for (p = &dm->labels; (l = *p); p = &l->next) { }
7384:   *p = tmpLabel;
7385:   PetscCall(PetscObjectReference((PetscObject)label));
7386:   PetscCall(PetscStrcmp(lname, "depth", &flg));
7387:   if (flg) dm->depthLabel = label;
7388:   PetscCall(PetscStrcmp(lname, "celltype", &flg));
7389:   if (flg) dm->celltypeLabel = label;
7390:   PetscFunctionReturn(PETSC_SUCCESS);
7391: }

7393: // PetscClangLinter pragma ignore: -fdoc-section-header-unknown
7394: /*@
7395:   DMSetLabel - Replaces the label of a given name, or ignores it if the name is not present

7397:   Not Collective

7399:   Input Parameters:
7400: + dm    - The `DM` object
7401: - label - The `DMLabel`, having the same name, to substitute

7403:   Default labels in a `DMPLEX`:
7404: + "depth"       - Holds the depth (co-dimension) of each mesh point
7405: . "celltype"    - Holds the topological type of each cell
7406: . "ghost"       - If the DM is distributed with overlap, this marks the cells and faces in the overlap
7407: . "Cell Sets"   - Mirrors the cell sets defined by GMsh and ExodusII
7408: . "Face Sets"   - Mirrors the face sets defined by GMsh and ExodusII
7409: - "Vertex Sets" - Mirrors the vertex sets defined by GMsh

7411:   Level: intermediate

7413: .seealso: [](ch_dmbase), `DM`, `DMLabel`, `DMCreateLabel()`, `DMHasLabel()`, `DMPlexGetDepthLabel()`, `DMPlexGetCellType()`
7414: @*/
7415: PetscErrorCode DMSetLabel(DM dm, DMLabel label)
7416: {
7417:   DMLabelLink next = dm->labels;
7418:   PetscBool   hasLabel, flg;
7419:   const char *name, *lname;

7421:   PetscFunctionBegin;
7424:   PetscCall(PetscObjectGetName((PetscObject)label, &name));
7425:   while (next) {
7426:     PetscCall(PetscObjectGetName((PetscObject)next->label, &lname));
7427:     PetscCall(PetscStrcmp(name, lname, &hasLabel));
7428:     if (hasLabel) {
7429:       PetscCall(PetscObjectReference((PetscObject)label));
7430:       PetscCall(PetscStrcmp(lname, "depth", &flg));
7431:       if (flg) dm->depthLabel = label;
7432:       PetscCall(PetscStrcmp(lname, "celltype", &flg));
7433:       if (flg) dm->celltypeLabel = label;
7434:       PetscCall(DMLabelDestroy(&next->label));
7435:       next->label = label;
7436:       break;
7437:     }
7438:     next = next->next;
7439:   }
7440:   PetscFunctionReturn(PETSC_SUCCESS);
7441: }

7443: /*@
7444:   DMRemoveLabel - Remove the label given by name from this `DM`

7446:   Not Collective

7448:   Input Parameters:
7449: + dm   - The `DM` object
7450: - name - The label name

7452:   Output Parameter:
7453: . label - The `DMLabel`, or `NULL` if the label is absent. Pass in `NULL` to call `DMLabelDestroy()` on the label, otherwise the
7454:           caller is responsible for calling `DMLabelDestroy()`.

7456:   Level: developer

7458: .seealso: [](ch_dmbase), `DM`, `DMLabel`, `DMCreateLabel()`, `DMHasLabel()`, `DMGetLabel()`, `DMGetLabelValue()`, `DMSetLabelValue()`, `DMLabelDestroy()`, `DMRemoveLabelBySelf()`
7459: @*/
7460: PetscErrorCode DMRemoveLabel(DM dm, const char name[], DMLabel *label)
7461: {
7462:   DMLabelLink link, *pnext;
7463:   PetscBool   hasLabel;
7464:   const char *lname;

7466:   PetscFunctionBegin;
7468:   PetscAssertPointer(name, 2);
7469:   if (label) {
7470:     PetscAssertPointer(label, 3);
7471:     *label = NULL;
7472:   }
7473:   for (pnext = &dm->labels; (link = *pnext); pnext = &link->next) {
7474:     PetscCall(PetscObjectGetName((PetscObject)link->label, &lname));
7475:     PetscCall(PetscStrcmp(name, lname, &hasLabel));
7476:     if (hasLabel) {
7477:       *pnext = link->next; /* Remove from list */
7478:       PetscCall(PetscStrcmp(name, "depth", &hasLabel));
7479:       if (hasLabel) dm->depthLabel = NULL;
7480:       PetscCall(PetscStrcmp(name, "celltype", &hasLabel));
7481:       if (hasLabel) dm->celltypeLabel = NULL;
7482:       if (label) *label = link->label;
7483:       else PetscCall(DMLabelDestroy(&link->label));
7484:       PetscCall(PetscFree(link));
7485:       break;
7486:     }
7487:   }
7488:   PetscFunctionReturn(PETSC_SUCCESS);
7489: }

7491: /*@
7492:   DMRemoveLabelBySelf - Remove the label from this `DM`

7494:   Not Collective

7496:   Input Parameters:
7497: + dm           - The `DM` object
7498: . label        - The `DMLabel` to be removed from the `DM`
7499: - failNotFound - Should it fail if the label is not found in the `DM`?

7501:   Level: developer

7503:   Note:
7504:   Only exactly the same instance is removed if found, name match is ignored.
7505:   If the `DM` has an exclusive reference to the label, the label gets destroyed and
7506:   *label nullified.

7508: .seealso: [](ch_dmbase), `DM`, `DMLabel`, `DMCreateLabel()`, `DMHasLabel()`, `DMGetLabel()`, `DMGetLabelValue()`, `DMSetLabelValue()`, `DMLabelDestroy()`, `DMRemoveLabel()`
7509: @*/
7510: PetscErrorCode DMRemoveLabelBySelf(DM dm, DMLabel *label, PetscBool failNotFound)
7511: {
7512:   DMLabelLink link, *pnext;
7513:   PetscBool   hasLabel = PETSC_FALSE;

7515:   PetscFunctionBegin;
7517:   PetscAssertPointer(label, 2);
7518:   if (!*label && !failNotFound) PetscFunctionReturn(PETSC_SUCCESS);
7521:   for (pnext = &dm->labels; (link = *pnext); pnext = &link->next) {
7522:     if (*label == link->label) {
7523:       hasLabel = PETSC_TRUE;
7524:       *pnext   = link->next; /* Remove from list */
7525:       if (*label == dm->depthLabel) dm->depthLabel = NULL;
7526:       if (*label == dm->celltypeLabel) dm->celltypeLabel = NULL;
7527:       if (((PetscObject)link->label)->refct < 2) *label = NULL; /* nullify if exclusive reference */
7528:       PetscCall(DMLabelDestroy(&link->label));
7529:       PetscCall(PetscFree(link));
7530:       break;
7531:     }
7532:   }
7533:   PetscCheck(hasLabel || !failNotFound, PetscObjectComm((PetscObject)dm), PETSC_ERR_ARG_WRONG, "Given label not found in DM");
7534:   PetscFunctionReturn(PETSC_SUCCESS);
7535: }

7537: /*@
7538:   DMGetLabelOutput - Get the output flag for a given label

7540:   Not Collective

7542:   Input Parameters:
7543: + dm   - The `DM` object
7544: - name - The label name

7546:   Output Parameter:
7547: . output - The flag for output

7549:   Level: developer

7551: .seealso: [](ch_dmbase), `DM`, `DMLabel`, `DMSetLabelOutput()`, `DMCreateLabel()`, `DMHasLabel()`, `DMGetLabelValue()`, `DMSetLabelValue()`, `DMGetStratumIS()`
7552: @*/
7553: PetscErrorCode DMGetLabelOutput(DM dm, const char name[], PetscBool *output)
7554: {
7555:   DMLabelLink next = dm->labels;
7556:   const char *lname;

7558:   PetscFunctionBegin;
7560:   PetscAssertPointer(name, 2);
7561:   PetscAssertPointer(output, 3);
7562:   while (next) {
7563:     PetscBool flg;

7565:     PetscCall(PetscObjectGetName((PetscObject)next->label, &lname));
7566:     PetscCall(PetscStrcmp(name, lname, &flg));
7567:     if (flg) {
7568:       *output = next->output;
7569:       PetscFunctionReturn(PETSC_SUCCESS);
7570:     }
7571:     next = next->next;
7572:   }
7573:   SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "No label named %s was present in this dm", name);
7574: }

7576: /*@
7577:   DMSetLabelOutput - Set if a given label should be saved to a `PetscViewer` in calls to `DMView()`

7579:   Not Collective

7581:   Input Parameters:
7582: + dm     - The `DM` object
7583: . name   - The label name
7584: - output - `PETSC_TRUE` to save the label to the viewer

7586:   Level: developer

7588: .seealso: [](ch_dmbase), `DM`, `DMLabel`, `DMGetOutputFlag()`, `DMGetLabelOutput()`, `DMCreateLabel()`, `DMHasLabel()`, `DMGetLabelValue()`, `DMSetLabelValue()`, `DMGetStratumIS()`
7589: @*/
7590: PetscErrorCode DMSetLabelOutput(DM dm, const char name[], PetscBool output)
7591: {
7592:   DMLabelLink next = dm->labels;
7593:   const char *lname;

7595:   PetscFunctionBegin;
7597:   PetscAssertPointer(name, 2);
7598:   while (next) {
7599:     PetscBool flg;

7601:     PetscCall(PetscObjectGetName((PetscObject)next->label, &lname));
7602:     PetscCall(PetscStrcmp(name, lname, &flg));
7603:     if (flg) {
7604:       next->output = output;
7605:       PetscFunctionReturn(PETSC_SUCCESS);
7606:     }
7607:     next = next->next;
7608:   }
7609:   SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "No label named %s was present in this dm", name);
7610: }

7612: /*@
7613:   DMCopyLabels - Copy labels from one `DM` mesh to another `DM` with a superset of the points

7615:   Collective

7617:   Input Parameters:
7618: + dmA   - The `DM` object with initial labels
7619: . dmB   - The `DM` object to which labels are copied
7620: . mode  - Copy labels by pointers (`PETSC_OWN_POINTER`) or duplicate them (`PETSC_COPY_VALUES`)
7621: . all   - Copy all labels including "depth", "dim", and "celltype" (`PETSC_TRUE`) which are otherwise ignored (`PETSC_FALSE`)
7622: - emode - How to behave when a `DMLabel` in the source and destination `DM`s with the same name is encountered (see `DMCopyLabelsMode`)

7624:   Level: intermediate

7626:   Note:
7627:   This is typically used when interpolating or otherwise adding to a mesh, or testing.

7629: .seealso: [](ch_dmbase), `DM`, `DMLabel`, `DMAddLabel()`, `DMCopyLabelsMode`
7630: @*/
7631: PetscErrorCode DMCopyLabels(DM dmA, DM dmB, PetscCopyMode mode, PetscBool all, DMCopyLabelsMode emode)
7632: {
7633:   DMLabel     label, labelNew, labelOld;
7634:   const char *name;
7635:   PetscBool   flg;
7636:   DMLabelLink link;

7638:   PetscFunctionBegin;
7643:   PetscCheck(mode != PETSC_USE_POINTER, PetscObjectComm((PetscObject)dmA), PETSC_ERR_SUP, "PETSC_USE_POINTER not supported for objects");
7644:   if (dmA == dmB) PetscFunctionReturn(PETSC_SUCCESS);
7645:   for (link = dmA->labels; link; link = link->next) {
7646:     label = link->label;
7647:     PetscCall(PetscObjectGetName((PetscObject)label, &name));
7648:     if (!all) {
7649:       PetscCall(PetscStrcmp(name, "depth", &flg));
7650:       if (flg) continue;
7651:       PetscCall(PetscStrcmp(name, "dim", &flg));
7652:       if (flg) continue;
7653:       PetscCall(PetscStrcmp(name, "celltype", &flg));
7654:       if (flg) continue;
7655:     }
7656:     PetscCall(DMGetLabel(dmB, name, &labelOld));
7657:     if (labelOld) {
7658:       switch (emode) {
7659:       case DM_COPY_LABELS_KEEP:
7660:         continue;
7661:       case DM_COPY_LABELS_REPLACE:
7662:         PetscCall(DMRemoveLabelBySelf(dmB, &labelOld, PETSC_TRUE));
7663:         break;
7664:       case DM_COPY_LABELS_FAIL:
7665:         SETERRQ(PetscObjectComm((PetscObject)dmA), PETSC_ERR_ARG_OUTOFRANGE, "Label %s already exists in destination DM", name);
7666:       default:
7667:         SETERRQ(PetscObjectComm((PetscObject)dmA), PETSC_ERR_ARG_OUTOFRANGE, "Unhandled DMCopyLabelsMode %d", (int)emode);
7668:       }
7669:     }
7670:     if (mode == PETSC_COPY_VALUES) PetscCall(DMLabelDuplicate(label, &labelNew));
7671:     else labelNew = label;
7672:     PetscCall(DMAddLabel(dmB, labelNew));
7673:     if (mode == PETSC_COPY_VALUES) PetscCall(DMLabelDestroy(&labelNew));
7674:   }
7675:   PetscFunctionReturn(PETSC_SUCCESS);
7676: }

7678: /*@C
7679:   DMCompareLabels - Compare labels between two `DM` objects

7681:   Collective; No Fortran Support

7683:   Input Parameters:
7684: + dm0 - First `DM` object
7685: - dm1 - Second `DM` object

7687:   Output Parameters:
7688: + equal   - (Optional) Flag whether labels of `dm0` and `dm1` are the same
7689: - message - (Optional) Message describing the difference, or `NULL` if there is no difference

7691:   Level: intermediate

7693:   Notes:
7694:   The output flag equal will be the same on all processes.

7696:   If equal is passed as `NULL` and difference is found, an error is thrown on all processes.

7698:   Make sure to pass equal is `NULL` on all processes or none of them.

7700:   The output message is set independently on each rank.

7702:   message must be freed with `PetscFree()`

7704:   If message is passed as `NULL` and a difference is found, the difference description is printed to `stderr` in synchronized manner.

7706:   Make sure to pass message as `NULL` on all processes or no processes.

7708:   Labels are matched by name. If the number of labels and their names are equal,
7709:   `DMLabelCompare()` is used to compare each pair of labels with the same name.

7711:   Developer Note:
7712:   Cannot automatically generate the Fortran stub because `message` must be freed with `PetscFree()`

7714: .seealso: [](ch_dmbase), `DM`, `DMLabel`, `DMAddLabel()`, `DMCopyLabelsMode`, `DMLabelCompare()`
7715: @*/
7716: PetscErrorCode DMCompareLabels(DM dm0, DM dm1, PetscBool *equal, char *message[]) PeNS
7717: {
7718:   PetscInt    n, i;
7719:   char        msg[PETSC_MAX_PATH_LEN] = "";
7720:   PetscBool   eq;
7721:   MPI_Comm    comm;
7722:   PetscMPIInt rank;

7724:   PetscFunctionBegin;
7727:   PetscCheckSameComm(dm0, 1, dm1, 2);
7728:   if (equal) PetscAssertPointer(equal, 3);
7729:   if (message) PetscAssertPointer(message, 4);
7730:   PetscCall(PetscObjectGetComm((PetscObject)dm0, &comm));
7731:   PetscCallMPI(MPI_Comm_rank(comm, &rank));
7732:   {
7733:     PetscInt n1;

7735:     PetscCall(DMGetNumLabels(dm0, &n));
7736:     PetscCall(DMGetNumLabels(dm1, &n1));
7737:     eq = (PetscBool)(n == n1);
7738:     if (!eq) PetscCall(PetscSNPrintf(msg, sizeof(msg), "Number of labels in dm0 = %" PetscInt_FMT " != %" PetscInt_FMT " = Number of labels in dm1", n, n1));
7739:     PetscCallMPI(MPIU_Allreduce(MPI_IN_PLACE, &eq, 1, MPI_C_BOOL, MPI_LAND, comm));
7740:     if (!eq) goto finish;
7741:   }
7742:   for (i = 0; i < n; i++) {
7743:     DMLabel     l0, l1;
7744:     const char *name;
7745:     char       *msgInner;

7747:     /* Ignore label order */
7748:     PetscCall(DMGetLabelByNum(dm0, i, &l0));
7749:     PetscCall(PetscObjectGetName((PetscObject)l0, &name));
7750:     PetscCall(DMGetLabel(dm1, name, &l1));
7751:     if (!l1) {
7752:       PetscCall(PetscSNPrintf(msg, sizeof(msg), "Label \"%s\" (#%" PetscInt_FMT " in dm0) not found in dm1", name, i));
7753:       eq = PETSC_FALSE;
7754:       break;
7755:     }
7756:     PetscCall(DMLabelCompare(comm, l0, l1, &eq, &msgInner));
7757:     PetscCall(PetscStrncpy(msg, msgInner, sizeof(msg)));
7758:     PetscCall(PetscFree(msgInner));
7759:     if (!eq) break;
7760:   }
7761:   PetscCallMPI(MPIU_Allreduce(MPI_IN_PLACE, &eq, 1, MPI_C_BOOL, MPI_LAND, comm));
7762: finish:
7763:   /* If message output arg not set, print to stderr */
7764:   if (message) {
7765:     *message = NULL;
7766:     if (msg[0]) PetscCall(PetscStrallocpy(msg, message));
7767:   } else {
7768:     if (msg[0]) PetscCall(PetscSynchronizedFPrintf(comm, PETSC_STDERR, "[%d] %s\n", rank, msg));
7769:     PetscCall(PetscSynchronizedFlush(comm, PETSC_STDERR));
7770:   }
7771:   /* If same output arg not ser and labels are not equal, throw error */
7772:   if (equal) *equal = eq;
7773:   else PetscCheck(eq, comm, PETSC_ERR_ARG_INCOMP, "DMLabels are not the same in dm0 and dm1");
7774:   PetscFunctionReturn(PETSC_SUCCESS);
7775: }

7777: PetscErrorCode DMSetLabelValue_Fast(DM dm, DMLabel *label, const char name[], PetscInt point, PetscInt value)
7778: {
7779:   PetscFunctionBegin;
7780:   PetscAssertPointer(label, 2);
7781:   if (!*label) {
7782:     PetscCall(DMCreateLabel(dm, name));
7783:     PetscCall(DMGetLabel(dm, name, label));
7784:   }
7785:   PetscCall(DMLabelSetValue(*label, point, value));
7786:   PetscFunctionReturn(PETSC_SUCCESS);
7787: }

7789: /*
7790:   Many mesh programs, such as Triangle and TetGen, allow only a single label for each mesh point. Therefore, we would
7791:   like to encode all label IDs using a single, universal label. We can do this by assigning an integer to every
7792:   (label, id) pair in the DM.

7794:   However, a mesh point can have multiple labels, so we must separate all these values. We will assign a bit range to
7795:   each label.
7796: */
7797: PetscErrorCode DMUniversalLabelCreate(DM dm, DMUniversalLabel *universal)
7798: {
7799:   DMUniversalLabel ul;
7800:   PetscBool       *active;
7801:   PetscInt         pStart, pEnd, p, Nl, l, m;

7803:   PetscFunctionBegin;
7804:   PetscCall(PetscMalloc1(1, &ul));
7805:   PetscCall(DMLabelCreate(PETSC_COMM_SELF, "universal", &ul->label));
7806:   PetscCall(DMGetNumLabels(dm, &Nl));
7807:   PetscCall(PetscCalloc1(Nl, &active));
7808:   ul->Nl = 0;
7809:   for (l = 0; l < Nl; ++l) {
7810:     PetscBool   isdepth, iscelltype;
7811:     const char *name;

7813:     PetscCall(DMGetLabelName(dm, l, &name));
7814:     PetscCall(PetscStrncmp(name, "depth", 6, &isdepth));
7815:     PetscCall(PetscStrncmp(name, "celltype", 9, &iscelltype));
7816:     active[l] = !(isdepth || iscelltype) ? PETSC_TRUE : PETSC_FALSE;
7817:     if (active[l]) ++ul->Nl;
7818:   }
7819:   PetscCall(PetscCalloc5(ul->Nl, &ul->names, ul->Nl, &ul->indices, ul->Nl + 1, &ul->offsets, ul->Nl + 1, &ul->bits, ul->Nl, &ul->masks));
7820:   ul->Nv = 0;
7821:   for (l = 0, m = 0; l < Nl; ++l) {
7822:     DMLabel     label;
7823:     PetscInt    nv;
7824:     const char *name;

7826:     if (!active[l]) continue;
7827:     PetscCall(DMGetLabelName(dm, l, &name));
7828:     PetscCall(DMGetLabelByNum(dm, l, &label));
7829:     PetscCall(DMLabelGetNumValues(label, &nv));
7830:     PetscCall(PetscStrallocpy(name, &ul->names[m]));
7831:     ul->indices[m] = l;
7832:     ul->Nv += nv;
7833:     ul->offsets[m + 1] = nv;
7834:     ul->bits[m + 1]    = PetscCeilReal(PetscLog2Real(nv + 1));
7835:     ++m;
7836:   }
7837:   for (l = 1; l <= ul->Nl; ++l) {
7838:     ul->offsets[l] = ul->offsets[l - 1] + ul->offsets[l];
7839:     ul->bits[l]    = ul->bits[l - 1] + ul->bits[l];
7840:   }
7841:   for (l = 0; l < ul->Nl; ++l) {
7842:     PetscInt b;

7844:     ul->masks[l] = 0;
7845:     for (b = ul->bits[l]; b < ul->bits[l + 1]; ++b) ul->masks[l] |= 1 << b;
7846:   }
7847:   PetscCall(PetscMalloc1(ul->Nv, &ul->values));
7848:   for (l = 0, m = 0; l < Nl; ++l) {
7849:     DMLabel         label;
7850:     IS              valueIS;
7851:     const PetscInt *varr;
7852:     PetscInt        nv, v;

7854:     if (!active[l]) continue;
7855:     PetscCall(DMGetLabelByNum(dm, l, &label));
7856:     PetscCall(DMLabelGetNumValues(label, &nv));
7857:     PetscCall(DMLabelGetValueIS(label, &valueIS));
7858:     PetscCall(ISGetIndices(valueIS, &varr));
7859:     for (v = 0; v < nv; ++v) ul->values[ul->offsets[m] + v] = varr[v];
7860:     PetscCall(ISRestoreIndices(valueIS, &varr));
7861:     PetscCall(ISDestroy(&valueIS));
7862:     PetscCall(PetscSortInt(nv, &ul->values[ul->offsets[m]]));
7863:     ++m;
7864:   }
7865:   PetscCall(DMPlexGetChart(dm, &pStart, &pEnd));
7866:   for (p = pStart; p < pEnd; ++p) {
7867:     PetscInt  uval   = 0;
7868:     PetscBool marked = PETSC_FALSE;

7870:     for (l = 0, m = 0; l < Nl; ++l) {
7871:       DMLabel  label;
7872:       PetscInt val, defval, loc, nv;

7874:       if (!active[l]) continue;
7875:       PetscCall(DMGetLabelByNum(dm, l, &label));
7876:       PetscCall(DMLabelGetValue(label, p, &val));
7877:       PetscCall(DMLabelGetDefaultValue(label, &defval));
7878:       if (val == defval) {
7879:         ++m;
7880:         continue;
7881:       }
7882:       nv     = ul->offsets[m + 1] - ul->offsets[m];
7883:       marked = PETSC_TRUE;
7884:       PetscCall(PetscFindInt(val, nv, &ul->values[ul->offsets[m]], &loc));
7885:       PetscCheck(loc >= 0, PETSC_COMM_SELF, PETSC_ERR_PLIB, "Label value %" PetscInt_FMT " not found in compression array", val);
7886:       uval += (loc + 1) << ul->bits[m];
7887:       ++m;
7888:     }
7889:     if (marked) PetscCall(DMLabelSetValue(ul->label, p, uval));
7890:   }
7891:   PetscCall(PetscFree(active));
7892:   *universal = ul;
7893:   PetscFunctionReturn(PETSC_SUCCESS);
7894: }

7896: PetscErrorCode DMUniversalLabelDestroy(DMUniversalLabel *universal)
7897: {
7898:   PetscInt l;

7900:   PetscFunctionBegin;
7901:   for (l = 0; l < (*universal)->Nl; ++l) PetscCall(PetscFree((*universal)->names[l]));
7902:   PetscCall(DMLabelDestroy(&(*universal)->label));
7903:   PetscCall(PetscFree5((*universal)->names, (*universal)->indices, (*universal)->offsets, (*universal)->bits, (*universal)->masks));
7904:   PetscCall(PetscFree((*universal)->values));
7905:   PetscCall(PetscFree(*universal));
7906:   *universal = NULL;
7907:   PetscFunctionReturn(PETSC_SUCCESS);
7908: }

7910: PetscErrorCode DMUniversalLabelGetLabel(DMUniversalLabel ul, DMLabel *ulabel)
7911: {
7912:   PetscFunctionBegin;
7913:   PetscAssertPointer(ulabel, 2);
7914:   *ulabel = ul->label;
7915:   PetscFunctionReturn(PETSC_SUCCESS);
7916: }

7918: PetscErrorCode DMUniversalLabelCreateLabels(DMUniversalLabel ul, PetscBool preserveOrder, DM dm)
7919: {
7920:   PetscInt Nl = ul->Nl, l;

7922:   PetscFunctionBegin;
7924:   for (l = 0; l < Nl; ++l) {
7925:     if (preserveOrder) PetscCall(DMCreateLabelAtIndex(dm, ul->indices[l], ul->names[l]));
7926:     else PetscCall(DMCreateLabel(dm, ul->names[l]));
7927:   }
7928:   if (preserveOrder) {
7929:     for (l = 0; l < ul->Nl; ++l) {
7930:       const char *name;
7931:       PetscBool   match;

7933:       PetscCall(DMGetLabelName(dm, ul->indices[l], &name));
7934:       PetscCall(PetscStrcmp(name, ul->names[l], &match));
7935:       PetscCheck(match, PetscObjectComm((PetscObject)dm), PETSC_ERR_ARG_WRONG, "Label %" PetscInt_FMT " name %s does not match new name %s", l, name, ul->names[l]);
7936:     }
7937:   }
7938:   PetscFunctionReturn(PETSC_SUCCESS);
7939: }

7941: PetscErrorCode DMUniversalLabelSetLabelValue(DMUniversalLabel ul, DM dm, PetscBool useIndex, PetscInt p, PetscInt value)
7942: {
7943:   PetscInt l;

7945:   PetscFunctionBegin;
7946:   for (l = 0; l < ul->Nl; ++l) {
7947:     DMLabel  label;
7948:     PetscInt lval = (value & ul->masks[l]) >> ul->bits[l];

7950:     if (lval) {
7951:       if (useIndex) PetscCall(DMGetLabelByNum(dm, ul->indices[l], &label));
7952:       else PetscCall(DMGetLabel(dm, ul->names[l], &label));
7953:       PetscCall(DMLabelSetValue(label, p, ul->values[ul->offsets[l] + lval - 1]));
7954:     }
7955:   }
7956:   PetscFunctionReturn(PETSC_SUCCESS);
7957: }

7959: /*@
7960:   DMGetCoarseDM - Get the coarse `DM`from which this `DM` was obtained by refinement

7962:   Not Collective

7964:   Input Parameter:
7965: . dm - The `DM` object

7967:   Output Parameter:
7968: . cdm - The coarse `DM`

7970:   Level: intermediate

7972: .seealso: [](ch_dmbase), `DM`, `DMSetCoarseDM()`, `DMCoarsen()`
7973: @*/
7974: PetscErrorCode DMGetCoarseDM(DM dm, DM *cdm)
7975: {
7976:   PetscFunctionBegin;
7978:   PetscAssertPointer(cdm, 2);
7979:   *cdm = dm->coarseMesh;
7980:   PetscFunctionReturn(PETSC_SUCCESS);
7981: }

7983: /*@
7984:   DMSetCoarseDM - Set the coarse `DM` from which this `DM` was obtained by refinement

7986:   Input Parameters:
7987: + dm  - The `DM` object
7988: - cdm - The coarse `DM`

7990:   Level: intermediate

7992:   Note:
7993:   Normally this is set automatically by `DMRefine()`

7995: .seealso: [](ch_dmbase), `DM`, `DMGetCoarseDM()`, `DMCoarsen()`, `DMSetRefine()`, `DMSetFineDM()`
7996: @*/
7997: PetscErrorCode DMSetCoarseDM(DM dm, DM cdm)
7998: {
7999:   PetscFunctionBegin;
8002:   if (dm == cdm) cdm = NULL;
8003:   PetscCall(PetscObjectReference((PetscObject)cdm));
8004:   PetscCall(DMDestroy(&dm->coarseMesh));
8005:   dm->coarseMesh = cdm;
8006:   PetscFunctionReturn(PETSC_SUCCESS);
8007: }

8009: /*@
8010:   DMGetFineDM - Get the fine mesh from which this `DM` was obtained by coarsening

8012:   Input Parameter:
8013: . dm - The `DM` object

8015:   Output Parameter:
8016: . fdm - The fine `DM`

8018:   Level: intermediate

8020: .seealso: [](ch_dmbase), `DM`, `DMSetFineDM()`, `DMCoarsen()`, `DMRefine()`
8021: @*/
8022: PetscErrorCode DMGetFineDM(DM dm, DM *fdm)
8023: {
8024:   PetscFunctionBegin;
8026:   PetscAssertPointer(fdm, 2);
8027:   *fdm = dm->fineMesh;
8028:   PetscFunctionReturn(PETSC_SUCCESS);
8029: }

8031: /*@
8032:   DMSetFineDM - Set the fine mesh from which this was obtained by coarsening

8034:   Input Parameters:
8035: + dm  - The `DM` object
8036: - fdm - The fine `DM`

8038:   Level: developer

8040:   Note:
8041:   Normally this is set automatically by `DMCoarsen()`

8043: .seealso: [](ch_dmbase), `DM`, `DMGetFineDM()`, `DMCoarsen()`, `DMRefine()`
8044: @*/
8045: PetscErrorCode DMSetFineDM(DM dm, DM fdm)
8046: {
8047:   PetscFunctionBegin;
8050:   if (dm == fdm) fdm = NULL;
8051:   PetscCall(PetscObjectReference((PetscObject)fdm));
8052:   PetscCall(DMDestroy(&dm->fineMesh));
8053:   dm->fineMesh = fdm;
8054:   PetscFunctionReturn(PETSC_SUCCESS);
8055: }

8057: /*@C
8058:   DMAddBoundary - Add a boundary condition, for a single field, to a model represented by a `DM`

8060:   Collective

8062:   Input Parameters:
8063: + dm       - The `DM`, with a `PetscDS` that matches the problem being constrained
8064: . type     - The type of condition, e.g. `DM_BC_ESSENTIAL_ANALYTIC`, `DM_BC_ESSENTIAL_FIELD` (Dirichlet), or `DM_BC_NATURAL` (Neumann)
8065: . name     - The BC name
8066: . label    - The label defining constrained points
8067: . Nv       - The number of `DMLabel` values for constrained points
8068: . values   - An array of values for constrained points
8069: . field    - The field to constrain
8070: . Nc       - The number of constrained field components (0 will constrain all components)
8071: . comps    - An array of constrained component numbers
8072: . bcFunc   - A pointwise function giving boundary values
8073: . bcFunc_t - A pointwise function giving the time derivative of the boundary values, or `NULL`
8074: - ctx      - An optional user context for bcFunc

8076:   Output Parameter:
8077: . bd - (Optional) Boundary number

8079:   Options Database Keys:
8080: + -bc_NAME values     - Overrides the boundary ids for boundary named NAME
8081: - -bc_NAME_comp comps - Overrides the boundary components for boundary named NAME

8083:   Level: intermediate

8085:   Notes:
8086:   If the `DM` is of type `DMPLEX` and the field is of type `PetscFE`, then this function completes the label using `DMPlexLabelComplete()`.

8088:   Both bcFunc and bcFunc_t will depend on the boundary condition type. If the type if `DM_BC_ESSENTIAL`, then the calling sequence is\:
8089: .vb
8090:  void bcFunc(PetscInt dim, PetscReal time, const PetscReal x[], PetscInt Nc, PetscScalar bcval[])
8091: .ve

8093:   If the type is `DM_BC_ESSENTIAL_FIELD` or other _FIELD value, then the calling sequence is\:

8095: .vb
8096:   void bcFunc(PetscInt dim, PetscInt Nf, PetscInt NfAux,
8097:               const PetscInt uOff[], const PetscInt uOff_x[], const PetscScalar u[], const PetscScalar u_t[], const PetscScalar u_x[],
8098:               const PetscInt aOff[], const PetscInt aOff_x[], const PetscScalar a[], const PetscScalar a_t[], const PetscScalar a_x[],
8099:               PetscReal time, const PetscReal x[], PetscScalar bcval[])
8100: .ve
8101: + dim - the spatial dimension
8102: . Nf - the number of fields
8103: . uOff - the offset into u[] and u_t[] for each field
8104: . uOff_x - the offset into u_x[] for each field
8105: . u - each field evaluated at the current point
8106: . u_t - the time derivative of each field evaluated at the current point
8107: . u_x - the gradient of each field evaluated at the current point
8108: . aOff - the offset into a[] and a_t[] for each auxiliary field
8109: . aOff_x - the offset into a_x[] for each auxiliary field
8110: . a - each auxiliary field evaluated at the current point
8111: . a_t - the time derivative of each auxiliary field evaluated at the current point
8112: . a_x - the gradient of auxiliary each field evaluated at the current point
8113: . t - current time
8114: . x - coordinates of the current point
8115: . numConstants - number of constant parameters
8116: . constants - constant parameters
8117: - bcval - output values at the current point

8119: .seealso: [](ch_dmbase), `DM`, `DSGetBoundary()`, `PetscDSAddBoundary()`
8120: @*/
8121: PetscErrorCode DMAddBoundary(DM dm, DMBoundaryConditionType type, const char name[], DMLabel label, PetscInt Nv, const PetscInt values[], PetscInt field, PetscInt Nc, const PetscInt comps[], PetscVoidFn *bcFunc, PetscVoidFn *bcFunc_t, PetscCtx ctx, PetscInt *bd)
8122: {
8123:   PetscDS ds;

8125:   PetscFunctionBegin;
8132:   PetscCheck(!dm->localSection, PetscObjectComm((PetscObject)dm), PETSC_ERR_ARG_WRONGSTATE, "Cannot add boundary to DM after creating local section");
8133:   PetscCall(DMGetDS(dm, &ds));
8134:   /* Complete label */
8135:   if (label) {
8136:     PetscObject  obj;
8137:     PetscClassId id;

8139:     PetscCall(DMGetField(dm, field, NULL, &obj));
8140:     PetscCall(PetscObjectGetClassId(obj, &id));
8141:     if (id == PETSCFE_CLASSID) {
8142:       DM plex;

8144:       PetscCall(DMConvert(dm, DMPLEX, &plex));
8145:       if (plex) PetscCall(DMPlexLabelComplete(plex, label));
8146:       PetscCall(DMDestroy(&plex));
8147:     }
8148:   }
8149:   PetscCall(PetscDSAddBoundary(ds, type, name, label, Nv, values, field, Nc, comps, bcFunc, bcFunc_t, ctx, bd));
8150:   PetscFunctionReturn(PETSC_SUCCESS);
8151: }

8153: /* TODO Remove this since now the structures are the same */
8154: static PetscErrorCode DMPopulateBoundary(DM dm)
8155: {
8156:   PetscDS     ds;
8157:   DMBoundary *lastnext;
8158:   DSBoundary  dsbound;

8160:   PetscFunctionBegin;
8161:   PetscCall(DMGetDS(dm, &ds));
8162:   dsbound = ds->boundary;
8163:   if (dm->boundary) {
8164:     DMBoundary next = dm->boundary;

8166:     /* quick check to see if the PetscDS has changed */
8167:     if (next->dsboundary == dsbound) PetscFunctionReturn(PETSC_SUCCESS);
8168:     /* the PetscDS has changed: tear down and rebuild */
8169:     while (next) {
8170:       DMBoundary b = next;

8172:       next = b->next;
8173:       PetscCall(PetscFree(b));
8174:     }
8175:     dm->boundary = NULL;
8176:   }

8178:   lastnext = &dm->boundary;
8179:   while (dsbound) {
8180:     DMBoundary dmbound;

8182:     PetscCall(PetscNew(&dmbound));
8183:     dmbound->dsboundary = dsbound;
8184:     dmbound->label      = dsbound->label;
8185:     /* push on the back instead of the front so that it is in the same order as in the PetscDS */
8186:     *lastnext = dmbound;
8187:     lastnext  = &dmbound->next;
8188:     dsbound   = dsbound->next;
8189:   }
8190:   PetscFunctionReturn(PETSC_SUCCESS);
8191: }

8193: /* TODO: missing manual page */
8194: PetscErrorCode DMIsBoundaryPoint(DM dm, PetscInt point, PetscBool *isBd)
8195: {
8196:   DMBoundary b;

8198:   PetscFunctionBegin;
8200:   PetscAssertPointer(isBd, 3);
8201:   *isBd = PETSC_FALSE;
8202:   PetscCall(DMPopulateBoundary(dm));
8203:   b = dm->boundary;
8204:   while (b && !*isBd) {
8205:     DMLabel    label = b->label;
8206:     DSBoundary dsb   = b->dsboundary;
8207:     PetscInt   i;

8209:     if (label) {
8210:       for (i = 0; i < dsb->Nv && !*isBd; ++i) PetscCall(DMLabelStratumHasPoint(label, dsb->values[i], point, isBd));
8211:     }
8212:     b = b->next;
8213:   }
8214:   PetscFunctionReturn(PETSC_SUCCESS);
8215: }

8217: /*@
8218:   DMHasBound - Determine whether a bound condition was specified

8220:   Logically collective

8222:   Input Parameter:
8223: . dm - The `DM`, with a `PetscDS` that matches the problem being constrained

8225:   Output Parameter:
8226: . hasBound - Flag indicating if a bound condition was specified

8228:   Level: intermediate

8230: .seealso: [](ch_dmbase), `DM`, `DSAddBoundary()`, `PetscDSAddBoundary()`
8231: @*/
8232: PetscErrorCode DMHasBound(DM dm, PetscBool *hasBound)
8233: {
8234:   PetscDS  ds;
8235:   PetscInt Nf, numBd;

8237:   PetscFunctionBegin;
8238:   *hasBound = PETSC_FALSE;
8239:   PetscCall(DMGetDS(dm, &ds));
8240:   PetscCall(PetscDSGetNumFields(ds, &Nf));
8241:   for (PetscInt f = 0; f < Nf; ++f) {
8242:     PetscSimplePointFn *lfunc, *ufunc;

8244:     PetscCall(PetscDSGetLowerBound(ds, f, &lfunc, NULL));
8245:     PetscCall(PetscDSGetUpperBound(ds, f, &ufunc, NULL));
8246:     if (lfunc || ufunc) *hasBound = PETSC_TRUE;
8247:   }

8249:   PetscCall(PetscDSGetNumBoundary(ds, &numBd));
8250:   PetscCall(PetscDSUpdateBoundaryLabels(ds, dm));
8251:   for (PetscInt b = 0; b < numBd; ++b) {
8252:     PetscWeakForm           wf;
8253:     DMBoundaryConditionType type;
8254:     const char             *name;
8255:     DMLabel                 label;
8256:     PetscInt                numids;
8257:     const PetscInt         *ids;
8258:     PetscInt                field, Nc;
8259:     const PetscInt         *comps;
8260:     PetscVoidFn            *bvfunc;
8261:     void                   *ctx;

8263:     PetscCall(PetscDSGetBoundary(ds, b, &wf, &type, &name, &label, &numids, &ids, &field, &Nc, &comps, &bvfunc, NULL, &ctx));
8264:     if (type == DM_BC_LOWER_BOUND || type == DM_BC_UPPER_BOUND) *hasBound = PETSC_TRUE;
8265:   }
8266:   PetscFunctionReturn(PETSC_SUCCESS);
8267: }

8269: /*@C
8270:   DMProjectFunction - This projects the given function into the function space provided by a `DM`, putting the coefficients in a global vector.

8272:   Collective

8274:   Input Parameters:
8275: + dm    - The `DM`
8276: . time  - The time
8277: . funcs - The coordinate functions to evaluate, one per field
8278: . ctxs  - Optional array of contexts to pass to each coordinate function.  ctxs itself may be null.
8279: - mode  - The insertion mode for values

8281:   Output Parameter:
8282: . X - vector

8284:   Calling sequence of `funcs`:
8285: + dim  - The spatial dimension
8286: . time - The time at which to sample
8287: . x    - The coordinates
8288: . Nc   - The number of components
8289: . u    - The output field values
8290: - ctx  - optional function context

8292:   Level: developer

8294:   Developer Notes:
8295:   This API is specific to only particular usage of `DM`

8297:   The notes need to provide some information about what has to be provided to the `DM` to be able to perform the computation.

8299: .seealso: [](ch_dmbase), `DM`, `DMProjectFunctionLocal()`, `DMProjectFunctionLabel()`, `DMComputeL2Diff()`
8300: @*/
8301: PetscErrorCode DMProjectFunction(DM dm, PetscReal time, PetscErrorCode (**funcs)(PetscInt dim, PetscReal time, const PetscReal x[], PetscInt Nc, PetscScalar *u, PetscCtx ctx), void **ctxs, InsertMode mode, Vec X)
8302: {
8303:   Vec localX;

8305:   PetscFunctionBegin;
8307:   PetscCall(PetscLogEventBegin(DM_ProjectFunction, dm, X, 0, 0));
8308:   PetscCall(DMGetLocalVector(dm, &localX));
8309:   PetscCall(VecSet(localX, 0.));
8310:   PetscCall(DMProjectFunctionLocal(dm, time, funcs, ctxs, mode, localX));
8311:   PetscCall(DMLocalToGlobalBegin(dm, localX, mode, X));
8312:   PetscCall(DMLocalToGlobalEnd(dm, localX, mode, X));
8313:   PetscCall(DMRestoreLocalVector(dm, &localX));
8314:   PetscCall(PetscLogEventEnd(DM_ProjectFunction, dm, X, 0, 0));
8315:   PetscFunctionReturn(PETSC_SUCCESS);
8316: }

8318: /*@C
8319:   DMProjectFunctionLocal - This projects the given function into the function space provided by a `DM`, putting the coefficients in a local vector.

8321:   Not Collective

8323:   Input Parameters:
8324: + dm    - The `DM`
8325: . time  - The time
8326: . funcs - The coordinate functions to evaluate, one per field
8327: . ctxs  - Optional array of contexts to pass to each coordinate function.  ctxs itself may be null.
8328: - mode  - The insertion mode for values

8330:   Output Parameter:
8331: . localX - vector

8333:   Calling sequence of `funcs`:
8334: + dim  - The spatial dimension
8335: . time - The current timestep
8336: . x    - The coordinates
8337: . Nc   - The number of components
8338: . u    - The output field values
8339: - ctx  - optional function context

8341:   Level: developer

8343:   Developer Notes:
8344:   This API is specific to only particular usage of `DM`

8346:   The notes need to provide some information about what has to be provided to the `DM` to be able to perform the computation.

8348: .seealso: [](ch_dmbase), `DM`, `DMProjectFunction()`, `DMProjectFunctionLabel()`, `DMComputeL2Diff()`
8349: @*/
8350: PetscErrorCode DMProjectFunctionLocal(DM dm, PetscReal time, PetscErrorCode (**funcs)(PetscInt dim, PetscReal time, const PetscReal x[], PetscInt Nc, PetscScalar *u, PetscCtx ctx), void **ctxs, InsertMode mode, Vec localX)
8351: {
8352:   PetscFunctionBegin;
8355:   PetscUseTypeMethod(dm, projectfunctionlocal, time, funcs, ctxs, mode, localX);
8356:   PetscFunctionReturn(PETSC_SUCCESS);
8357: }

8359: /*@C
8360:   DMProjectFunctionLabel - This projects the given function into the function space provided by the `DM`, putting the coefficients in a global vector, setting values only for points in the given label.

8362:   Collective

8364:   Input Parameters:
8365: + dm     - The `DM`
8366: . time   - The time
8367: . numIds - The number of ids
8368: . ids    - The ids
8369: . Nc     - The number of components
8370: . comps  - The components
8371: . label  - The `DMLabel` selecting the portion of the mesh for projection
8372: . funcs  - The coordinate functions to evaluate, one per field
8373: . ctxs   - Optional array of contexts to pass to each coordinate function.  ctxs may be null.
8374: - mode   - The insertion mode for values

8376:   Output Parameter:
8377: . X - vector

8379:   Calling sequence of `funcs`:
8380: + dim  - The spatial dimension
8381: . time - The current timestep
8382: . x    - The coordinates
8383: . Nc   - The number of components
8384: . u    - The output field values
8385: - ctx  - optional function context

8387:   Level: developer

8389:   Developer Notes:
8390:   This API is specific to only particular usage of `DM`

8392:   The notes need to provide some information about what has to be provided to the `DM` to be able to perform the computation.

8394: .seealso: [](ch_dmbase), `DM`, `DMProjectFunction()`, `DMProjectFunctionLocal()`, `DMProjectFunctionLabelLocal()`, `DMComputeL2Diff()`
8395: @*/
8396: PetscErrorCode DMProjectFunctionLabel(DM dm, PetscReal time, DMLabel label, PetscInt numIds, const PetscInt ids[], PetscInt Nc, const PetscInt comps[], PetscErrorCode (**funcs)(PetscInt dim, PetscReal time, const PetscReal x[], PetscInt Nc, PetscScalar *u, PetscCtx ctx), void **ctxs, InsertMode mode, Vec X)
8397: {
8398:   Vec localX;

8400:   PetscFunctionBegin;
8402:   PetscCall(DMGetLocalVector(dm, &localX));
8403:   PetscCall(VecSet(localX, 0.));
8404:   PetscCall(DMProjectFunctionLabelLocal(dm, time, label, numIds, ids, Nc, comps, funcs, ctxs, mode, localX));
8405:   PetscCall(DMLocalToGlobalBegin(dm, localX, mode, X));
8406:   PetscCall(DMLocalToGlobalEnd(dm, localX, mode, X));
8407:   PetscCall(DMRestoreLocalVector(dm, &localX));
8408:   PetscFunctionReturn(PETSC_SUCCESS);
8409: }

8411: /*@C
8412:   DMProjectFunctionLabelLocal - This projects the given function into the function space provided by the `DM`, putting the coefficients in a local vector, setting values only for points in the given label.

8414:   Not Collective

8416:   Input Parameters:
8417: + dm     - The `DM`
8418: . time   - The time
8419: . label  - The `DMLabel` selecting the portion of the mesh for projection
8420: . numIds - The number of ids
8421: . ids    - The ids
8422: . Nc     - The number of components
8423: . comps  - The components
8424: . funcs  - The coordinate functions to evaluate, one per field
8425: . ctxs   - Optional array of contexts to pass to each coordinate function.  ctxs itself may be null.
8426: - mode   - The insertion mode for values

8428:   Output Parameter:
8429: . localX - vector

8431:   Calling sequence of `funcs`:
8432: + dim  - The spatial dimension
8433: . time - The current time
8434: . x    - The coordinates
8435: . Nc   - The number of components
8436: . u    - The output field values
8437: - ctx  - optional function context

8439:   Level: developer

8441:   Developer Notes:
8442:   This API is specific to only particular usage of `DM`

8444:   The notes need to provide some information about what has to be provided to the `DM` to be able to perform the computation.

8446: .seealso: [](ch_dmbase), `DM`, `DMProjectFunction()`, `DMProjectFunctionLocal()`, `DMProjectFunctionLabel()`, `DMComputeL2Diff()`
8447: @*/
8448: PetscErrorCode DMProjectFunctionLabelLocal(DM dm, PetscReal time, DMLabel label, PetscInt numIds, const PetscInt ids[], PetscInt Nc, const PetscInt comps[], PetscErrorCode (**funcs)(PetscInt dim, PetscReal time, const PetscReal x[], PetscInt Nc, PetscScalar *u, PetscCtx ctx), void **ctxs, InsertMode mode, Vec localX)
8449: {
8450:   PetscFunctionBegin;
8453:   PetscUseTypeMethod(dm, projectfunctionlabellocal, time, label, numIds, ids, Nc, comps, funcs, ctxs, mode, localX);
8454:   PetscFunctionReturn(PETSC_SUCCESS);
8455: }

8457: /*@C
8458:   DMProjectFieldLocal - This projects the given function of the input fields into the function space provided by the `DM`, putting the coefficients in a local vector.

8460:   Not Collective

8462:   Input Parameters:
8463: + dm     - The `DM`
8464: . time   - The time
8465: . localU - The input field vector; may be `NULL` if projection is defined purely by coordinates
8466: . funcs  - The functions to evaluate, one per field
8467: - mode   - The insertion mode for values

8469:   Output Parameter:
8470: . localX - The output vector

8472:   Calling sequence of `funcs`:
8473: + dim          - The spatial dimension
8474: . Nf           - The number of input fields
8475: . NfAux        - The number of input auxiliary fields
8476: . uOff         - The offset of each field in u[]
8477: . uOff_x       - The offset of each field in u_x[]
8478: . u            - The field values at this point in space
8479: . u_t          - The field time derivative at this point in space (or `NULL`)
8480: . u_x          - The field derivatives at this point in space
8481: . aOff         - The offset of each auxiliary field in u[]
8482: . aOff_x       - The offset of each auxiliary field in u_x[]
8483: . a            - The auxiliary field values at this point in space
8484: . a_t          - The auxiliary field time derivative at this point in space (or `NULL`)
8485: . a_x          - The auxiliary field derivatives at this point in space
8486: . t            - The current time
8487: . x            - The coordinates of this point
8488: . numConstants - The number of constants
8489: . constants    - The value of each constant
8490: - f            - The value of the function at this point in space

8492:   Level: intermediate

8494:   Note:
8495:   There are three different `DM`s that potentially interact in this function. The output `DM`, dm, specifies the layout of the values calculates by funcs.
8496:   The input `DM`, attached to U, may be different. For example, you can input the solution over the full domain, but output over a piece of the boundary, or
8497:   a subdomain. You can also output a different number of fields than the input, with different discretizations. Last the auxiliary `DM`, attached to the
8498:   auxiliary field vector, which is attached to dm, can also be different. It can have a different topology, number of fields, and discretizations.

8500:   Developer Notes:
8501:   This API is specific to only particular usage of `DM`

8503:   The notes need to provide some information about what has to be provided to the `DM` to be able to perform the computation.

8505: .seealso: [](ch_dmbase), `DM`, `DMProjectField()`, `DMProjectFieldLabelLocal()`,
8506: `DMProjectFunction()`, `DMComputeL2Diff()`
8507: @*/
8508: PetscErrorCode DMProjectFieldLocal(DM dm, PetscReal time, Vec localU, void (**funcs)(PetscInt dim, PetscInt Nf, PetscInt NfAux, const PetscInt uOff[], const PetscInt uOff_x[], const PetscScalar u[], const PetscScalar u_t[], const PetscScalar u_x[], const PetscInt aOff[], const PetscInt aOff_x[], const PetscScalar a[], const PetscScalar a_t[], const PetscScalar a_x[], PetscReal t, const PetscReal x[], PetscInt numConstants, const PetscScalar constants[], PetscScalar f[]), InsertMode mode, Vec localX)
8509: {
8510:   PetscFunctionBegin;
8514:   PetscUseTypeMethod(dm, projectfieldlocal, time, localU, funcs, mode, localX);
8515:   PetscFunctionReturn(PETSC_SUCCESS);
8516: }

8518: /*@C
8519:   DMProjectFieldLabelLocal - This projects the given function of the input fields into the function space provided, putting the coefficients in a local vector, calculating only over the portion of the domain specified by the label.

8521:   Not Collective

8523:   Input Parameters:
8524: + dm     - The `DM`
8525: . time   - The time
8526: . label  - The `DMLabel` marking the portion of the domain to output
8527: . numIds - The number of label ids to use
8528: . ids    - The label ids to use for marking
8529: . Nc     - The number of components to set in the output, or `PETSC_DETERMINE` for all components
8530: . comps  - The components to set in the output, or `NULL` for all components
8531: . localU - The input field vector
8532: . funcs  - The functions to evaluate, one per field
8533: - mode   - The insertion mode for values

8535:   Output Parameter:
8536: . localX - The output vector

8538:   Calling sequence of `funcs`:
8539: + dim          - The spatial dimension
8540: . Nf           - The number of input fields
8541: . NfAux        - The number of input auxiliary fields
8542: . uOff         - The offset of each field in u[]
8543: . uOff_x       - The offset of each field in u_x[]
8544: . u            - The field values at this point in space
8545: . u_t          - The field time derivative at this point in space (or `NULL`)
8546: . u_x          - The field derivatives at this point in space
8547: . aOff         - The offset of each auxiliary field in u[]
8548: . aOff_x       - The offset of each auxiliary field in u_x[]
8549: . a            - The auxiliary field values at this point in space
8550: . a_t          - The auxiliary field time derivative at this point in space (or `NULL`)
8551: . a_x          - The auxiliary field derivatives at this point in space
8552: . t            - The current time
8553: . x            - The coordinates of this point
8554: . numConstants - The number of constants
8555: . constants    - The value of each constant
8556: - f            - The value of the function at this point in space

8558:   Level: intermediate

8560:   Note:
8561:   There are three different `DM`s that potentially interact in this function. The output `DM`, dm, specifies the layout of the values calculates by funcs.
8562:   The input `DM`, attached to localU, may be different. For example, you can input the solution over the full domain, but output over a piece of the boundary, or
8563:   a subdomain. You can also output a different number of fields than the input, with different discretizations. Last the auxiliary `DM`, attached to the
8564:   auxiliary field vector, which is attached to dm, can also be different. It can have a different topology, number of fields, and discretizations.

8566:   Developer Notes:
8567:   This API is specific to only particular usage of `DM`

8569:   The notes need to provide some information about what has to be provided to the `DM` to be able to perform the computation.

8571: .seealso: [](ch_dmbase), `DM`, `DMProjectField()`, `DMProjectFieldLabel()`, `DMProjectFunction()`, `DMComputeL2Diff()`
8572: @*/
8573: PetscErrorCode DMProjectFieldLabelLocal(DM dm, PetscReal time, DMLabel label, PetscInt numIds, const PetscInt ids[], PetscInt Nc, const PetscInt comps[], Vec localU, void (**funcs)(PetscInt dim, PetscInt Nf, PetscInt NfAux, const PetscInt uOff[], const PetscInt uOff_x[], const PetscScalar u[], const PetscScalar u_t[], const PetscScalar u_x[], const PetscInt aOff[], const PetscInt aOff_x[], const PetscScalar a[], const PetscScalar a_t[], const PetscScalar a_x[], PetscReal t, const PetscReal x[], PetscInt numConstants, const PetscScalar constants[], PetscScalar f[]), InsertMode mode, Vec localX)
8574: {
8575:   PetscFunctionBegin;
8579:   PetscUseTypeMethod(dm, projectfieldlabellocal, time, label, numIds, ids, Nc, comps, localU, funcs, mode, localX);
8580:   PetscFunctionReturn(PETSC_SUCCESS);
8581: }

8583: /*@C
8584:   DMProjectFieldLabel - This projects the given function of the input fields into the function space provided, putting the coefficients in a global vector, calculating only over the portion of the domain specified by the label.

8586:   Not Collective

8588:   Input Parameters:
8589: + dm     - The `DM`
8590: . time   - The time
8591: . label  - The `DMLabel` marking the portion of the domain to output
8592: . numIds - The number of label ids to use
8593: . ids    - The label ids to use for marking
8594: . Nc     - The number of components to set in the output, or `PETSC_DETERMINE` for all components
8595: . comps  - The components to set in the output, or `NULL` for all components
8596: . U      - The input field vector
8597: . funcs  - The functions to evaluate, one per field
8598: - mode   - The insertion mode for values

8600:   Output Parameter:
8601: . X - The output vector

8603:   Calling sequence of `funcs`:
8604: + dim          - The spatial dimension
8605: . Nf           - The number of input fields
8606: . NfAux        - The number of input auxiliary fields
8607: . uOff         - The offset of each field in u[]
8608: . uOff_x       - The offset of each field in u_x[]
8609: . u            - The field values at this point in space
8610: . u_t          - The field time derivative at this point in space (or `NULL`)
8611: . u_x          - The field derivatives at this point in space
8612: . aOff         - The offset of each auxiliary field in u[]
8613: . aOff_x       - The offset of each auxiliary field in u_x[]
8614: . a            - The auxiliary field values at this point in space
8615: . a_t          - The auxiliary field time derivative at this point in space (or `NULL`)
8616: . a_x          - The auxiliary field derivatives at this point in space
8617: . t            - The current time
8618: . x            - The coordinates of this point
8619: . numConstants - The number of constants
8620: . constants    - The value of each constant
8621: - f            - The value of the function at this point in space

8623:   Level: intermediate

8625:   Note:
8626:   There are three different `DM`s that potentially interact in this function. The output `DM`, dm, specifies the layout of the values calculates by funcs.
8627:   The input `DM`, attached to U, may be different. For example, you can input the solution over the full domain, but output over a piece of the boundary, or
8628:   a subdomain. You can also output a different number of fields than the input, with different discretizations. Last the auxiliary `DM`, attached to the
8629:   auxiliary field vector, which is attached to dm, can also be different. It can have a different topology, number of fields, and discretizations.

8631:   Developer Notes:
8632:   This API is specific to only particular usage of `DM`

8634:   The notes need to provide some information about what has to be provided to the `DM` to be able to perform the computation.

8636: .seealso: [](ch_dmbase), `DM`, `DMProjectField()`, `DMProjectFieldLabelLocal()`, `DMProjectFunction()`, `DMComputeL2Diff()`
8637: @*/
8638: PetscErrorCode DMProjectFieldLabel(DM dm, PetscReal time, DMLabel label, PetscInt numIds, const PetscInt ids[], PetscInt Nc, const PetscInt comps[], Vec U, void (**funcs)(PetscInt dim, PetscInt Nf, PetscInt NfAux, const PetscInt uOff[], const PetscInt uOff_x[], const PetscScalar u[], const PetscScalar u_t[], const PetscScalar u_x[], const PetscInt aOff[], const PetscInt aOff_x[], const PetscScalar a[], const PetscScalar a_t[], const PetscScalar a_x[], PetscReal t, const PetscReal x[], PetscInt numConstants, const PetscScalar constants[], PetscScalar f[]), InsertMode mode, Vec X)
8639: {
8640:   DM  dmIn;
8641:   Vec localU, localX;

8643:   PetscFunctionBegin;
8645:   PetscCall(VecGetDM(U, &dmIn));
8646:   PetscCall(DMGetLocalVector(dmIn, &localU));
8647:   PetscCall(DMGetLocalVector(dm, &localX));
8648:   PetscCall(VecSet(localX, 0.));
8649:   PetscCall(DMGlobalToLocalBegin(dmIn, U, mode, localU));
8650:   PetscCall(DMGlobalToLocalEnd(dmIn, U, mode, localU));
8651:   PetscCall(DMProjectFieldLabelLocal(dm, time, label, numIds, ids, Nc, comps, localU, funcs, mode, localX));
8652:   PetscCall(DMLocalToGlobalBegin(dm, localX, mode, X));
8653:   PetscCall(DMLocalToGlobalEnd(dm, localX, mode, X));
8654:   PetscCall(DMRestoreLocalVector(dm, &localX));
8655:   PetscCall(DMRestoreLocalVector(dmIn, &localU));
8656:   PetscFunctionReturn(PETSC_SUCCESS);
8657: }

8659: /*@C
8660:   DMProjectBdFieldLabelLocal - This projects the given function of the input fields into the function space provided, putting the coefficients in a local vector, calculating only over the portion of the domain boundary specified by the label.

8662:   Not Collective

8664:   Input Parameters:
8665: + dm     - The `DM`
8666: . time   - The time
8667: . label  - The `DMLabel` marking the portion of the domain boundary to output
8668: . numIds - The number of label ids to use
8669: . ids    - The label ids to use for marking
8670: . Nc     - The number of components to set in the output, or `PETSC_DETERMINE` for all components
8671: . comps  - The components to set in the output, or `NULL` for all components
8672: . localU - The input field vector
8673: . funcs  - The functions to evaluate, one per field
8674: - mode   - The insertion mode for values

8676:   Output Parameter:
8677: . localX - The output vector

8679:   Calling sequence of `funcs`:
8680: + dim          - The spatial dimension
8681: . Nf           - The number of input fields
8682: . NfAux        - The number of input auxiliary fields
8683: . uOff         - The offset of each field in u[]
8684: . uOff_x       - The offset of each field in u_x[]
8685: . u            - The field values at this point in space
8686: . u_t          - The field time derivative at this point in space (or `NULL`)
8687: . u_x          - The field derivatives at this point in space
8688: . aOff         - The offset of each auxiliary field in u[]
8689: . aOff_x       - The offset of each auxiliary field in u_x[]
8690: . a            - The auxiliary field values at this point in space
8691: . a_t          - The auxiliary field time derivative at this point in space (or `NULL`)
8692: . a_x          - The auxiliary field derivatives at this point in space
8693: . t            - The current time
8694: . x            - The coordinates of this point
8695: . n            - The face normal
8696: . numConstants - The number of constants
8697: . constants    - The value of each constant
8698: - f            - The value of the function at this point in space

8700:   Level: intermediate

8702:   Note:
8703:   There are three different `DM`s that potentially interact in this function. The output `DM`, dm, specifies the layout of the values calculates by funcs.
8704:   The input `DM`, attached to U, may be different. For example, you can input the solution over the full domain, but output over a piece of the boundary, or
8705:   a subdomain. You can also output a different number of fields than the input, with different discretizations. Last the auxiliary `DM`, attached to the
8706:   auxiliary field vector, which is attached to dm, can also be different. It can have a different topology, number of fields, and discretizations.

8708:   Developer Notes:
8709:   This API is specific to only particular usage of `DM`

8711:   The notes need to provide some information about what has to be provided to the `DM` to be able to perform the computation.

8713: .seealso: [](ch_dmbase), `DM`, `DMProjectField()`, `DMProjectFieldLabelLocal()`, `DMProjectFunction()`, `DMComputeL2Diff()`
8714: @*/
8715: PetscErrorCode DMProjectBdFieldLabelLocal(DM dm, PetscReal time, DMLabel label, PetscInt numIds, const PetscInt ids[], PetscInt Nc, const PetscInt comps[], Vec localU, void (**funcs)(PetscInt dim, PetscInt Nf, PetscInt NfAux, const PetscInt uOff[], const PetscInt uOff_x[], const PetscScalar u[], const PetscScalar u_t[], const PetscScalar u_x[], const PetscInt aOff[], const PetscInt aOff_x[], const PetscScalar a[], const PetscScalar a_t[], const PetscScalar a_x[], PetscReal t, const PetscReal x[], const PetscReal n[], PetscInt numConstants, const PetscScalar constants[], PetscScalar f[]), InsertMode mode, Vec localX)
8716: {
8717:   PetscFunctionBegin;
8721:   PetscUseTypeMethod(dm, projectbdfieldlabellocal, time, label, numIds, ids, Nc, comps, localU, funcs, mode, localX);
8722:   PetscFunctionReturn(PETSC_SUCCESS);
8723: }

8725: /*@C
8726:   DMComputeL2Diff - This function computes the L_2 difference between a function u and an FEM interpolant solution u_h.

8728:   Collective

8730:   Input Parameters:
8731: + dm    - The `DM`
8732: . time  - The time
8733: . funcs - The functions to evaluate for each field component
8734: . ctxs  - Optional array of contexts to pass to each function, or `NULL`.
8735: - X     - The coefficient vector u_h, a global vector

8737:   Output Parameter:
8738: . diff - The diff ||u - u_h||_2

8740:   Level: developer

8742:   Developer Notes:
8743:   This API is specific to only particular usage of `DM`

8745:   The notes need to provide some information about what has to be provided to the `DM` to be able to perform the computation.

8747: .seealso: [](ch_dmbase), `DM`, `DMProjectFunction()`, `DMComputeL2FieldDiff()`, `DMComputeL2GradientDiff()`
8748: @*/
8749: PetscErrorCode DMComputeL2Diff(DM dm, PetscReal time, PetscErrorCode (**funcs)(PetscInt, PetscReal, const PetscReal[], PetscInt, PetscScalar *, void *), void **ctxs, Vec X, PetscReal *diff)
8750: {
8751:   PetscFunctionBegin;
8754:   PetscUseTypeMethod(dm, computel2diff, time, funcs, ctxs, X, diff);
8755:   PetscFunctionReturn(PETSC_SUCCESS);
8756: }

8758: /*@C
8759:   DMComputeL2GradientDiff - This function computes the L_2 difference between the gradient of a function u and an FEM interpolant solution grad u_h.

8761:   Collective

8763:   Input Parameters:
8764: + dm    - The `DM`
8765: . time  - The time
8766: . funcs - The gradient functions to evaluate for each field component
8767: . ctxs  - Optional array of contexts to pass to each function, or `NULL`.
8768: . X     - The coefficient vector u_h, a global vector
8769: - n     - The vector to project along

8771:   Output Parameter:
8772: . diff - The diff ||(grad u - grad u_h) . n||_2

8774:   Level: developer

8776:   Developer Notes:
8777:   This API is specific to only particular usage of `DM`

8779:   The notes need to provide some information about what has to be provided to the `DM` to be able to perform the computation.

8781: .seealso: [](ch_dmbase), `DM`, `DMProjectFunction()`, `DMComputeL2Diff()`, `DMComputeL2FieldDiff()`
8782: @*/
8783: PetscErrorCode DMComputeL2GradientDiff(DM dm, PetscReal time, PetscErrorCode (**funcs)(PetscInt, PetscReal, const PetscReal[], const PetscReal[], PetscInt, PetscScalar *, void *), void **ctxs, Vec X, const PetscReal n[], PetscReal *diff)
8784: {
8785:   PetscFunctionBegin;
8788:   PetscUseTypeMethod(dm, computel2gradientdiff, time, funcs, ctxs, X, n, diff);
8789:   PetscFunctionReturn(PETSC_SUCCESS);
8790: }

8792: /*@C
8793:   DMComputeL2FieldDiff - This function computes the L_2 difference between a function u and an FEM interpolant solution u_h, separated into field components.

8795:   Collective

8797:   Input Parameters:
8798: + dm    - The `DM`
8799: . time  - The time
8800: . funcs - The functions to evaluate for each field component
8801: . ctxs  - Optional array of contexts to pass to each function, or `NULL`.
8802: - X     - The coefficient vector u_h, a global vector

8804:   Output Parameter:
8805: . diff - The array of differences, ||u^f - u^f_h||_2

8807:   Level: developer

8809:   Developer Notes:
8810:   This API is specific to only particular usage of `DM`

8812:   The notes need to provide some information about what has to be provided to the `DM` to be able to perform the computation.

8814: .seealso: [](ch_dmbase), `DM`, `DMProjectFunction()`, `DMComputeL2GradientDiff()`
8815: @*/
8816: PetscErrorCode DMComputeL2FieldDiff(DM dm, PetscReal time, PetscErrorCode (**funcs)(PetscInt, PetscReal, const PetscReal[], PetscInt, PetscScalar *, void *), void **ctxs, Vec X, PetscReal diff[])
8817: {
8818:   PetscFunctionBegin;
8821:   PetscUseTypeMethod(dm, computel2fielddiff, time, funcs, ctxs, X, diff);
8822:   PetscFunctionReturn(PETSC_SUCCESS);
8823: }

8825: /*@C
8826:   DMGetNeighbors - Gets an array containing the MPI ranks of all the processes neighbors

8828:   Not Collective

8830:   Input Parameter:
8831: . dm - The `DM`

8833:   Output Parameters:
8834: + nranks - the number of neighbours
8835: - ranks  - the neighbors ranks

8837:   Level: beginner

8839:   Note:
8840:   Do not free the array, it is freed when the `DM` is destroyed.

8842: .seealso: [](ch_dmbase), `DM`, `DMDAGetNeighbors()`, `PetscSFGetRootRanks()`
8843: @*/
8844: PetscErrorCode DMGetNeighbors(DM dm, PetscInt *nranks, const PetscMPIInt *ranks[])
8845: {
8846:   PetscFunctionBegin;
8848:   PetscUseTypeMethod(dm, getneighbors, nranks, ranks);
8849:   PetscFunctionReturn(PETSC_SUCCESS);
8850: }

8852: #include <petsc/private/matimpl.h>

8854: /*
8855:     Converts the input vector to a ghosted vector and then calls the standard coloring code.
8856:     This must be a different function because it requires DM which is not defined in the Mat library
8857: */
8858: static PetscErrorCode MatFDColoringApply_AIJDM(Mat J, MatFDColoring coloring, Vec x1, void *sctx)
8859: {
8860:   PetscFunctionBegin;
8861:   if (coloring->ctype == IS_COLORING_LOCAL) {
8862:     Vec x1local;
8863:     DM  dm;
8864:     PetscCall(MatGetDM(J, &dm));
8865:     PetscCheck(dm, PetscObjectComm((PetscObject)J), PETSC_ERR_ARG_INCOMP, "IS_COLORING_LOCAL requires a DM");
8866:     PetscCall(DMGetLocalVector(dm, &x1local));
8867:     PetscCall(DMGlobalToLocalBegin(dm, x1, INSERT_VALUES, x1local));
8868:     PetscCall(DMGlobalToLocalEnd(dm, x1, INSERT_VALUES, x1local));
8869:     x1 = x1local;
8870:   }
8871:   PetscCall(MatFDColoringApply_AIJ(J, coloring, x1, sctx));
8872:   if (coloring->ctype == IS_COLORING_LOCAL) {
8873:     DM dm;
8874:     PetscCall(MatGetDM(J, &dm));
8875:     PetscCall(DMRestoreLocalVector(dm, &x1));
8876:   }
8877:   PetscFunctionReturn(PETSC_SUCCESS);
8878: }

8880: /*@
8881:   MatFDColoringUseDM - allows a `MatFDColoring` object to use the `DM` associated with the matrix to compute a `IS_COLORING_LOCAL` coloring

8883:   Input Parameters:
8884: + coloring   - The matrix to get the `DM` from
8885: - fdcoloring - the `MatFDColoring` object

8887:   Level: advanced

8889:   Developer Note:
8890:   This routine exists because the PETSc `Mat` library does not know about the `DM` objects

8892: .seealso: [](ch_dmbase), `DM`, `MatFDColoring`, `MatFDColoringCreate()`, `ISColoringType`
8893: @*/
8894: PetscErrorCode MatFDColoringUseDM(Mat coloring, MatFDColoring fdcoloring)
8895: {
8896:   PetscFunctionBegin;
8897:   coloring->ops->fdcoloringapply = MatFDColoringApply_AIJDM;
8898:   PetscFunctionReturn(PETSC_SUCCESS);
8899: }

8901: /*@
8902:   DMGetCompatibility - determine if two `DM`s are compatible

8904:   Collective

8906:   Input Parameters:
8907: + dm1 - the first `DM`
8908: - dm2 - the second `DM`

8910:   Output Parameters:
8911: + compatible - whether or not the two `DM`s are compatible
8912: - set        - whether or not the compatible value was actually determined and set

8914:   Level: advanced

8916:   Notes:
8917:   Two `DM`s are deemed compatible if they represent the same parallel decomposition
8918:   of the same topology. This implies that the section (field data) on one
8919:   "makes sense" with respect to the topology and parallel decomposition of the other.
8920:   Loosely speaking, compatible `DM`s represent the same domain and parallel
8921:   decomposition, but hold different data.

8923:   Typically, one would confirm compatibility if intending to simultaneously iterate
8924:   over a pair of vectors obtained from different `DM`s.

8926:   For example, two `DMDA` objects are compatible if they have the same local
8927:   and global sizes and the same stencil width. They can have different numbers
8928:   of degrees of freedom per node. Thus, one could use the node numbering from
8929:   either `DM` in bounds for a loop over vectors derived from either `DM`.

8931:   Consider the operation of summing data living on a 2-dof `DMDA` to data living
8932:   on a 1-dof `DMDA`, which should be compatible, as in the following snippet.
8933: .vb
8934:   ...
8935:   PetscCall(DMGetCompatibility(da1,da2,&compatible,&set));
8936:   if (set && compatible)  {
8937:     PetscCall(DMDAVecGetArrayDOF(da1,vec1,&arr1));
8938:     PetscCall(DMDAVecGetArrayDOF(da2,vec2,&arr2));
8939:     PetscCall(DMDAGetCorners(da1,&x,&y,NULL,&m,&n,NULL));
8940:     for (j=y; j<y+n; ++j) {
8941:       for (i=x; i<x+m, ++i) {
8942:         arr1[j][i][0] = arr2[j][i][0] + arr2[j][i][1];
8943:       }
8944:     }
8945:     PetscCall(DMDAVecRestoreArrayDOF(da1,vec1,&arr1));
8946:     PetscCall(DMDAVecRestoreArrayDOF(da2,vec2,&arr2));
8947:   } else {
8948:     SETERRQ(PetscObjectComm((PetscObject)da1,PETSC_ERR_ARG_INCOMP,"DMDA objects incompatible");
8949:   }
8950:   ...
8951: .ve

8953:   Checking compatibility might be expensive for a given implementation of `DM`,
8954:   or might be impossible to unambiguously confirm or deny. For this reason,
8955:   this function may decline to determine compatibility, and hence users should
8956:   always check the "set" output parameter.

8958:   A `DM` is always compatible with itself.

8960:   In the current implementation, `DM`s which live on "unequal" communicators
8961:   (MPI_UNEQUAL in the terminology of MPI_Comm_compare()) are always deemed
8962:   incompatible.

8964:   This function is labeled "Collective," as information about all subdomains
8965:   is required on each rank. However, in `DM` implementations which store all this
8966:   information locally, this function may be merely "Logically Collective".

8968:   Developer Note:
8969:   Compatibility is assumed to be a symmetric concept; `DM` A is compatible with `DM` B
8970:   iff B is compatible with A. Thus, this function checks the implementations
8971:   of both dm and dmc (if they are of different types), attempting to determine
8972:   compatibility. It is left to `DM` implementers to ensure that symmetry is
8973:   preserved. The simplest way to do this is, when implementing type-specific
8974:   logic for this function, is to check for existing logic in the implementation
8975:   of other `DM` types and let *set = PETSC_FALSE if found.

8977: .seealso: [](ch_dmbase), `DM`, `DMDACreateCompatibleDMDA()`, `DMStagCreateCompatibleDMStag()`
8978: @*/
8979: PetscErrorCode DMGetCompatibility(DM dm1, DM dm2, PetscBool *compatible, PetscBool *set)
8980: {
8981:   PetscMPIInt compareResult;
8982:   DMType      type, type2;
8983:   PetscBool   sameType;

8985:   PetscFunctionBegin;

8989:   /* Declare a DM compatible with itself */
8990:   if (dm1 == dm2) {
8991:     *set        = PETSC_TRUE;
8992:     *compatible = PETSC_TRUE;
8993:     PetscFunctionReturn(PETSC_SUCCESS);
8994:   }

8996:   /* Declare a DM incompatible with a DM that lives on an "unequal"
8997:      communicator. Note that this does not preclude compatibility with
8998:      DMs living on "congruent" or "similar" communicators, but this must be
8999:      determined by the implementation-specific logic */
9000:   PetscCallMPI(MPI_Comm_compare(PetscObjectComm((PetscObject)dm1), PetscObjectComm((PetscObject)dm2), &compareResult));
9001:   if (compareResult == MPI_UNEQUAL) {
9002:     *set        = PETSC_TRUE;
9003:     *compatible = PETSC_FALSE;
9004:     PetscFunctionReturn(PETSC_SUCCESS);
9005:   }

9007:   /* Pass to the implementation-specific routine, if one exists. */
9008:   if (dm1->ops->getcompatibility) {
9009:     PetscUseTypeMethod(dm1, getcompatibility, dm2, compatible, set);
9010:     if (*set) PetscFunctionReturn(PETSC_SUCCESS);
9011:   }

9013:   /* If dm1 and dm2 are of different types, then attempt to check compatibility
9014:      with an implementation of this function from dm2 */
9015:   PetscCall(DMGetType(dm1, &type));
9016:   PetscCall(DMGetType(dm2, &type2));
9017:   PetscCall(PetscStrcmp(type, type2, &sameType));
9018:   if (!sameType && dm2->ops->getcompatibility) {
9019:     PetscUseTypeMethod(dm2, getcompatibility, dm1, compatible, set); /* Note argument order */
9020:   } else {
9021:     *set = PETSC_FALSE;
9022:   }
9023:   PetscFunctionReturn(PETSC_SUCCESS);
9024: }

9026: /*@C
9027:   DMMonitorSet - Sets an additional monitor function that is to be used after a solve to monitor discretization performance.

9029:   Logically Collective

9031:   Input Parameters:
9032: + dm             - the `DM`
9033: . f              - the monitor function
9034: . mctx           - [optional] context for private data for the monitor routine (use `NULL` if no context is desired)
9035: - monitordestroy - [optional] routine that frees monitor context (may be `NULL`), see `PetscCtxDestroyFn` for the calling sequence

9037:   Options Database Key:
9038: . -dm_monitor_cancel - cancels all monitors that have been hardwired into a code by calls to `DMMonitorSet()`, but
9039:                        does not cancel those set via the options database.

9041:   Level: intermediate

9043:   Note:
9044:   Several different monitoring routines may be set by calling
9045:   `DMMonitorSet()` multiple times or with `DMMonitorSetFromOptions()`; all will be called in the
9046:   order in which they were set.

9048:   Fortran Note:
9049:   Only a single monitor function can be set for each `DM` object

9051:   Developer Note:
9052:   This API has a generic name but seems specific to a very particular aspect of the use of `DM`

9054: .seealso: [](ch_dmbase), `DM`, `DMMonitorCancel()`, `DMMonitorSetFromOptions()`, `DMMonitor()`, `PetscCtxDestroyFn`
9055: @*/
9056: PetscErrorCode DMMonitorSet(DM dm, PetscErrorCode (*f)(DM, void *), void *mctx, PetscCtxDestroyFn *monitordestroy)
9057: {
9058:   PetscFunctionBegin;
9060:   for (PetscInt m = 0; m < dm->numbermonitors; ++m) {
9061:     PetscBool identical;

9063:     PetscCall(PetscMonitorCompare((PetscErrorCode (*)(void))(PetscVoidFn *)f, mctx, monitordestroy, (PetscErrorCode (*)(void))(PetscVoidFn *)dm->monitor[m], dm->monitorcontext[m], dm->monitordestroy[m], &identical));
9064:     if (identical) PetscFunctionReturn(PETSC_SUCCESS);
9065:   }
9066:   PetscCheck(dm->numbermonitors < MAXDMMONITORS, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Too many monitors set");
9067:   dm->monitor[dm->numbermonitors]          = f;
9068:   dm->monitordestroy[dm->numbermonitors]   = monitordestroy;
9069:   dm->monitorcontext[dm->numbermonitors++] = mctx;
9070:   PetscFunctionReturn(PETSC_SUCCESS);
9071: }

9073: /*@
9074:   DMMonitorCancel - Clears all the monitor functions for a `DM` object.

9076:   Logically Collective

9078:   Input Parameter:
9079: . dm - the DM

9081:   Options Database Key:
9082: . -dm_monitor_cancel - cancels all monitors that have been hardwired
9083:   into a code by calls to `DMonitorSet()`, but does not cancel those
9084:   set via the options database

9086:   Level: intermediate

9088:   Note:
9089:   There is no way to clear one specific monitor from a `DM` object.

9091: .seealso: [](ch_dmbase), `DM`, `DMMonitorSet()`, `DMMonitorSetFromOptions()`, `DMMonitor()`
9092: @*/
9093: PetscErrorCode DMMonitorCancel(DM dm)
9094: {
9095:   PetscInt m;

9097:   PetscFunctionBegin;
9099:   for (m = 0; m < dm->numbermonitors; ++m) {
9100:     if (dm->monitordestroy[m]) PetscCall((*dm->monitordestroy[m])(&dm->monitorcontext[m]));
9101:   }
9102:   dm->numbermonitors = 0;
9103:   PetscFunctionReturn(PETSC_SUCCESS);
9104: }

9106: /*@C
9107:   DMMonitorSetFromOptions - Sets a monitor function and viewer appropriate for the type indicated by the user

9109:   Collective

9111:   Input Parameters:
9112: + dm           - `DM` object you wish to monitor
9113: . name         - the monitor type one is seeking
9114: . help         - message indicating what monitoring is done
9115: . manual       - manual page for the monitor
9116: . monitor      - the monitor function, this must use a `PetscViewerFormat` as its context
9117: - monitorsetup - a function that is called once ONLY if the user selected this monitor that may set additional features of the `DM` or `PetscViewer` objects

9119:   Output Parameter:
9120: . flg - Flag set if the monitor was created

9122:   Calling sequence of `monitor`:
9123: + dm  - the `DM` to be monitored
9124: - ctx - monitor context

9126:   Calling sequence of `monitorsetup`:
9127: + dm - the `DM` to be monitored
9128: - vf - the `PetscViewer` and format to be used by the monitor

9130:   Level: developer

9132: .seealso: [](ch_dmbase), `DM`, `PetscOptionsCreateViewer()`, `PetscOptionsGetReal()`, `PetscOptionsHasName()`, `PetscOptionsGetString()`,
9133:           `PetscOptionsGetIntArray()`, `PetscOptionsGetRealArray()`, `PetscOptionsBool()`,
9134:           `PetscOptionsInt()`, `PetscOptionsString()`, `PetscOptionsReal()`,
9135:           `PetscOptionsName()`, `PetscOptionsBegin()`, `PetscOptionsEnd()`, `PetscOptionsHeadBegin()`,
9136:           `PetscOptionsStringArray()`, `PetscOptionsRealArray()`, `PetscOptionsScalar()`,
9137:           `PetscOptionsBoolGroupBegin()`, `PetscOptionsBoolGroup()`, `PetscOptionsBoolGroupEnd()`,
9138:           `PetscOptionsFList()`, `PetscOptionsEList()`, `DMMonitor()`, `DMMonitorSet()`
9139: @*/
9140: PetscErrorCode DMMonitorSetFromOptions(DM dm, const char name[], const char help[], const char manual[], PetscErrorCode (*monitor)(DM dm, PetscCtx ctx), PetscErrorCode (*monitorsetup)(DM dm, PetscViewerAndFormat *vf), PetscBool *flg)
9141: {
9142:   PetscViewer       viewer;
9143:   PetscViewerFormat format;

9145:   PetscFunctionBegin;
9147:   PetscCall(PetscOptionsCreateViewer(PetscObjectComm((PetscObject)dm), ((PetscObject)dm)->options, ((PetscObject)dm)->prefix, name, &viewer, &format, flg));
9148:   if (*flg) {
9149:     PetscViewerAndFormat *vf;

9151:     PetscCall(PetscViewerAndFormatCreate(viewer, format, &vf));
9152:     PetscCall(PetscViewerDestroy(&viewer));
9153:     if (monitorsetup) PetscCall((*monitorsetup)(dm, vf));
9154:     PetscCall(DMMonitorSet(dm, monitor, vf, (PetscCtxDestroyFn *)PetscViewerAndFormatDestroy));
9155:   }
9156:   PetscFunctionReturn(PETSC_SUCCESS);
9157: }

9159: /*@
9160:   DMMonitor - runs the user provided monitor routines, if they exist

9162:   Collective

9164:   Input Parameter:
9165: . dm - The `DM`

9167:   Level: developer

9169:   Developer Note:
9170:   Note should indicate when during the life of the `DM` the monitor is run. It appears to be
9171:   related to the discretization process seems rather specialized since some `DM` have no
9172:   concept of discretization.

9174: .seealso: [](ch_dmbase), `DM`, `DMMonitorSet()`, `DMMonitorSetFromOptions()`
9175: @*/
9176: PetscErrorCode DMMonitor(DM dm)
9177: {
9178:   PetscInt m;

9180:   PetscFunctionBegin;
9181:   if (!dm) PetscFunctionReturn(PETSC_SUCCESS);
9183:   for (m = 0; m < dm->numbermonitors; ++m) PetscCall((*dm->monitor[m])(dm, dm->monitorcontext[m]));
9184:   PetscFunctionReturn(PETSC_SUCCESS);
9185: }

9187: /*@
9188:   DMComputeError - Computes the error assuming the user has provided the exact solution functions

9190:   Collective

9192:   Input Parameters:
9193: + dm  - The `DM`
9194: - sol - The solution vector

9196:   Input/Output Parameter:
9197: . errors - An array of length Nf, the number of fields, or `NULL` for no output; on output
9198:            contains the error in each field

9200:   Output Parameter:
9201: . errorVec - A vector to hold the cellwise error (may be `NULL`)

9203:   Level: developer

9205:   Note:
9206:   The exact solutions come from the `PetscDS` object, and the time comes from `DMGetOutputSequenceNumber()`.

9208: .seealso: [](ch_dmbase), `DM`, `DMMonitorSet()`, `DMGetRegionNumDS()`, `PetscDSGetExactSolution()`, `DMGetOutputSequenceNumber()`
9209: @*/
9210: PetscErrorCode DMComputeError(DM dm, Vec sol, PetscReal errors[], Vec *errorVec)
9211: {
9212:   PetscErrorCode (**exactSol)(PetscInt, PetscReal, const PetscReal[], PetscInt, PetscScalar[], void *);
9213:   void    **ctxs;
9214:   PetscReal time;
9215:   PetscInt  Nf, f, Nds, s;

9217:   PetscFunctionBegin;
9218:   PetscCall(DMGetNumFields(dm, &Nf));
9219:   PetscCall(PetscCalloc2(Nf, &exactSol, Nf, &ctxs));
9220:   PetscCall(DMGetNumDS(dm, &Nds));
9221:   for (s = 0; s < Nds; ++s) {
9222:     PetscDS         ds;
9223:     DMLabel         label;
9224:     IS              fieldIS;
9225:     const PetscInt *fields;
9226:     PetscInt        dsNf;

9228:     PetscCall(DMGetRegionNumDS(dm, s, &label, &fieldIS, &ds, NULL));
9229:     PetscCall(PetscDSGetNumFields(ds, &dsNf));
9230:     if (fieldIS) PetscCall(ISGetIndices(fieldIS, &fields));
9231:     for (f = 0; f < dsNf; ++f) {
9232:       const PetscInt field = fields[f];
9233:       PetscCall(PetscDSGetExactSolution(ds, field, &exactSol[field], &ctxs[field]));
9234:     }
9235:     if (fieldIS) PetscCall(ISRestoreIndices(fieldIS, &fields));
9236:   }
9237:   for (f = 0; f < Nf; ++f) PetscCheck(exactSol[f], PetscObjectComm((PetscObject)dm), PETSC_ERR_ARG_WRONG, "DS must contain exact solution functions in order to calculate error, missing for field %" PetscInt_FMT, f);
9238:   PetscCall(DMGetOutputSequenceNumber(dm, NULL, &time));
9239:   if (errors) PetscCall(DMComputeL2FieldDiff(dm, time, exactSol, ctxs, sol, errors));
9240:   if (errorVec) {
9241:     DM             edm;
9242:     DMPolytopeType ct;
9243:     PetscBool      simplex;
9244:     PetscInt       dim, cStart, Nf;

9246:     PetscCall(DMClone(dm, &edm));
9247:     PetscCall(DMGetDimension(edm, &dim));
9248:     PetscCall(DMPlexGetHeightStratum(dm, 0, &cStart, NULL));
9249:     PetscCall(DMPlexGetCellType(dm, cStart, &ct));
9250:     simplex = DMPolytopeTypeGetNumVertices(ct) == DMPolytopeTypeGetDim(ct) + 1 ? PETSC_TRUE : PETSC_FALSE;
9251:     PetscCall(DMGetNumFields(dm, &Nf));
9252:     for (f = 0; f < Nf; ++f) {
9253:       PetscFE         fe, efe;
9254:       PetscQuadrature q;
9255:       const char     *name;

9257:       PetscCall(DMGetField(dm, f, NULL, (PetscObject *)&fe));
9258:       PetscCall(PetscFECreateLagrange(PETSC_COMM_SELF, dim, Nf, simplex, 0, PETSC_DETERMINE, &efe));
9259:       PetscCall(PetscObjectGetName((PetscObject)fe, &name));
9260:       PetscCall(PetscObjectSetName((PetscObject)efe, name));
9261:       PetscCall(PetscFEGetQuadrature(fe, &q));
9262:       PetscCall(PetscFESetQuadrature(efe, q));
9263:       PetscCall(DMSetField(edm, f, NULL, (PetscObject)efe));
9264:       PetscCall(PetscFEDestroy(&efe));
9265:     }
9266:     PetscCall(DMCreateDS(edm));

9268:     PetscCall(DMCreateGlobalVector(edm, errorVec));
9269:     PetscCall(PetscObjectSetName((PetscObject)*errorVec, "Error"));
9270:     PetscCall(DMPlexComputeL2DiffVec(dm, time, exactSol, ctxs, sol, *errorVec));
9271:     PetscCall(DMDestroy(&edm));
9272:   }
9273:   PetscCall(PetscFree2(exactSol, ctxs));
9274:   PetscFunctionReturn(PETSC_SUCCESS);
9275: }

9277: /*@
9278:   DMGetNumAuxiliaryVec - Get the number of auxiliary vectors associated with this `DM`

9280:   Not Collective

9282:   Input Parameter:
9283: . dm - The `DM`

9285:   Output Parameter:
9286: . numAux - The number of auxiliary data vectors

9288:   Level: advanced

9290: .seealso: [](ch_dmbase), `DM`, `DMClearAuxiliaryVec()`, `DMSetAuxiliaryVec()`, `DMGetAuxiliaryLabels()`, `DMGetAuxiliaryVec()`
9291: @*/
9292: PetscErrorCode DMGetNumAuxiliaryVec(DM dm, PetscInt *numAux)
9293: {
9294:   PetscFunctionBegin;
9296:   PetscCall(PetscHMapAuxGetSize(dm->auxData, numAux));
9297:   PetscFunctionReturn(PETSC_SUCCESS);
9298: }

9300: /*@
9301:   DMGetAuxiliaryVec - Get the auxiliary vector for region specified by the given label and value, and equation part

9303:   Not Collective

9305:   Input Parameters:
9306: + dm    - The `DM`
9307: . label - The `DMLabel`
9308: . value - The label value indicating the region
9309: - part  - The equation part, or 0 if unused

9311:   Output Parameter:
9312: . aux - The `Vec` holding auxiliary field data

9314:   Level: advanced

9316:   Note:
9317:   If no auxiliary vector is found for this (label, value), (`NULL`, 0, 0) is checked as well.

9319: .seealso: [](ch_dmbase), `DM`, `DMClearAuxiliaryVec()`, `DMSetAuxiliaryVec()`, `DMGetNumAuxiliaryVec()`, `DMGetAuxiliaryLabels()`
9320: @*/
9321: PetscErrorCode DMGetAuxiliaryVec(DM dm, DMLabel label, PetscInt value, PetscInt part, Vec *aux)
9322: {
9323:   PetscHashAuxKey key, wild = {NULL, 0, 0};
9324:   PetscBool       has;

9326:   PetscFunctionBegin;
9329:   key.label = label;
9330:   key.value = value;
9331:   key.part  = part;
9332:   PetscCall(PetscHMapAuxHas(dm->auxData, key, &has));
9333:   if (has) PetscCall(PetscHMapAuxGet(dm->auxData, key, aux));
9334:   else PetscCall(PetscHMapAuxGet(dm->auxData, wild, aux));
9335:   PetscFunctionReturn(PETSC_SUCCESS);
9336: }

9338: /*@
9339:   DMSetAuxiliaryVec - Set an auxiliary vector for region specified by the given label and value, and equation part

9341:   Not Collective because auxiliary vectors are not parallel

9343:   Input Parameters:
9344: + dm    - The `DM`
9345: . label - The `DMLabel`
9346: . value - The label value indicating the region
9347: . part  - The equation part, or 0 if unused
9348: - aux   - The `Vec` holding auxiliary field data

9350:   Level: advanced

9352: .seealso: [](ch_dmbase), `DM`, `DMClearAuxiliaryVec()`, `DMGetAuxiliaryVec()`, `DMGetAuxiliaryLabels()`, `DMCopyAuxiliaryVec()`
9353: @*/
9354: PetscErrorCode DMSetAuxiliaryVec(DM dm, DMLabel label, PetscInt value, PetscInt part, Vec aux)
9355: {
9356:   Vec             old;
9357:   PetscHashAuxKey key;

9359:   PetscFunctionBegin;
9362:   key.label = label;
9363:   key.value = value;
9364:   key.part  = part;
9365:   PetscCall(PetscHMapAuxGet(dm->auxData, key, &old));
9366:   PetscCall(PetscObjectReference((PetscObject)aux));
9367:   if (!aux) PetscCall(PetscHMapAuxDel(dm->auxData, key));
9368:   else PetscCall(PetscHMapAuxSet(dm->auxData, key, aux));
9369:   PetscCall(VecDestroy(&old));
9370:   PetscFunctionReturn(PETSC_SUCCESS);
9371: }

9373: /*@
9374:   DMGetAuxiliaryLabels - Get the labels, values, and parts for all auxiliary vectors in this `DM`

9376:   Not Collective

9378:   Input Parameter:
9379: . dm - The `DM`

9381:   Output Parameters:
9382: + labels - The `DMLabel`s for each `Vec`
9383: . values - The label values for each `Vec`
9384: - parts  - The equation parts for each `Vec`

9386:   Level: advanced

9388:   Note:
9389:   The arrays passed in must be at least as large as `DMGetNumAuxiliaryVec()`.

9391: .seealso: [](ch_dmbase), `DM`, `DMClearAuxiliaryVec()`, `DMGetNumAuxiliaryVec()`, `DMGetAuxiliaryVec()`, `DMSetAuxiliaryVec()`, `DMCopyAuxiliaryVec()`
9392: @*/
9393: PetscErrorCode DMGetAuxiliaryLabels(DM dm, DMLabel labels[], PetscInt values[], PetscInt parts[])
9394: {
9395:   PetscHashAuxKey *keys;
9396:   PetscInt         n, i, off = 0;

9398:   PetscFunctionBegin;
9400:   PetscAssertPointer(labels, 2);
9401:   PetscAssertPointer(values, 3);
9402:   PetscAssertPointer(parts, 4);
9403:   PetscCall(DMGetNumAuxiliaryVec(dm, &n));
9404:   PetscCall(PetscMalloc1(n, &keys));
9405:   PetscCall(PetscHMapAuxGetKeys(dm->auxData, &off, keys));
9406:   for (i = 0; i < n; ++i) {
9407:     labels[i] = keys[i].label;
9408:     values[i] = keys[i].value;
9409:     parts[i]  = keys[i].part;
9410:   }
9411:   PetscCall(PetscFree(keys));
9412:   PetscFunctionReturn(PETSC_SUCCESS);
9413: }

9415: /*@
9416:   DMCopyAuxiliaryVec - Copy the auxiliary vector data on a `DM` to a new `DM`

9418:   Not Collective

9420:   Input Parameter:
9421: . dm - The `DM`

9423:   Output Parameter:
9424: . dmNew - The new `DM`, now with the same auxiliary data

9426:   Level: advanced

9428:   Note:
9429:   This is a shallow copy of the auxiliary vectors

9431: .seealso: [](ch_dmbase), `DM`, `DMClearAuxiliaryVec()`, `DMGetNumAuxiliaryVec()`, `DMGetAuxiliaryVec()`, `DMSetAuxiliaryVec()`
9432: @*/
9433: PetscErrorCode DMCopyAuxiliaryVec(DM dm, DM dmNew)
9434: {
9435:   PetscFunctionBegin;
9438:   if (dm == dmNew) PetscFunctionReturn(PETSC_SUCCESS);
9439:   PetscCall(DMClearAuxiliaryVec(dmNew));

9441:   PetscCall(PetscHMapAuxDestroy(&dmNew->auxData));
9442:   PetscCall(PetscHMapAuxDuplicate(dm->auxData, &dmNew->auxData));
9443:   {
9444:     Vec     *auxData;
9445:     PetscInt n, i, off = 0;

9447:     PetscCall(PetscHMapAuxGetSize(dmNew->auxData, &n));
9448:     PetscCall(PetscMalloc1(n, &auxData));
9449:     PetscCall(PetscHMapAuxGetVals(dmNew->auxData, &off, auxData));
9450:     for (i = 0; i < n; ++i) PetscCall(PetscObjectReference((PetscObject)auxData[i]));
9451:     PetscCall(PetscFree(auxData));
9452:   }
9453:   PetscFunctionReturn(PETSC_SUCCESS);
9454: }

9456: /*@
9457:   DMClearAuxiliaryVec - Destroys the auxiliary vector information and creates a new empty one

9459:   Not Collective

9461:   Input Parameter:
9462: . dm - The `DM`

9464:   Level: advanced

9466: .seealso: [](ch_dmbase), `DM`, `DMCopyAuxiliaryVec()`, `DMGetNumAuxiliaryVec()`, `DMGetAuxiliaryVec()`, `DMSetAuxiliaryVec()`
9467: @*/
9468: PetscErrorCode DMClearAuxiliaryVec(DM dm)
9469: {
9470:   Vec     *auxData;
9471:   PetscInt n, i, off = 0;

9473:   PetscFunctionBegin;
9474:   PetscCall(PetscHMapAuxGetSize(dm->auxData, &n));
9475:   PetscCall(PetscMalloc1(n, &auxData));
9476:   PetscCall(PetscHMapAuxGetVals(dm->auxData, &off, auxData));
9477:   for (i = 0; i < n; ++i) PetscCall(VecDestroy(&auxData[i]));
9478:   PetscCall(PetscFree(auxData));
9479:   PetscCall(PetscHMapAuxDestroy(&dm->auxData));
9480:   PetscCall(PetscHMapAuxCreate(&dm->auxData));
9481:   PetscFunctionReturn(PETSC_SUCCESS);
9482: }

9484: /*@
9485:   DMPolytopeMatchOrientation - Determine an orientation (transformation) that takes the source face arrangement to the target face arrangement

9487:   Not Collective

9489:   Input Parameters:
9490: + ct         - The `DMPolytopeType`
9491: . sourceCone - The source arrangement of faces
9492: - targetCone - The target arrangement of faces

9494:   Output Parameters:
9495: + ornt  - The orientation (transformation) which will take the source arrangement to the target arrangement
9496: - found - Flag indicating that a suitable orientation was found

9498:   Level: advanced

9500:   Note:
9501:   An arrangement is a face order combined with an orientation for each face

9503:   Each orientation (transformation) is labeled with an integer from negative `DMPolytopeTypeGetNumArrangements(ct)`/2 to `DMPolytopeTypeGetNumArrangements(ct)`/2
9504:   that labels each arrangement (face ordering plus orientation for each face).

9506:   See `DMPolytopeMatchVertexOrientation()` to find a new vertex orientation that takes the source vertex arrangement to the target vertex arrangement

9508: .seealso: [](ch_dmbase), `DM`, `DMPolytopeGetOrientation()`, `DMPolytopeMatchVertexOrientation()`, `DMPolytopeGetVertexOrientation()`
9509: @*/
9510: PetscErrorCode DMPolytopeMatchOrientation(DMPolytopeType ct, const PetscInt sourceCone[], const PetscInt targetCone[], PetscInt *ornt, PetscBool *found)
9511: {
9512:   const PetscInt cS = DMPolytopeTypeGetConeSize(ct);
9513:   const PetscInt nO = DMPolytopeTypeGetNumArrangements(ct) / 2;
9514:   PetscInt       o, c;

9516:   PetscFunctionBegin;
9517:   if (!nO) {
9518:     *ornt  = 0;
9519:     *found = PETSC_TRUE;
9520:     PetscFunctionReturn(PETSC_SUCCESS);
9521:   }
9522:   for (o = -nO; o < nO; ++o) {
9523:     const PetscInt *arr = DMPolytopeTypeGetArrangement(ct, o);

9525:     for (c = 0; c < cS; ++c)
9526:       if (sourceCone[arr[c * 2]] != targetCone[c]) break;
9527:     if (c == cS) {
9528:       *ornt = o;
9529:       break;
9530:     }
9531:   }
9532:   *found = o == nO ? PETSC_FALSE : PETSC_TRUE;
9533:   PetscFunctionReturn(PETSC_SUCCESS);
9534: }

9536: /*@
9537:   DMPolytopeGetOrientation - Determine an orientation (transformation) that takes the source face arrangement to the target face arrangement

9539:   Not Collective

9541:   Input Parameters:
9542: + ct         - The `DMPolytopeType`
9543: . sourceCone - The source arrangement of faces
9544: - targetCone - The target arrangement of faces

9546:   Output Parameter:
9547: . ornt - The orientation (transformation) which will take the source arrangement to the target arrangement

9549:   Level: advanced

9551:   Note:
9552:   This function is the same as `DMPolytopeMatchOrientation()` except it will generate an error if no suitable orientation can be found.

9554:   Developer Note:
9555:   It is unclear why this function needs to exist since one can simply call `DMPolytopeMatchOrientation()` and error if none is found

9557: .seealso: [](ch_dmbase), `DM`, `DMPolytopeType`, `DMPolytopeMatchOrientation()`, `DMPolytopeGetVertexOrientation()`, `DMPolytopeMatchVertexOrientation()`
9558: @*/
9559: PetscErrorCode DMPolytopeGetOrientation(DMPolytopeType ct, const PetscInt sourceCone[], const PetscInt targetCone[], PetscInt *ornt)
9560: {
9561:   PetscBool found;

9563:   PetscFunctionBegin;
9564:   PetscCall(DMPolytopeMatchOrientation(ct, sourceCone, targetCone, ornt, &found));
9565:   PetscCheck(found, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Could not find orientation for %s", DMPolytopeTypes[ct]);
9566:   PetscFunctionReturn(PETSC_SUCCESS);
9567: }

9569: /*@
9570:   DMPolytopeMatchVertexOrientation - Determine an orientation (transformation) that takes the source vertex arrangement to the target vertex arrangement

9572:   Not Collective

9574:   Input Parameters:
9575: + ct         - The `DMPolytopeType`
9576: . sourceVert - The source arrangement of vertices
9577: - targetVert - The target arrangement of vertices

9579:   Output Parameters:
9580: + ornt  - The orientation (transformation) which will take the source arrangement to the target arrangement
9581: - found - Flag indicating that a suitable orientation was found

9583:   Level: advanced

9585:   Notes:
9586:   An arrangement is a vertex order

9588:   Each orientation (transformation) is labeled with an integer from negative `DMPolytopeTypeGetNumArrangements(ct)`/2 to `DMPolytopeTypeGetNumArrangements(ct)`/2
9589:   that labels each arrangement (vertex ordering).

9591:   See `DMPolytopeMatchOrientation()` to find a new face orientation that takes the source face arrangement to the target face arrangement

9593: .seealso: [](ch_dmbase), `DM`, `DMPolytopeType`, `DMPolytopeGetOrientation()`, `DMPolytopeMatchOrientation()`, `DMPolytopeTypeGetNumVertices()`, `DMPolytopeTypeGetVertexArrangement()`
9594: @*/
9595: PetscErrorCode DMPolytopeMatchVertexOrientation(DMPolytopeType ct, const PetscInt sourceVert[], const PetscInt targetVert[], PetscInt *ornt, PetscBool *found)
9596: {
9597:   const PetscInt cS = DMPolytopeTypeGetNumVertices(ct);
9598:   const PetscInt nO = DMPolytopeTypeGetNumArrangements(ct) / 2;
9599:   PetscInt       o, c;

9601:   PetscFunctionBegin;
9602:   if (!nO) {
9603:     *ornt  = 0;
9604:     *found = PETSC_TRUE;
9605:     PetscFunctionReturn(PETSC_SUCCESS);
9606:   }
9607:   for (o = -nO; o < nO; ++o) {
9608:     const PetscInt *arr = DMPolytopeTypeGetVertexArrangement(ct, o);

9610:     for (c = 0; c < cS; ++c)
9611:       if (sourceVert[arr[c]] != targetVert[c]) break;
9612:     if (c == cS) {
9613:       *ornt = o;
9614:       break;
9615:     }
9616:   }
9617:   *found = o == nO ? PETSC_FALSE : PETSC_TRUE;
9618:   PetscFunctionReturn(PETSC_SUCCESS);
9619: }

9621: /*@
9622:   DMPolytopeGetVertexOrientation - Determine an orientation (transformation) that takes the source vertex arrangement to the target vertex arrangement

9624:   Not Collective

9626:   Input Parameters:
9627: + ct         - The `DMPolytopeType`
9628: . sourceCone - The source arrangement of vertices
9629: - targetCone - The target arrangement of vertices

9631:   Output Parameter:
9632: . ornt - The orientation (transformation) which will take the source arrangement to the target arrangement

9634:   Level: advanced

9636:   Note:
9637:   This function is the same as `DMPolytopeMatchVertexOrientation()` except it errors if not orientation is possible.

9639:   Developer Note:
9640:   It is unclear why this function needs to exist since one can simply call `DMPolytopeMatchVertexOrientation()` and error if none is found

9642: .seealso: [](ch_dmbase), `DM`, `DMPolytopeType`, `DMPolytopeMatchVertexOrientation()`, `DMPolytopeGetOrientation()`
9643: @*/
9644: PetscErrorCode DMPolytopeGetVertexOrientation(DMPolytopeType ct, const PetscInt sourceCone[], const PetscInt targetCone[], PetscInt *ornt)
9645: {
9646:   PetscBool found;

9648:   PetscFunctionBegin;
9649:   PetscCall(DMPolytopeMatchVertexOrientation(ct, sourceCone, targetCone, ornt, &found));
9650:   PetscCheck(found, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Could not find orientation for %s", DMPolytopeTypes[ct]);
9651:   PetscFunctionReturn(PETSC_SUCCESS);
9652: }

9654: /*@
9655:   DMPolytopeInCellTest - Check whether a point lies inside the reference cell of given type

9657:   Not Collective

9659:   Input Parameters:
9660: + ct    - The `DMPolytopeType`
9661: - point - Coordinates of the point

9663:   Output Parameter:
9664: . inside - Flag indicating whether the point is inside the reference cell of given type

9666:   Level: advanced

9668: .seealso: [](ch_dmbase), `DM`, `DMPolytopeType`, `DMLocatePoints()`
9669: @*/
9670: PetscErrorCode DMPolytopeInCellTest(DMPolytopeType ct, const PetscReal point[], PetscBool *inside)
9671: {
9672:   PetscReal sum = 0.0;
9673:   PetscInt  d;

9675:   PetscFunctionBegin;
9676:   *inside = PETSC_TRUE;
9677:   switch (ct) {
9678:   case DM_POLYTOPE_TRIANGLE:
9679:   case DM_POLYTOPE_TETRAHEDRON:
9680:     for (d = 0; d < DMPolytopeTypeGetDim(ct); ++d) {
9681:       if (point[d] < -1.0) {
9682:         *inside = PETSC_FALSE;
9683:         break;
9684:       }
9685:       sum += point[d];
9686:     }
9687:     if (sum > PETSC_SMALL) {
9688:       *inside = PETSC_FALSE;
9689:       break;
9690:     }
9691:     break;
9692:   case DM_POLYTOPE_QUADRILATERAL:
9693:   case DM_POLYTOPE_HEXAHEDRON:
9694:     for (d = 0; d < DMPolytopeTypeGetDim(ct); ++d)
9695:       if (PetscAbsReal(point[d]) > 1. + PETSC_SMALL) {
9696:         *inside = PETSC_FALSE;
9697:         break;
9698:       }
9699:     break;
9700:   default:
9701:     SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Unsupported polytope type %s", DMPolytopeTypes[ct]);
9702:   }
9703:   PetscFunctionReturn(PETSC_SUCCESS);
9704: }

9706: /*@
9707:   DMReorderSectionSetDefault - Set flag indicating whether the local section should be reordered by default

9709:   Logically collective

9711:   Input Parameters:
9712: + dm      - The DM
9713: - reorder - Flag for reordering

9715:   Level: intermediate

9717: .seealso: `DMReorderSectionGetDefault()`
9718: @*/
9719: PetscErrorCode DMReorderSectionSetDefault(DM dm, DMReorderDefaultFlag reorder)
9720: {
9721:   PetscFunctionBegin;
9723:   PetscTryMethod(dm, "DMReorderSectionSetDefault_C", (DM, DMReorderDefaultFlag), (dm, reorder));
9724:   PetscFunctionReturn(PETSC_SUCCESS);
9725: }

9727: /*@
9728:   DMReorderSectionGetDefault - Get flag indicating whether the local section should be reordered by default

9730:   Not collective

9732:   Input Parameter:
9733: . dm - The DM

9735:   Output Parameter:
9736: . reorder - Flag for reordering

9738:   Level: intermediate

9740: .seealso: `DMReorderSetDefault()`
9741: @*/
9742: PetscErrorCode DMReorderSectionGetDefault(DM dm, DMReorderDefaultFlag *reorder)
9743: {
9744:   PetscFunctionBegin;
9746:   PetscAssertPointer(reorder, 2);
9747:   *reorder = DM_REORDER_DEFAULT_NOTSET;
9748:   PetscTryMethod(dm, "DMReorderSectionGetDefault_C", (DM, DMReorderDefaultFlag *), (dm, reorder));
9749:   PetscFunctionReturn(PETSC_SUCCESS);
9750: }

9752: /*@
9753:   DMReorderSectionSetType - Set the type of local section reordering

9755:   Logically collective

9757:   Input Parameters:
9758: + dm      - The DM
9759: - reorder - The reordering method

9761:   Level: intermediate

9763: .seealso: `DMReorderSectionGetType()`, `DMReorderSectionSetDefault()`
9764: @*/
9765: PetscErrorCode DMReorderSectionSetType(DM dm, MatOrderingType reorder)
9766: {
9767:   PetscFunctionBegin;
9769:   PetscTryMethod(dm, "DMReorderSectionSetType_C", (DM, MatOrderingType), (dm, reorder));
9770:   PetscFunctionReturn(PETSC_SUCCESS);
9771: }

9773: /*@
9774:   DMReorderSectionGetType - Get the reordering type for the local section

9776:   Not collective

9778:   Input Parameter:
9779: . dm - The DM

9781:   Output Parameter:
9782: . reorder - The reordering method

9784:   Level: intermediate

9786: .seealso: `DMReorderSetDefault()`, `DMReorderSectionGetDefault()`
9787: @*/
9788: PetscErrorCode DMReorderSectionGetType(DM dm, MatOrderingType *reorder)
9789: {
9790:   PetscFunctionBegin;
9792:   PetscAssertPointer(reorder, 2);
9793:   *reorder = NULL;
9794:   PetscTryMethod(dm, "DMReorderSectionGetType_C", (DM, MatOrderingType *), (dm, reorder));
9795:   PetscFunctionReturn(PETSC_SUCCESS);
9796: }