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 - Creates a matrix of appropriate size and nonzero structure for a `DM`. The matrix is most commonly used to store the Jacobian
1504:   of a discrete PDE operator.

1506:   Collective

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

1511:   Output Parameter:
1512: . mat - the matrix

1514:   Options Database Key:
1515: . -dm_preallocate_only (true|false) - Only preallocate the matrix for `DMCreateMatrix()` and `DMCreateMassMatrix()`, but do not fill its nonzero structure

1517:   Level: beginner

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

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

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

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

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

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

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

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

1579:   Logically Collective

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

1585:   Level: developer

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

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

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

1605:   Logically Collective

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

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

1614:   Level: developer

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

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

1630:   Logically Collective

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

1636:   Level: developer

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

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

1651:   Logically Collective

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

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

1660:   Level: advanced

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

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

1675:   Not Collective

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

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

1683:   Level: advanced

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

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

1699:   Not Collective

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

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

1709:   Level: developer

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

1714:   The array may contain nonzero values

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

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

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

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

1762:   Not Collective

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

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

1772:   Level: developer

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

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

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

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

1804:   Logically Collective; No Fortran Support

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

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

1817:   Level: intermediate

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

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

1834:   Not Collective; No Fortran Support

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

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

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

1849:   Level: intermediate

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

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

1867:   Logically Collective; No Fortran Support

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

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

1880:   Level: intermediate

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

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

1898:   Not Collective; No Fortran Support

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

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

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

1913:   Level: intermediate

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

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

1932:   Not Collective; No Fortran Support

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

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

1942:   Level: intermediate

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

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

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

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

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

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

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

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

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

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

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

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

2057:   Not Collective; No Fortran Support

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

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

2068:   Level: intermediate

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

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

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

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

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

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

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

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

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

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

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

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

2159:   Not collective

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

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

2170:   Level: intermediate

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

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

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

2191:   Not collective

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

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

2201:   Level: intermediate

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

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

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

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

2230:   Not Collective

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

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

2242:   Level: intermediate

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

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

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

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

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

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

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

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

2316:   Not Collective

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

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

2328:   Level: developer

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

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

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

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

2354:   Collective

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

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

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

2366:   Level: developer

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

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

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

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

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

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

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

2403:   Logically Collective; No Fortran Support

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

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

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

2422:   Level: advanced

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

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

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

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

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

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

2456:   Logically Collective; No Fortran Support

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

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

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

2475:   Level: advanced

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

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

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

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

2502:   Collective if any hooks are

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

2509:   Level: developer

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

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

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

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

2531:   Collective

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

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

2544:   Level: developer

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

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

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

2561:   PetscFunctionBegin;

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

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

2579:   Not Collective

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

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

2587:   Level: developer

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

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

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

2605:   Not Collective

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

2611:   Level: advanced

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

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

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

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

2631:   Collective

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

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

2640:   Level: developer

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

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

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

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

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

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

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

2688:   Level: developer

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

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

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

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

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

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

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

2768:   Logically Collective

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

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

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

2790:   Level: advanced

2792:   Note:
2793:   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.

2795: .seealso: [](ch_dmbase), `DM`, `DMGlobalToLocal()`, `DMRefineHookAdd()`, `SNESFASGetInterpolation()`, `SNESFASGetInjection()`, `PetscObjectCompose()`, `PetscContainerCreate()`
2796: @*/
2797: 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)
2798: {
2799:   DMGlobalToLocalHookLink link, *p;

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

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

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

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

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

2851:   Neighbor-wise Collective

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

2859:   Level: beginner

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

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

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

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

2882:   Neighbor-wise Collective

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

2890:   Level: intermediate

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

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

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

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

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

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

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

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

2934:   Neighbor-wise Collective

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

2942:   Level: intermediate

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

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

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

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

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

2984:   Logically Collective

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

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

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

3006:   Level: advanced

3008: .seealso: [](ch_dmbase), `DM`, `DMLocalToGlobal()`, `DMRefineHookAdd()`, `DMGlobalToLocalHookAdd()`, `SNESFASGetInterpolation()`, `SNESFASGetInjection()`, `PetscObjectCompose()`, `PetscContainerCreate()`
3009: @*/
3010: 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)
3011: {
3012:   DMLocalToGlobalHookLink link, *p;

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

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

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

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

3067:   Neighbor-wise Collective

3069:   Input Parameters:
3070: + dm   - the `DM` object
3071: . l    - the local vector
3072: . 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.
3073: - g    - the global vector

3075:   Level: beginner

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

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

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

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

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

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

3100:   Neighbor-wise Collective

3102:   Input Parameters:
3103: + dm   - the `DM` object
3104: . l    - the local vector
3105: . 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.
3106: - g    - the global vector

3108:   Level: intermediate

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

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

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

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

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

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

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

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

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

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

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

3236:   Neighbor-wise Collective

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

3244:   Level: intermediate

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

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

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

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

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

3310:   Neighbor-wise Collective

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

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

3320:   Level: intermediate

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

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

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

3341:   Neighbor-wise Collective

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

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

3351:   Level: intermediate

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

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

3368:   Collective

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

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

3377:   Level: developer

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

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

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

3411:   Logically Collective; No Fortran Support

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

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

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

3432:   Level: advanced

3434:   Notes:
3435:   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`.

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

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

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

3444: .seealso: [](ch_dmbase), `DM`, `DMCoarsenHookRemove()`, `DMRefineHookAdd()`, `SNESFASGetInterpolation()`, `SNESFASGetInjection()`, `PetscObjectCompose()`, `PetscContainerCreate()`
3445: @*/
3446: 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)
3447: {
3448:   DMCoarsenHookLink link, *p;

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

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

3467:   Logically Collective; No Fortran Support

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

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

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

3488:   Level: advanced

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

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

3495: .seealso: [](ch_dmbase), `DM`, `DMCoarsenHookAdd()`, `DMRefineHookAdd()`, `SNESFASGetInterpolation()`, `SNESFASGetInjection()`, `PetscObjectCompose()`, `PetscContainerCreate()`
3496: @*/
3497: 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)
3498: {
3499:   DMCoarsenHookLink link, *p;

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

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

3517:   Collective if any hooks are

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

3526:   Level: developer

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

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

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

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

3547:   Logically Collective; No Fortran Support

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

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

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

3567:   Level: advanced

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

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

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

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

3580: .seealso: [](ch_dmbase), `DM`, `DMSubDomainHookRemove()`, `DMRefineHookAdd()`, `SNESFASGetInterpolation()`, `SNESFASGetInjection()`, `PetscObjectCompose()`, `PetscContainerCreate()`, `DMCreateDomainDecomposition()`
3581: @*/
3582: 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)
3583: {
3584:   DMSubDomainHookLink link, *p;

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

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

3603:   Logically Collective; No Fortran Support

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

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

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

3623:   Level: advanced

3625: .seealso: [](ch_dmbase), `DM`, `DMSubDomainHookAdd()`, `SNESFASGetInterpolation()`, `SNESFASGetInjection()`, `PetscObjectCompose()`, `PetscContainerCreate()`,
3626:           `DMCreateDomainDecomposition()`
3627: @*/
3628: 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)
3629: {
3630:   DMSubDomainHookLink link, *p;

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

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

3648:   Collective if any hooks are

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

3656:   Level: developer

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

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

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

3674:   Not Collective

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

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

3682:   Level: developer

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

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

3698:   Collective

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

3704:   Level: developer

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

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

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

3722:   Collective

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

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

3731:   Level: developer

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

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

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

3754:   Collective

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

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

3763:   Level: developer

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

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

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

3786:   Logically Collective if the function is collective

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

3792:   Level: intermediate

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

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

3808:   Not Collective

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

3814:   Level: intermediate

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

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

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

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

3840:   Not Collective

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

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

3848:   Level: intermediate

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

3853:   Fortran Notes:
3854:   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
3855:   function that tells the Fortran compiler the derived data type that is returned as the `ctx` argument. For example,
3856: .vb
3857:   Interface DMGetApplicationContext
3858:     Subroutine DMGetApplicationContext(dm,ctx,ierr)
3859:   #include <petsc/finclude/petscdm.h>
3860:       use petscdm
3861:       DM dm
3862:       type(tUsertype), pointer :: ctx
3863:       PetscErrorCode ierr
3864:     End Subroutine
3865:   End Interface DMGetApplicationContext
3866: .ve

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

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

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

3886:   Logically Collective

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

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

3897:   Level: intermediate

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

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

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

3916:   Not Collective

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

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

3924:   Level: developer

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

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

3940:   Logically Collective

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

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

3949:   Level: advanced

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

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

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

3969:   Not Collective

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

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

3977:   Level: developer

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

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

3993:   Not Collective

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

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

4001:   Level: developer

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

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

4017:   Not Collective

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

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

4025:   Level: developer

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

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

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

4045:   Collective

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

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

4054:   Level: intermediate

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

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

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

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

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

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

4085:   Not Collective

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

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

4093:   Level: intermediate

4095:   Note:
4096:   `type` should not be retained for later use as it will be an invalid pointer if the `DMType` of `dm` is changed.

4098: .seealso: [](ch_dmbase), `DM`, `DMType`, `DMDA`, `DMPLEX`, `DMSetType()`, `DMCreate()`, `PetscObjectTypeCompare()`, `PetscObjectTypeCompareAny()`
4099: @*/
4100: PetscErrorCode DMGetType(DM dm, DMType *type)
4101: {
4102:   PetscFunctionBegin;
4104:   PetscAssertPointer(type, 2);
4105:   PetscCall(DMRegisterAll());
4106:   *type = ((PetscObject)dm)->type_name;
4107:   PetscFunctionReturn(PETSC_SUCCESS);
4108: }

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

4113:   Collective

4115:   Input Parameters:
4116: + dm      - the `DM`
4117: - newtype - new `DM` type (use "same" for the same type)

4119:   Output Parameter:
4120: . M - pointer to new `DM`

4122:   Level: intermediate

4124:   Note:
4125:   Cannot be used to convert a sequential `DM` to a parallel or a parallel to sequential,
4126:   the MPI communicator of the generated `DM` is always the same as the communicator
4127:   of the input `DM`.

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

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

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

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

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

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

4188:     /* 4) See if a good general converter is known for the current matrix */
4189:     if (dm->ops->convert) conv = dm->ops->convert;
4190:     if (conv) goto foundconv;
4191: #endif

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

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

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

4217: /*@C
4218:   DMRegister -  Adds a new `DM` type implementation

4220:   Not Collective, No Fortran Support

4222:   Input Parameters:
4223: + sname    - The name of a new user-defined creation routine
4224: - function - The creation routine itself

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

4229:   Level: advanced

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

4234:   Example Usage:
4235: .vb
4236:     DMRegister("my_da", MyDMCreate);
4237: .ve

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

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

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

4262:   Collective

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

4270:   Level: intermediate

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

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

4279: .seealso: [](ch_dmbase), `DM`, `PetscViewerBinaryOpen()`, `DMView()`, `MatLoad()`, `VecLoad()`
4280: @*/
4281: PetscErrorCode DMLoad(DM newdm, PetscViewer viewer)
4282: {
4283:   PetscBool isbinary, ishdf5;

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

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

4308: /* FEM Support */

4310: PetscErrorCode DMPrintCellIndices(PetscInt c, const char name[], PetscInt len, const PetscInt x[])
4311: {
4312:   PetscInt f;

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

4320: PetscErrorCode DMPrintCellVector(PetscInt c, const char name[], PetscInt len, const PetscScalar x[])
4321: {
4322:   PetscInt f;

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

4330: PetscErrorCode DMPrintCellVectorReal(PetscInt c, const char name[], PetscInt len, const PetscReal x[])
4331: {
4332:   PetscInt f;

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

4340: PetscErrorCode DMPrintCellMatrix(PetscInt c, const char name[], PetscInt rows, PetscInt cols, const PetscScalar A[])
4341: {
4342:   PetscInt f, g;

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

4354: PetscErrorCode DMPrintLocalVec(DM dm, const char name[], PetscReal tol, Vec X)
4355: {
4356:   PetscInt           localSize, bs;
4357:   PetscMPIInt        size;
4358:   Vec                x, xglob;
4359:   const PetscScalar *xarray;

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

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

4387:   Input Parameter:
4388: . dm - The `DM`

4390:   Output Parameter:
4391: . section - The `PetscSection`

4393:   Options Database Key:
4394: . -dm_petscsection_view - View the section created by the `DM`

4396:   Level: intermediate

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

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

4411:     if (dm->setfromoptionscalled) {
4412:       PetscObject       obj = (PetscObject)dm;
4413:       PetscViewer       viewer;
4414:       PetscViewerFormat format;
4415:       PetscBool         flg;

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

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

4439:   Input Parameters:
4440: + dm      - The `DM`
4441: - section - The `PetscSection`

4443:   Level: intermediate

4445:   Note:
4446:   Any existing Section will be destroyed

4448: .seealso: [](ch_dmbase), `DM`, `PetscSection`, `DMGetLocalSection()`, `DMSetGlobalSection()`
4449: @*/
4450: PetscErrorCode DMSetLocalSection(DM dm, PetscSection section)
4451: {
4452:   PetscInt numFields = 0;
4453:   PetscInt f;

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

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

4479:   /* Clear scratch vectors */
4480:   PetscCall(DMClearGlobalVectors(dm));
4481:   PetscCall(DMClearLocalVectors(dm));
4482:   PetscCall(DMClearNamedGlobalVectors(dm));
4483:   PetscCall(DMClearNamedLocalVectors(dm));
4484:   PetscFunctionReturn(PETSC_SUCCESS);
4485: }

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

4490:   Input Parameter:
4491: . dm - The `DM`

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

4497:   Level: developer

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

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

4513:   not Collective

4515:   Input Parameter:
4516: . dm - The `DM`

4518:   Output Parameters:
4519: + 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.
4520: . 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.
4521: - bias    - Vector containing bias to be added to constrained dofs

4523:   Level: advanced

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

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

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

4544:   Collective

4546:   Input Parameters:
4547: + dm      - The `DM`
4548: . 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).
4549: . 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).
4550: - 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).

4552:   Level: advanced

4554:   Notes:
4555:   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()`.

4557:   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.

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

4561: .seealso: [](ch_dmbase), `DM`, `DMGetDefaultConstraints()`
4562: @*/
4563: PetscErrorCode DMSetDefaultConstraints(DM dm, PetscSection section, Mat mat, Vec bias)
4564: {
4565:   PetscMPIInt result;

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

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

4600:   Input Parameters:
4601: + dm - The `DM`
4602: . localSection - `PetscSection` describing the local data layout
4603: - globalSection - `PetscSection` describing the global data layout

4605:   Level: intermediate

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

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

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

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

4674: PetscErrorCode DMGetIsoperiodicPointSF_Internal(DM dm, PetscSF *sf)
4675: {
4676:   PetscErrorCode (*f)(DM, PetscSF *);

4678:   PetscFunctionBegin;
4680:   PetscAssertPointer(sf, 2);
4681:   PetscCall(PetscObjectQueryFunction((PetscObject)dm, "DMGetIsoperiodicPointSF_C", &f));
4682:   if (f) PetscCall(f(dm, sf));
4683:   else *sf = dm->sf;
4684:   PetscFunctionReturn(PETSC_SUCCESS);
4685: }

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

4690:   Collective

4692:   Input Parameter:
4693: . dm - The `DM`

4695:   Output Parameter:
4696: . section - The `PetscSection`

4698:   Level: intermediate

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

4703: .seealso: [](ch_dmbase), `DM`, `DMSetLocalSection()`, `DMGetLocalSection()`
4704: @*/
4705: PetscErrorCode DMGetGlobalSection(DM dm, PetscSection *section)
4706: {
4707:   PetscFunctionBegin;
4709:   PetscAssertPointer(section, 2);
4710:   if (!dm->globalSection) {
4711:     PetscSection s;
4712:     PetscSF      sf;

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

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

4730:   Input Parameters:
4731: + dm      - The `DM`
4732: - section - The PetscSection, or `NULL`

4734:   Level: intermediate

4736:   Note:
4737:   Any existing `PetscSection` will be destroyed

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

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

4764:   Input Parameter:
4765: . dm - The `DM`

4767:   Output Parameter:
4768: . sf - The `PetscSF`

4770:   Level: intermediate

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

4775: .seealso: [](ch_dmbase), `DM`, `DMSetSectionSF()`, `DMCreateSectionSF()`
4776: @*/
4777: PetscErrorCode DMGetSectionSF(DM dm, PetscSF *sf)
4778: {
4779:   PetscInt nroots;

4781:   PetscFunctionBegin;
4783:   PetscAssertPointer(sf, 2);
4784:   if (!dm->sectionSF) PetscCall(PetscSFCreate(PetscObjectComm((PetscObject)dm), &dm->sectionSF));
4785:   PetscCall(PetscSFGetGraph(dm->sectionSF, &nroots, NULL, NULL, NULL));
4786:   if (nroots < 0) {
4787:     PetscSection section, gSection;

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

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

4805:   Input Parameters:
4806: + dm - The `DM`
4807: - sf - The `PetscSF`

4809:   Level: intermediate

4811:   Note:
4812:   Any previous `PetscSF` is destroyed

4814: .seealso: [](ch_dmbase), `DM`, `DMGetSectionSF()`, `DMCreateSectionSF()`
4815: @*/
4816: PetscErrorCode DMSetSectionSF(DM dm, PetscSF sf)
4817: {
4818:   PetscFunctionBegin;
4821:   PetscCall(PetscObjectReference((PetscObject)sf));
4822:   PetscCall(PetscSFDestroy(&dm->sectionSF));
4823:   dm->sectionSF = sf;
4824:   PetscFunctionReturn(PETSC_SUCCESS);
4825: }

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

4831:   Input Parameters:
4832: + dm            - The `DM`
4833: . localSection  - `PetscSection` describing the local data layout
4834: - globalSection - `PetscSection` describing the global data layout

4836:   Level: developer

4838:   Note:
4839:   One usually uses `DMGetSectionSF()` to obtain the `PetscSF`

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

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

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

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

4862:   Input Parameter:
4863: . dm - The `DM`

4865:   Output Parameter:
4866: . sf - The `PetscSF`

4868:   Level: intermediate

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

4873: .seealso: [](ch_dmbase), `DM`, `DMSetPointSF()`, `DMGetSectionSF()`, `DMSetSectionSF()`, `DMCreateSectionSF()`
4874: @*/
4875: PetscErrorCode DMGetPointSF(DM dm, PetscSF *sf)
4876: {
4877:   PetscFunctionBegin;
4879:   PetscAssertPointer(sf, 2);
4880:   *sf = dm->sf;
4881:   PetscFunctionReturn(PETSC_SUCCESS);
4882: }

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

4887:   Collective

4889:   Input Parameters:
4890: + dm - The `DM`
4891: - sf - The `PetscSF`

4893:   Level: intermediate

4895: .seealso: [](ch_dmbase), `DM`, `DMGetPointSF()`, `DMGetSectionSF()`, `DMSetSectionSF()`, `DMCreateSectionSF()`
4896: @*/
4897: PetscErrorCode DMSetPointSF(DM dm, PetscSF sf)
4898: {
4899:   PetscFunctionBegin;
4902:   PetscCall(PetscObjectReference((PetscObject)sf));
4903:   PetscCall(PetscSFDestroy(&dm->sf));
4904:   dm->sf = sf;
4905:   PetscFunctionReturn(PETSC_SUCCESS);
4906: }

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

4911:   Input Parameter:
4912: . dm - The `DM`

4914:   Output Parameter:
4915: . sf - The `PetscSF`

4917:   Level: intermediate

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

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

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

4936:   Input Parameters:
4937: + dm - The DM
4938: - sf - The PetscSF

4940:   Level: intermediate

4942: .seealso: [](ch_dmbase), `DM`, `DMGetNaturalSF()`, `DMSetUseNatural()`, `DMGetUseNatural()`, `DMPlexCreateGlobalToNaturalSF()`, `DMPlexDistribute()`
4943: @*/
4944: PetscErrorCode DMSetNaturalSF(DM dm, PetscSF sf)
4945: {
4946:   PetscFunctionBegin;
4949:   PetscCall(PetscObjectReference((PetscObject)sf));
4950:   PetscCall(PetscSFDestroy(&dm->sfNatural));
4951:   dm->sfNatural = sf;
4952:   PetscFunctionReturn(PETSC_SUCCESS);
4953: }

4955: static PetscErrorCode DMSetDefaultAdjacency_Private(DM dm, PetscInt f, PetscObject disc)
4956: {
4957:   PetscClassId id;

4959:   PetscFunctionBegin;
4960:   PetscCall(PetscObjectGetClassId(disc, &id));
4961:   if (id == PETSCFE_CLASSID) PetscCall(DMSetAdjacency(dm, f, PETSC_FALSE, PETSC_TRUE));
4962:   else if (id == PETSCFV_CLASSID) PetscCall(DMSetAdjacency(dm, f, PETSC_TRUE, PETSC_FALSE));
4963:   else PetscCall(DMSetAdjacency(dm, f, PETSC_FALSE, PETSC_TRUE));
4964:   PetscFunctionReturn(PETSC_SUCCESS);
4965: }

4967: static PetscErrorCode DMFieldEnlarge_Static(DM dm, PetscInt NfNew)
4968: {
4969:   RegionField *tmpr;
4970:   PetscInt     Nf = dm->Nf, f;

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

4987: /*@
4988:   DMClearFields - Remove all fields from the `DM`

4990:   Logically Collective

4992:   Input Parameter:
4993: . dm - The `DM`

4995:   Level: intermediate

4997: .seealso: [](ch_dmbase), `DM`, `DMGetNumFields()`, `DMSetNumFields()`, `DMSetField()`
4998: @*/
4999: PetscErrorCode DMClearFields(DM dm)
5000: {
5001:   PetscInt f;

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

5016: /*@
5017:   DMGetNumFields - Get the number of fields in the `DM`

5019:   Not Collective

5021:   Input Parameter:
5022: . dm - The `DM`

5024:   Output Parameter:
5025: . numFields - The number of fields

5027:   Level: intermediate

5029: .seealso: [](ch_dmbase), `DM`, `DMSetNumFields()`, `DMSetField()`
5030: @*/
5031: PetscErrorCode DMGetNumFields(DM dm, PetscInt *numFields)
5032: {
5033:   PetscFunctionBegin;
5035:   PetscAssertPointer(numFields, 2);
5036:   *numFields = dm->Nf;
5037:   PetscFunctionReturn(PETSC_SUCCESS);
5038: }

5040: /*@
5041:   DMSetNumFields - Set the number of fields in the `DM`

5043:   Logically Collective

5045:   Input Parameters:
5046: + dm        - The `DM`
5047: - numFields - The number of fields

5049:   Level: intermediate

5051: .seealso: [](ch_dmbase), `DM`, `DMGetNumFields()`, `DMSetField()`
5052: @*/
5053: PetscErrorCode DMSetNumFields(DM dm, PetscInt numFields)
5054: {
5055:   PetscInt Nf, f;

5057:   PetscFunctionBegin;
5059:   PetscCall(DMGetNumFields(dm, &Nf));
5060:   for (f = Nf; f < numFields; ++f) {
5061:     PetscContainer obj;

5063:     PetscCall(PetscContainerCreate(PetscObjectComm((PetscObject)dm), &obj));
5064:     PetscCall(DMAddField(dm, NULL, (PetscObject)obj));
5065:     PetscCall(PetscContainerDestroy(&obj));
5066:   }
5067:   PetscFunctionReturn(PETSC_SUCCESS);
5068: }

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

5073:   Not Collective

5075:   Input Parameters:
5076: + dm - The `DM`
5077: - f  - The field number

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

5083:   Level: intermediate

5085: .seealso: [](ch_dmbase), `DM`, `DMAddField()`, `DMSetField()`
5086: @*/
5087: PetscErrorCode DMGetField(DM dm, PetscInt f, DMLabel *label, PetscObject *disc)
5088: {
5089:   PetscFunctionBegin;
5091:   PetscAssertPointer(disc, 4);
5092:   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);
5093:   if (!dm->fields) {
5094:     if (label) *label = NULL;
5095:     if (disc) *disc = NULL;
5096:   } else { // some DM such as DMDA do not have dm->fields
5097:     if (label) *label = dm->fields[f].label;
5098:     if (disc) *disc = dm->fields[f].disc;
5099:   }
5100:   PetscFunctionReturn(PETSC_SUCCESS);
5101: }

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

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

5121:   Logically Collective

5123:   Input Parameters:
5124: + dm    - The `DM`
5125: . f     - The field number
5126: . label - The label indicating the support of the field, or `NULL` for the entire mesh
5127: - disc  - The discretization object

5129:   Level: intermediate

5131: .seealso: [](ch_dmbase), `DM`, `DMAddField()`, `DMGetField()`
5132: @*/
5133: PetscErrorCode DMSetField(DM dm, PetscInt f, DMLabel label, PetscObject disc)
5134: {
5135:   PetscFunctionBegin;
5139:   PetscCheck(f >= 0, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Field number %" PetscInt_FMT " must be non-negative", f);
5140:   PetscCall(DMSetField_Internal(dm, f, label, disc));
5141:   PetscCall(DMSetDefaultAdjacency_Private(dm, f, disc));
5142:   PetscCall(DMClearDS(dm));
5143:   PetscFunctionReturn(PETSC_SUCCESS);
5144: }

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

5150:   Logically Collective

5152:   Input Parameters:
5153: + dm    - The `DM`
5154: . label - The label indicating the support of the field, or `NULL` for the entire mesh
5155: - disc  - The discretization object

5157:   Level: intermediate

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

5162:   For example, a piecewise continuous pressure field can be defined by coefficients at the cell centers of a mesh and piecewise constant functions
5163:   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
5164:   geometry entities, a `DMLabel` indicating a subset of those geometric entities, and a discretization object, such as a `PetscFE`.

5166:   Fortran Note:
5167:   Use the argument `PetscObjectCast(disc)` as the second argument

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

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

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

5192:   Logically Collective

5194:   Input Parameters:
5195: + dm          - The `DM`
5196: . f           - The field index
5197: - avoidTensor - `PETSC_TRUE` to skip defining the field on tensor cells

5199:   Level: intermediate

5201: .seealso: [](ch_dmbase), `DM`, `DMGetFieldAvoidTensor()`, `DMSetField()`, `DMGetField()`
5202: @*/
5203: PetscErrorCode DMSetFieldAvoidTensor(DM dm, PetscInt f, PetscBool avoidTensor)
5204: {
5205:   PetscFunctionBegin;
5206:   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);
5207:   dm->fields[f].avoidTensor = avoidTensor;
5208:   PetscFunctionReturn(PETSC_SUCCESS);
5209: }

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

5214:   Not Collective

5216:   Input Parameters:
5217: + dm - The `DM`
5218: - f  - The field index

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

5223:   Level: intermediate

5225: .seealso: [](ch_dmbase), `DM`, `DMAddField()`, `DMSetField()`, `DMGetField()`, `DMSetFieldAvoidTensor()`
5226: @*/
5227: PetscErrorCode DMGetFieldAvoidTensor(DM dm, PetscInt f, PetscBool *avoidTensor)
5228: {
5229:   PetscFunctionBegin;
5230:   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);
5231:   *avoidTensor = dm->fields[f].avoidTensor;
5232:   PetscFunctionReturn(PETSC_SUCCESS);
5233: }

5235: /*@
5236:   DMCopyFields - Copy the discretizations for the `DM` into another `DM`

5238:   Collective

5240:   Input Parameters:
5241: + dm        - The `DM`
5242: . minDegree - Minimum degree for a discretization, or `PETSC_DETERMINE` for no limit
5243: - maxDegree - Maximum degree for a discretization, or `PETSC_DETERMINE` for no limit

5245:   Output Parameter:
5246: . newdm - The `DM`

5248:   Level: advanced

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

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

5266:     PetscCall(DMGetField(dm, f, &label, &field));
5267:     PetscCall(PetscObjectGetClassId(field, &id));
5268:     if (id == PETSCFE_CLASSID) {
5269:       PetscFE newfe;

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

5288: /*@
5289:   DMGetAdjacency - Returns the flags for determining variable influence

5291:   Not Collective

5293:   Input Parameters:
5294: + dm - The `DM` object
5295: - f  - The field number, or `PETSC_DEFAULT` for the default adjacency

5297:   Output Parameters:
5298: + useCone    - Flag for variable influence starting with the cone operation
5299: - useClosure - Flag for variable influence using transitive closure

5301:   Level: developer

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

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

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

5333: /*@
5334:   DMSetAdjacency - Set the flags for determining variable influence

5336:   Not Collective

5338:   Input Parameters:
5339: + dm         - The `DM` object
5340: . f          - The field number
5341: . useCone    - Flag for variable influence starting with the cone operation
5342: - useClosure - Flag for variable influence using transitive closure

5344:   Level: developer

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

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

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

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

5377:   Not collective

5379:   Input Parameter:
5380: . dm - The `DM` object

5382:   Output Parameters:
5383: + useCone    - Flag for variable influence starting with the cone operation
5384: - useClosure - Flag for variable influence using transitive closure

5386:   Level: developer

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

5395: .seealso: [](ch_dmbase), `DM`, `DMSetBasicAdjacency()`, `DMGetField()`, `DMSetField()`
5396: @*/
5397: PetscErrorCode DMGetBasicAdjacency(DM dm, PetscBool *useCone, PetscBool *useClosure)
5398: {
5399:   PetscInt Nf;

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

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

5417:   Not Collective

5419:   Input Parameters:
5420: + dm         - The `DM` object
5421: . useCone    - Flag for variable influence starting with the cone operation
5422: - useClosure - Flag for variable influence using transitive closure

5424:   Level: developer

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

5433: .seealso: [](ch_dmbase), `DM`, `DMGetBasicAdjacency()`, `DMGetField()`, `DMSetField()`
5434: @*/
5435: PetscErrorCode DMSetBasicAdjacency(DM dm, PetscBool useCone, PetscBool useClosure)
5436: {
5437:   PetscInt Nf;

5439:   PetscFunctionBegin;
5441:   PetscCall(DMGetNumFields(dm, &Nf));
5442:   if (!Nf) {
5443:     PetscCall(DMSetAdjacency(dm, PETSC_DEFAULT, useCone, useClosure));
5444:   } else {
5445:     PetscCall(DMSetAdjacency(dm, 0, useCone, useClosure));
5446:   }
5447:   PetscFunctionReturn(PETSC_SUCCESS);
5448: }

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

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

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

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

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

5538: static PetscErrorCode DMDSEnlarge_Static(DM dm, PetscInt NdsNew)
5539: {
5540:   DMSpace *tmpd;
5541:   PetscInt Nds = dm->Nds, s;

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

5558: /*@
5559:   DMGetNumDS - Get the number of discrete systems in the `DM`

5561:   Not Collective

5563:   Input Parameter:
5564: . dm - The `DM`

5566:   Output Parameter:
5567: . Nds - The number of `PetscDS` objects

5569:   Level: intermediate

5571: .seealso: [](ch_dmbase), `DM`, `DMGetDS()`, `DMGetCellDS()`
5572: @*/
5573: PetscErrorCode DMGetNumDS(DM dm, PetscInt *Nds)
5574: {
5575:   PetscFunctionBegin;
5577:   PetscAssertPointer(Nds, 2);
5578:   *Nds = dm->Nds;
5579:   PetscFunctionReturn(PETSC_SUCCESS);
5580: }

5582: /*@
5583:   DMClearDS - Remove all discrete systems from the `DM`

5585:   Logically Collective

5587:   Input Parameter:
5588: . dm - The `DM`

5590:   Level: intermediate

5592: .seealso: [](ch_dmbase), `DM`, `DMGetNumDS()`, `DMGetDS()`, `DMSetField()`
5593: @*/
5594: PetscErrorCode DMClearDS(DM dm)
5595: {
5596:   PetscInt s;

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

5612: /*@
5613:   DMGetDS - Get the default `PetscDS`

5615:   Not Collective

5617:   Input Parameter:
5618: . dm - The `DM`

5620:   Output Parameter:
5621: . ds - The default `PetscDS`

5623:   Level: intermediate

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

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

5640: /*@
5641:   DMGetCellDS - Get the `PetscDS` defined on a given cell

5643:   Not Collective

5645:   Input Parameters:
5646: + dm    - The `DM`
5647: - point - Cell for the `PetscDS`

5649:   Output Parameters:
5650: + ds   - The `PetscDS` defined on the given cell
5651: - dsIn - The `PetscDS` for input on the given cell, or `NULL` if the same ds

5653:   Level: developer

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

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

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

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

5690:   Not Collective

5692:   Input Parameters:
5693: + dm    - The `DM`
5694: - label - The `DMLabel` defining the mesh region, or `NULL` for the entire mesh

5696:   Output Parameters:
5697: + fields - The `IS` containing the `DM` field numbers for the fields in this `PetscDS`, or `NULL`
5698: . ds     - The `PetscDS` defined on the given region, or `NULL`
5699: - dsIn   - The `PetscDS` for input in the given region, or `NULL`

5701:   Level: advanced

5703:   Note:
5704:   If a non-`NULL` label is given, but there is no `PetscDS` on that specific label,
5705:   the `PetscDS` for the full domain (if present) is returned. Returns with
5706:   fields = `NULL` and ds = `NULL` if there is no `PetscDS` for the full domain.

5708: .seealso: [](ch_dmbase), `DM`, `DMGetRegionNumDS()`, `DMSetRegionDS()`, `DMGetDS()`, `DMGetCellDS()`
5709: @*/
5710: PetscErrorCode DMGetRegionDS(DM dm, DMLabel label, IS *fields, PetscDS *ds, PetscDS *dsIn)
5711: {
5712:   PetscInt Nds = dm->Nds, s;

5714:   PetscFunctionBegin;
5717:   if (fields) {
5718:     PetscAssertPointer(fields, 3);
5719:     *fields = NULL;
5720:   }
5721:   if (ds) {
5722:     PetscAssertPointer(ds, 4);
5723:     *ds = NULL;
5724:   }
5725:   if (dsIn) {
5726:     PetscAssertPointer(dsIn, 5);
5727:     *dsIn = NULL;
5728:   }
5729:   for (s = 0; s < Nds; ++s) {
5730:     if (dm->probs[s].label == label || !dm->probs[s].label) {
5731:       if (fields) *fields = dm->probs[s].fields;
5732:       if (ds) *ds = dm->probs[s].ds;
5733:       if (dsIn) *dsIn = dm->probs[s].dsIn;
5734:       if (dm->probs[s].label) PetscFunctionReturn(PETSC_SUCCESS);
5735:     }
5736:   }
5737:   PetscFunctionReturn(PETSC_SUCCESS);
5738: }

5740: /*@
5741:   DMSetRegionDS - Set the `PetscDS` for a given mesh region, defined by a `DMLabel`

5743:   Collective

5745:   Input Parameters:
5746: + dm     - The `DM`
5747: . label  - The `DMLabel` defining the mesh region, or `NULL` for the entire mesh
5748: . fields - The `IS` containing the `DM` field numbers for the fields in this `PetscDS`, or `NULL` for all fields
5749: . ds     - The `PetscDS` defined on the given region
5750: - dsIn   - The `PetscDS` for input on the given cell, or `NULL` if it is the same `PetscDS`

5752:   Level: advanced

5754:   Note:
5755:   If the label has a `PetscDS` defined, it will be replaced. Otherwise, it will be added to the `DM`. If the `PetscDS` is replaced,
5756:   the fields argument is ignored.

5758: .seealso: [](ch_dmbase), `DM`, `DMGetRegionDS()`, `DMSetRegionNumDS()`, `DMGetDS()`, `DMGetCellDS()`
5759: @*/
5760: PetscErrorCode DMSetRegionDS(DM dm, DMLabel label, IS fields, PetscDS ds, PetscDS dsIn)
5761: {
5762:   PetscInt Nds = dm->Nds, s;

5764:   PetscFunctionBegin;
5770:   for (s = 0; s < Nds; ++s) {
5771:     if (dm->probs[s].label == label) {
5772:       PetscCall(PetscDSDestroy(&dm->probs[s].ds));
5773:       PetscCall(PetscDSDestroy(&dm->probs[s].dsIn));
5774:       dm->probs[s].ds   = ds;
5775:       dm->probs[s].dsIn = dsIn;
5776:       PetscFunctionReturn(PETSC_SUCCESS);
5777:     }
5778:   }
5779:   PetscCall(DMDSEnlarge_Static(dm, Nds + 1));
5780:   PetscCall(PetscObjectReference((PetscObject)label));
5781:   PetscCall(PetscObjectReference((PetscObject)fields));
5782:   PetscCall(PetscObjectReference((PetscObject)ds));
5783:   PetscCall(PetscObjectReference((PetscObject)dsIn));
5784:   if (!label) {
5785:     /* Put the NULL label at the front, so it is returned as the default */
5786:     for (s = Nds - 1; s >= 0; --s) dm->probs[s + 1] = dm->probs[s];
5787:     Nds = 0;
5788:   }
5789:   dm->probs[Nds].label  = label;
5790:   dm->probs[Nds].fields = fields;
5791:   dm->probs[Nds].ds     = ds;
5792:   dm->probs[Nds].dsIn   = dsIn;
5793:   PetscFunctionReturn(PETSC_SUCCESS);
5794: }

5796: /*@
5797:   DMGetRegionNumDS - Get the `PetscDS` for a given mesh region, defined by the region number

5799:   Not Collective

5801:   Input Parameters:
5802: + dm  - The `DM`
5803: - num - The region number, in [0, Nds)

5805:   Output Parameters:
5806: + label  - The region label, or `NULL`
5807: . fields - The `IS` containing the `DM` field numbers for the fields in this `PetscDS`, or `NULL`
5808: . ds     - The `PetscDS` defined on the given region, or `NULL`
5809: - dsIn   - The `PetscDS` for input in the given region, or `NULL`

5811:   Level: advanced

5813: .seealso: [](ch_dmbase), `DM`, `DMGetRegionDS()`, `DMSetRegionDS()`, `DMGetDS()`, `DMGetCellDS()`
5814: @*/
5815: PetscErrorCode DMGetRegionNumDS(DM dm, PetscInt num, DMLabel *label, IS *fields, PetscDS *ds, PetscDS *dsIn)
5816: {
5817:   PetscInt Nds;

5819:   PetscFunctionBegin;
5821:   PetscCall(DMGetNumDS(dm, &Nds));
5822:   PetscCheck((num >= 0) && (num < Nds), PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Region number %" PetscInt_FMT " is not in [0, %" PetscInt_FMT ")", num, Nds);
5823:   if (label) {
5824:     PetscAssertPointer(label, 3);
5825:     *label = dm->probs[num].label;
5826:   }
5827:   if (fields) {
5828:     PetscAssertPointer(fields, 4);
5829:     *fields = dm->probs[num].fields;
5830:   }
5831:   if (ds) {
5832:     PetscAssertPointer(ds, 5);
5833:     *ds = dm->probs[num].ds;
5834:   }
5835:   if (dsIn) {
5836:     PetscAssertPointer(dsIn, 6);
5837:     *dsIn = dm->probs[num].dsIn;
5838:   }
5839:   PetscFunctionReturn(PETSC_SUCCESS);
5840: }

5842: /*@
5843:   DMSetRegionNumDS - Set the `PetscDS` for a given mesh region, defined by the region number

5845:   Not Collective

5847:   Input Parameters:
5848: + dm     - The `DM`
5849: . num    - The region number, in [0, Nds)
5850: . label  - The region label, or `NULL`
5851: . fields - The `IS` containing the `DM` field numbers for the fields in this `PetscDS`, or `NULL` to prevent setting
5852: . ds     - The `PetscDS` defined on the given region, or `NULL` to prevent setting
5853: - dsIn   - The `PetscDS` for input on the given cell, or `NULL` if it is the same `PetscDS`

5855:   Level: advanced

5857: .seealso: [](ch_dmbase), `DM`, `DMGetRegionDS()`, `DMSetRegionDS()`, `DMGetDS()`, `DMGetCellDS()`
5858: @*/
5859: PetscErrorCode DMSetRegionNumDS(DM dm, PetscInt num, DMLabel label, IS fields, PetscDS ds, PetscDS dsIn)
5860: {
5861:   PetscInt Nds;

5863:   PetscFunctionBegin;
5866:   PetscCall(DMGetNumDS(dm, &Nds));
5867:   PetscCheck((num >= 0) && (num < Nds), PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Region number %" PetscInt_FMT " is not in [0, %" PetscInt_FMT ")", num, Nds);
5868:   PetscCall(PetscObjectReference((PetscObject)label));
5869:   PetscCall(DMLabelDestroy(&dm->probs[num].label));
5870:   dm->probs[num].label = label;
5871:   if (fields) {
5873:     PetscCall(PetscObjectReference((PetscObject)fields));
5874:     PetscCall(ISDestroy(&dm->probs[num].fields));
5875:     dm->probs[num].fields = fields;
5876:   }
5877:   if (ds) {
5879:     PetscCall(PetscObjectReference((PetscObject)ds));
5880:     PetscCall(PetscDSDestroy(&dm->probs[num].ds));
5881:     dm->probs[num].ds = ds;
5882:   }
5883:   if (dsIn) {
5885:     PetscCall(PetscObjectReference((PetscObject)dsIn));
5886:     PetscCall(PetscDSDestroy(&dm->probs[num].dsIn));
5887:     dm->probs[num].dsIn = dsIn;
5888:   }
5889:   PetscFunctionReturn(PETSC_SUCCESS);
5890: }

5892: /*@
5893:   DMFindRegionNum - Find the region number for a given `PetscDS`, or -1 if it is not found.

5895:   Not Collective

5897:   Input Parameters:
5898: + dm - The `DM`
5899: - ds - The `PetscDS` defined on the given region

5901:   Output Parameter:
5902: . num - The region number, in [0, Nds), or -1 if not found

5904:   Level: advanced

5906: .seealso: [](ch_dmbase), `DM`, `DMGetRegionNumDS()`, `DMGetRegionDS()`, `DMSetRegionDS()`, `DMGetDS()`, `DMGetCellDS()`
5907: @*/
5908: PetscErrorCode DMFindRegionNum(DM dm, PetscDS ds, PetscInt *num)
5909: {
5910:   PetscInt Nds, n;

5912:   PetscFunctionBegin;
5915:   PetscAssertPointer(num, 3);
5916:   PetscCall(DMGetNumDS(dm, &Nds));
5917:   for (n = 0; n < Nds; ++n)
5918:     if (ds == dm->probs[n].ds) break;
5919:   if (n >= Nds) *num = -1;
5920:   else *num = n;
5921:   PetscFunctionReturn(PETSC_SUCCESS);
5922: }

5924: /*@
5925:   DMCreateFEDefault - Create a `PetscFE` based on the celltype for the mesh

5927:   Not Collective

5929:   Input Parameters:
5930: + dm     - The `DM`
5931: . Nc     - The number of components for the field
5932: . prefix - The options prefix for the output `PetscFE`, or `NULL`
5933: - qorder - The quadrature order or `PETSC_DETERMINE` to use `PetscSpace` polynomial degree

5935:   Output Parameter:
5936: . fem - The `PetscFE`

5938:   Level: intermediate

5940:   Note:
5941:   This is a convenience method that just calls `PetscFECreateByCell()` underneath.

5943: .seealso: [](ch_dmbase), `DM`, `PetscFECreateByCell()`, `DMAddField()`, `DMCreateDS()`, `DMGetCellDS()`, `DMGetRegionDS()`
5944: @*/
5945: PetscErrorCode DMCreateFEDefault(DM dm, PetscInt Nc, const char prefix[], PetscInt qorder, PetscFE *fem)
5946: {
5947:   DMPolytopeType ct;
5948:   PetscInt       dim, cStart;

5950:   PetscFunctionBegin;
5953:   if (prefix) PetscAssertPointer(prefix, 3);
5955:   PetscAssertPointer(fem, 5);
5956:   PetscCall(DMGetDimension(dm, &dim));
5957:   PetscCall(DMPlexGetHeightStratum(dm, 0, &cStart, NULL));
5958:   PetscCall(DMPlexGetCellType(dm, cStart, &ct));
5959:   PetscCall(PetscFECreateByCell(PETSC_COMM_SELF, dim, Nc, ct, prefix, qorder, fem));
5960:   PetscFunctionReturn(PETSC_SUCCESS);
5961: }

5963: /*@
5964:   DMCreateDS - Create the discrete systems for the `DM` based upon the fields added to the `DM`

5966:   Collective

5968:   Input Parameter:
5969: . dm - The `DM`

5971:   Options Database Key:
5972: . -dm_petscds_view - View all the `PetscDS` objects in this `DM`

5974:   Level: intermediate

5976:   Developer Note:
5977:   The name of this function is wrong. Create functions always return the created object as one of the arguments.

5979: .seealso: [](ch_dmbase), `DM`, `DMSetField`, `DMAddField()`, `DMGetDS()`, `DMGetCellDS()`, `DMGetRegionDS()`, `DMSetRegionDS()`
5980: @*/
5981: PetscErrorCode DMCreateDS(DM dm)
5982: {
5983:   MPI_Comm  comm;
5984:   PetscDS   dsDef;
5985:   DMLabel  *labelSet;
5986:   PetscInt  dE, Nf = dm->Nf, f, s, Nl, l, Ndef, k;
5987:   PetscBool doSetup = PETSC_TRUE, flg;

5989:   PetscFunctionBegin;
5991:   if (!dm->fields) PetscFunctionReturn(PETSC_SUCCESS);
5992:   PetscCall(PetscObjectGetComm((PetscObject)dm, &comm));
5993:   PetscCall(DMGetCoordinateDim(dm, &dE));
5994:   // Create nullspace constructor slots
5995:   PetscCall(PetscFree2(dm->nullspaceConstructors, dm->nearnullspaceConstructors));
5996:   PetscCall(PetscCalloc2(Nf, &dm->nullspaceConstructors, Nf, &dm->nearnullspaceConstructors));
5997:   /* Determine how many regions we have */
5998:   PetscCall(PetscMalloc1(Nf, &labelSet));
5999:   Nl   = 0;
6000:   Ndef = 0;
6001:   for (f = 0; f < Nf; ++f) {
6002:     DMLabel  label = dm->fields[f].label;
6003:     PetscInt l;

6005: #ifdef PETSC_HAVE_LIBCEED
6006:     /* Move CEED context to discretizations */
6007:     {
6008:       PetscClassId id;

6010:       PetscCall(PetscObjectGetClassId(dm->fields[f].disc, &id));
6011:       if (id == PETSCFE_CLASSID) {
6012:         Ceed ceed;

6014:         PetscCall(DMGetCeed(dm, &ceed));
6015:         PetscCall(PetscFESetCeed((PetscFE)dm->fields[f].disc, ceed));
6016:       }
6017:     }
6018: #endif
6019:     if (!label) {
6020:       ++Ndef;
6021:       continue;
6022:     }
6023:     for (l = 0; l < Nl; ++l)
6024:       if (label == labelSet[l]) break;
6025:     if (l < Nl) continue;
6026:     labelSet[Nl++] = label;
6027:   }
6028:   /* Create default DS if there are no labels to intersect with */
6029:   PetscCall(DMGetRegionDS(dm, NULL, NULL, &dsDef, NULL));
6030:   if (!dsDef && Ndef && !Nl) {
6031:     IS        fields;
6032:     PetscInt *fld, nf;

6034:     for (f = 0, nf = 0; f < Nf; ++f)
6035:       if (!dm->fields[f].label) ++nf;
6036:     PetscCheck(nf, comm, PETSC_ERR_PLIB, "All fields have labels, but we are trying to create a default DS");
6037:     PetscCall(PetscMalloc1(nf, &fld));
6038:     for (f = 0, nf = 0; f < Nf; ++f)
6039:       if (!dm->fields[f].label) fld[nf++] = f;
6040:     PetscCall(ISCreate(PETSC_COMM_SELF, &fields));
6041:     PetscCall(PetscObjectSetOptionsPrefix((PetscObject)fields, "dm_fields_"));
6042:     PetscCall(ISSetType(fields, ISGENERAL));
6043:     PetscCall(ISGeneralSetIndices(fields, nf, fld, PETSC_OWN_POINTER));

6045:     PetscCall(PetscDSCreate(PETSC_COMM_SELF, &dsDef));
6046:     PetscCall(DMSetRegionDS(dm, NULL, fields, dsDef, NULL));
6047:     PetscCall(PetscDSDestroy(&dsDef));
6048:     PetscCall(ISDestroy(&fields));
6049:   }
6050:   PetscCall(DMGetRegionDS(dm, NULL, NULL, &dsDef, NULL));
6051:   if (dsDef) PetscCall(PetscDSSetCoordinateDimension(dsDef, dE));
6052:   /* Intersect labels with default fields */
6053:   if (Ndef && Nl) {
6054:     DM              plex;
6055:     DMLabel         cellLabel;
6056:     IS              fieldIS, allcellIS, defcellIS = NULL;
6057:     PetscInt       *fields;
6058:     const PetscInt *cells;
6059:     PetscInt        depth, nf = 0, n, c;

6061:     PetscCall(DMConvert(dm, DMPLEX, &plex));
6062:     PetscCall(DMPlexGetDepth(plex, &depth));
6063:     PetscCall(DMGetStratumIS(plex, "dim", depth, &allcellIS));
6064:     if (!allcellIS) PetscCall(DMGetStratumIS(plex, "depth", depth, &allcellIS));
6065:     /* TODO This looks like it only works for one label */
6066:     for (l = 0; l < Nl; ++l) {
6067:       DMLabel label = labelSet[l];
6068:       IS      pointIS;

6070:       PetscCall(ISDestroy(&defcellIS));
6071:       PetscCall(DMLabelGetStratumIS(label, 1, &pointIS));
6072:       PetscCall(ISDifference(allcellIS, pointIS, &defcellIS));
6073:       PetscCall(ISDestroy(&pointIS));
6074:     }
6075:     PetscCall(ISDestroy(&allcellIS));

6077:     PetscCall(DMLabelCreate(PETSC_COMM_SELF, "defaultCells", &cellLabel));
6078:     PetscCall(ISGetLocalSize(defcellIS, &n));
6079:     PetscCall(ISGetIndices(defcellIS, &cells));
6080:     for (c = 0; c < n; ++c) PetscCall(DMLabelSetValue(cellLabel, cells[c], 1));
6081:     PetscCall(ISRestoreIndices(defcellIS, &cells));
6082:     PetscCall(ISDestroy(&defcellIS));
6083:     PetscCall(DMPlexLabelComplete(plex, cellLabel));

6085:     PetscCall(PetscMalloc1(Ndef, &fields));
6086:     for (f = 0; f < Nf; ++f)
6087:       if (!dm->fields[f].label) fields[nf++] = f;
6088:     PetscCall(ISCreate(PETSC_COMM_SELF, &fieldIS));
6089:     PetscCall(PetscObjectSetOptionsPrefix((PetscObject)fieldIS, "dm_fields_"));
6090:     PetscCall(ISSetType(fieldIS, ISGENERAL));
6091:     PetscCall(ISGeneralSetIndices(fieldIS, nf, fields, PETSC_OWN_POINTER));

6093:     PetscCall(PetscDSCreate(PETSC_COMM_SELF, &dsDef));
6094:     PetscCall(DMSetRegionDS(dm, cellLabel, fieldIS, dsDef, NULL));
6095:     PetscCall(PetscDSSetCoordinateDimension(dsDef, dE));
6096:     PetscCall(DMLabelDestroy(&cellLabel));
6097:     PetscCall(PetscDSDestroy(&dsDef));
6098:     PetscCall(ISDestroy(&fieldIS));
6099:     PetscCall(DMDestroy(&plex));
6100:   }
6101:   /* Create label DSes
6102:      - WE ONLY SUPPORT IDENTICAL OR DISJOINT LABELS
6103:   */
6104:   /* TODO Should check that labels are disjoint */
6105:   for (l = 0; l < Nl; ++l) {
6106:     DMLabel   label = labelSet[l];
6107:     PetscDS   ds, dsIn = NULL;
6108:     IS        fields;
6109:     PetscInt *fld, nf;

6111:     PetscCall(PetscDSCreate(PETSC_COMM_SELF, &ds));
6112:     for (f = 0, nf = 0; f < Nf; ++f)
6113:       if (label == dm->fields[f].label || !dm->fields[f].label) ++nf;
6114:     PetscCall(PetscMalloc1(nf, &fld));
6115:     for (f = 0, nf = 0; f < Nf; ++f)
6116:       if (label == dm->fields[f].label || !dm->fields[f].label) fld[nf++] = f;
6117:     PetscCall(ISCreate(PETSC_COMM_SELF, &fields));
6118:     PetscCall(PetscObjectSetOptionsPrefix((PetscObject)fields, "dm_fields_"));
6119:     PetscCall(ISSetType(fields, ISGENERAL));
6120:     PetscCall(ISGeneralSetIndices(fields, nf, fld, PETSC_OWN_POINTER));
6121:     PetscCall(PetscDSSetCoordinateDimension(ds, dE));
6122:     {
6123:       DMPolytopeType ct;
6124:       PetscInt       lStart, lEnd;
6125:       PetscBool      isCohesiveLocal = PETSC_FALSE, isCohesive;

6127:       PetscCall(DMLabelGetBounds(label, &lStart, &lEnd));
6128:       if (lStart >= 0) {
6129:         PetscCall(DMPlexGetCellType(dm, lStart, &ct));
6130:         switch (ct) {
6131:         case DM_POLYTOPE_POINT_PRISM_TENSOR:
6132:         case DM_POLYTOPE_SEG_PRISM_TENSOR:
6133:         case DM_POLYTOPE_TRI_PRISM_TENSOR:
6134:         case DM_POLYTOPE_QUAD_PRISM_TENSOR:
6135:           isCohesiveLocal = PETSC_TRUE;
6136:           break;
6137:         default:
6138:           break;
6139:         }
6140:       }
6141:       PetscCallMPI(MPIU_Allreduce(&isCohesiveLocal, &isCohesive, 1, MPI_C_BOOL, MPI_LOR, comm));
6142:       if (isCohesive) {
6143:         PetscCall(PetscDSCreate(PETSC_COMM_SELF, &dsIn));
6144:         PetscCall(PetscDSSetCoordinateDimension(dsIn, dE));
6145:       }
6146:       for (f = 0, nf = 0; f < Nf; ++f) {
6147:         if (label == dm->fields[f].label || !dm->fields[f].label) {
6148:           if (label == dm->fields[f].label) {
6149:             PetscCall(PetscDSSetDiscretization(ds, nf, NULL));
6150:             PetscCall(PetscDSSetCohesive(ds, nf, isCohesive));
6151:             if (dsIn) {
6152:               PetscCall(PetscDSSetDiscretization(dsIn, nf, NULL));
6153:               PetscCall(PetscDSSetCohesive(dsIn, nf, isCohesive));
6154:             }
6155:           }
6156:           ++nf;
6157:         }
6158:       }
6159:     }
6160:     PetscCall(DMSetRegionDS(dm, label, fields, ds, dsIn));
6161:     PetscCall(ISDestroy(&fields));
6162:     PetscCall(PetscDSDestroy(&ds));
6163:     PetscCall(PetscDSDestroy(&dsIn));
6164:   }
6165:   PetscCall(PetscFree(labelSet));
6166:   /* Set fields in DSes */
6167:   for (s = 0; s < dm->Nds; ++s) {
6168:     PetscDS         ds     = dm->probs[s].ds;
6169:     PetscDS         dsIn   = dm->probs[s].dsIn;
6170:     IS              fields = dm->probs[s].fields;
6171:     const PetscInt *fld;
6172:     PetscInt        nf, dsnf;
6173:     PetscBool       isCohesive;

6175:     PetscCall(PetscDSGetNumFields(ds, &dsnf));
6176:     PetscCall(PetscDSIsCohesive(ds, &isCohesive));
6177:     PetscCall(ISGetLocalSize(fields, &nf));
6178:     PetscCall(ISGetIndices(fields, &fld));
6179:     for (f = 0; f < nf; ++f) {
6180:       PetscObject  disc = dm->fields[fld[f]].disc;
6181:       PetscBool    isCohesiveField;
6182:       PetscClassId id;

6184:       /* Handle DS with no fields */
6185:       if (dsnf) PetscCall(PetscDSGetCohesive(ds, f, &isCohesiveField));
6186:       /* If this is a cohesive cell, then regular fields need the lower dimensional discretization */
6187:       if (isCohesive) {
6188:         if (!isCohesiveField) {
6189:           PetscObject bdDisc;

6191:           PetscCall(PetscFEGetHeightSubspace((PetscFE)disc, 1, (PetscFE *)&bdDisc));
6192:           PetscCall(PetscDSSetDiscretization(ds, f, bdDisc));
6193:           PetscCall(PetscDSSetDiscretization(dsIn, f, disc));
6194:         } else {
6195:           PetscCall(PetscDSSetDiscretization(ds, f, disc));
6196:           PetscCall(PetscDSSetDiscretization(dsIn, f, disc));
6197:         }
6198:       } else {
6199:         PetscCall(PetscDSSetDiscretization(ds, f, disc));
6200:       }
6201:       /* We allow people to have placeholder fields and construct the Section by hand */
6202:       PetscCall(PetscObjectGetClassId(disc, &id));
6203:       if ((id != PETSCFE_CLASSID) && (id != PETSCFV_CLASSID)) doSetup = PETSC_FALSE;
6204:     }
6205:     PetscCall(ISRestoreIndices(fields, &fld));
6206:   }
6207:   /* Allow k-jet tabulation */
6208:   PetscCall(PetscOptionsGetInt(NULL, ((PetscObject)dm)->prefix, "-dm_ds_jet_degree", &k, &flg));
6209:   if (flg) {
6210:     for (s = 0; s < dm->Nds; ++s) {
6211:       PetscDS  ds   = dm->probs[s].ds;
6212:       PetscDS  dsIn = dm->probs[s].dsIn;
6213:       PetscInt Nf, f;

6215:       PetscCall(PetscDSGetNumFields(ds, &Nf));
6216:       for (f = 0; f < Nf; ++f) {
6217:         PetscCall(PetscDSSetJetDegree(ds, f, k));
6218:         if (dsIn) PetscCall(PetscDSSetJetDegree(dsIn, f, k));
6219:       }
6220:     }
6221:   }
6222:   /* Setup DSes */
6223:   if (doSetup) {
6224:     for (s = 0; s < dm->Nds; ++s) {
6225:       if (dm->setfromoptionscalled) {
6226:         PetscCall(PetscDSSetFromOptions(dm->probs[s].ds));
6227:         if (dm->probs[s].dsIn) PetscCall(PetscDSSetFromOptions(dm->probs[s].dsIn));
6228:       }
6229:       PetscCall(PetscDSSetUp(dm->probs[s].ds));
6230:       if (dm->probs[s].dsIn) PetscCall(PetscDSSetUp(dm->probs[s].dsIn));
6231:     }
6232:   }
6233:   PetscFunctionReturn(PETSC_SUCCESS);
6234: }

6236: /*@
6237:   DMUseTensorOrder - Use a tensor product closure ordering for the default section

6239:   Input Parameters:
6240: + dm     - The DM
6241: - tensor - Flag for tensor order

6243:   Level: developer

6245: .seealso: `DMPlexSetClosurePermutationTensor()`, `PetscSectionResetClosurePermutation()`
6246: @*/
6247: PetscErrorCode DMUseTensorOrder(DM dm, PetscBool tensor)
6248: {
6249:   PetscInt  Nf;
6250:   PetscBool reorder = PETSC_TRUE, isPlex;

6252:   PetscFunctionBegin;
6253:   PetscCall(PetscObjectTypeCompare((PetscObject)dm, DMPLEX, &isPlex));
6254:   PetscCall(DMGetNumFields(dm, &Nf));
6255:   for (PetscInt f = 0; f < Nf; ++f) {
6256:     PetscObject  obj;
6257:     PetscClassId id;

6259:     PetscCall(DMGetField(dm, f, NULL, &obj));
6260:     PetscCall(PetscObjectGetClassId(obj, &id));
6261:     if (id == PETSCFE_CLASSID) {
6262:       PetscSpace sp;
6263:       PetscBool  tensor;

6265:       PetscCall(PetscFEGetBasisSpace((PetscFE)obj, &sp));
6266:       PetscCall(PetscSpacePolynomialGetTensor(sp, &tensor));
6267:       reorder = reorder && tensor ? PETSC_TRUE : PETSC_FALSE;
6268:     } else reorder = PETSC_FALSE;
6269:   }
6270:   if (tensor) {
6271:     if (reorder && isPlex) PetscCall(DMPlexSetClosurePermutationTensor(dm, PETSC_DETERMINE, NULL));
6272:   } else {
6273:     PetscSection s;

6275:     PetscCall(DMGetLocalSection(dm, &s));
6276:     if (s) PetscCall(PetscSectionResetClosurePermutation(s));
6277:   }
6278:   PetscFunctionReturn(PETSC_SUCCESS);
6279: }

6281: /*@
6282:   DMComputeExactSolution - Compute the exact solution for a given `DM`, using the `PetscDS` information.

6284:   Collective

6286:   Input Parameters:
6287: + dm   - The `DM`
6288: - time - The time

6290:   Output Parameters:
6291: + u   - The vector will be filled with exact solution values, or `NULL`
6292: - u_t - The vector will be filled with the time derivative of exact solution values, or `NULL`

6294:   Level: developer

6296:   Note:
6297:   The user must call `PetscDSSetExactSolution()` before using this routine

6299: .seealso: [](ch_dmbase), `DM`, `PetscDSSetExactSolution()`
6300: @*/
6301: PetscErrorCode DMComputeExactSolution(DM dm, PetscReal time, Vec u, Vec u_t)
6302: {
6303:   PetscErrorCode (**exacts)(PetscInt, PetscReal, const PetscReal x[], PetscInt, PetscScalar *u, PetscCtx ctx);
6304:   void   **ectxs;
6305:   Vec      locu, locu_t;
6306:   PetscInt Nf, Nds, s;

6308:   PetscFunctionBegin;
6310:   if (u) {
6312:     PetscCall(DMGetLocalVector(dm, &locu));
6313:     PetscCall(VecSet(locu, 0.));
6314:   }
6315:   if (u_t) {
6317:     PetscCall(DMGetLocalVector(dm, &locu_t));
6318:     PetscCall(VecSet(locu_t, 0.));
6319:   }
6320:   PetscCall(DMGetNumFields(dm, &Nf));
6321:   PetscCall(PetscMalloc2(Nf, &exacts, Nf, &ectxs));
6322:   PetscCall(DMGetNumDS(dm, &Nds));
6323:   for (s = 0; s < Nds; ++s) {
6324:     PetscDS         ds;
6325:     DMLabel         label;
6326:     IS              fieldIS;
6327:     const PetscInt *fields, id = 1;
6328:     PetscInt        dsNf, f;

6330:     PetscCall(DMGetRegionNumDS(dm, s, &label, &fieldIS, &ds, NULL));
6331:     PetscCall(PetscDSGetNumFields(ds, &dsNf));
6332:     PetscCall(ISGetIndices(fieldIS, &fields));
6333:     PetscCall(PetscArrayzero(exacts, Nf));
6334:     PetscCall(PetscArrayzero(ectxs, Nf));
6335:     if (u) {
6336:       for (f = 0; f < dsNf; ++f) PetscCall(PetscDSGetExactSolution(ds, fields[f], &exacts[fields[f]], &ectxs[fields[f]]));
6337:       if (label) PetscCall(DMProjectFunctionLabelLocal(dm, time, label, 1, &id, 0, NULL, exacts, ectxs, INSERT_ALL_VALUES, locu));
6338:       else PetscCall(DMProjectFunctionLocal(dm, time, exacts, ectxs, INSERT_ALL_VALUES, locu));
6339:     }
6340:     if (u_t) {
6341:       PetscCall(PetscArrayzero(exacts, Nf));
6342:       PetscCall(PetscArrayzero(ectxs, Nf));
6343:       for (f = 0; f < dsNf; ++f) PetscCall(PetscDSGetExactSolutionTimeDerivative(ds, fields[f], &exacts[fields[f]], &ectxs[fields[f]]));
6344:       if (label) PetscCall(DMProjectFunctionLabelLocal(dm, time, label, 1, &id, 0, NULL, exacts, ectxs, INSERT_ALL_VALUES, locu_t));
6345:       else PetscCall(DMProjectFunctionLocal(dm, time, exacts, ectxs, INSERT_ALL_VALUES, locu_t));
6346:     }
6347:     PetscCall(ISRestoreIndices(fieldIS, &fields));
6348:   }
6349:   if (u) {
6350:     PetscCall(PetscObjectSetName((PetscObject)u, "Exact Solution"));
6351:     PetscCall(PetscObjectSetOptionsPrefix((PetscObject)u, "exact_"));
6352:   }
6353:   if (u_t) {
6354:     PetscCall(PetscObjectSetName((PetscObject)u, "Exact Solution Time Derivative"));
6355:     PetscCall(PetscObjectSetOptionsPrefix((PetscObject)u_t, "exact_t_"));
6356:   }
6357:   PetscCall(PetscFree2(exacts, ectxs));
6358:   if (u) {
6359:     PetscCall(DMLocalToGlobalBegin(dm, locu, INSERT_ALL_VALUES, u));
6360:     PetscCall(DMLocalToGlobalEnd(dm, locu, INSERT_ALL_VALUES, u));
6361:     PetscCall(DMRestoreLocalVector(dm, &locu));
6362:   }
6363:   if (u_t) {
6364:     PetscCall(DMLocalToGlobalBegin(dm, locu_t, INSERT_ALL_VALUES, u_t));
6365:     PetscCall(DMLocalToGlobalEnd(dm, locu_t, INSERT_ALL_VALUES, u_t));
6366:     PetscCall(DMRestoreLocalVector(dm, &locu_t));
6367:   }
6368:   PetscFunctionReturn(PETSC_SUCCESS);
6369: }

6371: static PetscErrorCode DMTransferDS_Internal(DM dm, DMLabel label, IS fields, PetscInt minDegree, PetscInt maxDegree, PetscDS ds, PetscDS dsIn)
6372: {
6373:   PetscDS dsNew, dsInNew = NULL;

6375:   PetscFunctionBegin;
6376:   PetscCall(PetscDSCreate(PetscObjectComm((PetscObject)ds), &dsNew));
6377:   PetscCall(PetscDSCopy(ds, minDegree, maxDegree, dm, dsNew));
6378:   if (dsIn) {
6379:     PetscCall(PetscDSCreate(PetscObjectComm((PetscObject)dsIn), &dsInNew));
6380:     PetscCall(PetscDSCopy(dsIn, minDegree, maxDegree, dm, dsInNew));
6381:   }
6382:   PetscCall(DMSetRegionDS(dm, label, fields, dsNew, dsInNew));
6383:   PetscCall(PetscDSDestroy(&dsNew));
6384:   PetscCall(PetscDSDestroy(&dsInNew));
6385:   PetscFunctionReturn(PETSC_SUCCESS);
6386: }

6388: /*@
6389:   DMCopyDS - Copy the discrete systems for the `DM` into another `DM`

6391:   Collective

6393:   Input Parameters:
6394: + dm        - The `DM`
6395: . minDegree - Minimum degree for a discretization, or `PETSC_DETERMINE` for no limit
6396: - maxDegree - Maximum degree for a discretization, or `PETSC_DETERMINE` for no limit

6398:   Output Parameter:
6399: . newdm - The `DM`

6401:   Level: advanced

6403: .seealso: [](ch_dmbase), `DM`, `DMCopyFields()`, `DMAddField()`, `DMGetDS()`, `DMGetCellDS()`, `DMGetRegionDS()`, `DMSetRegionDS()`
6404: @*/
6405: PetscErrorCode DMCopyDS(DM dm, PetscInt minDegree, PetscInt maxDegree, DM newdm)
6406: {
6407:   PetscInt Nds, s;

6409:   PetscFunctionBegin;
6410:   if (dm == newdm) PetscFunctionReturn(PETSC_SUCCESS);
6411:   PetscCall(DMGetNumDS(dm, &Nds));
6412:   PetscCall(DMClearDS(newdm));
6413:   for (s = 0; s < Nds; ++s) {
6414:     DMLabel  label;
6415:     IS       fields;
6416:     PetscDS  ds, dsIn, newds;
6417:     PetscInt Nbd, bd;

6419:     PetscCall(DMGetRegionNumDS(dm, s, &label, &fields, &ds, &dsIn));
6420:     /* TODO: We need to change all keys from labels in the old DM to labels in the new DM */
6421:     PetscCall(DMTransferDS_Internal(newdm, label, fields, minDegree, maxDegree, ds, dsIn));
6422:     /* Complete new labels in the new DS */
6423:     PetscCall(DMGetRegionDS(newdm, label, NULL, &newds, NULL));
6424:     PetscCall(PetscDSGetNumBoundary(newds, &Nbd));
6425:     for (bd = 0; bd < Nbd; ++bd) {
6426:       PetscWeakForm wf;
6427:       DMLabel       label;
6428:       PetscInt      field;

6430:       PetscCall(PetscDSGetBoundary(newds, bd, &wf, NULL, NULL, &label, NULL, NULL, &field, NULL, NULL, NULL, NULL, NULL));
6431:       PetscCall(PetscWeakFormReplaceLabel(wf, label));
6432:     }
6433:   }
6434:   PetscCall(DMCompleteBCLabels_Internal(newdm));
6435:   PetscFunctionReturn(PETSC_SUCCESS);
6436: }

6438: /*@
6439:   DMCopyDisc - Copy the fields and discrete systems for the `DM` into another `DM`

6441:   Collective

6443:   Input Parameter:
6444: . dm - The `DM`

6446:   Output Parameter:
6447: . newdm - The `DM`

6449:   Level: advanced

6451:   Developer Note:
6452:   Really ugly name, nothing in PETSc is called a `Disc` plus it is an ugly abbreviation

6454: .seealso: [](ch_dmbase), `DM`, `DMCopyFields()`, `DMCopyDS()`
6455: @*/
6456: PetscErrorCode DMCopyDisc(DM dm, DM newdm)
6457: {
6458:   PetscFunctionBegin;
6459:   PetscCall(DMCopyFields(dm, PETSC_DETERMINE, PETSC_DETERMINE, newdm));
6460:   PetscCall(DMCopyDS(dm, PETSC_DETERMINE, PETSC_DETERMINE, newdm));
6461:   PetscFunctionReturn(PETSC_SUCCESS);
6462: }

6464: /*@
6465:   DMGetDimension - Return the topological dimension of the `DM`

6467:   Not Collective

6469:   Input Parameter:
6470: . dm - The `DM`

6472:   Output Parameter:
6473: . dim - The topological dimension

6475:   Level: beginner

6477: .seealso: [](ch_dmbase), `DM`, `DMSetDimension()`, `DMCreate()`
6478: @*/
6479: PetscErrorCode DMGetDimension(DM dm, PetscInt *dim)
6480: {
6481:   PetscFunctionBegin;
6483:   PetscAssertPointer(dim, 2);
6484:   *dim = dm->dim;
6485:   PetscFunctionReturn(PETSC_SUCCESS);
6486: }

6488: /*@
6489:   DMSetDimension - Set the topological dimension of the `DM`

6491:   Collective

6493:   Input Parameters:
6494: + dm  - The `DM`
6495: - dim - The topological dimension

6497:   Level: beginner

6499: .seealso: [](ch_dmbase), `DM`, `DMGetDimension()`, `DMCreate()`
6500: @*/
6501: PetscErrorCode DMSetDimension(DM dm, PetscInt dim)
6502: {
6503:   PetscDS  ds;
6504:   PetscInt Nds, n;

6506:   PetscFunctionBegin;
6509:   if (dm->dim != dim) PetscCall(DMSetPeriodicity(dm, NULL, NULL, NULL));
6510:   dm->dim = dim;
6511:   if (dm->dim >= 0) {
6512:     PetscCall(DMGetNumDS(dm, &Nds));
6513:     for (n = 0; n < Nds; ++n) {
6514:       PetscCall(DMGetRegionNumDS(dm, n, NULL, NULL, &ds, NULL));
6515:       if (ds->dimEmbed < 0) PetscCall(PetscDSSetCoordinateDimension(ds, dim));
6516:     }
6517:   }
6518:   PetscFunctionReturn(PETSC_SUCCESS);
6519: }

6521: /*@
6522:   DMGetDimPoints - Get the half-open interval for all points of a given dimension

6524:   Collective

6526:   Input Parameters:
6527: + dm  - the `DM`
6528: - dim - the dimension

6530:   Output Parameters:
6531: + pStart - The first point of the given dimension
6532: - pEnd   - The first point following points of the given dimension

6534:   Level: intermediate

6536:   Note:
6537:   The points are vertices in the Hasse diagram encoding the topology. This is explained in
6538:   https://arxiv.org/abs/0908.4427. If no points exist of this dimension in the storage scheme,
6539:   then the interval is empty.

6541: .seealso: [](ch_dmbase), `DM`, `DMPLEX`, `DMPlexGetDepthStratum()`, `DMPlexGetHeightStratum()`
6542: @*/
6543: PetscErrorCode DMGetDimPoints(DM dm, PetscInt dim, PetscInt *pStart, PetscInt *pEnd)
6544: {
6545:   PetscInt d;

6547:   PetscFunctionBegin;
6549:   PetscCall(DMGetDimension(dm, &d));
6550:   PetscCheck((dim >= 0) && (dim <= d), PetscObjectComm((PetscObject)dm), PETSC_ERR_ARG_OUTOFRANGE, "Invalid dimension %" PetscInt_FMT, dim);
6551:   PetscUseTypeMethod(dm, getdimpoints, dim, pStart, pEnd);
6552:   PetscFunctionReturn(PETSC_SUCCESS);
6553: }

6555: /*@
6556:   DMGetOutputDM - Retrieve the `DM` associated with the layout for output

6558:   Collective

6560:   Input Parameter:
6561: . dm - The original `DM`

6563:   Output Parameter:
6564: . odm - The `DM` which provides the layout for output

6566:   Level: intermediate

6568:   Note:
6569:   In some situations the vector obtained with `DMCreateGlobalVector()` excludes points for degrees of freedom that are associated with fixed (Dirichelet) boundary
6570:   conditions since the algebraic solver does not solve for those variables. The output `DM` includes these excluded points and its global vector contains the
6571:   locations for those dof so that they can be output to a file or other viewer along with the unconstrained dof.

6573: .seealso: [](ch_dmbase), `DM`, `VecView()`, `DMGetGlobalSection()`, `DMCreateGlobalVector()`, `PetscSectionHasConstraints()`, `DMSetGlobalSection()`
6574: @*/
6575: PetscErrorCode DMGetOutputDM(DM dm, DM *odm)
6576: {
6577:   PetscSection section;
6578:   IS           perm;
6579:   PetscBool    hasConstraints, newDM, gnewDM;
6580:   PetscInt     num_face_sfs = 0;

6582:   PetscFunctionBegin;
6584:   PetscAssertPointer(odm, 2);
6585:   PetscCall(DMGetLocalSection(dm, &section));
6586:   PetscCall(PetscSectionHasConstraints(section, &hasConstraints));
6587:   PetscCall(PetscSectionGetPermutation(section, &perm));
6588:   PetscCall(DMPlexGetIsoperiodicFaceSF(dm, &num_face_sfs, NULL));
6589:   newDM = hasConstraints || perm || (num_face_sfs > 0) ? PETSC_TRUE : PETSC_FALSE;
6590:   PetscCallMPI(MPIU_Allreduce(&newDM, &gnewDM, 1, MPI_C_BOOL, MPI_LOR, PetscObjectComm((PetscObject)dm)));
6591:   if (!gnewDM) {
6592:     *odm = dm;
6593:     PetscFunctionReturn(PETSC_SUCCESS);
6594:   }
6595:   if (!dm->dmBC) {
6596:     PetscSection newSection, gsection;
6597:     PetscSF      sf, sfNatural;
6598:     PetscBool    usePerm = dm->ignorePermOutput ? PETSC_FALSE : PETSC_TRUE;

6600:     PetscCall(DMClone(dm, &dm->dmBC));
6601:     PetscCall(DMCopyDisc(dm, dm->dmBC));
6602:     PetscCall(PetscSectionClone(section, &newSection));
6603:     PetscCall(DMSetLocalSection(dm->dmBC, newSection));
6604:     PetscCall(PetscSectionDestroy(&newSection));
6605:     PetscCall(DMGetNaturalSF(dm, &sfNatural));
6606:     PetscCall(DMSetNaturalSF(dm->dmBC, sfNatural));
6607:     PetscCall(DMGetPointSF(dm->dmBC, &sf));
6608:     PetscCall(PetscSectionCreateGlobalSection(section, sf, usePerm, PETSC_TRUE, PETSC_FALSE, &gsection));
6609:     PetscCall(DMSetGlobalSection(dm->dmBC, gsection));
6610:     PetscCall(PetscSectionDestroy(&gsection));
6611:   }
6612:   *odm = dm->dmBC;
6613:   PetscFunctionReturn(PETSC_SUCCESS);
6614: }

6616: /*@
6617:   DMGetOutputSequenceNumber - Retrieve the sequence number/value for output

6619:   Input Parameter:
6620: . dm - The original `DM`

6622:   Output Parameters:
6623: + num - The output sequence number
6624: - val - The output sequence value

6626:   Level: intermediate

6628:   Note:
6629:   This is intended for output that should appear in sequence, for instance
6630:   a set of timesteps in an `PETSCVIEWERHDF5` file, or a set of realizations of a stochastic system.

6632:   Developer Note:
6633:   The `DM` serves as a convenient place to store the current iteration value. The iteration is not
6634:   not directly related to the `DM`.

6636: .seealso: [](ch_dmbase), `DM`, `VecView()`
6637: @*/
6638: PetscErrorCode DMGetOutputSequenceNumber(DM dm, PetscInt *num, PetscReal *val)
6639: {
6640:   PetscFunctionBegin;
6642:   if (num) {
6643:     PetscAssertPointer(num, 2);
6644:     *num = dm->outputSequenceNum;
6645:   }
6646:   if (val) {
6647:     PetscAssertPointer(val, 3);
6648:     *val = dm->outputSequenceVal;
6649:   }
6650:   PetscFunctionReturn(PETSC_SUCCESS);
6651: }

6653: /*@
6654:   DMSetOutputSequenceNumber - Set the sequence number/value for output

6656:   Input Parameters:
6657: + dm  - The original `DM`
6658: . num - The output sequence number
6659: - val - The output sequence value

6661:   Level: intermediate

6663:   Note:
6664:   This is intended for output that should appear in sequence, for instance
6665:   a set of timesteps in an `PETSCVIEWERHDF5` file, or a set of realizations of a stochastic system.

6667: .seealso: [](ch_dmbase), `DM`, `VecView()`
6668: @*/
6669: PetscErrorCode DMSetOutputSequenceNumber(DM dm, PetscInt num, PetscReal val)
6670: {
6671:   PetscFunctionBegin;
6673:   dm->outputSequenceNum = num;
6674:   dm->outputSequenceVal = val;
6675:   PetscFunctionReturn(PETSC_SUCCESS);
6676: }

6678: /*@
6679:   DMOutputSequenceLoad - Retrieve the sequence value from a `PetscViewer`

6681:   Input Parameters:
6682: + dm     - The original `DM`
6683: . viewer - The `PetscViewer` to get it from
6684: . name   - The sequence name
6685: - num    - The output sequence number

6687:   Output Parameter:
6688: . val - The output sequence value

6690:   Level: intermediate

6692:   Note:
6693:   This is intended for output that should appear in sequence, for instance
6694:   a set of timesteps in an `PETSCVIEWERHDF5` file, or a set of realizations of a stochastic system.

6696:   Developer Note:
6697:   It is unclear at the user API level why a `DM` is needed as input

6699: .seealso: [](ch_dmbase), `DM`, `DMGetOutputSequenceNumber()`, `DMSetOutputSequenceNumber()`, `VecView()`
6700: @*/
6701: PetscErrorCode DMOutputSequenceLoad(DM dm, PetscViewer viewer, const char name[], PetscInt num, PetscReal *val)
6702: {
6703:   PetscBool ishdf5;

6705:   PetscFunctionBegin;
6708:   PetscAssertPointer(name, 3);
6709:   PetscAssertPointer(val, 5);
6710:   PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERHDF5, &ishdf5));
6711:   PetscCheck(ishdf5, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Invalid viewer; open viewer with PetscViewerHDF5Open()");
6712: #if defined(PETSC_HAVE_HDF5)
6713:   PetscScalar value;

6715:   PetscCall(DMSequenceLoad_HDF5_Internal(dm, name, num, &value, viewer));
6716:   *val = PetscRealPart(value);
6717: #endif
6718:   PetscFunctionReturn(PETSC_SUCCESS);
6719: }

6721: /*@
6722:   DMGetOutputSequenceLength - Retrieve the number of sequence values from a `PetscViewer`

6724:   Input Parameters:
6725: + dm     - The original `DM`
6726: . viewer - The `PetscViewer` to get it from
6727: - name   - The sequence name

6729:   Output Parameter:
6730: . len - The length of the output sequence

6732:   Level: intermediate

6734:   Note:
6735:   This is intended for output that should appear in sequence, for instance
6736:   a set of timesteps in an `PETSCVIEWERHDF5` file, or a set of realizations of a stochastic system.

6738:   Developer Note:
6739:   It is unclear at the user API level why a `DM` is needed as input

6741: .seealso: [](ch_dmbase), `DM`, `DMGetOutputSequenceNumber()`, `DMSetOutputSequenceNumber()`, `VecView()`
6742: @*/
6743: PetscErrorCode DMGetOutputSequenceLength(DM dm, PetscViewer viewer, const char name[], PetscInt *len)
6744: {
6745:   PetscBool ishdf5;

6747:   PetscFunctionBegin;
6750:   PetscAssertPointer(name, 3);
6751:   PetscAssertPointer(len, 4);
6752:   PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERHDF5, &ishdf5));
6753:   PetscCheck(ishdf5, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Invalid viewer; open viewer with PetscViewerHDF5Open()");
6754: #if defined(PETSC_HAVE_HDF5)
6755:   PetscCall(DMSequenceGetLength_HDF5_Internal(dm, name, len, viewer));
6756: #endif
6757:   PetscFunctionReturn(PETSC_SUCCESS);
6758: }

6760: /*@
6761:   DMGetUseNatural - Get the flag for creating a mapping to the natural order when a `DM` is (re)distributed in parallel

6763:   Not Collective

6765:   Input Parameter:
6766: . dm - The `DM`

6768:   Output Parameter:
6769: . useNatural - `PETSC_TRUE` to build the mapping to a natural order during distribution

6771:   Level: beginner

6773: .seealso: [](ch_dmbase), `DM`, `DMSetUseNatural()`, `DMCreate()`
6774: @*/
6775: PetscErrorCode DMGetUseNatural(DM dm, PetscBool *useNatural)
6776: {
6777:   PetscFunctionBegin;
6779:   PetscAssertPointer(useNatural, 2);
6780:   *useNatural = dm->useNatural;
6781:   PetscFunctionReturn(PETSC_SUCCESS);
6782: }

6784: /*@
6785:   DMSetUseNatural - Set the flag for creating a mapping to the natural order when a `DM` is (re)distributed in parallel

6787:   Collective

6789:   Input Parameters:
6790: + dm         - The `DM`
6791: - useNatural - `PETSC_TRUE` to build the mapping to a natural order during distribution

6793:   Level: beginner

6795:   Note:
6796:   This also causes the map to be build after `DMCreateSubDM()` and `DMCreateSuperDM()`

6798: .seealso: [](ch_dmbase), `DM`, `DMGetUseNatural()`, `DMCreate()`, `DMPlexDistribute()`, `DMCreateSubDM()`, `DMCreateSuperDM()`
6799: @*/
6800: PetscErrorCode DMSetUseNatural(DM dm, PetscBool useNatural)
6801: {
6802:   PetscFunctionBegin;
6805:   dm->useNatural = useNatural;
6806:   PetscFunctionReturn(PETSC_SUCCESS);
6807: }

6809: /*@
6810:   DMCreateLabel - Create a label of the given name if it does not already exist in the `DM`

6812:   Not Collective

6814:   Input Parameters:
6815: + dm   - The `DM` object
6816: - name - The label name

6818:   Level: intermediate

6820: .seealso: [](ch_dmbase), `DM`, `DMLabelCreate()`, `DMHasLabel()`, `DMGetLabelValue()`, `DMSetLabelValue()`, `DMGetStratumIS()`
6821: @*/
6822: PetscErrorCode DMCreateLabel(DM dm, const char name[])
6823: {
6824:   PetscBool flg;
6825:   DMLabel   label;

6827:   PetscFunctionBegin;
6829:   PetscAssertPointer(name, 2);
6830:   PetscCall(DMHasLabel(dm, name, &flg));
6831:   if (!flg) {
6832:     PetscCall(DMLabelCreate(PETSC_COMM_SELF, name, &label));
6833:     PetscCall(DMAddLabel(dm, label));
6834:     PetscCall(DMLabelDestroy(&label));
6835:   }
6836:   PetscFunctionReturn(PETSC_SUCCESS);
6837: }

6839: /*@
6840:   DMCreateLabelAtIndex - Create a label of the given name at the given index. If it already exists in the `DM`, move it to this index.

6842:   Not Collective

6844:   Input Parameters:
6845: + dm   - The `DM` object
6846: . l    - The index for the label
6847: - name - The label name

6849:   Level: intermediate

6851: .seealso: [](ch_dmbase), `DM`, `DMCreateLabel()`, `DMLabelCreate()`, `DMHasLabel()`, `DMGetLabelValue()`, `DMSetLabelValue()`, `DMGetStratumIS()`
6852: @*/
6853: PetscErrorCode DMCreateLabelAtIndex(DM dm, PetscInt l, const char name[])
6854: {
6855:   DMLabelLink orig, prev = NULL;
6856:   DMLabel     label;
6857:   PetscInt    Nl, m;
6858:   PetscBool   flg, match;
6859:   const char *lname;

6861:   PetscFunctionBegin;
6863:   PetscAssertPointer(name, 3);
6864:   PetscCall(DMHasLabel(dm, name, &flg));
6865:   if (!flg) {
6866:     PetscCall(DMLabelCreate(PETSC_COMM_SELF, name, &label));
6867:     PetscCall(DMAddLabel(dm, label));
6868:     PetscCall(DMLabelDestroy(&label));
6869:   }
6870:   PetscCall(DMGetNumLabels(dm, &Nl));
6871:   PetscCheck(l < Nl, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Label index %" PetscInt_FMT " must be in [0, %" PetscInt_FMT ")", l, Nl);
6872:   for (m = 0, orig = dm->labels; m < Nl; ++m, prev = orig, orig = orig->next) {
6873:     PetscCall(PetscObjectGetName((PetscObject)orig->label, &lname));
6874:     PetscCall(PetscStrcmp(name, lname, &match));
6875:     if (match) break;
6876:   }
6877:   if (m == l) PetscFunctionReturn(PETSC_SUCCESS);
6878:   if (!m) dm->labels = orig->next;
6879:   else prev->next = orig->next;
6880:   if (!l) {
6881:     orig->next = dm->labels;
6882:     dm->labels = orig;
6883:   } else {
6884:     for (m = 0, prev = dm->labels; m < l - 1; ++m, prev = prev->next);
6885:     orig->next = prev->next;
6886:     prev->next = orig;
6887:   }
6888:   PetscFunctionReturn(PETSC_SUCCESS);
6889: }

6891: /*@
6892:   DMGetLabelValue - Get the value in a `DMLabel` for the given point, with -1 as the default

6894:   Not Collective

6896:   Input Parameters:
6897: + dm    - The `DM` object
6898: . name  - The label name
6899: - point - The mesh point

6901:   Output Parameter:
6902: . value - The label value for this point, or -1 if the point is not in the label

6904:   Level: beginner

6906: .seealso: [](ch_dmbase), `DM`, `DMLabelGetValue()`, `DMSetLabelValue()`, `DMGetStratumIS()`
6907: @*/
6908: PetscErrorCode DMGetLabelValue(DM dm, const char name[], PetscInt point, PetscInt *value)
6909: {
6910:   DMLabel label;

6912:   PetscFunctionBegin;
6914:   PetscAssertPointer(name, 2);
6915:   PetscCall(DMGetLabel(dm, name, &label));
6916:   PetscCheck(label, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "No label named %s was found", name);
6917:   PetscCall(DMLabelGetValue(label, point, value));
6918:   PetscFunctionReturn(PETSC_SUCCESS);
6919: }

6921: /*@
6922:   DMSetLabelValue - Add a point to a `DMLabel` with given value

6924:   Not Collective

6926:   Input Parameters:
6927: + dm    - The `DM` object
6928: . name  - The label name
6929: . point - The mesh point
6930: - value - The label value for this point

6932:   Output Parameter:

6934:   Level: beginner

6936: .seealso: [](ch_dmbase), `DM`, `DMLabelSetValue()`, `DMGetStratumIS()`, `DMClearLabelValue()`
6937: @*/
6938: PetscErrorCode DMSetLabelValue(DM dm, const char name[], PetscInt point, PetscInt value)
6939: {
6940:   DMLabel label;

6942:   PetscFunctionBegin;
6944:   PetscAssertPointer(name, 2);
6945:   PetscCall(DMGetLabel(dm, name, &label));
6946:   if (!label) {
6947:     PetscCall(DMCreateLabel(dm, name));
6948:     PetscCall(DMGetLabel(dm, name, &label));
6949:   }
6950:   PetscCall(DMLabelSetValue(label, point, value));
6951:   PetscFunctionReturn(PETSC_SUCCESS);
6952: }

6954: /*@
6955:   DMClearLabelValue - Remove a point from a `DMLabel` with given value

6957:   Not Collective

6959:   Input Parameters:
6960: + dm    - The `DM` object
6961: . name  - The label name
6962: . point - The mesh point
6963: - value - The label value for this point

6965:   Level: beginner

6967: .seealso: [](ch_dmbase), `DM`, `DMLabelClearValue()`, `DMSetLabelValue()`, `DMGetStratumIS()`
6968: @*/
6969: PetscErrorCode DMClearLabelValue(DM dm, const char name[], PetscInt point, PetscInt value)
6970: {
6971:   DMLabel label;

6973:   PetscFunctionBegin;
6975:   PetscAssertPointer(name, 2);
6976:   PetscCall(DMGetLabel(dm, name, &label));
6977:   if (!label) PetscFunctionReturn(PETSC_SUCCESS);
6978:   PetscCall(DMLabelClearValue(label, point, value));
6979:   PetscFunctionReturn(PETSC_SUCCESS);
6980: }

6982: /*@
6983:   DMGetLabelSize - Get the value of `DMLabelGetNumValues()` of a `DMLabel` in the `DM`

6985:   Not Collective

6987:   Input Parameters:
6988: + dm   - The `DM` object
6989: - name - The label name

6991:   Output Parameter:
6992: . size - The number of different integer ids, or 0 if the label does not exist

6994:   Level: beginner

6996:   Developer Note:
6997:   This should be renamed to something like `DMGetLabelNumValues()` or removed.

6999: .seealso: [](ch_dmbase), `DM`, `DMLabelGetNumValues()`, `DMSetLabelValue()`, `DMGetLabel()`
7000: @*/
7001: PetscErrorCode DMGetLabelSize(DM dm, const char name[], PetscInt *size)
7002: {
7003:   DMLabel label;

7005:   PetscFunctionBegin;
7007:   PetscAssertPointer(name, 2);
7008:   PetscAssertPointer(size, 3);
7009:   PetscCall(DMGetLabel(dm, name, &label));
7010:   *size = 0;
7011:   if (!label) PetscFunctionReturn(PETSC_SUCCESS);
7012:   PetscCall(DMLabelGetNumValues(label, size));
7013:   PetscFunctionReturn(PETSC_SUCCESS);
7014: }

7016: /*@
7017:   DMGetLabelIdIS - Get the `DMLabelGetValueIS()` from a `DMLabel` in the `DM`

7019:   Not Collective

7021:   Input Parameters:
7022: + dm   - The `DM` object
7023: - name - The label name

7025:   Output Parameter:
7026: . ids - The integer ids, or `NULL` if the label does not exist

7028:   Level: beginner

7030: .seealso: [](ch_dmbase), `DM`, `DMLabelGetValueIS()`, `DMGetLabelSize()`
7031: @*/
7032: PetscErrorCode DMGetLabelIdIS(DM dm, const char name[], IS *ids)
7033: {
7034:   DMLabel label;

7036:   PetscFunctionBegin;
7038:   PetscAssertPointer(name, 2);
7039:   PetscAssertPointer(ids, 3);
7040:   PetscCall(DMGetLabel(dm, name, &label));
7041:   *ids = NULL;
7042:   if (label) PetscCall(DMLabelGetValueIS(label, ids));
7043:   else {
7044:     /* returning an empty IS */
7045:     PetscCall(ISCreateGeneral(PETSC_COMM_SELF, 0, NULL, PETSC_USE_POINTER, ids));
7046:   }
7047:   PetscFunctionReturn(PETSC_SUCCESS);
7048: }

7050: /*@
7051:   DMGetStratumSize - Get the number of points in a label stratum

7053:   Not Collective

7055:   Input Parameters:
7056: + dm    - The `DM` object
7057: . name  - The label name of the stratum
7058: - value - The stratum value

7060:   Output Parameter:
7061: . size - The number of points, also called the stratum size

7063:   Level: beginner

7065: .seealso: [](ch_dmbase), `DM`, `DMLabelGetStratumSize()`, `DMGetLabelSize()`, `DMGetLabelIds()`
7066: @*/
7067: PetscErrorCode DMGetStratumSize(DM dm, const char name[], PetscInt value, PetscInt *size)
7068: {
7069:   DMLabel label;

7071:   PetscFunctionBegin;
7073:   PetscAssertPointer(name, 2);
7074:   PetscAssertPointer(size, 4);
7075:   PetscCall(DMGetLabel(dm, name, &label));
7076:   *size = 0;
7077:   if (!label) PetscFunctionReturn(PETSC_SUCCESS);
7078:   PetscCall(DMLabelGetStratumSize(label, value, size));
7079:   PetscFunctionReturn(PETSC_SUCCESS);
7080: }

7082: /*@
7083:   DMGetStratumIS - Get the points in a label stratum

7085:   Not Collective

7087:   Input Parameters:
7088: + dm    - The `DM` object
7089: . name  - The label name
7090: - value - The stratum value

7092:   Output Parameter:
7093: . points - The stratum points, or `NULL` if the label does not exist or does not have that value

7095:   Level: beginner

7097: .seealso: [](ch_dmbase), `DM`, `DMLabelGetStratumIS()`, `DMGetStratumSize()`
7098: @*/
7099: PetscErrorCode DMGetStratumIS(DM dm, const char name[], PetscInt value, IS *points)
7100: {
7101:   DMLabel label;

7103:   PetscFunctionBegin;
7105:   PetscAssertPointer(name, 2);
7106:   PetscAssertPointer(points, 4);
7107:   PetscCall(DMGetLabel(dm, name, &label));
7108:   *points = NULL;
7109:   if (!label) PetscFunctionReturn(PETSC_SUCCESS);
7110:   PetscCall(DMLabelGetStratumIS(label, value, points));
7111:   PetscFunctionReturn(PETSC_SUCCESS);
7112: }

7114: /*@
7115:   DMSetStratumIS - Set the points in a label stratum

7117:   Not Collective

7119:   Input Parameters:
7120: + dm     - The `DM` object
7121: . name   - The label name
7122: . value  - The stratum value
7123: - points - The stratum points

7125:   Level: beginner

7127: .seealso: [](ch_dmbase), `DM`, `DMLabel`, `DMClearLabelStratum()`, `DMLabelClearStratum()`, `DMLabelSetStratumIS()`, `DMGetStratumSize()`
7128: @*/
7129: PetscErrorCode DMSetStratumIS(DM dm, const char name[], PetscInt value, IS points)
7130: {
7131:   DMLabel label;

7133:   PetscFunctionBegin;
7135:   PetscAssertPointer(name, 2);
7137:   PetscCall(DMGetLabel(dm, name, &label));
7138:   if (!label) PetscFunctionReturn(PETSC_SUCCESS);
7139:   PetscCall(DMLabelSetStratumIS(label, value, points));
7140:   PetscFunctionReturn(PETSC_SUCCESS);
7141: }

7143: /*@
7144:   DMClearLabelStratum - Remove all points from a stratum from a `DMLabel`

7146:   Not Collective

7148:   Input Parameters:
7149: + dm    - The `DM` object
7150: . name  - The label name
7151: - value - The label value for this point

7153:   Output Parameter:

7155:   Level: beginner

7157: .seealso: [](ch_dmbase), `DM`, `DMLabel`, `DMLabelClearStratum()`, `DMSetLabelValue()`, `DMGetStratumIS()`, `DMClearLabelValue()`
7158: @*/
7159: PetscErrorCode DMClearLabelStratum(DM dm, const char name[], PetscInt value)
7160: {
7161:   DMLabel label;

7163:   PetscFunctionBegin;
7165:   PetscAssertPointer(name, 2);
7166:   PetscCall(DMGetLabel(dm, name, &label));
7167:   if (!label) PetscFunctionReturn(PETSC_SUCCESS);
7168:   PetscCall(DMLabelClearStratum(label, value));
7169:   PetscFunctionReturn(PETSC_SUCCESS);
7170: }

7172: /*@
7173:   DMGetNumLabels - Return the number of labels defined by on the `DM`

7175:   Not Collective

7177:   Input Parameter:
7178: . dm - The `DM` object

7180:   Output Parameter:
7181: . numLabels - the number of Labels

7183:   Level: intermediate

7185: .seealso: [](ch_dmbase), `DM`, `DMLabel`, `DMGetLabelByNum()`, `DMGetLabelName()`, `DMGetLabelValue()`, `DMSetLabelValue()`, `DMGetStratumIS()`
7186: @*/
7187: PetscErrorCode DMGetNumLabels(DM dm, PetscInt *numLabels)
7188: {
7189:   DMLabelLink next = dm->labels;
7190:   PetscInt    n    = 0;

7192:   PetscFunctionBegin;
7194:   PetscAssertPointer(numLabels, 2);
7195:   while (next) {
7196:     ++n;
7197:     next = next->next;
7198:   }
7199:   *numLabels = n;
7200:   PetscFunctionReturn(PETSC_SUCCESS);
7201: }

7203: /*@
7204:   DMGetLabelName - Return the name of nth label

7206:   Not Collective

7208:   Input Parameters:
7209: + dm - The `DM` object
7210: - n  - the label number

7212:   Output Parameter:
7213: . name - the label name

7215:   Level: intermediate

7217:   Developer Note:
7218:   Some of the functions that appropriate on labels using their number have the suffix ByNum, others do not.

7220: .seealso: [](ch_dmbase), `DM`, `DMLabel`, `DMGetLabelByNum()`, `DMGetLabel()`, `DMGetLabelValue()`, `DMSetLabelValue()`, `DMGetStratumIS()`
7221: @*/
7222: PetscErrorCode DMGetLabelName(DM dm, PetscInt n, const char *name[])
7223: {
7224:   DMLabelLink next = dm->labels;
7225:   PetscInt    l    = 0;

7227:   PetscFunctionBegin;
7229:   PetscAssertPointer(name, 3);
7230:   while (next) {
7231:     if (l == n) {
7232:       PetscCall(PetscObjectGetName((PetscObject)next->label, name));
7233:       PetscFunctionReturn(PETSC_SUCCESS);
7234:     }
7235:     ++l;
7236:     next = next->next;
7237:   }
7238:   SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Label %" PetscInt_FMT " does not exist in this DM", n);
7239: }

7241: /*@
7242:   DMHasLabel - Determine whether the `DM` has a label of a given name

7244:   Not Collective

7246:   Input Parameters:
7247: + dm   - The `DM` object
7248: - name - The label name

7250:   Output Parameter:
7251: . hasLabel - `PETSC_TRUE` if the label is present

7253:   Level: intermediate

7255: .seealso: [](ch_dmbase), `DM`, `DMLabel`, `DMGetLabel()`, `DMGetLabelByNum()`, `DMCreateLabel()`, `DMGetLabelValue()`, `DMSetLabelValue()`, `DMGetStratumIS()`
7256: @*/
7257: PetscErrorCode DMHasLabel(DM dm, const char name[], PetscBool *hasLabel)
7258: {
7259:   DMLabelLink next = dm->labels;
7260:   const char *lname;

7262:   PetscFunctionBegin;
7264:   PetscAssertPointer(name, 2);
7265:   PetscAssertPointer(hasLabel, 3);
7266:   *hasLabel = PETSC_FALSE;
7267:   while (next) {
7268:     PetscCall(PetscObjectGetName((PetscObject)next->label, &lname));
7269:     PetscCall(PetscStrcmp(name, lname, hasLabel));
7270:     if (*hasLabel) break;
7271:     next = next->next;
7272:   }
7273:   PetscFunctionReturn(PETSC_SUCCESS);
7274: }

7276: // PetscClangLinter pragma ignore: -fdoc-section-header-unknown
7277: /*@
7278:   DMGetLabel - Return the label of a given name, or `NULL`, from a `DM`

7280:   Not Collective

7282:   Input Parameters:
7283: + dm   - The `DM` object
7284: - name - The label name

7286:   Output Parameter:
7287: . label - The `DMLabel`, or `NULL` if the label is absent

7289:   Default labels in a `DMPLEX`:
7290: + "depth"       - Holds the depth (co-dimension) of each mesh point
7291: . "celltype"    - Holds the topological type of each cell
7292: . "ghost"       - If the DM is distributed with overlap, this marks the cells and faces in the overlap
7293: . "Cell Sets"   - Mirrors the cell sets defined by GMsh and ExodusII
7294: . "Face Sets"   - Mirrors the face sets defined by GMsh and ExodusII
7295: - "Vertex Sets" - Mirrors the vertex sets defined by GMsh

7297:   Level: intermediate

7299: .seealso: [](ch_dmbase), `DM`, `DMLabel`, `DMHasLabel()`, `DMGetLabelByNum()`, `DMAddLabel()`, `DMCreateLabel()`, `DMPlexGetDepthLabel()`, `DMPlexGetCellType()`
7300: @*/
7301: PetscErrorCode DMGetLabel(DM dm, const char name[], DMLabel *label)
7302: {
7303:   DMLabelLink next = dm->labels;
7304:   PetscBool   hasLabel;
7305:   const char *lname;

7307:   PetscFunctionBegin;
7309:   PetscAssertPointer(name, 2);
7310:   PetscAssertPointer(label, 3);
7311:   *label = NULL;
7312:   while (next) {
7313:     PetscCall(PetscObjectGetName((PetscObject)next->label, &lname));
7314:     PetscCall(PetscStrcmp(name, lname, &hasLabel));
7315:     if (hasLabel) {
7316:       *label = next->label;
7317:       break;
7318:     }
7319:     next = next->next;
7320:   }
7321:   PetscFunctionReturn(PETSC_SUCCESS);
7322: }

7324: /*@
7325:   DMGetLabelByNum - Return the nth label on a `DM`

7327:   Not Collective

7329:   Input Parameters:
7330: + dm - The `DM` object
7331: - n  - the label number

7333:   Output Parameter:
7334: . label - the label

7336:   Level: intermediate

7338: .seealso: [](ch_dmbase), `DM`, `DMLabel`, `DMAddLabel()`, `DMGetLabelValue()`, `DMSetLabelValue()`, `DMGetStratumIS()`
7339: @*/
7340: PetscErrorCode DMGetLabelByNum(DM dm, PetscInt n, DMLabel *label)
7341: {
7342:   DMLabelLink next = dm->labels;
7343:   PetscInt    l    = 0;

7345:   PetscFunctionBegin;
7347:   PetscAssertPointer(label, 3);
7348:   while (next) {
7349:     if (l == n) {
7350:       *label = next->label;
7351:       PetscFunctionReturn(PETSC_SUCCESS);
7352:     }
7353:     ++l;
7354:     next = next->next;
7355:   }
7356:   SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Label %" PetscInt_FMT " does not exist in this DM", n);
7357: }

7359: /*@
7360:   DMAddLabel - Add the label to this `DM`

7362:   Not Collective

7364:   Input Parameters:
7365: + dm    - The `DM` object
7366: - label - The `DMLabel`

7368:   Level: developer

7370: .seealso: [](ch_dmbase), `DM`, `DMLabel`, `DMCreateLabel()`, `DMHasLabel()`, `DMGetLabelValue()`, `DMSetLabelValue()`, `DMGetStratumIS()`
7371: @*/
7372: PetscErrorCode DMAddLabel(DM dm, DMLabel label)
7373: {
7374:   DMLabelLink l, *p, tmpLabel;
7375:   PetscBool   hasLabel;
7376:   const char *lname;
7377:   PetscBool   flg;

7379:   PetscFunctionBegin;
7381:   PetscCall(PetscObjectGetName((PetscObject)label, &lname));
7382:   PetscCall(DMHasLabel(dm, lname, &hasLabel));
7383:   PetscCheck(!hasLabel, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Label %s already exists in this DM", lname);
7384:   PetscCall(PetscCalloc1(1, &tmpLabel));
7385:   tmpLabel->label  = label;
7386:   tmpLabel->output = PETSC_TRUE;
7387:   for (p = &dm->labels; (l = *p); p = &l->next) { }
7388:   *p = tmpLabel;
7389:   PetscCall(PetscObjectReference((PetscObject)label));
7390:   PetscCall(PetscStrcmp(lname, "depth", &flg));
7391:   if (flg) dm->depthLabel = label;
7392:   PetscCall(PetscStrcmp(lname, "celltype", &flg));
7393:   if (flg) dm->celltypeLabel = label;
7394:   PetscFunctionReturn(PETSC_SUCCESS);
7395: }

7397: // PetscClangLinter pragma ignore: -fdoc-section-header-unknown
7398: /*@
7399:   DMSetLabel - Replaces the label of a given name, or ignores it if the name is not present

7401:   Not Collective

7403:   Input Parameters:
7404: + dm    - The `DM` object
7405: - label - The `DMLabel`, having the same name, to substitute

7407:   Default labels in a `DMPLEX`:
7408: + "depth"       - Holds the depth (co-dimension) of each mesh point
7409: . "celltype"    - Holds the topological type of each cell
7410: . "ghost"       - If the DM is distributed with overlap, this marks the cells and faces in the overlap
7411: . "Cell Sets"   - Mirrors the cell sets defined by GMsh and ExodusII
7412: . "Face Sets"   - Mirrors the face sets defined by GMsh and ExodusII
7413: - "Vertex Sets" - Mirrors the vertex sets defined by GMsh

7415:   Level: intermediate

7417: .seealso: [](ch_dmbase), `DM`, `DMLabel`, `DMCreateLabel()`, `DMHasLabel()`, `DMPlexGetDepthLabel()`, `DMPlexGetCellType()`
7418: @*/
7419: PetscErrorCode DMSetLabel(DM dm, DMLabel label)
7420: {
7421:   DMLabelLink next = dm->labels;
7422:   PetscBool   hasLabel, flg;
7423:   const char *name, *lname;

7425:   PetscFunctionBegin;
7428:   PetscCall(PetscObjectGetName((PetscObject)label, &name));
7429:   while (next) {
7430:     PetscCall(PetscObjectGetName((PetscObject)next->label, &lname));
7431:     PetscCall(PetscStrcmp(name, lname, &hasLabel));
7432:     if (hasLabel) {
7433:       PetscCall(PetscObjectReference((PetscObject)label));
7434:       PetscCall(PetscStrcmp(lname, "depth", &flg));
7435:       if (flg) dm->depthLabel = label;
7436:       PetscCall(PetscStrcmp(lname, "celltype", &flg));
7437:       if (flg) dm->celltypeLabel = label;
7438:       PetscCall(DMLabelDestroy(&next->label));
7439:       next->label = label;
7440:       break;
7441:     }
7442:     next = next->next;
7443:   }
7444:   PetscFunctionReturn(PETSC_SUCCESS);
7445: }

7447: /*@
7448:   DMRemoveLabel - Remove the label given by name from this `DM`

7450:   Not Collective

7452:   Input Parameters:
7453: + dm   - The `DM` object
7454: - name - The label name

7456:   Output Parameter:
7457: . label - The `DMLabel`, or `NULL` if the label is absent. Pass in `NULL` to call `DMLabelDestroy()` on the label, otherwise the
7458:           caller is responsible for calling `DMLabelDestroy()`.

7460:   Level: developer

7462: .seealso: [](ch_dmbase), `DM`, `DMLabel`, `DMCreateLabel()`, `DMHasLabel()`, `DMGetLabel()`, `DMGetLabelValue()`, `DMSetLabelValue()`, `DMLabelDestroy()`, `DMRemoveLabelBySelf()`
7463: @*/
7464: PetscErrorCode DMRemoveLabel(DM dm, const char name[], DMLabel *label)
7465: {
7466:   DMLabelLink link, *pnext;
7467:   PetscBool   hasLabel;
7468:   const char *lname;

7470:   PetscFunctionBegin;
7472:   PetscAssertPointer(name, 2);
7473:   if (label) {
7474:     PetscAssertPointer(label, 3);
7475:     *label = NULL;
7476:   }
7477:   for (pnext = &dm->labels; (link = *pnext); pnext = &link->next) {
7478:     PetscCall(PetscObjectGetName((PetscObject)link->label, &lname));
7479:     PetscCall(PetscStrcmp(name, lname, &hasLabel));
7480:     if (hasLabel) {
7481:       *pnext = link->next; /* Remove from list */
7482:       PetscCall(PetscStrcmp(name, "depth", &hasLabel));
7483:       if (hasLabel) dm->depthLabel = NULL;
7484:       PetscCall(PetscStrcmp(name, "celltype", &hasLabel));
7485:       if (hasLabel) dm->celltypeLabel = NULL;
7486:       if (label) *label = link->label;
7487:       else PetscCall(DMLabelDestroy(&link->label));
7488:       PetscCall(PetscFree(link));
7489:       break;
7490:     }
7491:   }
7492:   PetscFunctionReturn(PETSC_SUCCESS);
7493: }

7495: /*@
7496:   DMRemoveLabelBySelf - Remove the label from this `DM`

7498:   Not Collective

7500:   Input Parameters:
7501: + dm           - The `DM` object
7502: . label        - The `DMLabel` to be removed from the `DM`
7503: - failNotFound - Should it fail if the label is not found in the `DM`?

7505:   Level: developer

7507:   Note:
7508:   Only exactly the same instance is removed if found, name match is ignored.
7509:   If the `DM` has an exclusive reference to the label, the label gets destroyed and
7510:   *label nullified.

7512: .seealso: [](ch_dmbase), `DM`, `DMLabel`, `DMCreateLabel()`, `DMHasLabel()`, `DMGetLabel()`, `DMGetLabelValue()`, `DMSetLabelValue()`, `DMLabelDestroy()`, `DMRemoveLabel()`
7513: @*/
7514: PetscErrorCode DMRemoveLabelBySelf(DM dm, DMLabel *label, PetscBool failNotFound)
7515: {
7516:   DMLabelLink link, *pnext;
7517:   PetscBool   hasLabel = PETSC_FALSE;

7519:   PetscFunctionBegin;
7521:   PetscAssertPointer(label, 2);
7522:   if (!*label && !failNotFound) PetscFunctionReturn(PETSC_SUCCESS);
7525:   for (pnext = &dm->labels; (link = *pnext); pnext = &link->next) {
7526:     if (*label == link->label) {
7527:       hasLabel = PETSC_TRUE;
7528:       *pnext   = link->next; /* Remove from list */
7529:       if (*label == dm->depthLabel) dm->depthLabel = NULL;
7530:       if (*label == dm->celltypeLabel) dm->celltypeLabel = NULL;
7531:       if (((PetscObject)link->label)->refct < 2) *label = NULL; /* nullify if exclusive reference */
7532:       PetscCall(DMLabelDestroy(&link->label));
7533:       PetscCall(PetscFree(link));
7534:       break;
7535:     }
7536:   }
7537:   PetscCheck(hasLabel || !failNotFound, PetscObjectComm((PetscObject)dm), PETSC_ERR_ARG_WRONG, "Given label not found in DM");
7538:   PetscFunctionReturn(PETSC_SUCCESS);
7539: }

7541: /*@
7542:   DMGetLabelOutput - Get the output flag for a given label

7544:   Not Collective

7546:   Input Parameters:
7547: + dm   - The `DM` object
7548: - name - The label name

7550:   Output Parameter:
7551: . output - The flag for output

7553:   Level: developer

7555: .seealso: [](ch_dmbase), `DM`, `DMLabel`, `DMSetLabelOutput()`, `DMCreateLabel()`, `DMHasLabel()`, `DMGetLabelValue()`, `DMSetLabelValue()`, `DMGetStratumIS()`
7556: @*/
7557: PetscErrorCode DMGetLabelOutput(DM dm, const char name[], PetscBool *output)
7558: {
7559:   DMLabelLink next = dm->labels;
7560:   const char *lname;

7562:   PetscFunctionBegin;
7564:   PetscAssertPointer(name, 2);
7565:   PetscAssertPointer(output, 3);
7566:   while (next) {
7567:     PetscBool flg;

7569:     PetscCall(PetscObjectGetName((PetscObject)next->label, &lname));
7570:     PetscCall(PetscStrcmp(name, lname, &flg));
7571:     if (flg) {
7572:       *output = next->output;
7573:       PetscFunctionReturn(PETSC_SUCCESS);
7574:     }
7575:     next = next->next;
7576:   }
7577:   SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "No label named %s was present in this dm", name);
7578: }

7580: /*@
7581:   DMSetLabelOutput - Set if a given label should be saved to a `PetscViewer` in calls to `DMView()`

7583:   Not Collective

7585:   Input Parameters:
7586: + dm     - The `DM` object
7587: . name   - The label name
7588: - output - `PETSC_TRUE` to save the label to the viewer

7590:   Level: developer

7592: .seealso: [](ch_dmbase), `DM`, `DMLabel`, `DMGetOutputFlag()`, `DMGetLabelOutput()`, `DMCreateLabel()`, `DMHasLabel()`, `DMGetLabelValue()`, `DMSetLabelValue()`, `DMGetStratumIS()`
7593: @*/
7594: PetscErrorCode DMSetLabelOutput(DM dm, const char name[], PetscBool output)
7595: {
7596:   DMLabelLink next = dm->labels;
7597:   const char *lname;

7599:   PetscFunctionBegin;
7601:   PetscAssertPointer(name, 2);
7602:   while (next) {
7603:     PetscBool flg;

7605:     PetscCall(PetscObjectGetName((PetscObject)next->label, &lname));
7606:     PetscCall(PetscStrcmp(name, lname, &flg));
7607:     if (flg) {
7608:       next->output = output;
7609:       PetscFunctionReturn(PETSC_SUCCESS);
7610:     }
7611:     next = next->next;
7612:   }
7613:   SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "No label named %s was present in this dm", name);
7614: }

7616: /*@
7617:   DMCopyLabels - Copy labels from one `DM` mesh to another `DM` with a superset of the points

7619:   Collective

7621:   Input Parameters:
7622: + dmA   - The `DM` object with initial labels
7623: . dmB   - The `DM` object to which labels are copied
7624: . mode  - Copy labels by pointers (`PETSC_OWN_POINTER`) or duplicate them (`PETSC_COPY_VALUES`)
7625: . all   - Copy all labels including "depth", "dim", and "celltype" (`PETSC_TRUE`) which are otherwise ignored (`PETSC_FALSE`)
7626: - emode - How to behave when a `DMLabel` in the source and destination `DM`s with the same name is encountered (see `DMCopyLabelsMode`)

7628:   Level: intermediate

7630:   Note:
7631:   This is typically used when interpolating or otherwise adding to a mesh, or testing.

7633: .seealso: [](ch_dmbase), `DM`, `DMLabel`, `DMAddLabel()`, `DMCopyLabelsMode`
7634: @*/
7635: PetscErrorCode DMCopyLabels(DM dmA, DM dmB, PetscCopyMode mode, PetscBool all, DMCopyLabelsMode emode)
7636: {
7637:   DMLabel     label, labelNew, labelOld;
7638:   const char *name;
7639:   PetscBool   flg;
7640:   DMLabelLink link;

7642:   PetscFunctionBegin;
7647:   PetscCheck(mode != PETSC_USE_POINTER, PetscObjectComm((PetscObject)dmA), PETSC_ERR_SUP, "PETSC_USE_POINTER not supported for objects");
7648:   if (dmA == dmB) PetscFunctionReturn(PETSC_SUCCESS);
7649:   for (link = dmA->labels; link; link = link->next) {
7650:     label = link->label;
7651:     PetscCall(PetscObjectGetName((PetscObject)label, &name));
7652:     if (!all) {
7653:       PetscCall(PetscStrcmp(name, "depth", &flg));
7654:       if (flg) continue;
7655:       PetscCall(PetscStrcmp(name, "dim", &flg));
7656:       if (flg) continue;
7657:       PetscCall(PetscStrcmp(name, "celltype", &flg));
7658:       if (flg) continue;
7659:     }
7660:     PetscCall(DMGetLabel(dmB, name, &labelOld));
7661:     if (labelOld) {
7662:       switch (emode) {
7663:       case DM_COPY_LABELS_KEEP:
7664:         continue;
7665:       case DM_COPY_LABELS_REPLACE:
7666:         PetscCall(DMRemoveLabelBySelf(dmB, &labelOld, PETSC_TRUE));
7667:         break;
7668:       case DM_COPY_LABELS_FAIL:
7669:         SETERRQ(PetscObjectComm((PetscObject)dmA), PETSC_ERR_ARG_OUTOFRANGE, "Label %s already exists in destination DM", name);
7670:       default:
7671:         SETERRQ(PetscObjectComm((PetscObject)dmA), PETSC_ERR_ARG_OUTOFRANGE, "Unhandled DMCopyLabelsMode %d", (int)emode);
7672:       }
7673:     }
7674:     if (mode == PETSC_COPY_VALUES) PetscCall(DMLabelDuplicate(label, &labelNew));
7675:     else labelNew = label;
7676:     PetscCall(DMAddLabel(dmB, labelNew));
7677:     if (mode == PETSC_COPY_VALUES) PetscCall(DMLabelDestroy(&labelNew));
7678:   }
7679:   PetscFunctionReturn(PETSC_SUCCESS);
7680: }

7682: /*@C
7683:   DMCompareLabels - Compare labels between two `DM` objects

7685:   Collective; No Fortran Support

7687:   Input Parameters:
7688: + dm0 - First `DM` object
7689: - dm1 - Second `DM` object

7691:   Output Parameters:
7692: + equal   - (Optional) Flag whether labels of `dm0` and `dm1` are the same
7693: - message - (Optional) Message describing the difference, or `NULL` if there is no difference

7695:   Level: intermediate

7697:   Notes:
7698:   The output flag equal will be the same on all processes.

7700:   If equal is passed as `NULL` and difference is found, an error is thrown on all processes.

7702:   Make sure to pass equal is `NULL` on all processes or none of them.

7704:   The output message is set independently on each rank.

7706:   message must be freed with `PetscFree()`

7708:   If message is passed as `NULL` and a difference is found, the difference description is printed to `stderr` in synchronized manner.

7710:   Make sure to pass message as `NULL` on all processes or no processes.

7712:   Labels are matched by name. If the number of labels and their names are equal,
7713:   `DMLabelCompare()` is used to compare each pair of labels with the same name.

7715:   Developer Note:
7716:   Cannot automatically generate the Fortran stub because `message` must be freed with `PetscFree()`

7718: .seealso: [](ch_dmbase), `DM`, `DMLabel`, `DMAddLabel()`, `DMCopyLabelsMode`, `DMLabelCompare()`
7719: @*/
7720: PetscErrorCode DMCompareLabels(DM dm0, DM dm1, PetscBool *equal, char *message[]) PeNS
7721: {
7722:   PetscInt    n, i;
7723:   char        msg[PETSC_MAX_PATH_LEN] = "";
7724:   PetscBool   eq;
7725:   MPI_Comm    comm;
7726:   PetscMPIInt rank;

7728:   PetscFunctionBegin;
7731:   PetscCheckSameComm(dm0, 1, dm1, 2);
7732:   if (equal) PetscAssertPointer(equal, 3);
7733:   if (message) PetscAssertPointer(message, 4);
7734:   PetscCall(PetscObjectGetComm((PetscObject)dm0, &comm));
7735:   PetscCallMPI(MPI_Comm_rank(comm, &rank));
7736:   {
7737:     PetscInt n1;

7739:     PetscCall(DMGetNumLabels(dm0, &n));
7740:     PetscCall(DMGetNumLabels(dm1, &n1));
7741:     eq = (PetscBool)(n == n1);
7742:     if (!eq) PetscCall(PetscSNPrintf(msg, sizeof(msg), "Number of labels in dm0 = %" PetscInt_FMT " != %" PetscInt_FMT " = Number of labels in dm1", n, n1));
7743:     PetscCallMPI(MPIU_Allreduce(MPI_IN_PLACE, &eq, 1, MPI_C_BOOL, MPI_LAND, comm));
7744:     if (!eq) goto finish;
7745:   }
7746:   for (i = 0; i < n; i++) {
7747:     DMLabel     l0, l1;
7748:     const char *name;
7749:     char       *msgInner;

7751:     /* Ignore label order */
7752:     PetscCall(DMGetLabelByNum(dm0, i, &l0));
7753:     PetscCall(PetscObjectGetName((PetscObject)l0, &name));
7754:     PetscCall(DMGetLabel(dm1, name, &l1));
7755:     if (!l1) {
7756:       PetscCall(PetscSNPrintf(msg, sizeof(msg), "Label \"%s\" (#%" PetscInt_FMT " in dm0) not found in dm1", name, i));
7757:       eq = PETSC_FALSE;
7758:       break;
7759:     }
7760:     PetscCall(DMLabelCompare(comm, l0, l1, &eq, &msgInner));
7761:     PetscCall(PetscStrncpy(msg, msgInner, sizeof(msg)));
7762:     PetscCall(PetscFree(msgInner));
7763:     if (!eq) break;
7764:   }
7765:   PetscCallMPI(MPIU_Allreduce(MPI_IN_PLACE, &eq, 1, MPI_C_BOOL, MPI_LAND, comm));
7766: finish:
7767:   /* If message output arg not set, print to stderr */
7768:   if (message) {
7769:     *message = NULL;
7770:     if (msg[0]) PetscCall(PetscStrallocpy(msg, message));
7771:   } else {
7772:     if (msg[0]) PetscCall(PetscSynchronizedFPrintf(comm, PETSC_STDERR, "[%d] %s\n", rank, msg));
7773:     PetscCall(PetscSynchronizedFlush(comm, PETSC_STDERR));
7774:   }
7775:   /* If same output arg not ser and labels are not equal, throw error */
7776:   if (equal) *equal = eq;
7777:   else PetscCheck(eq, comm, PETSC_ERR_ARG_INCOMP, "DMLabels are not the same in dm0 and dm1");
7778:   PetscFunctionReturn(PETSC_SUCCESS);
7779: }

7781: PetscErrorCode DMSetLabelValue_Fast(DM dm, DMLabel *label, const char name[], PetscInt point, PetscInt value)
7782: {
7783:   PetscFunctionBegin;
7784:   PetscAssertPointer(label, 2);
7785:   if (!*label) {
7786:     PetscCall(DMCreateLabel(dm, name));
7787:     PetscCall(DMGetLabel(dm, name, label));
7788:   }
7789:   PetscCall(DMLabelSetValue(*label, point, value));
7790:   PetscFunctionReturn(PETSC_SUCCESS);
7791: }

7793: /*
7794:   Many mesh programs, such as Triangle and TetGen, allow only a single label for each mesh point. Therefore, we would
7795:   like to encode all label IDs using a single, universal label. We can do this by assigning an integer to every
7796:   (label, id) pair in the DM.

7798:   However, a mesh point can have multiple labels, so we must separate all these values. We will assign a bit range to
7799:   each label.
7800: */
7801: PetscErrorCode DMUniversalLabelCreate(DM dm, DMUniversalLabel *universal)
7802: {
7803:   DMUniversalLabel ul;
7804:   PetscBool       *active;
7805:   PetscInt         pStart, pEnd, p, Nl, l, m;

7807:   PetscFunctionBegin;
7808:   PetscCall(PetscMalloc1(1, &ul));
7809:   PetscCall(DMLabelCreate(PETSC_COMM_SELF, "universal", &ul->label));
7810:   PetscCall(DMGetNumLabels(dm, &Nl));
7811:   PetscCall(PetscCalloc1(Nl, &active));
7812:   ul->Nl = 0;
7813:   for (l = 0; l < Nl; ++l) {
7814:     PetscBool   isdepth, iscelltype;
7815:     const char *name;

7817:     PetscCall(DMGetLabelName(dm, l, &name));
7818:     PetscCall(PetscStrncmp(name, "depth", 6, &isdepth));
7819:     PetscCall(PetscStrncmp(name, "celltype", 9, &iscelltype));
7820:     active[l] = !(isdepth || iscelltype) ? PETSC_TRUE : PETSC_FALSE;
7821:     if (active[l]) ++ul->Nl;
7822:   }
7823:   PetscCall(PetscCalloc5(ul->Nl, &ul->names, ul->Nl, &ul->indices, ul->Nl + 1, &ul->offsets, ul->Nl + 1, &ul->bits, ul->Nl, &ul->masks));
7824:   ul->Nv = 0;
7825:   for (l = 0, m = 0; l < Nl; ++l) {
7826:     DMLabel     label;
7827:     PetscInt    nv;
7828:     const char *name;

7830:     if (!active[l]) continue;
7831:     PetscCall(DMGetLabelName(dm, l, &name));
7832:     PetscCall(DMGetLabelByNum(dm, l, &label));
7833:     PetscCall(DMLabelGetNumValues(label, &nv));
7834:     PetscCall(PetscStrallocpy(name, &ul->names[m]));
7835:     ul->indices[m] = l;
7836:     ul->Nv += nv;
7837:     ul->offsets[m + 1] = nv;
7838:     ul->bits[m + 1]    = PetscCeilReal(PetscLog2Real(nv + 1));
7839:     ++m;
7840:   }
7841:   for (l = 1; l <= ul->Nl; ++l) {
7842:     ul->offsets[l] = ul->offsets[l - 1] + ul->offsets[l];
7843:     ul->bits[l]    = ul->bits[l - 1] + ul->bits[l];
7844:   }
7845:   for (l = 0; l < ul->Nl; ++l) {
7846:     PetscInt b;

7848:     ul->masks[l] = 0;
7849:     for (b = ul->bits[l]; b < ul->bits[l + 1]; ++b) ul->masks[l] |= 1 << b;
7850:   }
7851:   PetscCall(PetscMalloc1(ul->Nv, &ul->values));
7852:   for (l = 0, m = 0; l < Nl; ++l) {
7853:     DMLabel         label;
7854:     IS              valueIS;
7855:     const PetscInt *varr;
7856:     PetscInt        nv, v;

7858:     if (!active[l]) continue;
7859:     PetscCall(DMGetLabelByNum(dm, l, &label));
7860:     PetscCall(DMLabelGetNumValues(label, &nv));
7861:     PetscCall(DMLabelGetValueIS(label, &valueIS));
7862:     PetscCall(ISGetIndices(valueIS, &varr));
7863:     for (v = 0; v < nv; ++v) ul->values[ul->offsets[m] + v] = varr[v];
7864:     PetscCall(ISRestoreIndices(valueIS, &varr));
7865:     PetscCall(ISDestroy(&valueIS));
7866:     PetscCall(PetscSortInt(nv, &ul->values[ul->offsets[m]]));
7867:     ++m;
7868:   }
7869:   PetscCall(DMPlexGetChart(dm, &pStart, &pEnd));
7870:   for (p = pStart; p < pEnd; ++p) {
7871:     PetscInt  uval   = 0;
7872:     PetscBool marked = PETSC_FALSE;

7874:     for (l = 0, m = 0; l < Nl; ++l) {
7875:       DMLabel  label;
7876:       PetscInt val, defval, loc, nv;

7878:       if (!active[l]) continue;
7879:       PetscCall(DMGetLabelByNum(dm, l, &label));
7880:       PetscCall(DMLabelGetValue(label, p, &val));
7881:       PetscCall(DMLabelGetDefaultValue(label, &defval));
7882:       if (val == defval) {
7883:         ++m;
7884:         continue;
7885:       }
7886:       nv     = ul->offsets[m + 1] - ul->offsets[m];
7887:       marked = PETSC_TRUE;
7888:       PetscCall(PetscFindInt(val, nv, &ul->values[ul->offsets[m]], &loc));
7889:       PetscCheck(loc >= 0, PETSC_COMM_SELF, PETSC_ERR_PLIB, "Label value %" PetscInt_FMT " not found in compression array", val);
7890:       uval += (loc + 1) << ul->bits[m];
7891:       ++m;
7892:     }
7893:     if (marked) PetscCall(DMLabelSetValue(ul->label, p, uval));
7894:   }
7895:   PetscCall(PetscFree(active));
7896:   *universal = ul;
7897:   PetscFunctionReturn(PETSC_SUCCESS);
7898: }

7900: PetscErrorCode DMUniversalLabelDestroy(DMUniversalLabel *universal)
7901: {
7902:   PetscInt l;

7904:   PetscFunctionBegin;
7905:   for (l = 0; l < (*universal)->Nl; ++l) PetscCall(PetscFree((*universal)->names[l]));
7906:   PetscCall(DMLabelDestroy(&(*universal)->label));
7907:   PetscCall(PetscFree5((*universal)->names, (*universal)->indices, (*universal)->offsets, (*universal)->bits, (*universal)->masks));
7908:   PetscCall(PetscFree((*universal)->values));
7909:   PetscCall(PetscFree(*universal));
7910:   *universal = NULL;
7911:   PetscFunctionReturn(PETSC_SUCCESS);
7912: }

7914: PetscErrorCode DMUniversalLabelGetLabel(DMUniversalLabel ul, DMLabel *ulabel)
7915: {
7916:   PetscFunctionBegin;
7917:   PetscAssertPointer(ulabel, 2);
7918:   *ulabel = ul->label;
7919:   PetscFunctionReturn(PETSC_SUCCESS);
7920: }

7922: PetscErrorCode DMUniversalLabelCreateLabels(DMUniversalLabel ul, PetscBool preserveOrder, DM dm)
7923: {
7924:   PetscInt Nl = ul->Nl, l;

7926:   PetscFunctionBegin;
7928:   for (l = 0; l < Nl; ++l) {
7929:     if (preserveOrder) PetscCall(DMCreateLabelAtIndex(dm, ul->indices[l], ul->names[l]));
7930:     else PetscCall(DMCreateLabel(dm, ul->names[l]));
7931:   }
7932:   if (preserveOrder) {
7933:     for (l = 0; l < ul->Nl; ++l) {
7934:       const char *name;
7935:       PetscBool   match;

7937:       PetscCall(DMGetLabelName(dm, ul->indices[l], &name));
7938:       PetscCall(PetscStrcmp(name, ul->names[l], &match));
7939:       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]);
7940:     }
7941:   }
7942:   PetscFunctionReturn(PETSC_SUCCESS);
7943: }

7945: PetscErrorCode DMUniversalLabelSetLabelValue(DMUniversalLabel ul, DM dm, PetscBool useIndex, PetscInt p, PetscInt value)
7946: {
7947:   PetscInt l;

7949:   PetscFunctionBegin;
7950:   for (l = 0; l < ul->Nl; ++l) {
7951:     DMLabel  label;
7952:     PetscInt lval = (value & ul->masks[l]) >> ul->bits[l];

7954:     if (lval) {
7955:       if (useIndex) PetscCall(DMGetLabelByNum(dm, ul->indices[l], &label));
7956:       else PetscCall(DMGetLabel(dm, ul->names[l], &label));
7957:       PetscCall(DMLabelSetValue(label, p, ul->values[ul->offsets[l] + lval - 1]));
7958:     }
7959:   }
7960:   PetscFunctionReturn(PETSC_SUCCESS);
7961: }

7963: /*@
7964:   DMGetCoarseDM - Get the coarse `DM`from which this `DM` was obtained by refinement

7966:   Not Collective

7968:   Input Parameter:
7969: . dm - The `DM` object

7971:   Output Parameter:
7972: . cdm - The coarse `DM`

7974:   Level: intermediate

7976: .seealso: [](ch_dmbase), `DM`, `DMSetCoarseDM()`, `DMCoarsen()`
7977: @*/
7978: PetscErrorCode DMGetCoarseDM(DM dm, DM *cdm)
7979: {
7980:   PetscFunctionBegin;
7982:   PetscAssertPointer(cdm, 2);
7983:   *cdm = dm->coarseMesh;
7984:   PetscFunctionReturn(PETSC_SUCCESS);
7985: }

7987: /*@
7988:   DMSetCoarseDM - Set the coarse `DM` from which this `DM` was obtained by refinement

7990:   Input Parameters:
7991: + dm  - The `DM` object
7992: - cdm - The coarse `DM`

7994:   Level: intermediate

7996:   Note:
7997:   Normally this is set automatically by `DMRefine()`

7999: .seealso: [](ch_dmbase), `DM`, `DMGetCoarseDM()`, `DMCoarsen()`, `DMSetRefine()`, `DMSetFineDM()`
8000: @*/
8001: PetscErrorCode DMSetCoarseDM(DM dm, DM cdm)
8002: {
8003:   PetscFunctionBegin;
8006:   if (dm == cdm) cdm = NULL;
8007:   PetscCall(PetscObjectReference((PetscObject)cdm));
8008:   PetscCall(DMDestroy(&dm->coarseMesh));
8009:   dm->coarseMesh = cdm;
8010:   PetscFunctionReturn(PETSC_SUCCESS);
8011: }

8013: /*@
8014:   DMGetFineDM - Get the fine mesh from which this `DM` was obtained by coarsening

8016:   Input Parameter:
8017: . dm - The `DM` object

8019:   Output Parameter:
8020: . fdm - The fine `DM`

8022:   Level: intermediate

8024: .seealso: [](ch_dmbase), `DM`, `DMSetFineDM()`, `DMCoarsen()`, `DMRefine()`
8025: @*/
8026: PetscErrorCode DMGetFineDM(DM dm, DM *fdm)
8027: {
8028:   PetscFunctionBegin;
8030:   PetscAssertPointer(fdm, 2);
8031:   *fdm = dm->fineMesh;
8032:   PetscFunctionReturn(PETSC_SUCCESS);
8033: }

8035: /*@
8036:   DMSetFineDM - Set the fine mesh from which this was obtained by coarsening

8038:   Input Parameters:
8039: + dm  - The `DM` object
8040: - fdm - The fine `DM`

8042:   Level: developer

8044:   Note:
8045:   Normally this is set automatically by `DMCoarsen()`

8047: .seealso: [](ch_dmbase), `DM`, `DMGetFineDM()`, `DMCoarsen()`, `DMRefine()`
8048: @*/
8049: PetscErrorCode DMSetFineDM(DM dm, DM fdm)
8050: {
8051:   PetscFunctionBegin;
8054:   if (dm == fdm) fdm = NULL;
8055:   PetscCall(PetscObjectReference((PetscObject)fdm));
8056:   PetscCall(DMDestroy(&dm->fineMesh));
8057:   dm->fineMesh = fdm;
8058:   PetscFunctionReturn(PETSC_SUCCESS);
8059: }

8061: /*@C
8062:   DMAddBoundary - Add a boundary condition, for a single field, to a model represented by a `DM`

8064:   Collective

8066:   Input Parameters:
8067: + dm       - The `DM`, with a `PetscDS` that matches the problem being constrained
8068: . type     - The type of condition, e.g. `DM_BC_ESSENTIAL_ANALYTIC`, `DM_BC_ESSENTIAL_FIELD` (Dirichlet), or `DM_BC_NATURAL` (Neumann)
8069: . name     - The BC name
8070: . label    - The label defining constrained points
8071: . Nv       - The number of `DMLabel` values for constrained points
8072: . values   - An array of values for constrained points
8073: . field    - The field to constrain
8074: . Nc       - The number of constrained field components (0 will constrain all components)
8075: . comps    - An array of constrained component numbers
8076: . bcFunc   - A pointwise function giving boundary values
8077: . bcFunc_t - A pointwise function giving the time derivative of the boundary values, or `NULL`
8078: - ctx      - An optional user context for bcFunc

8080:   Output Parameter:
8081: . bd - (Optional) Boundary number

8083:   Options Database Keys:
8084: + -bc_NAME values     - Overrides the boundary ids for boundary named NAME
8085: - -bc_NAME_comp comps - Overrides the boundary components for boundary named NAME

8087:   Level: intermediate

8089:   Notes:
8090:   If the `DM` is of type `DMPLEX` and the field is of type `PetscFE`, then this function completes the label using `DMPlexLabelComplete()`.

8092:   Both bcFunc and bcFunc_t will depend on the boundary condition type. If the type if `DM_BC_ESSENTIAL`, then the calling sequence is\:
8093: .vb
8094:  void bcFunc(PetscInt dim, PetscReal time, const PetscReal x[], PetscInt Nc, PetscScalar bcval[])
8095: .ve

8097:   If the type is `DM_BC_ESSENTIAL_FIELD` or other _FIELD value, then the calling sequence is\:

8099: .vb
8100:   void bcFunc(PetscInt dim, PetscInt Nf, PetscInt NfAux,
8101:               const PetscInt uOff[], const PetscInt uOff_x[], const PetscScalar u[], const PetscScalar u_t[], const PetscScalar u_x[],
8102:               const PetscInt aOff[], const PetscInt aOff_x[], const PetscScalar a[], const PetscScalar a_t[], const PetscScalar a_x[],
8103:               PetscReal time, const PetscReal x[], PetscScalar bcval[])
8104: .ve
8105: + dim - the spatial dimension
8106: . Nf - the number of fields
8107: . uOff - the offset into u[] and u_t[] for each field
8108: . uOff_x - the offset into u_x[] for each field
8109: . u - each field evaluated at the current point
8110: . u_t - the time derivative of each field evaluated at the current point
8111: . u_x - the gradient of each field evaluated at the current point
8112: . aOff - the offset into a[] and a_t[] for each auxiliary field
8113: . aOff_x - the offset into a_x[] for each auxiliary field
8114: . a - each auxiliary field evaluated at the current point
8115: . a_t - the time derivative of each auxiliary field evaluated at the current point
8116: . a_x - the gradient of auxiliary each field evaluated at the current point
8117: . t - current time
8118: . x - coordinates of the current point
8119: . numConstants - number of constant parameters
8120: . constants - constant parameters
8121: - bcval - output values at the current point

8123: .seealso: [](ch_dmbase), `DM`, `DSGetBoundary()`, `PetscDSAddBoundary()`
8124: @*/
8125: 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)
8126: {
8127:   PetscDS ds;

8129:   PetscFunctionBegin;
8136:   PetscCheck(!dm->localSection, PetscObjectComm((PetscObject)dm), PETSC_ERR_ARG_WRONGSTATE, "Cannot add boundary to DM after creating local section");
8137:   PetscCall(DMGetDS(dm, &ds));
8138:   /* Complete label */
8139:   if (label) {
8140:     PetscObject  obj;
8141:     PetscClassId id;

8143:     PetscCall(DMGetField(dm, field, NULL, &obj));
8144:     PetscCall(PetscObjectGetClassId(obj, &id));
8145:     if (id == PETSCFE_CLASSID) {
8146:       DM plex;

8148:       PetscCall(DMConvert(dm, DMPLEX, &plex));
8149:       if (plex) PetscCall(DMPlexLabelComplete(plex, label));
8150:       PetscCall(DMDestroy(&plex));
8151:     }
8152:   }
8153:   PetscCall(PetscDSAddBoundary(ds, type, name, label, Nv, values, field, Nc, comps, bcFunc, bcFunc_t, ctx, bd));
8154:   PetscFunctionReturn(PETSC_SUCCESS);
8155: }

8157: /* TODO Remove this since now the structures are the same */
8158: static PetscErrorCode DMPopulateBoundary(DM dm)
8159: {
8160:   PetscDS     ds;
8161:   DMBoundary *lastnext;
8162:   DSBoundary  dsbound;

8164:   PetscFunctionBegin;
8165:   PetscCall(DMGetDS(dm, &ds));
8166:   dsbound = ds->boundary;
8167:   if (dm->boundary) {
8168:     DMBoundary next = dm->boundary;

8170:     /* quick check to see if the PetscDS has changed */
8171:     if (next->dsboundary == dsbound) PetscFunctionReturn(PETSC_SUCCESS);
8172:     /* the PetscDS has changed: tear down and rebuild */
8173:     while (next) {
8174:       DMBoundary b = next;

8176:       next = b->next;
8177:       PetscCall(PetscFree(b));
8178:     }
8179:     dm->boundary = NULL;
8180:   }

8182:   lastnext = &dm->boundary;
8183:   while (dsbound) {
8184:     DMBoundary dmbound;

8186:     PetscCall(PetscNew(&dmbound));
8187:     dmbound->dsboundary = dsbound;
8188:     dmbound->label      = dsbound->label;
8189:     /* push on the back instead of the front so that it is in the same order as in the PetscDS */
8190:     *lastnext = dmbound;
8191:     lastnext  = &dmbound->next;
8192:     dsbound   = dsbound->next;
8193:   }
8194:   PetscFunctionReturn(PETSC_SUCCESS);
8195: }

8197: /* TODO: missing manual page */
8198: PetscErrorCode DMIsBoundaryPoint(DM dm, PetscInt point, PetscBool *isBd)
8199: {
8200:   DMBoundary b;

8202:   PetscFunctionBegin;
8204:   PetscAssertPointer(isBd, 3);
8205:   *isBd = PETSC_FALSE;
8206:   PetscCall(DMPopulateBoundary(dm));
8207:   b = dm->boundary;
8208:   while (b && !*isBd) {
8209:     DMLabel    label = b->label;
8210:     DSBoundary dsb   = b->dsboundary;
8211:     PetscInt   i;

8213:     if (label) {
8214:       for (i = 0; i < dsb->Nv && !*isBd; ++i) PetscCall(DMLabelStratumHasPoint(label, dsb->values[i], point, isBd));
8215:     }
8216:     b = b->next;
8217:   }
8218:   PetscFunctionReturn(PETSC_SUCCESS);
8219: }

8221: /*@
8222:   DMHasBound - Determine whether a bound condition was specified

8224:   Logically collective

8226:   Input Parameter:
8227: . dm - The `DM`, with a `PetscDS` that matches the problem being constrained

8229:   Output Parameter:
8230: . hasBound - Flag indicating if a bound condition was specified

8232:   Level: intermediate

8234: .seealso: [](ch_dmbase), `DM`, `DSAddBoundary()`, `PetscDSAddBoundary()`
8235: @*/
8236: PetscErrorCode DMHasBound(DM dm, PetscBool *hasBound)
8237: {
8238:   PetscDS  ds;
8239:   PetscInt Nf, numBd;

8241:   PetscFunctionBegin;
8242:   *hasBound = PETSC_FALSE;
8243:   PetscCall(DMGetDS(dm, &ds));
8244:   PetscCall(PetscDSGetNumFields(ds, &Nf));
8245:   for (PetscInt f = 0; f < Nf; ++f) {
8246:     PetscSimplePointFn *lfunc, *ufunc;

8248:     PetscCall(PetscDSGetLowerBound(ds, f, &lfunc, NULL));
8249:     PetscCall(PetscDSGetUpperBound(ds, f, &ufunc, NULL));
8250:     if (lfunc || ufunc) *hasBound = PETSC_TRUE;
8251:   }

8253:   PetscCall(PetscDSGetNumBoundary(ds, &numBd));
8254:   PetscCall(PetscDSUpdateBoundaryLabels(ds, dm));
8255:   for (PetscInt b = 0; b < numBd; ++b) {
8256:     PetscWeakForm           wf;
8257:     DMBoundaryConditionType type;
8258:     const char             *name;
8259:     DMLabel                 label;
8260:     PetscInt                numids;
8261:     const PetscInt         *ids;
8262:     PetscInt                field, Nc;
8263:     const PetscInt         *comps;
8264:     PetscVoidFn            *bvfunc;
8265:     void                   *ctx;

8267:     PetscCall(PetscDSGetBoundary(ds, b, &wf, &type, &name, &label, &numids, &ids, &field, &Nc, &comps, &bvfunc, NULL, &ctx));
8268:     if (type == DM_BC_LOWER_BOUND || type == DM_BC_UPPER_BOUND) *hasBound = PETSC_TRUE;
8269:   }
8270:   PetscFunctionReturn(PETSC_SUCCESS);
8271: }

8273: /*@C
8274:   DMProjectFunction - This projects the given function into the function space provided by a `DM`, putting the coefficients in a global vector.

8276:   Collective

8278:   Input Parameters:
8279: + dm    - The `DM`
8280: . time  - The time
8281: . funcs - The coordinate functions to evaluate, one per field
8282: . ctxs  - Optional array of contexts to pass to each coordinate function.  ctxs itself may be null.
8283: - mode  - The insertion mode for values

8285:   Output Parameter:
8286: . X - vector

8288:   Calling sequence of `funcs`:
8289: + dim  - The spatial dimension
8290: . time - The time at which to sample
8291: . x    - The coordinates
8292: . Nc   - The number of components
8293: . u    - The output field values
8294: - ctx  - optional function context

8296:   Level: developer

8298:   Developer Notes:
8299:   This API is specific to only particular usage of `DM`

8301:   The notes need to provide some information about what has to be provided to the `DM` to be able to perform the computation.

8303: .seealso: [](ch_dmbase), `DM`, `DMProjectFunctionLocal()`, `DMProjectFunctionLabel()`, `DMComputeL2Diff()`
8304: @*/
8305: 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)
8306: {
8307:   Vec localX;

8309:   PetscFunctionBegin;
8311:   PetscCall(PetscLogEventBegin(DM_ProjectFunction, dm, X, 0, 0));
8312:   PetscCall(DMGetLocalVector(dm, &localX));
8313:   PetscCall(VecSet(localX, 0.));
8314:   PetscCall(DMProjectFunctionLocal(dm, time, funcs, ctxs, mode, localX));
8315:   PetscCall(DMLocalToGlobalBegin(dm, localX, mode, X));
8316:   PetscCall(DMLocalToGlobalEnd(dm, localX, mode, X));
8317:   PetscCall(DMRestoreLocalVector(dm, &localX));
8318:   PetscCall(PetscLogEventEnd(DM_ProjectFunction, dm, X, 0, 0));
8319:   PetscFunctionReturn(PETSC_SUCCESS);
8320: }

8322: /*@C
8323:   DMProjectFunctionLocal - This projects the given function into the function space provided by a `DM`, putting the coefficients in a local vector.

8325:   Not Collective

8327:   Input Parameters:
8328: + dm    - The `DM`
8329: . time  - The time
8330: . funcs - The coordinate functions to evaluate, one per field
8331: . ctxs  - Optional array of contexts to pass to each coordinate function.  ctxs itself may be null.
8332: - mode  - The insertion mode for values

8334:   Output Parameter:
8335: . localX - vector

8337:   Calling sequence of `funcs`:
8338: + dim  - The spatial dimension
8339: . time - The current timestep
8340: . x    - The coordinates
8341: . Nc   - The number of components
8342: . u    - The output field values
8343: - ctx  - optional function context

8345:   Level: developer

8347:   Developer Notes:
8348:   This API is specific to only particular usage of `DM`

8350:   The notes need to provide some information about what has to be provided to the `DM` to be able to perform the computation.

8352: .seealso: [](ch_dmbase), `DM`, `DMProjectFunction()`, `DMProjectFunctionLabel()`, `DMComputeL2Diff()`
8353: @*/
8354: 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)
8355: {
8356:   PetscFunctionBegin;
8359:   PetscUseTypeMethod(dm, projectfunctionlocal, time, funcs, ctxs, mode, localX);
8360:   PetscFunctionReturn(PETSC_SUCCESS);
8361: }

8363: /*@C
8364:   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.

8366:   Collective

8368:   Input Parameters:
8369: + dm     - The `DM`
8370: . time   - The time
8371: . numIds - The number of ids
8372: . ids    - The ids
8373: . Nc     - The number of components
8374: . comps  - The components
8375: . label  - The `DMLabel` selecting the portion of the mesh for projection
8376: . funcs  - The coordinate functions to evaluate, one per field
8377: . ctxs   - Optional array of contexts to pass to each coordinate function.  ctxs may be null.
8378: - mode   - The insertion mode for values

8380:   Output Parameter:
8381: . X - vector

8383:   Calling sequence of `funcs`:
8384: + dim  - The spatial dimension
8385: . time - The current timestep
8386: . x    - The coordinates
8387: . Nc   - The number of components
8388: . u    - The output field values
8389: - ctx  - optional function context

8391:   Level: developer

8393:   Developer Notes:
8394:   This API is specific to only particular usage of `DM`

8396:   The notes need to provide some information about what has to be provided to the `DM` to be able to perform the computation.

8398: .seealso: [](ch_dmbase), `DM`, `DMProjectFunction()`, `DMProjectFunctionLocal()`, `DMProjectFunctionLabelLocal()`, `DMComputeL2Diff()`
8399: @*/
8400: 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)
8401: {
8402:   Vec localX;

8404:   PetscFunctionBegin;
8406:   PetscCall(DMGetLocalVector(dm, &localX));
8407:   PetscCall(VecSet(localX, 0.));
8408:   PetscCall(DMProjectFunctionLabelLocal(dm, time, label, numIds, ids, Nc, comps, funcs, ctxs, mode, localX));
8409:   PetscCall(DMLocalToGlobalBegin(dm, localX, mode, X));
8410:   PetscCall(DMLocalToGlobalEnd(dm, localX, mode, X));
8411:   PetscCall(DMRestoreLocalVector(dm, &localX));
8412:   PetscFunctionReturn(PETSC_SUCCESS);
8413: }

8415: /*@C
8416:   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.

8418:   Not Collective

8420:   Input Parameters:
8421: + dm     - The `DM`
8422: . time   - The time
8423: . label  - The `DMLabel` selecting the portion of the mesh for projection
8424: . numIds - The number of ids
8425: . ids    - The ids
8426: . Nc     - The number of components
8427: . comps  - The components
8428: . funcs  - The coordinate functions to evaluate, one per field
8429: . ctxs   - Optional array of contexts to pass to each coordinate function.  ctxs itself may be null.
8430: - mode   - The insertion mode for values

8432:   Output Parameter:
8433: . localX - vector

8435:   Calling sequence of `funcs`:
8436: + dim  - The spatial dimension
8437: . time - The current time
8438: . x    - The coordinates
8439: . Nc   - The number of components
8440: . u    - The output field values
8441: - ctx  - optional function context

8443:   Level: developer

8445:   Developer Notes:
8446:   This API is specific to only particular usage of `DM`

8448:   The notes need to provide some information about what has to be provided to the `DM` to be able to perform the computation.

8450: .seealso: [](ch_dmbase), `DM`, `DMProjectFunction()`, `DMProjectFunctionLocal()`, `DMProjectFunctionLabel()`, `DMComputeL2Diff()`
8451: @*/
8452: 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)
8453: {
8454:   PetscFunctionBegin;
8457:   PetscUseTypeMethod(dm, projectfunctionlabellocal, time, label, numIds, ids, Nc, comps, funcs, ctxs, mode, localX);
8458:   PetscFunctionReturn(PETSC_SUCCESS);
8459: }

8461: /*@C
8462:   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.

8464:   Not Collective

8466:   Input Parameters:
8467: + dm     - The `DM`
8468: . time   - The time
8469: . localU - The input field vector; may be `NULL` if projection is defined purely by coordinates
8470: . funcs  - The functions to evaluate, one per field
8471: - mode   - The insertion mode for values

8473:   Output Parameter:
8474: . localX - The output vector

8476:   Calling sequence of `funcs`:
8477: + dim          - The spatial dimension
8478: . Nf           - The number of input fields
8479: . NfAux        - The number of input auxiliary fields
8480: . uOff         - The offset of each field in u[]
8481: . uOff_x       - The offset of each field in u_x[]
8482: . u            - The field values at this point in space
8483: . u_t          - The field time derivative at this point in space (or `NULL`)
8484: . u_x          - The field derivatives at this point in space
8485: . aOff         - The offset of each auxiliary field in u[]
8486: . aOff_x       - The offset of each auxiliary field in u_x[]
8487: . a            - The auxiliary field values at this point in space
8488: . a_t          - The auxiliary field time derivative at this point in space (or `NULL`)
8489: . a_x          - The auxiliary field derivatives at this point in space
8490: . t            - The current time
8491: . x            - The coordinates of this point
8492: . numConstants - The number of constants
8493: . constants    - The value of each constant
8494: - f            - The value of the function at this point in space

8496:   Level: intermediate

8498:   Note:
8499:   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.
8500:   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
8501:   a subdomain. You can also output a different number of fields than the input, with different discretizations. Last the auxiliary `DM`, attached to the
8502:   auxiliary field vector, which is attached to dm, can also be different. It can have a different topology, number of fields, and discretizations.

8504:   Developer Notes:
8505:   This API is specific to only particular usage of `DM`

8507:   The notes need to provide some information about what has to be provided to the `DM` to be able to perform the computation.

8509: .seealso: [](ch_dmbase), `DM`, `DMProjectField()`, `DMProjectFieldLabelLocal()`,
8510: `DMProjectFunction()`, `DMComputeL2Diff()`
8511: @*/
8512: 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)
8513: {
8514:   PetscFunctionBegin;
8518:   PetscUseTypeMethod(dm, projectfieldlocal, time, localU, funcs, mode, localX);
8519:   PetscFunctionReturn(PETSC_SUCCESS);
8520: }

8522: /*@C
8523:   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.

8525:   Not Collective

8527:   Input Parameters:
8528: + dm     - The `DM`
8529: . time   - The time
8530: . label  - The `DMLabel` marking the portion of the domain to output
8531: . numIds - The number of label ids to use
8532: . ids    - The label ids to use for marking
8533: . Nc     - The number of components to set in the output, or `PETSC_DETERMINE` for all components
8534: . comps  - The components to set in the output, or `NULL` for all components
8535: . localU - The input field vector
8536: . funcs  - The functions to evaluate, one per field
8537: - mode   - The insertion mode for values

8539:   Output Parameter:
8540: . localX - The output vector

8542:   Calling sequence of `funcs`:
8543: + dim          - The spatial dimension
8544: . Nf           - The number of input fields
8545: . NfAux        - The number of input auxiliary fields
8546: . uOff         - The offset of each field in u[]
8547: . uOff_x       - The offset of each field in u_x[]
8548: . u            - The field values at this point in space
8549: . u_t          - The field time derivative at this point in space (or `NULL`)
8550: . u_x          - The field derivatives at this point in space
8551: . aOff         - The offset of each auxiliary field in u[]
8552: . aOff_x       - The offset of each auxiliary field in u_x[]
8553: . a            - The auxiliary field values at this point in space
8554: . a_t          - The auxiliary field time derivative at this point in space (or `NULL`)
8555: . a_x          - The auxiliary field derivatives at this point in space
8556: . t            - The current time
8557: . x            - The coordinates of this point
8558: . numConstants - The number of constants
8559: . constants    - The value of each constant
8560: - f            - The value of the function at this point in space

8562:   Level: intermediate

8564:   Note:
8565:   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.
8566:   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
8567:   a subdomain. You can also output a different number of fields than the input, with different discretizations. Last the auxiliary `DM`, attached to the
8568:   auxiliary field vector, which is attached to dm, can also be different. It can have a different topology, number of fields, and discretizations.

8570:   Developer Notes:
8571:   This API is specific to only particular usage of `DM`

8573:   The notes need to provide some information about what has to be provided to the `DM` to be able to perform the computation.

8575: .seealso: [](ch_dmbase), `DM`, `DMProjectField()`, `DMProjectFieldLabel()`, `DMProjectFunction()`, `DMComputeL2Diff()`
8576: @*/
8577: 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)
8578: {
8579:   PetscFunctionBegin;
8583:   PetscUseTypeMethod(dm, projectfieldlabellocal, time, label, numIds, ids, Nc, comps, localU, funcs, mode, localX);
8584:   PetscFunctionReturn(PETSC_SUCCESS);
8585: }

8587: /*@C
8588:   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.

8590:   Not Collective

8592:   Input Parameters:
8593: + dm     - The `DM`
8594: . time   - The time
8595: . label  - The `DMLabel` marking the portion of the domain to output
8596: . numIds - The number of label ids to use
8597: . ids    - The label ids to use for marking
8598: . Nc     - The number of components to set in the output, or `PETSC_DETERMINE` for all components
8599: . comps  - The components to set in the output, or `NULL` for all components
8600: . U      - The input field vector
8601: . funcs  - The functions to evaluate, one per field
8602: - mode   - The insertion mode for values

8604:   Output Parameter:
8605: . X - The output vector

8607:   Calling sequence of `funcs`:
8608: + dim          - The spatial dimension
8609: . Nf           - The number of input fields
8610: . NfAux        - The number of input auxiliary fields
8611: . uOff         - The offset of each field in u[]
8612: . uOff_x       - The offset of each field in u_x[]
8613: . u            - The field values at this point in space
8614: . u_t          - The field time derivative at this point in space (or `NULL`)
8615: . u_x          - The field derivatives at this point in space
8616: . aOff         - The offset of each auxiliary field in u[]
8617: . aOff_x       - The offset of each auxiliary field in u_x[]
8618: . a            - The auxiliary field values at this point in space
8619: . a_t          - The auxiliary field time derivative at this point in space (or `NULL`)
8620: . a_x          - The auxiliary field derivatives at this point in space
8621: . t            - The current time
8622: . x            - The coordinates of this point
8623: . numConstants - The number of constants
8624: . constants    - The value of each constant
8625: - f            - The value of the function at this point in space

8627:   Level: intermediate

8629:   Note:
8630:   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.
8631:   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
8632:   a subdomain. You can also output a different number of fields than the input, with different discretizations. Last the auxiliary `DM`, attached to the
8633:   auxiliary field vector, which is attached to dm, can also be different. It can have a different topology, number of fields, and discretizations.

8635:   Developer Notes:
8636:   This API is specific to only particular usage of `DM`

8638:   The notes need to provide some information about what has to be provided to the `DM` to be able to perform the computation.

8640: .seealso: [](ch_dmbase), `DM`, `DMProjectField()`, `DMProjectFieldLabelLocal()`, `DMProjectFunction()`, `DMComputeL2Diff()`
8641: @*/
8642: 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)
8643: {
8644:   DM  dmIn;
8645:   Vec localU, localX;

8647:   PetscFunctionBegin;
8649:   PetscCall(VecGetDM(U, &dmIn));
8650:   PetscCall(DMGetLocalVector(dmIn, &localU));
8651:   PetscCall(DMGetLocalVector(dm, &localX));
8652:   PetscCall(VecSet(localX, 0.));
8653:   PetscCall(DMGlobalToLocalBegin(dmIn, U, mode, localU));
8654:   PetscCall(DMGlobalToLocalEnd(dmIn, U, mode, localU));
8655:   PetscCall(DMProjectFieldLabelLocal(dm, time, label, numIds, ids, Nc, comps, localU, funcs, mode, localX));
8656:   PetscCall(DMLocalToGlobalBegin(dm, localX, mode, X));
8657:   PetscCall(DMLocalToGlobalEnd(dm, localX, mode, X));
8658:   PetscCall(DMRestoreLocalVector(dm, &localX));
8659:   PetscCall(DMRestoreLocalVector(dmIn, &localU));
8660:   PetscFunctionReturn(PETSC_SUCCESS);
8661: }

8663: /*@C
8664:   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.

8666:   Not Collective

8668:   Input Parameters:
8669: + dm     - The `DM`
8670: . time   - The time
8671: . label  - The `DMLabel` marking the portion of the domain boundary to output
8672: . numIds - The number of label ids to use
8673: . ids    - The label ids to use for marking
8674: . Nc     - The number of components to set in the output, or `PETSC_DETERMINE` for all components
8675: . comps  - The components to set in the output, or `NULL` for all components
8676: . localU - The input field vector
8677: . funcs  - The functions to evaluate, one per field
8678: - mode   - The insertion mode for values

8680:   Output Parameter:
8681: . localX - The output vector

8683:   Calling sequence of `funcs`:
8684: + dim          - The spatial dimension
8685: . Nf           - The number of input fields
8686: . NfAux        - The number of input auxiliary fields
8687: . uOff         - The offset of each field in u[]
8688: . uOff_x       - The offset of each field in u_x[]
8689: . u            - The field values at this point in space
8690: . u_t          - The field time derivative at this point in space (or `NULL`)
8691: . u_x          - The field derivatives at this point in space
8692: . aOff         - The offset of each auxiliary field in u[]
8693: . aOff_x       - The offset of each auxiliary field in u_x[]
8694: . a            - The auxiliary field values at this point in space
8695: . a_t          - The auxiliary field time derivative at this point in space (or `NULL`)
8696: . a_x          - The auxiliary field derivatives at this point in space
8697: . t            - The current time
8698: . x            - The coordinates of this point
8699: . n            - The face normal
8700: . numConstants - The number of constants
8701: . constants    - The value of each constant
8702: - f            - The value of the function at this point in space

8704:   Level: intermediate

8706:   Note:
8707:   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.
8708:   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
8709:   a subdomain. You can also output a different number of fields than the input, with different discretizations. Last the auxiliary `DM`, attached to the
8710:   auxiliary field vector, which is attached to dm, can also be different. It can have a different topology, number of fields, and discretizations.

8712:   Developer Notes:
8713:   This API is specific to only particular usage of `DM`

8715:   The notes need to provide some information about what has to be provided to the `DM` to be able to perform the computation.

8717: .seealso: [](ch_dmbase), `DM`, `DMProjectField()`, `DMProjectFieldLabelLocal()`, `DMProjectFunction()`, `DMComputeL2Diff()`
8718: @*/
8719: 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)
8720: {
8721:   PetscFunctionBegin;
8725:   PetscUseTypeMethod(dm, projectbdfieldlabellocal, time, label, numIds, ids, Nc, comps, localU, funcs, mode, localX);
8726:   PetscFunctionReturn(PETSC_SUCCESS);
8727: }

8729: /*@C
8730:   DMComputeL2Diff - This function computes the L_2 difference between a function u and an FEM interpolant solution u_h.

8732:   Collective

8734:   Input Parameters:
8735: + dm    - The `DM`
8736: . time  - The time
8737: . funcs - The functions to evaluate for each field component
8738: . ctxs  - Optional array of contexts to pass to each function, or `NULL`.
8739: - X     - The coefficient vector u_h, a global vector

8741:   Output Parameter:
8742: . diff - The diff ||u - u_h||_2

8744:   Level: developer

8746:   Developer Notes:
8747:   This API is specific to only particular usage of `DM`

8749:   The notes need to provide some information about what has to be provided to the `DM` to be able to perform the computation.

8751: .seealso: [](ch_dmbase), `DM`, `DMProjectFunction()`, `DMComputeL2FieldDiff()`, `DMComputeL2GradientDiff()`
8752: @*/
8753: PetscErrorCode DMComputeL2Diff(DM dm, PetscReal time, PetscErrorCode (**funcs)(PetscInt, PetscReal, const PetscReal[], PetscInt, PetscScalar *, void *), void **ctxs, Vec X, PetscReal *diff)
8754: {
8755:   PetscFunctionBegin;
8758:   PetscUseTypeMethod(dm, computel2diff, time, funcs, ctxs, X, diff);
8759:   PetscFunctionReturn(PETSC_SUCCESS);
8760: }

8762: /*@C
8763:   DMComputeL2GradientDiff - This function computes the L_2 difference between the gradient of a function u and an FEM interpolant solution grad u_h.

8765:   Collective

8767:   Input Parameters:
8768: + dm    - The `DM`
8769: . time  - The time
8770: . funcs - The gradient functions to evaluate for each field component
8771: . ctxs  - Optional array of contexts to pass to each function, or `NULL`.
8772: . X     - The coefficient vector u_h, a global vector
8773: - n     - The vector to project along

8775:   Output Parameter:
8776: . diff - The diff ||(grad u - grad u_h) . n||_2

8778:   Level: developer

8780:   Developer Notes:
8781:   This API is specific to only particular usage of `DM`

8783:   The notes need to provide some information about what has to be provided to the `DM` to be able to perform the computation.

8785: .seealso: [](ch_dmbase), `DM`, `DMProjectFunction()`, `DMComputeL2Diff()`, `DMComputeL2FieldDiff()`
8786: @*/
8787: 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)
8788: {
8789:   PetscFunctionBegin;
8792:   PetscUseTypeMethod(dm, computel2gradientdiff, time, funcs, ctxs, X, n, diff);
8793:   PetscFunctionReturn(PETSC_SUCCESS);
8794: }

8796: /*@C
8797:   DMComputeL2FieldDiff - This function computes the L_2 difference between a function u and an FEM interpolant solution u_h, separated into field components.

8799:   Collective

8801:   Input Parameters:
8802: + dm    - The `DM`
8803: . time  - The time
8804: . funcs - The functions to evaluate for each field component
8805: . ctxs  - Optional array of contexts to pass to each function, or `NULL`.
8806: - X     - The coefficient vector u_h, a global vector

8808:   Output Parameter:
8809: . diff - The array of differences, ||u^f - u^f_h||_2

8811:   Level: developer

8813:   Developer Notes:
8814:   This API is specific to only particular usage of `DM`

8816:   The notes need to provide some information about what has to be provided to the `DM` to be able to perform the computation.

8818: .seealso: [](ch_dmbase), `DM`, `DMProjectFunction()`, `DMComputeL2GradientDiff()`
8819: @*/
8820: PetscErrorCode DMComputeL2FieldDiff(DM dm, PetscReal time, PetscErrorCode (**funcs)(PetscInt, PetscReal, const PetscReal[], PetscInt, PetscScalar *, void *), void **ctxs, Vec X, PetscReal diff[])
8821: {
8822:   PetscFunctionBegin;
8825:   PetscUseTypeMethod(dm, computel2fielddiff, time, funcs, ctxs, X, diff);
8826:   PetscFunctionReturn(PETSC_SUCCESS);
8827: }

8829: /*@C
8830:   DMGetNeighbors - Gets an array containing the MPI ranks of all the processes neighbors

8832:   Not Collective

8834:   Input Parameter:
8835: . dm - The `DM`

8837:   Output Parameters:
8838: + nranks - the number of neighbours
8839: - ranks  - the neighbors ranks

8841:   Level: beginner

8843:   Note:
8844:   Do not free the array, it is freed when the `DM` is destroyed.

8846: .seealso: [](ch_dmbase), `DM`, `DMDAGetNeighbors()`, `PetscSFGetRootRanks()`
8847: @*/
8848: PetscErrorCode DMGetNeighbors(DM dm, PetscInt *nranks, const PetscMPIInt *ranks[])
8849: {
8850:   PetscFunctionBegin;
8852:   PetscUseTypeMethod(dm, getneighbors, nranks, ranks);
8853:   PetscFunctionReturn(PETSC_SUCCESS);
8854: }

8856: #include <petsc/private/matimpl.h>

8858: /*
8859:     Converts the input vector to a ghosted vector and then calls the standard coloring code.
8860:     This must be a different function because it requires DM which is not defined in the Mat library
8861: */
8862: static PetscErrorCode MatFDColoringApply_AIJDM(Mat J, MatFDColoring coloring, Vec x1, void *sctx)
8863: {
8864:   PetscFunctionBegin;
8865:   if (coloring->ctype == IS_COLORING_LOCAL) {
8866:     Vec x1local;
8867:     DM  dm;
8868:     PetscCall(MatGetDM(J, &dm));
8869:     PetscCheck(dm, PetscObjectComm((PetscObject)J), PETSC_ERR_ARG_INCOMP, "IS_COLORING_LOCAL requires a DM");
8870:     PetscCall(DMGetLocalVector(dm, &x1local));
8871:     PetscCall(DMGlobalToLocalBegin(dm, x1, INSERT_VALUES, x1local));
8872:     PetscCall(DMGlobalToLocalEnd(dm, x1, INSERT_VALUES, x1local));
8873:     x1 = x1local;
8874:   }
8875:   PetscCall(MatFDColoringApply_AIJ(J, coloring, x1, sctx));
8876:   if (coloring->ctype == IS_COLORING_LOCAL) {
8877:     DM dm;
8878:     PetscCall(MatGetDM(J, &dm));
8879:     PetscCall(DMRestoreLocalVector(dm, &x1));
8880:   }
8881:   PetscFunctionReturn(PETSC_SUCCESS);
8882: }

8884: /*@
8885:   MatFDColoringUseDM - allows a `MatFDColoring` object to use the `DM` associated with the matrix to compute a `IS_COLORING_LOCAL` coloring

8887:   Input Parameters:
8888: + coloring   - The matrix to get the `DM` from
8889: - fdcoloring - the `MatFDColoring` object

8891:   Level: advanced

8893:   Developer Note:
8894:   This routine exists because the PETSc `Mat` library does not know about the `DM` objects

8896: .seealso: [](ch_dmbase), `DM`, `MatFDColoring`, `MatFDColoringCreate()`, `ISColoringType`
8897: @*/
8898: PetscErrorCode MatFDColoringUseDM(Mat coloring, MatFDColoring fdcoloring)
8899: {
8900:   PetscFunctionBegin;
8901:   coloring->ops->fdcoloringapply = MatFDColoringApply_AIJDM;
8902:   PetscFunctionReturn(PETSC_SUCCESS);
8903: }

8905: /*@
8906:   DMGetCompatibility - determine if two `DM`s are compatible

8908:   Collective

8910:   Input Parameters:
8911: + dm1 - the first `DM`
8912: - dm2 - the second `DM`

8914:   Output Parameters:
8915: + compatible - whether or not the two `DM`s are compatible
8916: - set        - whether or not the compatible value was actually determined and set

8918:   Level: advanced

8920:   Notes:
8921:   Two `DM`s are deemed compatible if they represent the same parallel decomposition
8922:   of the same topology. This implies that the section (field data) on one
8923:   "makes sense" with respect to the topology and parallel decomposition of the other.
8924:   Loosely speaking, compatible `DM`s represent the same domain and parallel
8925:   decomposition, but hold different data.

8927:   Typically, one would confirm compatibility if intending to simultaneously iterate
8928:   over a pair of vectors obtained from different `DM`s.

8930:   For example, two `DMDA` objects are compatible if they have the same local
8931:   and global sizes and the same stencil width. They can have different numbers
8932:   of degrees of freedom per node. Thus, one could use the node numbering from
8933:   either `DM` in bounds for a loop over vectors derived from either `DM`.

8935:   Consider the operation of summing data living on a 2-dof `DMDA` to data living
8936:   on a 1-dof `DMDA`, which should be compatible, as in the following snippet.
8937: .vb
8938:   ...
8939:   PetscCall(DMGetCompatibility(da1,da2,&compatible,&set));
8940:   if (set && compatible)  {
8941:     PetscCall(DMDAVecGetArrayDOF(da1,vec1,&arr1));
8942:     PetscCall(DMDAVecGetArrayDOF(da2,vec2,&arr2));
8943:     PetscCall(DMDAGetCorners(da1,&x,&y,NULL,&m,&n,NULL));
8944:     for (j=y; j<y+n; ++j) {
8945:       for (i=x; i<x+m, ++i) {
8946:         arr1[j][i][0] = arr2[j][i][0] + arr2[j][i][1];
8947:       }
8948:     }
8949:     PetscCall(DMDAVecRestoreArrayDOF(da1,vec1,&arr1));
8950:     PetscCall(DMDAVecRestoreArrayDOF(da2,vec2,&arr2));
8951:   } else {
8952:     SETERRQ(PetscObjectComm((PetscObject)da1,PETSC_ERR_ARG_INCOMP,"DMDA objects incompatible");
8953:   }
8954:   ...
8955: .ve

8957:   Checking compatibility might be expensive for a given implementation of `DM`,
8958:   or might be impossible to unambiguously confirm or deny. For this reason,
8959:   this function may decline to determine compatibility, and hence users should
8960:   always check the "set" output parameter.

8962:   A `DM` is always compatible with itself.

8964:   In the current implementation, `DM`s which live on "unequal" communicators
8965:   (MPI_UNEQUAL in the terminology of MPI_Comm_compare()) are always deemed
8966:   incompatible.

8968:   This function is labeled "Collective," as information about all subdomains
8969:   is required on each rank. However, in `DM` implementations which store all this
8970:   information locally, this function may be merely "Logically Collective".

8972:   Developer Note:
8973:   Compatibility is assumed to be a symmetric concept; `DM` A is compatible with `DM` B
8974:   iff B is compatible with A. Thus, this function checks the implementations
8975:   of both dm and dmc (if they are of different types), attempting to determine
8976:   compatibility. It is left to `DM` implementers to ensure that symmetry is
8977:   preserved. The simplest way to do this is, when implementing type-specific
8978:   logic for this function, is to check for existing logic in the implementation
8979:   of other `DM` types and let *set = PETSC_FALSE if found.

8981: .seealso: [](ch_dmbase), `DM`, `DMDACreateCompatibleDMDA()`, `DMStagCreateCompatibleDMStag()`
8982: @*/
8983: PetscErrorCode DMGetCompatibility(DM dm1, DM dm2, PetscBool *compatible, PetscBool *set)
8984: {
8985:   PetscMPIInt compareResult;
8986:   DMType      type, type2;
8987:   PetscBool   sameType;

8989:   PetscFunctionBegin;

8993:   /* Declare a DM compatible with itself */
8994:   if (dm1 == dm2) {
8995:     *set        = PETSC_TRUE;
8996:     *compatible = PETSC_TRUE;
8997:     PetscFunctionReturn(PETSC_SUCCESS);
8998:   }

9000:   /* Declare a DM incompatible with a DM that lives on an "unequal"
9001:      communicator. Note that this does not preclude compatibility with
9002:      DMs living on "congruent" or "similar" communicators, but this must be
9003:      determined by the implementation-specific logic */
9004:   PetscCallMPI(MPI_Comm_compare(PetscObjectComm((PetscObject)dm1), PetscObjectComm((PetscObject)dm2), &compareResult));
9005:   if (compareResult == MPI_UNEQUAL) {
9006:     *set        = PETSC_TRUE;
9007:     *compatible = PETSC_FALSE;
9008:     PetscFunctionReturn(PETSC_SUCCESS);
9009:   }

9011:   /* Pass to the implementation-specific routine, if one exists. */
9012:   if (dm1->ops->getcompatibility) {
9013:     PetscUseTypeMethod(dm1, getcompatibility, dm2, compatible, set);
9014:     if (*set) PetscFunctionReturn(PETSC_SUCCESS);
9015:   }

9017:   /* If dm1 and dm2 are of different types, then attempt to check compatibility
9018:      with an implementation of this function from dm2 */
9019:   PetscCall(DMGetType(dm1, &type));
9020:   PetscCall(DMGetType(dm2, &type2));
9021:   PetscCall(PetscStrcmp(type, type2, &sameType));
9022:   if (!sameType && dm2->ops->getcompatibility) {
9023:     PetscUseTypeMethod(dm2, getcompatibility, dm1, compatible, set); /* Note argument order */
9024:   } else {
9025:     *set = PETSC_FALSE;
9026:   }
9027:   PetscFunctionReturn(PETSC_SUCCESS);
9028: }

9030: /*@C
9031:   DMMonitorSet - Sets an additional monitor function that is to be used after a solve to monitor discretization performance.

9033:   Logically Collective

9035:   Input Parameters:
9036: + dm             - the `DM`
9037: . f              - the monitor function
9038: . mctx           - [optional] context for private data for the monitor routine (use `NULL` if no context is desired)
9039: - monitordestroy - [optional] routine that frees monitor context (may be `NULL`), see `PetscCtxDestroyFn` for the calling sequence

9041:   Options Database Key:
9042: . -dm_monitor_cancel - cancels all monitors that have been hardwired into a code by calls to `DMMonitorSet()`, but
9043:                        does not cancel those set via the options database.

9045:   Level: intermediate

9047:   Note:
9048:   Several different monitoring routines may be set by calling
9049:   `DMMonitorSet()` multiple times or with `DMMonitorSetFromOptions()`; all will be called in the
9050:   order in which they were set.

9052:   Fortran Note:
9053:   Only a single monitor function can be set for each `DM` object

9055:   Developer Note:
9056:   This API has a generic name but seems specific to a very particular aspect of the use of `DM`

9058: .seealso: [](ch_dmbase), `DM`, `DMMonitorCancel()`, `DMMonitorSetFromOptions()`, `DMMonitor()`, `PetscCtxDestroyFn`
9059: @*/
9060: PetscErrorCode DMMonitorSet(DM dm, PetscErrorCode (*f)(DM, void *), void *mctx, PetscCtxDestroyFn *monitordestroy)
9061: {
9062:   PetscFunctionBegin;
9064:   for (PetscInt m = 0; m < dm->numbermonitors; ++m) {
9065:     PetscBool identical;

9067:     PetscCall(PetscMonitorCompare((PetscErrorCode (*)(void))(PetscVoidFn *)f, mctx, monitordestroy, (PetscErrorCode (*)(void))(PetscVoidFn *)dm->monitor[m], dm->monitorcontext[m], dm->monitordestroy[m], &identical));
9068:     if (identical) PetscFunctionReturn(PETSC_SUCCESS);
9069:   }
9070:   PetscCheck(dm->numbermonitors < MAXDMMONITORS, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Too many monitors set");
9071:   dm->monitor[dm->numbermonitors]          = f;
9072:   dm->monitordestroy[dm->numbermonitors]   = monitordestroy;
9073:   dm->monitorcontext[dm->numbermonitors++] = mctx;
9074:   PetscFunctionReturn(PETSC_SUCCESS);
9075: }

9077: /*@
9078:   DMMonitorCancel - Clears all the monitor functions for a `DM` object.

9080:   Logically Collective

9082:   Input Parameter:
9083: . dm - the DM

9085:   Options Database Key:
9086: . -dm_monitor_cancel - cancels all monitors that have been hardwired
9087:   into a code by calls to `DMonitorSet()`, but does not cancel those
9088:   set via the options database

9090:   Level: intermediate

9092:   Note:
9093:   There is no way to clear one specific monitor from a `DM` object.

9095: .seealso: [](ch_dmbase), `DM`, `DMMonitorSet()`, `DMMonitorSetFromOptions()`, `DMMonitor()`
9096: @*/
9097: PetscErrorCode DMMonitorCancel(DM dm)
9098: {
9099:   PetscInt m;

9101:   PetscFunctionBegin;
9103:   for (m = 0; m < dm->numbermonitors; ++m) {
9104:     if (dm->monitordestroy[m]) PetscCall((*dm->monitordestroy[m])(&dm->monitorcontext[m]));
9105:   }
9106:   dm->numbermonitors = 0;
9107:   PetscFunctionReturn(PETSC_SUCCESS);
9108: }

9110: /*@C
9111:   DMMonitorSetFromOptions - Sets a monitor function and viewer appropriate for the type indicated by the user

9113:   Collective

9115:   Input Parameters:
9116: + dm           - `DM` object you wish to monitor
9117: . name         - the monitor type one is seeking
9118: . help         - message indicating what monitoring is done
9119: . manual       - manual page for the monitor
9120: . monitor      - the monitor function, this must use a `PetscViewerFormat` as its context
9121: - 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

9123:   Output Parameter:
9124: . flg - Flag set if the monitor was created

9126:   Calling sequence of `monitor`:
9127: + dm  - the `DM` to be monitored
9128: - ctx - monitor context

9130:   Calling sequence of `monitorsetup`:
9131: + dm - the `DM` to be monitored
9132: - vf - the `PetscViewer` and format to be used by the monitor

9134:   Level: developer

9136: .seealso: [](ch_dmbase), `DM`, `PetscOptionsCreateViewer()`, `PetscOptionsGetReal()`, `PetscOptionsHasName()`, `PetscOptionsGetString()`,
9137:           `PetscOptionsGetIntArray()`, `PetscOptionsGetRealArray()`, `PetscOptionsBool()`,
9138:           `PetscOptionsInt()`, `PetscOptionsString()`, `PetscOptionsReal()`,
9139:           `PetscOptionsName()`, `PetscOptionsBegin()`, `PetscOptionsEnd()`, `PetscOptionsHeadBegin()`,
9140:           `PetscOptionsStringArray()`, `PetscOptionsRealArray()`, `PetscOptionsScalar()`,
9141:           `PetscOptionsBoolGroupBegin()`, `PetscOptionsBoolGroup()`, `PetscOptionsBoolGroupEnd()`,
9142:           `PetscOptionsFList()`, `PetscOptionsEList()`, `DMMonitor()`, `DMMonitorSet()`
9143: @*/
9144: 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)
9145: {
9146:   PetscViewer       viewer;
9147:   PetscViewerFormat format;

9149:   PetscFunctionBegin;
9151:   PetscCall(PetscOptionsCreateViewer(PetscObjectComm((PetscObject)dm), ((PetscObject)dm)->options, ((PetscObject)dm)->prefix, name, &viewer, &format, flg));
9152:   if (*flg) {
9153:     PetscViewerAndFormat *vf;

9155:     PetscCall(PetscViewerAndFormatCreate(viewer, format, &vf));
9156:     PetscCall(PetscViewerDestroy(&viewer));
9157:     if (monitorsetup) PetscCall((*monitorsetup)(dm, vf));
9158:     PetscCall(DMMonitorSet(dm, monitor, vf, (PetscCtxDestroyFn *)PetscViewerAndFormatDestroy));
9159:   }
9160:   PetscFunctionReturn(PETSC_SUCCESS);
9161: }

9163: /*@
9164:   DMMonitor - runs the user provided monitor routines, if they exist

9166:   Collective

9168:   Input Parameter:
9169: . dm - The `DM`

9171:   Level: developer

9173:   Developer Note:
9174:   Note should indicate when during the life of the `DM` the monitor is run. It appears to be
9175:   related to the discretization process seems rather specialized since some `DM` have no
9176:   concept of discretization.

9178: .seealso: [](ch_dmbase), `DM`, `DMMonitorSet()`, `DMMonitorSetFromOptions()`
9179: @*/
9180: PetscErrorCode DMMonitor(DM dm)
9181: {
9182:   PetscInt m;

9184:   PetscFunctionBegin;
9185:   if (!dm) PetscFunctionReturn(PETSC_SUCCESS);
9187:   for (m = 0; m < dm->numbermonitors; ++m) PetscCall((*dm->monitor[m])(dm, dm->monitorcontext[m]));
9188:   PetscFunctionReturn(PETSC_SUCCESS);
9189: }

9191: /*@
9192:   DMComputeError - Computes the error assuming the user has provided the exact solution functions

9194:   Collective

9196:   Input Parameters:
9197: + dm  - The `DM`
9198: - sol - The solution vector

9200:   Input/Output Parameter:
9201: . errors - An array of length Nf, the number of fields, or `NULL` for no output; on output
9202:            contains the error in each field

9204:   Output Parameter:
9205: . errorVec - A vector to hold the cellwise error (may be `NULL`)

9207:   Level: developer

9209:   Note:
9210:   The exact solutions come from the `PetscDS` object, and the time comes from `DMGetOutputSequenceNumber()`.

9212: .seealso: [](ch_dmbase), `DM`, `DMMonitorSet()`, `DMGetRegionNumDS()`, `PetscDSGetExactSolution()`, `DMGetOutputSequenceNumber()`
9213: @*/
9214: PetscErrorCode DMComputeError(DM dm, Vec sol, PetscReal errors[], Vec *errorVec)
9215: {
9216:   PetscErrorCode (**exactSol)(PetscInt, PetscReal, const PetscReal[], PetscInt, PetscScalar[], void *);
9217:   void    **ctxs;
9218:   PetscReal time;
9219:   PetscInt  Nf, f, Nds, s;

9221:   PetscFunctionBegin;
9222:   PetscCall(DMGetNumFields(dm, &Nf));
9223:   PetscCall(PetscCalloc2(Nf, &exactSol, Nf, &ctxs));
9224:   PetscCall(DMGetNumDS(dm, &Nds));
9225:   for (s = 0; s < Nds; ++s) {
9226:     PetscDS         ds;
9227:     DMLabel         label;
9228:     IS              fieldIS;
9229:     const PetscInt *fields;
9230:     PetscInt        dsNf;

9232:     PetscCall(DMGetRegionNumDS(dm, s, &label, &fieldIS, &ds, NULL));
9233:     PetscCall(PetscDSGetNumFields(ds, &dsNf));
9234:     if (fieldIS) PetscCall(ISGetIndices(fieldIS, &fields));
9235:     for (f = 0; f < dsNf; ++f) {
9236:       const PetscInt field = fields[f];
9237:       PetscCall(PetscDSGetExactSolution(ds, field, &exactSol[field], &ctxs[field]));
9238:     }
9239:     if (fieldIS) PetscCall(ISRestoreIndices(fieldIS, &fields));
9240:   }
9241:   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);
9242:   PetscCall(DMGetOutputSequenceNumber(dm, NULL, &time));
9243:   if (errors) PetscCall(DMComputeL2FieldDiff(dm, time, exactSol, ctxs, sol, errors));
9244:   if (errorVec) {
9245:     DM             edm;
9246:     DMPolytopeType ct;
9247:     PetscBool      simplex;
9248:     PetscInt       dim, cStart, Nf;

9250:     PetscCall(DMClone(dm, &edm));
9251:     PetscCall(DMGetDimension(edm, &dim));
9252:     PetscCall(DMPlexGetHeightStratum(dm, 0, &cStart, NULL));
9253:     PetscCall(DMPlexGetCellType(dm, cStart, &ct));
9254:     simplex = DMPolytopeTypeGetNumVertices(ct) == DMPolytopeTypeGetDim(ct) + 1 ? PETSC_TRUE : PETSC_FALSE;
9255:     PetscCall(DMGetNumFields(dm, &Nf));
9256:     for (f = 0; f < Nf; ++f) {
9257:       PetscFE         fe, efe;
9258:       PetscQuadrature q;
9259:       const char     *name;

9261:       PetscCall(DMGetField(dm, f, NULL, (PetscObject *)&fe));
9262:       PetscCall(PetscFECreateLagrange(PETSC_COMM_SELF, dim, Nf, simplex, 0, PETSC_DETERMINE, &efe));
9263:       PetscCall(PetscObjectGetName((PetscObject)fe, &name));
9264:       PetscCall(PetscObjectSetName((PetscObject)efe, name));
9265:       PetscCall(PetscFEGetQuadrature(fe, &q));
9266:       PetscCall(PetscFESetQuadrature(efe, q));
9267:       PetscCall(DMSetField(edm, f, NULL, (PetscObject)efe));
9268:       PetscCall(PetscFEDestroy(&efe));
9269:     }
9270:     PetscCall(DMCreateDS(edm));

9272:     PetscCall(DMCreateGlobalVector(edm, errorVec));
9273:     PetscCall(PetscObjectSetName((PetscObject)*errorVec, "Error"));
9274:     PetscCall(DMPlexComputeL2DiffVec(dm, time, exactSol, ctxs, sol, *errorVec));
9275:     PetscCall(DMDestroy(&edm));
9276:   }
9277:   PetscCall(PetscFree2(exactSol, ctxs));
9278:   PetscFunctionReturn(PETSC_SUCCESS);
9279: }

9281: /*@
9282:   DMGetNumAuxiliaryVec - Get the number of auxiliary vectors associated with this `DM`

9284:   Not Collective

9286:   Input Parameter:
9287: . dm - The `DM`

9289:   Output Parameter:
9290: . numAux - The number of auxiliary data vectors

9292:   Level: advanced

9294: .seealso: [](ch_dmbase), `DM`, `DMClearAuxiliaryVec()`, `DMSetAuxiliaryVec()`, `DMGetAuxiliaryLabels()`, `DMGetAuxiliaryVec()`
9295: @*/
9296: PetscErrorCode DMGetNumAuxiliaryVec(DM dm, PetscInt *numAux)
9297: {
9298:   PetscFunctionBegin;
9300:   PetscCall(PetscHMapAuxGetSize(dm->auxData, numAux));
9301:   PetscFunctionReturn(PETSC_SUCCESS);
9302: }

9304: /*@
9305:   DMGetAuxiliaryVec - Get the auxiliary vector for region specified by the given label and value, and equation part

9307:   Not Collective

9309:   Input Parameters:
9310: + dm    - The `DM`
9311: . label - The `DMLabel`
9312: . value - The label value indicating the region
9313: - part  - The equation part, or 0 if unused

9315:   Output Parameter:
9316: . aux - The `Vec` holding auxiliary field data

9318:   Level: advanced

9320:   Note:
9321:   If no auxiliary vector is found for this (label, value), (`NULL`, 0, 0) is checked as well.

9323: .seealso: [](ch_dmbase), `DM`, `DMClearAuxiliaryVec()`, `DMSetAuxiliaryVec()`, `DMGetNumAuxiliaryVec()`, `DMGetAuxiliaryLabels()`
9324: @*/
9325: PetscErrorCode DMGetAuxiliaryVec(DM dm, DMLabel label, PetscInt value, PetscInt part, Vec *aux)
9326: {
9327:   PetscHashAuxKey key, wild = {NULL, 0, 0};
9328:   PetscBool       has;

9330:   PetscFunctionBegin;
9333:   key.label = label;
9334:   key.value = value;
9335:   key.part  = part;
9336:   PetscCall(PetscHMapAuxHas(dm->auxData, key, &has));
9337:   if (has) PetscCall(PetscHMapAuxGet(dm->auxData, key, aux));
9338:   else PetscCall(PetscHMapAuxGet(dm->auxData, wild, aux));
9339:   PetscFunctionReturn(PETSC_SUCCESS);
9340: }

9342: /*@
9343:   DMSetAuxiliaryVec - Set an auxiliary vector for region specified by the given label and value, and equation part

9345:   Not Collective because auxiliary vectors are not parallel

9347:   Input Parameters:
9348: + dm    - The `DM`
9349: . label - The `DMLabel`
9350: . value - The label value indicating the region
9351: . part  - The equation part, or 0 if unused
9352: - aux   - The `Vec` holding auxiliary field data

9354:   Level: advanced

9356: .seealso: [](ch_dmbase), `DM`, `DMClearAuxiliaryVec()`, `DMGetAuxiliaryVec()`, `DMGetAuxiliaryLabels()`, `DMCopyAuxiliaryVec()`
9357: @*/
9358: PetscErrorCode DMSetAuxiliaryVec(DM dm, DMLabel label, PetscInt value, PetscInt part, Vec aux)
9359: {
9360:   Vec             old;
9361:   PetscHashAuxKey key;

9363:   PetscFunctionBegin;
9366:   key.label = label;
9367:   key.value = value;
9368:   key.part  = part;
9369:   PetscCall(PetscHMapAuxGet(dm->auxData, key, &old));
9370:   PetscCall(PetscObjectReference((PetscObject)aux));
9371:   if (!aux) PetscCall(PetscHMapAuxDel(dm->auxData, key));
9372:   else PetscCall(PetscHMapAuxSet(dm->auxData, key, aux));
9373:   PetscCall(VecDestroy(&old));
9374:   PetscFunctionReturn(PETSC_SUCCESS);
9375: }

9377: /*@
9378:   DMGetAuxiliaryLabels - Get the labels, values, and parts for all auxiliary vectors in this `DM`

9380:   Not Collective

9382:   Input Parameter:
9383: . dm - The `DM`

9385:   Output Parameters:
9386: + labels - The `DMLabel`s for each `Vec`
9387: . values - The label values for each `Vec`
9388: - parts  - The equation parts for each `Vec`

9390:   Level: advanced

9392:   Note:
9393:   The arrays passed in must be at least as large as `DMGetNumAuxiliaryVec()`.

9395: .seealso: [](ch_dmbase), `DM`, `DMClearAuxiliaryVec()`, `DMGetNumAuxiliaryVec()`, `DMGetAuxiliaryVec()`, `DMSetAuxiliaryVec()`, `DMCopyAuxiliaryVec()`
9396: @*/
9397: PetscErrorCode DMGetAuxiliaryLabels(DM dm, DMLabel labels[], PetscInt values[], PetscInt parts[])
9398: {
9399:   PetscHashAuxKey *keys;
9400:   PetscInt         n, i, off = 0;

9402:   PetscFunctionBegin;
9404:   PetscAssertPointer(labels, 2);
9405:   PetscAssertPointer(values, 3);
9406:   PetscAssertPointer(parts, 4);
9407:   PetscCall(DMGetNumAuxiliaryVec(dm, &n));
9408:   PetscCall(PetscMalloc1(n, &keys));
9409:   PetscCall(PetscHMapAuxGetKeys(dm->auxData, &off, keys));
9410:   for (i = 0; i < n; ++i) {
9411:     labels[i] = keys[i].label;
9412:     values[i] = keys[i].value;
9413:     parts[i]  = keys[i].part;
9414:   }
9415:   PetscCall(PetscFree(keys));
9416:   PetscFunctionReturn(PETSC_SUCCESS);
9417: }

9419: /*@
9420:   DMCopyAuxiliaryVec - Copy the auxiliary vector data on a `DM` to a new `DM`

9422:   Not Collective

9424:   Input Parameter:
9425: . dm - The `DM`

9427:   Output Parameter:
9428: . dmNew - The new `DM`, now with the same auxiliary data

9430:   Level: advanced

9432:   Note:
9433:   This is a shallow copy of the auxiliary vectors

9435: .seealso: [](ch_dmbase), `DM`, `DMClearAuxiliaryVec()`, `DMGetNumAuxiliaryVec()`, `DMGetAuxiliaryVec()`, `DMSetAuxiliaryVec()`
9436: @*/
9437: PetscErrorCode DMCopyAuxiliaryVec(DM dm, DM dmNew)
9438: {
9439:   PetscFunctionBegin;
9442:   if (dm == dmNew) PetscFunctionReturn(PETSC_SUCCESS);
9443:   PetscCall(DMClearAuxiliaryVec(dmNew));

9445:   PetscCall(PetscHMapAuxDestroy(&dmNew->auxData));
9446:   PetscCall(PetscHMapAuxDuplicate(dm->auxData, &dmNew->auxData));
9447:   {
9448:     Vec     *auxData;
9449:     PetscInt n, i, off = 0;

9451:     PetscCall(PetscHMapAuxGetSize(dmNew->auxData, &n));
9452:     PetscCall(PetscMalloc1(n, &auxData));
9453:     PetscCall(PetscHMapAuxGetVals(dmNew->auxData, &off, auxData));
9454:     for (i = 0; i < n; ++i) PetscCall(PetscObjectReference((PetscObject)auxData[i]));
9455:     PetscCall(PetscFree(auxData));
9456:   }
9457:   PetscFunctionReturn(PETSC_SUCCESS);
9458: }

9460: /*@
9461:   DMClearAuxiliaryVec - Destroys the auxiliary vector information and creates a new empty one

9463:   Not Collective

9465:   Input Parameter:
9466: . dm - The `DM`

9468:   Level: advanced

9470: .seealso: [](ch_dmbase), `DM`, `DMCopyAuxiliaryVec()`, `DMGetNumAuxiliaryVec()`, `DMGetAuxiliaryVec()`, `DMSetAuxiliaryVec()`
9471: @*/
9472: PetscErrorCode DMClearAuxiliaryVec(DM dm)
9473: {
9474:   Vec     *auxData;
9475:   PetscInt n, i, off = 0;

9477:   PetscFunctionBegin;
9478:   PetscCall(PetscHMapAuxGetSize(dm->auxData, &n));
9479:   PetscCall(PetscMalloc1(n, &auxData));
9480:   PetscCall(PetscHMapAuxGetVals(dm->auxData, &off, auxData));
9481:   for (i = 0; i < n; ++i) PetscCall(VecDestroy(&auxData[i]));
9482:   PetscCall(PetscFree(auxData));
9483:   PetscCall(PetscHMapAuxDestroy(&dm->auxData));
9484:   PetscCall(PetscHMapAuxCreate(&dm->auxData));
9485:   PetscFunctionReturn(PETSC_SUCCESS);
9486: }

9488: /*@
9489:   DMPolytopeMatchOrientation - Determine an orientation (transformation) that takes the source face arrangement to the target face arrangement

9491:   Not Collective

9493:   Input Parameters:
9494: + ct         - The `DMPolytopeType`
9495: . sourceCone - The source arrangement of faces
9496: - targetCone - The target arrangement of faces

9498:   Output Parameters:
9499: + ornt  - The orientation (transformation) which will take the source arrangement to the target arrangement
9500: - found - Flag indicating that a suitable orientation was found

9502:   Level: advanced

9504:   Note:
9505:   An arrangement is a face order combined with an orientation for each face

9507:   Each orientation (transformation) is labeled with an integer from negative `DMPolytopeTypeGetNumArrangements(ct)`/2 to `DMPolytopeTypeGetNumArrangements(ct)`/2
9508:   that labels each arrangement (face ordering plus orientation for each face).

9510:   See `DMPolytopeMatchVertexOrientation()` to find a new vertex orientation that takes the source vertex arrangement to the target vertex arrangement

9512: .seealso: [](ch_dmbase), `DM`, `DMPolytopeGetOrientation()`, `DMPolytopeMatchVertexOrientation()`, `DMPolytopeGetVertexOrientation()`
9513: @*/
9514: PetscErrorCode DMPolytopeMatchOrientation(DMPolytopeType ct, const PetscInt sourceCone[], const PetscInt targetCone[], PetscInt *ornt, PetscBool *found)
9515: {
9516:   const PetscInt cS = DMPolytopeTypeGetConeSize(ct);
9517:   const PetscInt nO = DMPolytopeTypeGetNumArrangements(ct) / 2;
9518:   PetscInt       o, c;

9520:   PetscFunctionBegin;
9521:   if (!nO) {
9522:     *ornt  = 0;
9523:     *found = PETSC_TRUE;
9524:     PetscFunctionReturn(PETSC_SUCCESS);
9525:   }
9526:   for (o = -nO; o < nO; ++o) {
9527:     const PetscInt *arr = DMPolytopeTypeGetArrangement(ct, o);

9529:     for (c = 0; c < cS; ++c)
9530:       if (sourceCone[arr[c * 2]] != targetCone[c]) break;
9531:     if (c == cS) {
9532:       *ornt = o;
9533:       break;
9534:     }
9535:   }
9536:   *found = o == nO ? PETSC_FALSE : PETSC_TRUE;
9537:   PetscFunctionReturn(PETSC_SUCCESS);
9538: }

9540: /*@
9541:   DMPolytopeGetOrientation - Determine an orientation (transformation) that takes the source face arrangement to the target face arrangement

9543:   Not Collective

9545:   Input Parameters:
9546: + ct         - The `DMPolytopeType`
9547: . sourceCone - The source arrangement of faces
9548: - targetCone - The target arrangement of faces

9550:   Output Parameter:
9551: . ornt - The orientation (transformation) which will take the source arrangement to the target arrangement

9553:   Level: advanced

9555:   Note:
9556:   This function is the same as `DMPolytopeMatchOrientation()` except it will generate an error if no suitable orientation can be found.

9558:   Developer Note:
9559:   It is unclear why this function needs to exist since one can simply call `DMPolytopeMatchOrientation()` and error if none is found

9561: .seealso: [](ch_dmbase), `DM`, `DMPolytopeType`, `DMPolytopeMatchOrientation()`, `DMPolytopeGetVertexOrientation()`, `DMPolytopeMatchVertexOrientation()`
9562: @*/
9563: PetscErrorCode DMPolytopeGetOrientation(DMPolytopeType ct, const PetscInt sourceCone[], const PetscInt targetCone[], PetscInt *ornt)
9564: {
9565:   PetscBool found;

9567:   PetscFunctionBegin;
9568:   PetscCall(DMPolytopeMatchOrientation(ct, sourceCone, targetCone, ornt, &found));
9569:   PetscCheck(found, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Could not find orientation for %s", DMPolytopeTypes[ct]);
9570:   PetscFunctionReturn(PETSC_SUCCESS);
9571: }

9573: /*@
9574:   DMPolytopeMatchVertexOrientation - Determine an orientation (transformation) that takes the source vertex arrangement to the target vertex arrangement

9576:   Not Collective

9578:   Input Parameters:
9579: + ct         - The `DMPolytopeType`
9580: . sourceVert - The source arrangement of vertices
9581: - targetVert - The target arrangement of vertices

9583:   Output Parameters:
9584: + ornt  - The orientation (transformation) which will take the source arrangement to the target arrangement
9585: - found - Flag indicating that a suitable orientation was found

9587:   Level: advanced

9589:   Notes:
9590:   An arrangement is a vertex order

9592:   Each orientation (transformation) is labeled with an integer from negative `DMPolytopeTypeGetNumArrangements(ct)`/2 to `DMPolytopeTypeGetNumArrangements(ct)`/2
9593:   that labels each arrangement (vertex ordering).

9595:   See `DMPolytopeMatchOrientation()` to find a new face orientation that takes the source face arrangement to the target face arrangement

9597: .seealso: [](ch_dmbase), `DM`, `DMPolytopeType`, `DMPolytopeGetOrientation()`, `DMPolytopeMatchOrientation()`, `DMPolytopeTypeGetNumVertices()`, `DMPolytopeTypeGetVertexArrangement()`
9598: @*/
9599: PetscErrorCode DMPolytopeMatchVertexOrientation(DMPolytopeType ct, const PetscInt sourceVert[], const PetscInt targetVert[], PetscInt *ornt, PetscBool *found)
9600: {
9601:   const PetscInt cS = DMPolytopeTypeGetNumVertices(ct);
9602:   const PetscInt nO = DMPolytopeTypeGetNumArrangements(ct) / 2;
9603:   PetscInt       o, c;

9605:   PetscFunctionBegin;
9606:   if (!nO) {
9607:     *ornt  = 0;
9608:     *found = PETSC_TRUE;
9609:     PetscFunctionReturn(PETSC_SUCCESS);
9610:   }
9611:   for (o = -nO; o < nO; ++o) {
9612:     const PetscInt *arr = DMPolytopeTypeGetVertexArrangement(ct, o);

9614:     for (c = 0; c < cS; ++c)
9615:       if (sourceVert[arr[c]] != targetVert[c]) break;
9616:     if (c == cS) {
9617:       *ornt = o;
9618:       break;
9619:     }
9620:   }
9621:   *found = o == nO ? PETSC_FALSE : PETSC_TRUE;
9622:   PetscFunctionReturn(PETSC_SUCCESS);
9623: }

9625: /*@
9626:   DMPolytopeGetVertexOrientation - Determine an orientation (transformation) that takes the source vertex arrangement to the target vertex arrangement

9628:   Not Collective

9630:   Input Parameters:
9631: + ct         - The `DMPolytopeType`
9632: . sourceCone - The source arrangement of vertices
9633: - targetCone - The target arrangement of vertices

9635:   Output Parameter:
9636: . ornt - The orientation (transformation) which will take the source arrangement to the target arrangement

9638:   Level: advanced

9640:   Note:
9641:   This function is the same as `DMPolytopeMatchVertexOrientation()` except it errors if not orientation is possible.

9643:   Developer Note:
9644:   It is unclear why this function needs to exist since one can simply call `DMPolytopeMatchVertexOrientation()` and error if none is found

9646: .seealso: [](ch_dmbase), `DM`, `DMPolytopeType`, `DMPolytopeMatchVertexOrientation()`, `DMPolytopeGetOrientation()`
9647: @*/
9648: PetscErrorCode DMPolytopeGetVertexOrientation(DMPolytopeType ct, const PetscInt sourceCone[], const PetscInt targetCone[], PetscInt *ornt)
9649: {
9650:   PetscBool found;

9652:   PetscFunctionBegin;
9653:   PetscCall(DMPolytopeMatchVertexOrientation(ct, sourceCone, targetCone, ornt, &found));
9654:   PetscCheck(found, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Could not find orientation for %s", DMPolytopeTypes[ct]);
9655:   PetscFunctionReturn(PETSC_SUCCESS);
9656: }

9658: /*@
9659:   DMPolytopeInCellTest - Check whether a point lies inside the reference cell of given type

9661:   Not Collective

9663:   Input Parameters:
9664: + ct    - The `DMPolytopeType`
9665: - point - Coordinates of the point

9667:   Output Parameter:
9668: . inside - Flag indicating whether the point is inside the reference cell of given type

9670:   Level: advanced

9672: .seealso: [](ch_dmbase), `DM`, `DMPolytopeType`, `DMLocatePoints()`
9673: @*/
9674: PetscErrorCode DMPolytopeInCellTest(DMPolytopeType ct, const PetscReal point[], PetscBool *inside)
9675: {
9676:   PetscReal sum = 0.0;
9677:   PetscInt  d;

9679:   PetscFunctionBegin;
9680:   *inside = PETSC_TRUE;
9681:   switch (ct) {
9682:   case DM_POLYTOPE_TRIANGLE:
9683:   case DM_POLYTOPE_TETRAHEDRON:
9684:     for (d = 0; d < DMPolytopeTypeGetDim(ct); ++d) {
9685:       if (point[d] < -1.0) {
9686:         *inside = PETSC_FALSE;
9687:         break;
9688:       }
9689:       sum += point[d];
9690:     }
9691:     if (sum > PETSC_SMALL) {
9692:       *inside = PETSC_FALSE;
9693:       break;
9694:     }
9695:     break;
9696:   case DM_POLYTOPE_QUADRILATERAL:
9697:   case DM_POLYTOPE_HEXAHEDRON:
9698:     for (d = 0; d < DMPolytopeTypeGetDim(ct); ++d)
9699:       if (PetscAbsReal(point[d]) > 1. + PETSC_SMALL) {
9700:         *inside = PETSC_FALSE;
9701:         break;
9702:       }
9703:     break;
9704:   default:
9705:     SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Unsupported polytope type %s", DMPolytopeTypes[ct]);
9706:   }
9707:   PetscFunctionReturn(PETSC_SUCCESS);
9708: }

9710: /*@
9711:   DMReorderSectionSetDefault - Set flag indicating whether the local section should be reordered by default

9713:   Logically collective

9715:   Input Parameters:
9716: + dm      - The DM
9717: - reorder - Flag for reordering

9719:   Level: intermediate

9721: .seealso: `DMReorderSectionGetDefault()`
9722: @*/
9723: PetscErrorCode DMReorderSectionSetDefault(DM dm, DMReorderDefaultFlag reorder)
9724: {
9725:   PetscFunctionBegin;
9727:   PetscTryMethod(dm, "DMReorderSectionSetDefault_C", (DM, DMReorderDefaultFlag), (dm, reorder));
9728:   PetscFunctionReturn(PETSC_SUCCESS);
9729: }

9731: /*@
9732:   DMReorderSectionGetDefault - Get flag indicating whether the local section should be reordered by default

9734:   Not collective

9736:   Input Parameter:
9737: . dm - The DM

9739:   Output Parameter:
9740: . reorder - Flag for reordering

9742:   Level: intermediate

9744: .seealso: `DMReorderSetDefault()`
9745: @*/
9746: PetscErrorCode DMReorderSectionGetDefault(DM dm, DMReorderDefaultFlag *reorder)
9747: {
9748:   PetscFunctionBegin;
9750:   PetscAssertPointer(reorder, 2);
9751:   *reorder = DM_REORDER_DEFAULT_NOTSET;
9752:   PetscTryMethod(dm, "DMReorderSectionGetDefault_C", (DM, DMReorderDefaultFlag *), (dm, reorder));
9753:   PetscFunctionReturn(PETSC_SUCCESS);
9754: }

9756: /*@
9757:   DMReorderSectionSetType - Set the type of local section reordering

9759:   Logically collective

9761:   Input Parameters:
9762: + dm      - The DM
9763: - reorder - The reordering method

9765:   Level: intermediate

9767: .seealso: `DMReorderSectionGetType()`, `DMReorderSectionSetDefault()`
9768: @*/
9769: PetscErrorCode DMReorderSectionSetType(DM dm, MatOrderingType reorder)
9770: {
9771:   PetscFunctionBegin;
9773:   PetscTryMethod(dm, "DMReorderSectionSetType_C", (DM, MatOrderingType), (dm, reorder));
9774:   PetscFunctionReturn(PETSC_SUCCESS);
9775: }

9777: /*@
9778:   DMReorderSectionGetType - Get the reordering type for the local section

9780:   Not collective

9782:   Input Parameter:
9783: . dm - The DM

9785:   Output Parameter:
9786: . reorder - The reordering method

9788:   Level: intermediate

9790: .seealso: `DMReorderSetDefault()`, `DMReorderSectionGetDefault()`
9791: @*/
9792: PetscErrorCode DMReorderSectionGetType(DM dm, MatOrderingType *reorder)
9793: {
9794:   PetscFunctionBegin;
9796:   PetscAssertPointer(reorder, 2);
9797:   *reorder = NULL;
9798:   PetscTryMethod(dm, "DMReorderSectionGetType_C", (DM, MatOrderingType *), (dm, reorder));
9799:   PetscFunctionReturn(PETSC_SUCCESS);
9800: }