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]) bs = 1;
1160:       else bs = bsMinMax[0];
1161:       bs = bs < 0 ? 1 : bs;
1162:       /* Must reduce indices by blocksize */
1163:       if (bs > 1) {
1164:         for (l = 0, k = 0; l < n; l += bs, ++k) {
1165:           // Integer division of negative values truncates toward zero(!), not toward negative infinity
1166:           ltog[k] = ltog[l] >= 0 ? ltog[l] / bs : -(-(ltog[l] + 1) / bs + 1);
1167:         }
1168:         n /= bs;
1169:       }
1170:       PetscCall(ISLocalToGlobalMappingCreate(PetscObjectComm((PetscObject)dm), bs, n, ltog, PETSC_OWN_POINTER, &dm->ltogmap));
1171:     } else PetscUseTypeMethod(dm, getlocaltoglobalmapping);
1172:   }
1173:   *ltog = dm->ltogmap;
1174:   PetscFunctionReturn(PETSC_SUCCESS);
1175: }

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

1180:   Not Collective

1182:   Input Parameter:
1183: . dm - the `DM` with block structure

1185:   Output Parameter:
1186: . bs - the block size, 1 implies no exploitable block structure

1188:   Level: intermediate

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

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

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

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

1212:   Collective

1214:   Input Parameters:
1215: + dmc - the `DM` object
1216: - dmf - the second, finer `DM` object

1218:   Output Parameters:
1219: + mat - the interpolation
1220: - vec - the scaling (optional, pass `NULL` if not needed), see `DMCreateInterpolationScale()`

1222:   Level: developer

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

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

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

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

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

1254:   Output Parameter:
1255: . scale - the scaled vector

1257:   Level: advanced

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

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

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

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

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

1302:   Collective

1304:   Input Parameters:
1305: + dmc - the `DM` object
1306: - dmf - the second, finer `DM` object

1308:   Output Parameter:
1309: . mat - the restriction

1311:   Level: developer

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

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

1331: /*@
1332:   DMCreateInjection - Gets injection matrix between two `DM` objects.

1334:   Collective

1336:   Input Parameters:
1337: + dac - the `DM` object
1338: - daf - the second, finer `DM` object

1340:   Output Parameter:
1341: . mat - the injection

1343:   Level: developer

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

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

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

1371: /*@
1372:   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
1373:   a Galerkin finite element model on the `DM`

1375:   Collective

1377:   Input Parameters:
1378: + dmc - the target `DM` object
1379: - dmf - the source `DM` object, can be `NULL`

1381:   Output Parameter:
1382: . mat - the mass matrix

1384:   Level: developer

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

1389:   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()`

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

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

1409:   Collective

1411:   Input Parameter:
1412: . dm - the `DM` object

1414:   Output Parameters:
1415: + llm - the local lumped mass matrix, which is a diagonal matrix, represented as a vector
1416: - lm  - the global lumped mass matrix, which is a diagonal matrix, represented as a vector

1418:   Level: developer

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

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

1435: /*@
1436:   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`

1438:   Collective

1440:   Input Parameters:
1441: + dmc - the target `DM` object
1442: - dmf - the source `DM` object, can be `NULL`

1444:   Output Parameter:
1445: . mat - the gradient matrix

1447:   Level: developer

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

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

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

1469:   Collective

1471:   Input Parameters:
1472: + dm    - the `DM` object
1473: - ctype - `IS_COLORING_LOCAL` or `IS_COLORING_GLOBAL`

1475:   Output Parameter:
1476: . coloring - the coloring

1478:   Level: developer

1480:   Notes:
1481:   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
1482:   matrix comes from (what this function provides). In general using the mesh produces a more optimal coloring (fewer colors).

1484:   This produces a coloring with the distance of 2, see `MatSetColoringDistance()` which can be used for efficiently computing Jacobians with `MatFDColoringCreate()`
1485:   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,
1486:   otherwise an error will be generated.

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

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

1502:   Collective

1504:   Input Parameter:
1505: . dm - the `DM` object

1507:   Output Parameter:
1508: . mat - the empty Jacobian

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

1513:   Level: beginner

1515:   Notes:
1516:   This properly preallocates the number of nonzeros in the sparse matrix so you
1517:   do not need to do it yourself.

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

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

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

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

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

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

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

1575:   Logically Collective

1577:   Input Parameters:
1578: + dm   - the `DM`
1579: - skip - `PETSC_TRUE` to skip preallocation

1581:   Level: developer

1583:   Note:
1584:   This is most useful to reduce initialization costs when `MatSetPreallocationCOO()` and
1585:   `MatSetValuesCOO()` will be used.

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

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

1601:   Logically Collective

1603:   Input Parameters:
1604: + dm   - the `DM`
1605: - only - `PETSC_TRUE` if only want preallocation

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

1610:   Level: developer

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

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

1626:   Logically Collective

1628:   Input Parameters:
1629: + dm   - the `DM`
1630: - only - `PETSC_TRUE` if you only want matrix nonzero structure

1632:   Level: developer

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

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

1647:   Logically Collective

1649:   Input Parameters:
1650: + dm    - the `DM`
1651: - btype - block by topological point or field node

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

1656:   Level: advanced

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

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

1671:   Not Collective

1673:   Input Parameter:
1674: . dm - the `DM`

1676:   Output Parameter:
1677: . btype - block by topological point or field node

1679:   Level: advanced

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

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

1695:   Not Collective

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

1702:   Output Parameter:
1703: . mem - the work array

1705:   Level: developer

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

1710:   The array may contain nonzero values

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

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

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

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

1758:   Not Collective

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

1765:   Output Parameter:
1766: . mem - the work array

1768:   Level: developer

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

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

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

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

1800:   Logically Collective; No Fortran Support

1802:   Input Parameters:
1803: + dm     - The `DM`
1804: . field  - The field number for the nullspace
1805: - nullsp - A callback to create the nullspace

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

1813:   Level: intermediate

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

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

1830:   Not Collective; No Fortran Support

1832:   Input Parameters:
1833: + dm    - The `DM`
1834: - field - The field number for the nullspace

1836:   Output Parameter:
1837: . nullsp - A callback to create the nullspace

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

1845:   Level: intermediate

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

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

1863:   Logically Collective; No Fortran Support

1865:   Input Parameters:
1866: + dm     - The `DM`
1867: . field  - The field number for the nullspace
1868: - nullsp - A callback to create the near-nullspace

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

1876:   Level: intermediate

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

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

1894:   Not Collective; No Fortran Support

1896:   Input Parameters:
1897: + dm    - The `DM`
1898: - field - The field number for the nullspace

1900:   Output Parameter:
1901: . nullsp - A callback to create the near-nullspace

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

1909:   Level: intermediate

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

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

1928:   Not Collective; No Fortran Support

1930:   Input Parameter:
1931: . dm - the `DM` object

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

1938:   Level: intermediate

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

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

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

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

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

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

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

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

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

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

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

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

2053:   Not Collective; No Fortran Support

2055:   Input Parameter:
2056: . dm - the `DM` object

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

2064:   Level: intermediate

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

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

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

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

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

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

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

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

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

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

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

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

2155:   Not collective

2157:   Input Parameters:
2158: + dm        - The `DM` object
2159: . numFields - The number of fields to select
2160: - fields    - The field numbers of the selected fields

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

2166:   Level: intermediate

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

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

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

2187:   Not collective

2189:   Input Parameters:
2190: + dms - The `DM` objects
2191: - n   - The number of `DM`s

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

2197:   Level: intermediate

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

2202: .seealso: [](ch_dmbase), `DM`, `DMCreateSubDM()`, `DMPlexSetMigrationSF()`, `DMDestroy()`, `DMView()`, `DMCreateInterpolation()`, `DMCreateColoring()`, `DMCreateMatrix()`, `DMCreateMassMatrix()`, `DMCreateFieldIS()`, `DMCreateDomainDecomposition()`
2203: @*/
2204: PetscErrorCode DMCreateSuperDM(DM dms[], PetscInt n, IS *is[], DM *superdm)
2205: {
2206:   PetscFunctionBegin;
2207:   PetscAssertPointer(dms, 1);
2209:   if (is) PetscAssertPointer(is, 3);
2210:   PetscAssertPointer(superdm, 4);
2211:   PetscCheck(n >= 0, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Number of DMs must be nonnegative: %" PetscInt_FMT, n);
2212:   if (n) {
2213:     DM dm = dms[0];
2214:     PetscCheck(dm->ops->createsuperdm, PetscObjectComm((PetscObject)dm), PETSC_ERR_SUP, "No method createsuperdm for DM of type %s", ((PetscObject)dm)->type_name);
2215:     PetscCall((*dm->ops->createsuperdm)(dms, n, is, superdm));
2216:   }
2217:   PetscFunctionReturn(PETSC_SUCCESS);
2218: }

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

2224:   Not Collective

2226:   Input Parameter:
2227: . dm - the `DM` object

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

2236:   Level: intermediate

2238:   Notes:
2239:   Each `IS` contains the global indices of the dofs of the corresponding subdomains with in the
2240:   dofs of the original `DM`. The inner subdomains conceptually define a nonoverlapping
2241:   covering, while outer subdomains can overlap.

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

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

2249:   Developer Notes:
2250:   The `dmlist` is for the inner subdomains or the outer subdomains or all subdomains?

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

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

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

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

2310:   Not Collective

2312:   Input Parameters:
2313: + dm     - the `DM` object
2314: . n      - the number of subdomains
2315: - subdms - the local subdomains

2317:   Output Parameters:
2318: + iscat - scatter from global vector to nonoverlapping global vector entries on subdomain
2319: . oscat - scatter from global vector to overlapping global vector entries on subdomain
2320: - gscat - scatter from global vector to local vector on subdomain (fills in ghosts)

2322:   Level: developer

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

2330:   Developer Note:
2331:   Can the `subdms` input be anything or are they exactly the `DM` obtained from
2332:   `DMCreateDomainDecomposition()`?

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

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

2348:   Collective

2350:   Input Parameters:
2351: + dm   - the `DM` object
2352: - comm - the communicator to contain the new `DM` object (or `MPI_COMM_NULL`)

2354:   Output Parameter:
2355: . dmf - the refined `DM`, or `NULL`

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

2360:   Level: developer

2362:   Note:
2363:   If no refinement was done, the return value is `NULL`

2365: .seealso: [](ch_dmbase), `DM`, `DMCoarsen()`, `DMDestroy()`, `DMView()`, `DMCreateGlobalVector()`, `DMCreateInterpolation()`, `DMCreateDomainDecomposition()`,
2366:           `DMRefineHookAdd()`, `DMRefineHookRemove()`
2367: @*/
2368: PetscErrorCode DMRefine(DM dm, MPI_Comm comm, DM *dmf)
2369: {
2370:   DMRefineHookLink link;

2372:   PetscFunctionBegin;
2374:   PetscCall(PetscLogEventBegin(DM_Refine, dm, 0, 0, 0));
2375:   PetscUseTypeMethod(dm, refine, comm, dmf);
2376:   if (*dmf) {
2377:     (*dmf)->ops->creatematrix = dm->ops->creatematrix;

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

2381:     (*dmf)->ctx       = dm->ctx;
2382:     (*dmf)->leveldown = dm->leveldown;
2383:     (*dmf)->levelup   = dm->levelup + 1;

2385:     PetscCall(DMSetMatType(*dmf, dm->mattype));
2386:     for (link = dm->refinehook; link; link = link->next) {
2387:       if (link->refinehook) PetscCall((*link->refinehook)(dm, *dmf, link->ctx));
2388:     }
2389:   }
2390:   PetscCall(PetscLogEventEnd(DM_Refine, dm, 0, 0, 0));
2391:   PetscFunctionReturn(PETSC_SUCCESS);
2392: }

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

2397:   Logically Collective; No Fortran Support

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

2405:   Calling sequence of `refinehook`:
2406: + coarse - coarse level `DM`
2407: . fine   - fine level `DM` to interpolate problem to
2408: - ctx    - optional function context

2410:   Calling sequence of `interphook`:
2411: + coarse - coarse level `DM`
2412: . interp - matrix interpolating a coarse-level solution to the finer grid
2413: . fine   - fine level `DM` to update
2414: - ctx    - optional function context

2416:   Level: advanced

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

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

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

2426: .seealso: [](ch_dmbase), `DM`, `DMCoarsenHookAdd()`, `DMInterpolate()`, `SNESFASGetInterpolation()`, `SNESFASGetInjection()`, `PetscObjectCompose()`, `PetscContainerCreate()`
2427: @*/
2428: PetscErrorCode DMRefineHookAdd(DM coarse, PetscErrorCode (*refinehook)(DM coarse, DM fine, PetscCtx ctx), PetscErrorCode (*interphook)(DM coarse, Mat interp, DM fine, PetscCtx ctx), PetscCtx ctx)
2429: {
2430:   DMRefineHookLink link, *p;

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

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

2450:   Logically Collective; No Fortran Support

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

2458:   Calling sequence of refinehook:
2459: + coarse - the coarse `DM`
2460: . fine   - the fine `DM`
2461: - ctx    - context for the function

2463:   Calling sequence of interphook:
2464: + coarse - the coarse `DM`
2465: . interp - the interpolation `Mat` from coarse to fine
2466: . fine   - the fine `DM`
2467: - ctx    - context for the function

2469:   Level: advanced

2471:   Note:
2472:   This function does nothing if the hook is not in the list.

2474: .seealso: [](ch_dmbase), `DM`, `DMRefineHookAdd()`, `DMCoarsenHookRemove()`, `DMInterpolate()`, `SNESFASGetInterpolation()`, `SNESFASGetInjection()`, `PetscObjectCompose()`, `PetscContainerCreate()`
2475: @*/
2476: PetscErrorCode DMRefineHookRemove(DM coarse, PetscErrorCode (*refinehook)(DM coarse, DM fine, PetscCtx ctx), PetscErrorCode (*interphook)(DM coarse, Mat interp, DM fine, PetscCtx ctx), PetscCtx ctx)
2477: {
2478:   DMRefineHookLink link, *p;

2480:   PetscFunctionBegin;
2482:   for (p = &coarse->refinehook; *p; p = &(*p)->next) { /* Search the list of current hooks */
2483:     if ((*p)->refinehook == refinehook && (*p)->interphook == interphook && (*p)->ctx == ctx) {
2484:       link = *p;
2485:       *p   = link->next;
2486:       PetscCall(PetscFree(link));
2487:       break;
2488:     }
2489:   }
2490:   PetscFunctionReturn(PETSC_SUCCESS);
2491: }

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

2496:   Collective if any hooks are

2498:   Input Parameters:
2499: + coarse - coarser `DM` to use as a base
2500: . interp - interpolation matrix, apply using `MatInterpolate()`
2501: - fine   - finer `DM` to update

2503:   Level: developer

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

2509: .seealso: [](ch_dmbase), `DM`, `DMRefineHookAdd()`, `MatInterpolate()`
2510: @*/
2511: PetscErrorCode DMInterpolate(DM coarse, Mat interp, DM fine)
2512: {
2513:   DMRefineHookLink link;

2515:   PetscFunctionBegin;
2516:   for (link = fine->refinehook; link; link = link->next) {
2517:     if (link->interphook) PetscCall((*link->interphook)(coarse, interp, fine, link->ctx));
2518:   }
2519:   PetscFunctionReturn(PETSC_SUCCESS);
2520: }

2522: /*@
2523:   DMInterpolateSolution - Interpolates a solution from a coarse mesh to a fine mesh.

2525:   Collective

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

2535:   Output Parameter:
2536: . fineSol - the interpolation of coarseSol to the fine mesh

2538:   Level: developer

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

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

2549: .seealso: [](ch_dmbase), `DM`, `DMInterpolate()`, `DMCreateInterpolation()`
2550: @*/
2551: PetscErrorCode DMInterpolateSolution(DM coarse, DM fine, Mat interp, Vec coarseSol, Vec fineSol)
2552: {
2553:   PetscErrorCode (*interpsol)(DM, DM, Mat, Vec, Vec) = NULL;

2555:   PetscFunctionBegin;

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

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

2573:   Not Collective

2575:   Input Parameter:
2576: . dm - the `DM` object

2578:   Output Parameter:
2579: . level - number of refinements

2581:   Level: developer

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

2586: .seealso: [](ch_dmbase), `DM`, `DMRefine()`, `DMCoarsen()`, `DMGetCoarsenLevel()`, `DMDestroy()`, `DMView()`, `DMCreateGlobalVector()`, `DMCreateInterpolation()`
2587: @*/
2588: PetscErrorCode DMGetRefineLevel(DM dm, PetscInt *level)
2589: {
2590:   PetscFunctionBegin;
2592:   *level = dm->levelup;
2593:   PetscFunctionReturn(PETSC_SUCCESS);
2594: }

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

2599:   Not Collective

2601:   Input Parameters:
2602: + dm    - the `DM` object
2603: - level - number of refinements

2605:   Level: advanced

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

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

2612: .seealso: [](ch_dmbase), `DM`, `DMGetRefineLevel()`, `DMCoarsen()`, `DMGetCoarsenLevel()`, `DMDestroy()`, `DMView()`, `DMCreateGlobalVector()`, `DMCreateInterpolation()`
2613: @*/
2614: PetscErrorCode DMSetRefineLevel(DM dm, PetscInt level)
2615: {
2616:   PetscFunctionBegin;
2618:   dm->levelup = level;
2619:   PetscFunctionReturn(PETSC_SUCCESS);
2620: }

2622: /*@
2623:   DMExtrude - Extrude a `DM` object from a surface

2625:   Collective

2627:   Input Parameters:
2628: + dm     - the `DM` object
2629: - layers - the number of extruded cell layers

2631:   Output Parameter:
2632: . dme - the extruded `DM`, or `NULL`

2634:   Level: developer

2636:   Note:
2637:   If no extrusion was done, the return value is `NULL`

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

2655: PetscErrorCode DMGetBasisTransformDM_Internal(DM dm, DM *tdm)
2656: {
2657:   PetscFunctionBegin;
2659:   PetscAssertPointer(tdm, 2);
2660:   *tdm = dm->transformDM;
2661:   PetscFunctionReturn(PETSC_SUCCESS);
2662: }

2664: PetscErrorCode DMGetBasisTransformVec_Internal(DM dm, Vec *tv)
2665: {
2666:   PetscFunctionBegin;
2668:   PetscAssertPointer(tv, 2);
2669:   *tv = dm->transform;
2670:   PetscFunctionReturn(PETSC_SUCCESS);
2671: }

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

2676:   Input Parameter:
2677: . dm - The `DM`

2679:   Output Parameter:
2680: . flg - `PETSC_TRUE` if a basis transformation should be done

2682:   Level: developer

2684: .seealso: [](ch_dmbase), `DM`, `DMPlexGlobalToLocalBasis()`, `DMPlexLocalToGlobalBasis()`, `DMPlexCreateBasisRotation()`
2685: @*/
2686: PetscErrorCode DMHasBasisTransform(DM dm, PetscBool *flg)
2687: {
2688:   Vec tv;

2690:   PetscFunctionBegin;
2692:   PetscAssertPointer(flg, 2);
2693:   PetscCall(DMGetBasisTransformVec_Internal(dm, &tv));
2694:   *flg = tv ? PETSC_TRUE : PETSC_FALSE;
2695:   PetscFunctionReturn(PETSC_SUCCESS);
2696: }

2698: PetscErrorCode DMConstructBasisTransform_Internal(DM dm)
2699: {
2700:   PetscSection s, ts;
2701:   PetscScalar *ta;
2702:   PetscInt     cdim, pStart, pEnd, p, Nf, f, Nc, dof;

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

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

2746: PetscErrorCode DMCopyTransform(DM dm, DM newdm)
2747: {
2748:   PetscFunctionBegin;
2751:   newdm->transformCtx       = dm->transformCtx;
2752:   newdm->transformSetUp     = dm->transformSetUp;
2753:   newdm->transformDestroy   = NULL;
2754:   newdm->transformGetMatrix = dm->transformGetMatrix;
2755:   if (newdm->transformSetUp) PetscCall(DMConstructBasisTransform_Internal(newdm));
2756:   PetscFunctionReturn(PETSC_SUCCESS);
2757: }

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

2762:   Logically Collective

2764:   Input Parameters:
2765: + dm        - the `DM`
2766: . beginhook - function to run at the beginning of `DMGlobalToLocalBegin()`
2767: . endhook   - function to run after `DMGlobalToLocalEnd()` has completed
2768: - ctx       - [optional] context for provide data for the hooks (may be `NULL`)

2770:   Calling sequence of `beginhook`:
2771: + dm   - global `DM`
2772: . g    - global vector
2773: . mode - mode
2774: . l    - local vector
2775: - ctx  - optional function context

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

2784:   Level: advanced

2786:   Note:
2787:   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.

2789: .seealso: [](ch_dmbase), `DM`, `DMGlobalToLocal()`, `DMRefineHookAdd()`, `SNESFASGetInterpolation()`, `SNESFASGetInjection()`, `PetscObjectCompose()`, `PetscContainerCreate()`
2790: @*/
2791: 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)
2792: {
2793:   DMGlobalToLocalHookLink link, *p;

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

2807: static PetscErrorCode DMGlobalToLocalHook_Constraints(DM dm, Vec g, InsertMode mode, Vec l, PetscCtx ctx)
2808: {
2809:   Mat          cMat;
2810:   Vec          cVec, cBias;
2811:   PetscSection section, cSec;
2812:   PetscInt     pStart, pEnd, p, dof;

2814:   PetscFunctionBegin;
2815:   (void)g;
2816:   (void)ctx;
2818:   PetscCall(DMGetDefaultConstraints(dm, &cSec, &cMat, &cBias));
2819:   if (cMat && (mode == INSERT_VALUES || mode == INSERT_ALL_VALUES || mode == INSERT_BC_VALUES)) {
2820:     PetscInt nRows;

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

2842: /*@
2843:   DMGlobalToLocal - update local vectors from global vector

2845:   Neighbor-wise Collective

2847:   Input Parameters:
2848: + dm   - the `DM` object
2849: . g    - the global vector
2850: . mode - `INSERT_VALUES` or `ADD_VALUES`
2851: - l    - the local vector

2853:   Level: beginner

2855:   Notes:
2856:   The communication involved in this update can be overlapped with computation by instead using
2857:   `DMGlobalToLocalBegin()` and `DMGlobalToLocalEnd()`.

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

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

2873: /*@
2874:   DMGlobalToLocalBegin - Begins updating local vectors from global vector

2876:   Neighbor-wise Collective

2878:   Input Parameters:
2879: + dm   - the `DM` object
2880: . g    - the global vector
2881: . mode - `INSERT_VALUES` or `ADD_VALUES`
2882: - l    - the local vector

2884:   Level: intermediate

2886:   Notes:
2887:   The operation is completed with `DMGlobalToLocalEnd()`

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

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

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

2895: .seealso: [](ch_dmbase), `DM`, `DMCoarsen()`, `DMDestroy()`, `DMView()`, `DMCreateGlobalVector()`, `DMCreateInterpolation()`, `DMGlobalToLocal()`, `DMGlobalToLocalEnd()`, `DMLocalToGlobalBegin()`, `DMLocalToGlobal()`, `DMLocalToGlobalEnd()`
2896: @*/
2897: PetscErrorCode DMGlobalToLocalBegin(DM dm, Vec g, InsertMode mode, Vec l)
2898: {
2899:   PetscSF                 sf;
2900:   DMGlobalToLocalHookLink link;

2902:   PetscFunctionBegin;
2904:   for (link = dm->gtolhook; link; link = link->next) {
2905:     if (link->beginhook) PetscCall((*link->beginhook)(dm, g, mode, l, link->ctx));
2906:   }
2907:   PetscCall(DMGetSectionSF(dm, &sf));
2908:   if (sf) {
2909:     const PetscScalar *gArray;
2910:     PetscScalar       *lArray;
2911:     PetscMemType       lmtype, gmtype;

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

2925: /*@
2926:   DMGlobalToLocalEnd - Ends updating local vectors from global vector

2928:   Neighbor-wise Collective

2930:   Input Parameters:
2931: + dm   - the `DM` object
2932: . g    - the global vector
2933: . mode - `INSERT_VALUES` or `ADD_VALUES`
2934: - l    - the local vector

2936:   Level: intermediate

2938:   Note:
2939:   See `DMGlobalToLocalBegin()` for details.

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

2952:   PetscFunctionBegin;
2954:   PetscCall(DMGetSectionSF(dm, &sf));
2955:   PetscCall(DMHasBasisTransform(dm, &transform));
2956:   if (sf) {
2957:     PetscCheck(mode != ADD_VALUES, PetscObjectComm((PetscObject)dm), PETSC_ERR_ARG_OUTOFRANGE, "Invalid insertion mode %d", (int)mode);

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

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

2978:   Logically Collective

2980:   Input Parameters:
2981: + dm        - the `DM`
2982: . beginhook - function to run at the beginning of `DMLocalToGlobalBegin()`
2983: . endhook   - function to run after `DMLocalToGlobalEnd()` has completed
2984: - ctx       - [optional] context for provide data for the hooks (may be `NULL`)

2986:   Calling sequence of `beginhook`:
2987: + global - global `DM`
2988: . l      - local vector
2989: . mode   - mode
2990: . g      - global vector
2991: - ctx    - optional function context

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

3000:   Level: advanced

3002: .seealso: [](ch_dmbase), `DM`, `DMLocalToGlobal()`, `DMRefineHookAdd()`, `DMGlobalToLocalHookAdd()`, `SNESFASGetInterpolation()`, `SNESFASGetInjection()`, `PetscObjectCompose()`, `PetscContainerCreate()`
3003: @*/
3004: 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)
3005: {
3006:   DMLocalToGlobalHookLink link, *p;

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

3020: static PetscErrorCode DMLocalToGlobalHook_Constraints(DM dm, Vec l, InsertMode mode, Vec g, PetscCtx ctx)
3021: {
3022:   PetscFunctionBegin;
3023:   (void)g;
3024:   (void)ctx;
3026:   if (mode == ADD_VALUES || mode == ADD_ALL_VALUES || mode == ADD_BC_VALUES) {
3027:     Mat          cMat;
3028:     Vec          cVec;
3029:     PetscInt     nRows;
3030:     PetscSection section, cSec;
3031:     PetscInt     pStart, pEnd, p, dof;

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

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

3061:   Neighbor-wise Collective

3063:   Input Parameters:
3064: + dm   - the `DM` object
3065: . l    - the local vector
3066: . 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.
3067: - g    - the global vector

3069:   Level: beginner

3071:   Notes:
3072:   The communication involved in this update can be overlapped with computation by using
3073:   `DMLocalToGlobalBegin()` and `DMLocalToGlobalEnd()`.

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

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

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

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

3091: /*@
3092:   DMLocalToGlobalBegin - begins updating global vectors from local vectors

3094:   Neighbor-wise Collective

3096:   Input Parameters:
3097: + dm   - the `DM` object
3098: . l    - the local vector
3099: . 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.
3100: - g    - the global vector

3102:   Level: intermediate

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

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

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

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

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

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

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

3174:       PetscCall(DMGetGlobalSection(dm, &gs));
3175:       PetscCall(PetscSectionGetChart(s, &pStart, &pEnd));
3176:       PetscCall(VecGetOwnershipRange(g, &gStart, NULL));
3177:       for (p = pStart; p < pEnd; ++p) {
3178:         PetscInt dof, gdof, cdof, gcdof, off, goff, d, e;

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

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

3227: /*@
3228:   DMLocalToGlobalEnd - updates global vectors from local vectors

3230:   Neighbor-wise Collective

3232:   Input Parameters:
3233: + dm   - the `DM` object
3234: . l    - the local vector
3235: . mode - `INSERT_VALUES` or `ADD_VALUES`
3236: - g    - the global vector

3238:   Level: intermediate

3240:   Note:
3241:   See `DMLocalToGlobalBegin()` for full details

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

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

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

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

3304:   Neighbor-wise Collective

3306:   Input Parameters:
3307: + dm   - the `DM` object
3308: . g    - the original local vector
3309: - mode - one of `INSERT_VALUES` or `ADD_VALUES`

3311:   Output Parameter:
3312: . l - the local vector with correct ghost values

3314:   Level: intermediate

3316:   Note:
3317:   Must be followed by `DMLocalToLocalEnd()`.

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

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

3335:   Neighbor-wise Collective

3337:   Input Parameters:
3338: + dm   - the `DM` object
3339: . g    - the original local vector
3340: - mode - one of `INSERT_VALUES` or `ADD_VALUES`

3342:   Output Parameter:
3343: . l - the local vector with correct ghost values

3345:   Level: intermediate

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

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

3362:   Collective

3364:   Input Parameters:
3365: + dm   - the `DM` object
3366: - comm - the communicator to contain the new `DM` object (or `MPI_COMM_NULL`)

3368:   Output Parameter:
3369: . dmc - the coarsened `DM`

3371:   Level: developer

3373: .seealso: [](ch_dmbase), `DM`, `DMRefine()`, `DMDestroy()`, `DMView()`, `DMCreateGlobalVector()`, `DMCreateInterpolation()`, `DMCreateDomainDecomposition()`,
3374:           `DMCoarsenHookAdd()`, `DMCoarsenHookRemove()`
3375: @*/
3376: PetscErrorCode DMCoarsen(DM dm, MPI_Comm comm, DM *dmc)
3377: {
3378:   DMCoarsenHookLink link;

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

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

3405:   Logically Collective; No Fortran Support

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

3413:   Calling sequence of `coarsenhook`:
3414: + fine   - fine level `DM`
3415: . coarse - coarse level `DM` to restrict problem to
3416: - ctx    - optional application function context

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

3426:   Level: advanced

3428:   Notes:
3429:   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`.

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

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

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

3438: .seealso: [](ch_dmbase), `DM`, `DMCoarsenHookRemove()`, `DMRefineHookAdd()`, `SNESFASGetInterpolation()`, `SNESFASGetInjection()`, `PetscObjectCompose()`, `PetscContainerCreate()`
3439: @*/
3440: 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)
3441: {
3442:   DMCoarsenHookLink link, *p;

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

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

3461:   Logically Collective; No Fortran Support

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

3469:   Calling sequence of `coarsenhook`:
3470: + fine   - fine level `DM`
3471: . coarse - coarse level `DM` to restrict problem to
3472: - ctx    - optional application function context

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

3482:   Level: advanced

3484:   Notes:
3485:   This function does nothing if the `coarsenhook` is not in the list.

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

3489: .seealso: [](ch_dmbase), `DM`, `DMCoarsenHookAdd()`, `DMRefineHookAdd()`, `SNESFASGetInterpolation()`, `SNESFASGetInjection()`, `PetscObjectCompose()`, `PetscContainerCreate()`
3490: @*/
3491: 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)
3492: {
3493:   DMCoarsenHookLink link, *p;

3495:   PetscFunctionBegin;
3497:   for (p = &fine->coarsenhook; *p; p = &(*p)->next) { /* Search the list of current hooks */
3498:     if ((*p)->coarsenhook == coarsenhook && (*p)->restricthook == restricthook && (*p)->ctx == ctx) {
3499:       link = *p;
3500:       *p   = link->next;
3501:       PetscCall(PetscFree(link));
3502:       break;
3503:     }
3504:   }
3505:   PetscFunctionReturn(PETSC_SUCCESS);
3506: }

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

3511:   Collective if any hooks are

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

3520:   Level: developer

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

3525: .seealso: [](ch_dmbase), `DM`, `DMCoarsenHookAdd()`, `MatRestrict()`, `DMInterpolate()`, `DMRefineHookAdd()`
3526: @*/
3527: PetscErrorCode DMRestrict(DM fine, Mat restrct, Vec rscale, Mat inject, DM coarse)
3528: {
3529:   DMCoarsenHookLink link;

3531:   PetscFunctionBegin;
3532:   for (link = fine->coarsenhook; link; link = link->next) {
3533:     if (link->restricthook) PetscCall((*link->restricthook)(fine, restrct, rscale, inject, coarse, link->ctx));
3534:   }
3535:   PetscFunctionReturn(PETSC_SUCCESS);
3536: }

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

3541:   Logically Collective; No Fortran Support

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

3549:   Calling sequence of `ddhook`:
3550: + global - global `DM`
3551: . block  - subdomain `DM`
3552: - ctx    - optional application function context

3554:   Calling sequence of `restricthook`:
3555: + global - global `DM`
3556: . out    - scatter to the outer (with ghost and overlap points) sub vector
3557: . in     - scatter to sub vector values only owned locally
3558: . block  - subdomain `DM`
3559: - ctx    - optional application function context

3561:   Level: advanced

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

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

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

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

3574: .seealso: [](ch_dmbase), `DM`, `DMSubDomainHookRemove()`, `DMRefineHookAdd()`, `SNESFASGetInterpolation()`, `SNESFASGetInjection()`, `PetscObjectCompose()`, `PetscContainerCreate()`, `DMCreateDomainDecomposition()`
3575: @*/
3576: 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)
3577: {
3578:   DMSubDomainHookLink link, *p;

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

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

3597:   Logically Collective; No Fortran Support

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

3605:   Calling sequence of `ddhook`:
3606: + dm    - global `DM`
3607: . block - subdomain `DM`
3608: - ctx   - optional application function context

3610:   Calling sequence of `restricthook`:
3611: + dm       - global `DM`
3612: . oscatter - scatter to the outer (with ghost and overlap points) sub vector
3613: . gscatter - scatter to sub vector values only owned locally
3614: . block    - subdomain `DM`
3615: - ctx      - optional application function context

3617:   Level: advanced

3619: .seealso: [](ch_dmbase), `DM`, `DMSubDomainHookAdd()`, `SNESFASGetInterpolation()`, `SNESFASGetInjection()`, `PetscObjectCompose()`, `PetscContainerCreate()`,
3620:           `DMCreateDomainDecomposition()`
3621: @*/
3622: 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)
3623: {
3624:   DMSubDomainHookLink link, *p;

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

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

3642:   Collective if any hooks are

3644:   Input Parameters:
3645: + global   - The global `DM` to use as a base
3646: . oscatter - The scatter from domain global vector filling subdomain global vector with overlap
3647: . gscatter - The scatter from domain global vector filling subdomain local vector with ghosts
3648: - subdm    - The subdomain `DM` to update

3650:   Level: developer

3652: .seealso: [](ch_dmbase), `DM`, `DMCoarsenHookAdd()`, `MatRestrict()`, `DMCreateDomainDecomposition()`
3653: @*/
3654: PetscErrorCode DMSubDomainRestrict(DM global, VecScatter oscatter, VecScatter gscatter, DM subdm)
3655: {
3656:   DMSubDomainHookLink link;

3658:   PetscFunctionBegin;
3659:   for (link = global->subdomainhook; link; link = link->next) {
3660:     if (link->restricthook) PetscCall((*link->restricthook)(global, oscatter, gscatter, subdm, link->ctx));
3661:   }
3662:   PetscFunctionReturn(PETSC_SUCCESS);
3663: }

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

3668:   Not Collective

3670:   Input Parameter:
3671: . dm - the `DM` object

3673:   Output Parameter:
3674: . level - number of coarsenings

3676:   Level: developer

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

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

3692:   Collective

3694:   Input Parameters:
3695: + dm    - the `DM` object
3696: - level - number of coarsenings

3698:   Level: developer

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

3703: .seealso: [](ch_dmbase), `DM`, `DMCoarsen()`, `DMGetCoarsenLevel()`, `DMGetRefineLevel()`, `DMDestroy()`, `DMView()`, `DMCreateGlobalVector()`, `DMCreateInterpolation()`
3704: @*/
3705: PetscErrorCode DMSetCoarsenLevel(DM dm, PetscInt level)
3706: {
3707:   PetscFunctionBegin;
3709:   dm->leveldown = level;
3710:   PetscFunctionReturn(PETSC_SUCCESS);
3711: }

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

3716:   Collective

3718:   Input Parameters:
3719: + dm      - the `DM` object
3720: - nlevels - the number of levels of refinement

3722:   Output Parameter:
3723: . dmf - the refined `DM` hierarchy

3725:   Level: developer

3727: .seealso: [](ch_dmbase), `DM`, `DMCoarsen()`, `DMCoarsenHierarchy()`, `DMDestroy()`, `DMView()`, `DMCreateGlobalVector()`, `DMCreateInterpolation()`
3728: @*/
3729: PetscErrorCode DMRefineHierarchy(DM dm, PetscInt nlevels, DM dmf[])
3730: {
3731:   PetscFunctionBegin;
3733:   PetscCheck(nlevels >= 0, PetscObjectComm((PetscObject)dm), PETSC_ERR_ARG_OUTOFRANGE, "nlevels cannot be negative");
3734:   if (nlevels == 0) PetscFunctionReturn(PETSC_SUCCESS);
3735:   PetscAssertPointer(dmf, 3);
3736:   if (dm->ops->refine && !dm->ops->refinehierarchy) {
3737:     PetscCall(DMRefine(dm, PetscObjectComm((PetscObject)dm), &dmf[0]));
3738:     for (PetscInt i = 1; i < nlevels; i++) PetscCall(DMRefine(dmf[i - 1], PetscObjectComm((PetscObject)dm), &dmf[i]));
3739:   } else PetscUseTypeMethod(dm, refinehierarchy, nlevels, dmf);
3740:   PetscFunctionReturn(PETSC_SUCCESS);
3741: }

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

3746:   Collective

3748:   Input Parameters:
3749: + dm      - the `DM` object
3750: - nlevels - the number of levels of coarsening

3752:   Output Parameter:
3753: . dmc - the coarsened `DM` hierarchy

3755:   Level: developer

3757: .seealso: [](ch_dmbase), `DM`, `DMCoarsen()`, `DMRefineHierarchy()`, `DMDestroy()`, `DMView()`, `DMCreateGlobalVector()`, `DMCreateInterpolation()`
3758: @*/
3759: PetscErrorCode DMCoarsenHierarchy(DM dm, PetscInt nlevels, DM dmc[])
3760: {
3761:   PetscFunctionBegin;
3763:   PetscCheck(nlevels >= 0, PetscObjectComm((PetscObject)dm), PETSC_ERR_ARG_OUTOFRANGE, "nlevels cannot be negative");
3764:   if (nlevels == 0) PetscFunctionReturn(PETSC_SUCCESS);
3765:   PetscAssertPointer(dmc, 3);
3766:   if (dm->ops->coarsen && !dm->ops->coarsenhierarchy) {
3767:     PetscCall(DMCoarsen(dm, PetscObjectComm((PetscObject)dm), &dmc[0]));
3768:     for (PetscInt i = 1; i < nlevels; i++) PetscCall(DMCoarsen(dmc[i - 1], PetscObjectComm((PetscObject)dm), &dmc[i]));
3769:   } else PetscUseTypeMethod(dm, coarsenhierarchy, nlevels, dmc);
3770:   PetscFunctionReturn(PETSC_SUCCESS);
3771: }

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

3776:   Logically Collective if the function is collective

3778:   Input Parameters:
3779: + dm      - the `DM` object
3780: - destroy - the destroy function, see `PetscCtxDestroyFn` for the calling sequence

3782:   Level: intermediate

3784: .seealso: [](ch_dmbase), `DM`, `DMSetApplicationContext()`, `DMView()`, `DMCreateGlobalVector()`, `DMCreateInterpolation()`, `DMCreateColoring()`, `DMCreateMatrix()`, `DMCreateMassMatrix()`,
3785:           `DMGetApplicationContext()`, `PetscCtxDestroyFn`
3786: @*/
3787: PetscErrorCode DMSetApplicationContextDestroy(DM dm, PetscCtxDestroyFn *destroy)
3788: {
3789:   PetscFunctionBegin;
3791:   dm->ctxdestroy = destroy;
3792:   PetscFunctionReturn(PETSC_SUCCESS);
3793: }

3795: /*@
3796:   DMSetApplicationContext - Set a user context into a `DM` object

3798:   Not Collective

3800:   Input Parameters:
3801: + dm  - the `DM` object
3802: - ctx - the user context

3804:   Level: intermediate

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

3811:   Fortran Notes:
3812:   This only works when the context is a Fortran derived type or a `PetscObject`. Declare `ctx` with
3813: .vb
3814:   type(tUsertype), pointer :: ctx
3815: .ve

3817: .seealso: [](ch_dmbase), `DM`, `DMGetApplicationContext()`, `DMView()`, `DMCreateGlobalVector()`, `DMCreateInterpolation()`, `DMCreateColoring()`, `DMCreateMatrix()`, `DMCreateMassMatrix()`
3818: @*/
3819: PetscErrorCode DMSetApplicationContext(DM dm, PetscCtx ctx)
3820: {
3821:   PetscFunctionBegin;
3823:   dm->ctx = ctx;
3824:   PetscFunctionReturn(PETSC_SUCCESS);
3825: }

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

3830:   Not Collective

3832:   Input Parameter:
3833: . dm - the `DM` object

3835:   Output Parameter:
3836: . ctx - a pointer to the user context

3838:   Level: intermediate

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

3843:   Fortran Notes:
3844:   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
3845:   function that tells the Fortran compiler the derived data type that is returned as the `ctx` argument. For example,
3846: .vb
3847:   Interface DMGetApplicationContext
3848:     Subroutine DMGetApplicationContext(dm,ctx,ierr)
3849:   #include <petsc/finclude/petscdm.h>
3850:       use petscdm
3851:       DM dm
3852:       type(tUsertype), pointer :: ctx
3853:       PetscErrorCode ierr
3854:     End Subroutine
3855:   End Interface DMGetApplicationContext
3856: .ve

3858:   The prototype for `ctx` must be
3859: .vb
3860:   type(tUsertype), pointer :: ctx
3861: .ve

3863: .seealso: [](ch_dmbase), `DM`, `DMView()`, `DMCreateGlobalVector()`, `DMCreateInterpolation()`, `DMCreateColoring()`, `DMCreateMatrix()`, `DMCreateMassMatrix()`
3864: @*/
3865: PetscErrorCode DMGetApplicationContext(DM dm, PetscCtxRt ctx)
3866: {
3867:   PetscFunctionBegin;
3869:   *(void **)ctx = dm->ctx;
3870:   PetscFunctionReturn(PETSC_SUCCESS);
3871: }

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

3876:   Logically Collective

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

3882:   Calling sequence of f:
3883: + dm    - the `DM`
3884: . lower - the vector to hold the lower bounds
3885: - upper - the vector to hold the upper bounds

3887:   Level: intermediate

3889:   Developer Note:
3890:   Should be called `DMSetComputeVIBounds()` or something similar

3892: .seealso: [](ch_dmbase), `DM`, `DMComputeVariableBounds()`, `DMHasVariableBounds()`, `DMView()`, `DMCreateGlobalVector()`, `DMCreateInterpolation()`, `DMCreateColoring()`, `DMCreateMatrix()`, `DMCreateMassMatrix()`, `DMGetApplicationContext()`,
3893:          `DMSetJacobian()`
3894: @*/
3895: PetscErrorCode DMSetVariableBounds(DM dm, PetscErrorCode (*f)(DM dm, Vec lower, Vec upper))
3896: {
3897:   PetscFunctionBegin;
3899:   dm->ops->computevariablebounds = f;
3900:   PetscFunctionReturn(PETSC_SUCCESS);
3901: }

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

3906:   Not Collective

3908:   Input Parameter:
3909: . dm - the `DM` object to destroy

3911:   Output Parameter:
3912: . flg - `PETSC_TRUE` if the variable bounds function exists

3914:   Level: developer

3916: .seealso: [](ch_dmbase), `DM`, `DMComputeVariableBounds()`, `DMView()`, `DMCreateGlobalVector()`, `DMCreateInterpolation()`, `DMCreateColoring()`, `DMCreateMatrix()`, `DMCreateMassMatrix()`, `DMGetApplicationContext()`
3917: @*/
3918: PetscErrorCode DMHasVariableBounds(DM dm, PetscBool *flg)
3919: {
3920:   PetscFunctionBegin;
3922:   PetscAssertPointer(flg, 2);
3923:   *flg = (dm->ops->computevariablebounds) ? PETSC_TRUE : PETSC_FALSE;
3924:   PetscFunctionReturn(PETSC_SUCCESS);
3925: }

3927: /*@
3928:   DMComputeVariableBounds - compute variable bounds used by `SNESVI`.

3930:   Logically Collective

3932:   Input Parameter:
3933: . dm - the `DM` object

3935:   Output Parameters:
3936: + xl - lower bound
3937: - xu - upper bound

3939:   Level: advanced

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

3944: .seealso: [](ch_dmbase), `DM`, `DMHasVariableBounds()`, `DMView()`, `DMCreateGlobalVector()`, `DMCreateInterpolation()`, `DMCreateColoring()`, `DMCreateMatrix()`, `DMCreateMassMatrix()`, `DMGetApplicationContext()`
3945: @*/
3946: PetscErrorCode DMComputeVariableBounds(DM dm, Vec xl, Vec xu)
3947: {
3948:   PetscFunctionBegin;
3952:   PetscUseTypeMethod(dm, computevariablebounds, xl, xu);
3953:   PetscFunctionReturn(PETSC_SUCCESS);
3954: }

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

3959:   Not Collective

3961:   Input Parameter:
3962: . dm - the DM object

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

3967:   Level: developer

3969: .seealso: [](ch_dmbase), `DM`, `DMCreateColoring()`
3970: @*/
3971: PetscErrorCode DMHasColoring(DM dm, PetscBool *flg)
3972: {
3973:   PetscFunctionBegin;
3975:   PetscAssertPointer(flg, 2);
3976:   *flg = (dm->ops->getcoloring) ? PETSC_TRUE : PETSC_FALSE;
3977:   PetscFunctionReturn(PETSC_SUCCESS);
3978: }

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

3983:   Not Collective

3985:   Input Parameter:
3986: . dm - the `DM` object

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

3991:   Level: developer

3993: .seealso: [](ch_dmbase), `DM`, `DMCreateRestriction()`, `DMHasCreateInterpolation()`, `DMHasCreateInjection()`
3994: @*/
3995: PetscErrorCode DMHasCreateRestriction(DM dm, PetscBool *flg)
3996: {
3997:   PetscFunctionBegin;
3999:   PetscAssertPointer(flg, 2);
4000:   *flg = (dm->ops->createrestriction) ? PETSC_TRUE : PETSC_FALSE;
4001:   PetscFunctionReturn(PETSC_SUCCESS);
4002: }

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

4007:   Not Collective

4009:   Input Parameter:
4010: . dm - the `DM` object

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

4015:   Level: developer

4017: .seealso: [](ch_dmbase), `DM`, `DMCreateInjection()`, `DMHasCreateRestriction()`, `DMHasCreateInterpolation()`
4018: @*/
4019: PetscErrorCode DMHasCreateInjection(DM dm, PetscBool *flg)
4020: {
4021:   PetscFunctionBegin;
4023:   PetscAssertPointer(flg, 2);
4024:   if (dm->ops->hascreateinjection) PetscUseTypeMethod(dm, hascreateinjection, flg);
4025:   else *flg = (dm->ops->createinjection) ? PETSC_TRUE : PETSC_FALSE;
4026:   PetscFunctionReturn(PETSC_SUCCESS);
4027: }

4029: PetscFunctionList DMList              = NULL;
4030: PetscBool         DMRegisterAllCalled = PETSC_FALSE;

4032: /*@
4033:   DMSetType - Builds a `DM`, for a particular `DM` implementation.

4035:   Collective

4037:   Input Parameters:
4038: + dm     - The `DM` object
4039: - method - The name of the `DMType`, for example `DMDA`, `DMPLEX`

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

4044:   Level: intermediate

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

4049: .seealso: [](ch_dmbase), `DM`, `DMType`, `DMDA`, `DMPLEX`, `DMGetType()`, `DMCreate()`, `DMDACreate2d()`
4050: @*/
4051: PetscErrorCode DMSetType(DM dm, DMType method)
4052: {
4053:   PetscErrorCode (*r)(DM);
4054:   PetscBool match;

4056:   PetscFunctionBegin;
4058:   PetscCall(PetscObjectTypeCompare((PetscObject)dm, method, &match));
4059:   if (match) PetscFunctionReturn(PETSC_SUCCESS);

4061:   PetscCall(DMRegisterAll());
4062:   PetscCall(PetscFunctionListFind(DMList, method, &r));
4063:   PetscCheck(r, PetscObjectComm((PetscObject)dm), PETSC_ERR_ARG_UNKNOWN_TYPE, "Unknown DM type: %s", method);

4065:   PetscTryTypeMethod(dm, destroy);
4066:   PetscCall(PetscMemzero(dm->ops, sizeof(*dm->ops)));
4067:   PetscCall(PetscObjectChangeTypeName((PetscObject)dm, method));
4068:   PetscCall((*r)(dm));
4069:   PetscFunctionReturn(PETSC_SUCCESS);
4070: }

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

4075:   Not Collective

4077:   Input Parameter:
4078: . dm - The `DM`

4080:   Output Parameter:
4081: . type - The `DMType` name

4083:   Level: intermediate

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

4088: .seealso: [](ch_dmbase), `DM`, `DMType`, `DMDA`, `DMPLEX`, `DMSetType()`, `DMCreate()`, `PetscObjectTypeCompare()`, `PetscObjectTypeCompareAny()`
4089: @*/
4090: PetscErrorCode DMGetType(DM dm, DMType *type)
4091: {
4092:   PetscFunctionBegin;
4094:   PetscAssertPointer(type, 2);
4095:   PetscCall(DMRegisterAll());
4096:   *type = ((PetscObject)dm)->type_name;
4097:   PetscFunctionReturn(PETSC_SUCCESS);
4098: }

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

4103:   Collective

4105:   Input Parameters:
4106: + dm      - the `DM`
4107: - newtype - new `DM` type (use "same" for the same type)

4109:   Output Parameter:
4110: . M - pointer to new `DM`

4112:   Level: intermediate

4114:   Note:
4115:   Cannot be used to convert a sequential `DM` to a parallel or a parallel to sequential,
4116:   the MPI communicator of the generated `DM` is always the same as the communicator
4117:   of the input `DM`.

4119: .seealso: [](ch_dmbase), `DM`, `DMSetType()`, `DMCreate()`, `DMClone()`
4120: @*/
4121: PetscErrorCode DMConvert(DM dm, DMType newtype, DM *M)
4122: {
4123:   DM        B;
4124:   char      convname[256];
4125:   PetscBool sametype /*, issame */;

4127:   PetscFunctionBegin;
4130:   PetscAssertPointer(M, 3);
4131:   PetscCall(PetscObjectTypeCompare((PetscObject)dm, newtype, &sametype));
4132:   /* PetscCall(PetscStrcmp(newtype, "same", &issame)); */
4133:   if (sametype) {
4134:     *M = dm;
4135:     PetscCall(PetscObjectReference((PetscObject)dm));
4136:     PetscFunctionReturn(PETSC_SUCCESS);
4137:   } else {
4138:     PetscErrorCode (*conv)(DM, DMType, DM *) = NULL;

4140:     /*
4141:        Order of precedence:
4142:        1) See if a specialized converter is known to the current DM.
4143:        2) See if a specialized converter is known to the desired DM class.
4144:        3) See if a good general converter is registered for the desired class
4145:        4) See if a good general converter is known for the current matrix.
4146:        5) Use a really basic converter.
4147:     */

4149:     /* 1) See if a specialized converter is known to the current DM and the desired class */
4150:     PetscCall(PetscStrncpy(convname, "DMConvert_", sizeof(convname)));
4151:     PetscCall(PetscStrlcat(convname, ((PetscObject)dm)->type_name, sizeof(convname)));
4152:     PetscCall(PetscStrlcat(convname, "_", sizeof(convname)));
4153:     PetscCall(PetscStrlcat(convname, newtype, sizeof(convname)));
4154:     PetscCall(PetscStrlcat(convname, "_C", sizeof(convname)));
4155:     PetscCall(PetscObjectQueryFunction((PetscObject)dm, convname, &conv));
4156:     if (conv) goto foundconv;

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

4172: #if 0
4173:     /* 3) See if a good general converter is registered for the desired class */
4174:     conv = B->ops->convertfrom;
4175:     PetscCall(DMDestroy(&B));
4176:     if (conv) goto foundconv;

4178:     /* 4) See if a good general converter is known for the current matrix */
4179:     if (dm->ops->convert) conv = dm->ops->convert;
4180:     if (conv) goto foundconv;
4181: #endif

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

4186:   foundconv:
4187:     PetscCall(PetscLogEventBegin(DM_Convert, dm, 0, 0, 0));
4188:     PetscCall((*conv)(dm, newtype, M));
4189:     /* Things that are independent of DM type: We should consult DMClone() here */
4190:     {
4191:       const PetscReal *maxCell, *Lstart, *L;

4193:       PetscCall(DMGetPeriodicity(dm, &maxCell, &Lstart, &L));
4194:       PetscCall(DMSetPeriodicity(*M, maxCell, Lstart, L));
4195:       (*M)->prealloc_only = dm->prealloc_only;
4196:       PetscCall(PetscFree((*M)->vectype));
4197:       PetscCall(PetscStrallocpy(dm->vectype, (char **)&(*M)->vectype));
4198:       PetscCall(PetscFree((*M)->mattype));
4199:       PetscCall(PetscStrallocpy(dm->mattype, (char **)&(*M)->mattype));
4200:     }
4201:     PetscCall(PetscLogEventEnd(DM_Convert, dm, 0, 0, 0));
4202:   }
4203:   PetscCall(PetscObjectStateIncrease((PetscObject)*M));
4204:   PetscFunctionReturn(PETSC_SUCCESS);
4205: }

4207: /*@C
4208:   DMRegister -  Adds a new `DM` type implementation

4210:   Not Collective, No Fortran Support

4212:   Input Parameters:
4213: + sname    - The name of a new user-defined creation routine
4214: - function - The creation routine itself

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

4219:   Level: advanced

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

4224:   Example Usage:
4225: .vb
4226:     DMRegister("my_da", MyDMCreate);
4227: .ve

4229:   Then, your `DM` type can be chosen with the procedural interface via
4230: .vb
4231:     DMCreate(MPI_Comm, DM *);
4232:     DMSetType(DM,"my_da");
4233: .ve
4234:   or at runtime via the option
4235: .vb
4236:     -da_type my_da
4237: .ve

4239: .seealso: [](ch_dmbase), `DM`, `DMType`, `DMSetType()`, `DMRegisterAll()`, `DMRegisterDestroy()`
4240: @*/
4241: PetscErrorCode DMRegister(const char sname[], PetscErrorCode (*function)(DM dm))
4242: {
4243:   PetscFunctionBegin;
4244:   PetscCall(DMInitializePackage());
4245:   PetscCall(PetscFunctionListAdd(&DMList, sname, function));
4246:   PetscFunctionReturn(PETSC_SUCCESS);
4247: }

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

4252:   Collective

4254:   Input Parameters:
4255: + newdm  - the newly loaded `DM`, this needs to have been created with `DMCreate()` or
4256:            some related function before a call to `DMLoad()`.
4257: - viewer - binary file viewer, obtained from `PetscViewerBinaryOpen()` or
4258:            `PETSCVIEWERHDF5` file viewer, obtained from `PetscViewerHDF5Open()`

4260:   Level: intermediate

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

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

4269: .seealso: [](ch_dmbase), `DM`, `PetscViewerBinaryOpen()`, `DMView()`, `MatLoad()`, `VecLoad()`
4270: @*/
4271: PetscErrorCode DMLoad(DM newdm, PetscViewer viewer)
4272: {
4273:   PetscBool isbinary, ishdf5;

4275:   PetscFunctionBegin;
4278:   PetscCall(PetscViewerCheckReadable(viewer));
4279:   PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERBINARY, &isbinary));
4280:   PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERHDF5, &ishdf5));
4281:   PetscCall(PetscLogEventBegin(DM_Load, viewer, 0, 0, 0));
4282:   if (isbinary) {
4283:     PetscInt classid;
4284:     char     type[256];

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

4298: /* FEM Support */

4300: PetscErrorCode DMPrintCellIndices(PetscInt c, const char name[], PetscInt len, const PetscInt x[])
4301: {
4302:   PetscInt f;

4304:   PetscFunctionBegin;
4305:   PetscCall(PetscPrintf(PETSC_COMM_SELF, "Cell %" PetscInt_FMT " Element %s\n", c, name));
4306:   for (f = 0; f < len; ++f) PetscCall(PetscPrintf(PETSC_COMM_SELF, "  | %" PetscInt_FMT " |\n", x[f]));
4307:   PetscFunctionReturn(PETSC_SUCCESS);
4308: }

4310: PetscErrorCode DMPrintCellVector(PetscInt c, const char name[], PetscInt len, const PetscScalar 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, "  | %g |\n", (double)PetscRealPart(x[f])));
4317:   PetscFunctionReturn(PETSC_SUCCESS);
4318: }

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

4328: PetscErrorCode DMPrintCellMatrix(PetscInt c, const char name[], PetscInt rows, PetscInt cols, const PetscScalar A[])
4329: {
4330:   PetscFunctionBegin;
4331:   PetscCall(PetscPrintf(PETSC_COMM_SELF, "Cell %" PetscInt_FMT " Element %s\n", c, name));
4332:   for (PetscInt f = 0; f < rows; ++f) {
4333:     PetscCall(PetscPrintf(PETSC_COMM_SELF, "  |"));
4334:     for (PetscInt g = 0; g < cols; ++g) PetscCall(PetscPrintf(PETSC_COMM_SELF, " % 9.5g", (double)PetscRealPart(A[f * cols + g])));
4335:     PetscCall(PetscPrintf(PETSC_COMM_SELF, " |\n"));
4336:   }
4337:   PetscFunctionReturn(PETSC_SUCCESS);
4338: }

4340: PetscErrorCode DMPrintLocalVec(DM dm, const char name[], PetscReal tol, Vec X)
4341: {
4342:   PetscInt           localSize, bs;
4343:   PetscMPIInt        size;
4344:   Vec                x, xglob;
4345:   const PetscScalar *xarray;

4347:   PetscFunctionBegin;
4348:   PetscCallMPI(MPI_Comm_size(PetscObjectComm((PetscObject)dm), &size));
4349:   PetscCall(VecDuplicate(X, &x));
4350:   PetscCall(VecCopy(X, x));
4351:   PetscCall(VecFilter(x, tol));
4352:   PetscCall(PetscPrintf(PetscObjectComm((PetscObject)dm), "%s:\n", name));
4353:   if (size > 1) {
4354:     PetscCall(VecGetLocalSize(x, &localSize));
4355:     PetscCall(VecGetArrayRead(x, &xarray));
4356:     PetscCall(VecGetBlockSize(x, &bs));
4357:     PetscCall(VecCreateMPIWithArray(PetscObjectComm((PetscObject)dm), bs, localSize, PETSC_DETERMINE, xarray, &xglob));
4358:   } else {
4359:     xglob = x;
4360:   }
4361:   PetscCall(VecView(xglob, PETSC_VIEWER_STDOUT_(PetscObjectComm((PetscObject)dm))));
4362:   if (size > 1) {
4363:     PetscCall(VecDestroy(&xglob));
4364:     PetscCall(VecRestoreArrayRead(x, &xarray));
4365:   }
4366:   PetscCall(VecDestroy(&x));
4367:   PetscFunctionReturn(PETSC_SUCCESS);
4368: }

4370: PetscErrorCode DMViewDSFromOptions_Internal(DM dm, const char opt[])
4371: {
4372:   PetscObject       obj = (PetscObject)dm;
4373:   PetscViewer       viewer;
4374:   PetscViewerFormat format;
4375:   PetscBool         flg;

4377:   PetscFunctionBegin;
4378:   PetscCall(PetscOptionsCreateViewer(PetscObjectComm(obj), obj->options, obj->prefix, opt, &viewer, &format, &flg));
4379:   if (flg) {
4380:     PetscCall(PetscViewerPushFormat(viewer, format));
4381:     for (PetscInt d = 0; d < dm->Nds; ++d) PetscCall(PetscDSView(dm->probs[d].ds, viewer));
4382:     PetscCall(PetscViewerFlush(viewer));
4383:     PetscCall(PetscViewerPopFormat(viewer));
4384:     PetscCall(PetscViewerDestroy(&viewer));
4385:   }
4386:   PetscFunctionReturn(PETSC_SUCCESS);
4387: }

4389: PetscErrorCode DMViewSectionFromOptions_Internal(DM dm, const char opt[])
4390: {
4391:   PetscObject       obj = (PetscObject)dm;
4392:   PetscViewer       viewer;
4393:   PetscViewerFormat format;
4394:   PetscBool         flg;

4396:   PetscFunctionBegin;
4397:   PetscCall(PetscOptionsCreateViewer(PetscObjectComm(obj), obj->options, obj->prefix, opt, &viewer, &format, &flg));
4398:   if (flg) {
4399:     PetscCall(PetscViewerPushFormat(viewer, format));
4400:     if (dm->localSection) PetscCall(PetscSectionView(dm->localSection, viewer));
4401:     PetscCall(PetscViewerFlush(viewer));
4402:     PetscCall(PetscViewerPopFormat(viewer));
4403:     PetscCall(PetscViewerDestroy(&viewer));
4404:   }
4405:   PetscFunctionReturn(PETSC_SUCCESS);
4406: }

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

4411:   Input Parameter:
4412: . dm - The `DM`

4414:   Output Parameter:
4415: . section - The `PetscSection`

4417:   Options Database Key:
4418: . -dm_petscsection_view - View the section created by the `DM`

4420:   Level: intermediate

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

4425: .seealso: [](ch_dmbase), `DM`, `DMSetLocalSection()`, `DMGetGlobalSection()`
4426: @*/
4427: PetscErrorCode DMGetLocalSection(DM dm, PetscSection *section)
4428: {
4429:   PetscFunctionBegin;
4431:   PetscAssertPointer(section, 2);
4432:   if (!dm->localSection && dm->ops->createlocalsection) {
4433:     if (dm->setfromoptionscalled) {
4434:       for (PetscInt d = 0; d < dm->Nds; ++d) PetscCall(PetscDSSetFromOptions(dm->probs[d].ds));
4435:       PetscCall(DMViewDSFromOptions_Internal(dm, "-dm_petscds_view"));
4436:     }
4437:     PetscUseTypeMethod(dm, createlocalsection);
4438:     if (dm->localSection) PetscCall(PetscObjectViewFromOptions((PetscObject)dm->localSection, NULL, "-dm_petscsection_view"));
4439:   }
4440:   *section = dm->localSection;
4441:   PetscFunctionReturn(PETSC_SUCCESS);
4442: }

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

4447:   Input Parameters:
4448: + dm      - The `DM`
4449: - section - The `PetscSection`

4451:   Level: intermediate

4453:   Note:
4454:   Any existing Section will be destroyed

4456: .seealso: [](ch_dmbase), `DM`, `PetscSection`, `DMGetLocalSection()`, `DMSetGlobalSection()`
4457: @*/
4458: PetscErrorCode DMSetLocalSection(DM dm, PetscSection section)
4459: {
4460:   PetscInt numFields = 0;

4462:   PetscFunctionBegin;
4465:   PetscCall(PetscObjectReference((PetscObject)section));
4466:   PetscCall(PetscSectionDestroy(&dm->localSection));
4467:   dm->localSection = section;
4468:   if (section) PetscCall(PetscSectionGetNumFields(dm->localSection, &numFields));
4469:   if (numFields) {
4470:     PetscCall(DMSetNumFields(dm, numFields));
4471:     for (PetscInt f = 0; f < numFields; ++f) {
4472:       PetscObject disc;
4473:       const char *name;

4475:       PetscCall(PetscSectionGetFieldName(dm->localSection, f, &name));
4476:       PetscCall(DMGetField(dm, f, NULL, &disc));
4477:       PetscCall(PetscObjectSetName(disc, name));
4478:     }
4479:   }
4480:   /* The global section and the SectionSF will be rebuilt
4481:      in the next call to DMGetGlobalSection() and DMGetSectionSF(). */
4482:   PetscCall(PetscSectionDestroy(&dm->globalSection));
4483:   PetscCall(PetscSFDestroy(&dm->sectionSF));
4484:   PetscCall(PetscSFCreate(PetscObjectComm((PetscObject)dm), &dm->sectionSF));

4486:   /* Clear scratch vectors */
4487:   PetscCall(DMClearGlobalVectors(dm));
4488:   PetscCall(DMClearLocalVectors(dm));
4489:   PetscCall(DMClearNamedGlobalVectors(dm));
4490:   PetscCall(DMClearNamedLocalVectors(dm));
4491:   PetscFunctionReturn(PETSC_SUCCESS);
4492: }

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

4497:   Input Parameter:
4498: . dm - The `DM`

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

4504:   Level: developer

4506: .seealso: [](ch_dmbase), `DM`, `PetscSection`, `DMGetLocalSection()`, `DMGetGlobalSection()`
4507: @*/
4508: PetscErrorCode DMCreateSectionPermutation(DM dm, IS *perm, PetscBT *blockStarts)
4509: {
4510:   PetscFunctionBegin;
4511:   *perm        = NULL;
4512:   *blockStarts = NULL;
4513:   PetscTryTypeMethod(dm, createsectionpermutation, perm, blockStarts);
4514:   PetscFunctionReturn(PETSC_SUCCESS);
4515: }

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

4520:   not Collective

4522:   Input Parameter:
4523: . dm - The `DM`

4525:   Output Parameters:
4526: + 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.
4527: . 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.
4528: - bias    - Vector containing bias to be added to constrained dofs

4530:   Level: advanced

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

4535: .seealso: [](ch_dmbase), `DM`, `DMSetDefaultConstraints()`
4536: @*/
4537: PetscErrorCode DMGetDefaultConstraints(DM dm, PetscSection *section, Mat *mat, Vec *bias)
4538: {
4539:   PetscFunctionBegin;
4541:   if (!dm->defaultConstraint.section && !dm->defaultConstraint.mat && dm->ops->createdefaultconstraints) PetscUseTypeMethod(dm, createdefaultconstraints);
4542:   if (section) *section = dm->defaultConstraint.section;
4543:   if (mat) *mat = dm->defaultConstraint.mat;
4544:   if (bias) *bias = dm->defaultConstraint.bias;
4545:   PetscFunctionReturn(PETSC_SUCCESS);
4546: }

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

4551:   Collective

4553:   Input Parameters:
4554: + dm      - The `DM`
4555: . 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).
4556: . 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).
4557: - 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).

4559:   Level: advanced

4561:   Notes:
4562:   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()`.

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

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

4568: .seealso: [](ch_dmbase), `DM`, `DMGetDefaultConstraints()`
4569: @*/
4570: PetscErrorCode DMSetDefaultConstraints(DM dm, PetscSection section, Mat mat, Vec bias)
4571: {
4572:   PetscMPIInt result;

4574:   PetscFunctionBegin;
4576:   if (section) {
4578:     PetscCallMPI(MPI_Comm_compare(PETSC_COMM_SELF, PetscObjectComm((PetscObject)section), &result));
4579:     PetscCheck(result == MPI_CONGRUENT || result == MPI_IDENT, PETSC_COMM_SELF, PETSC_ERR_ARG_NOTSAMECOMM, "constraint section must have local communicator");
4580:   }
4581:   if (mat) {
4583:     PetscCallMPI(MPI_Comm_compare(PETSC_COMM_SELF, PetscObjectComm((PetscObject)mat), &result));
4584:     PetscCheck(result == MPI_CONGRUENT || result == MPI_IDENT, PETSC_COMM_SELF, PETSC_ERR_ARG_NOTSAMECOMM, "constraint matrix must have local communicator");
4585:   }
4586:   if (bias) {
4588:     PetscCallMPI(MPI_Comm_compare(PETSC_COMM_SELF, PetscObjectComm((PetscObject)bias), &result));
4589:     PetscCheck(result == MPI_CONGRUENT || result == MPI_IDENT, PETSC_COMM_SELF, PETSC_ERR_ARG_NOTSAMECOMM, "constraint bias must have local communicator");
4590:   }
4591:   PetscCall(PetscObjectReference((PetscObject)section));
4592:   PetscCall(PetscSectionDestroy(&dm->defaultConstraint.section));
4593:   dm->defaultConstraint.section = section;
4594:   PetscCall(PetscObjectReference((PetscObject)mat));
4595:   PetscCall(MatDestroy(&dm->defaultConstraint.mat));
4596:   dm->defaultConstraint.mat = mat;
4597:   PetscCall(PetscObjectReference((PetscObject)bias));
4598:   PetscCall(VecDestroy(&dm->defaultConstraint.bias));
4599:   dm->defaultConstraint.bias = bias;
4600:   PetscFunctionReturn(PETSC_SUCCESS);
4601: }

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

4607:   Input Parameters:
4608: + dm - The `DM`
4609: . localSection - `PetscSection` describing the local data layout
4610: - globalSection - `PetscSection` describing the global data layout

4612:   Level: intermediate

4614: .seealso: [](ch_dmbase), `DM`, `DMGetSectionSF()`, `DMSetSectionSF()`
4615: */
4616: static PetscErrorCode DMDefaultSectionCheckConsistency_Internal(DM dm, PetscSection localSection, PetscSection globalSection)
4617: {
4618:   MPI_Comm        comm;
4619:   PetscLayout     layout;
4620:   const PetscInt *ranges;
4621:   PetscInt        pStart, pEnd, p, nroots;
4622:   PetscMPIInt     size, rank;
4623:   PetscBool       valid = PETSC_TRUE, gvalid;

4625:   PetscFunctionBegin;
4626:   PetscCall(PetscObjectGetComm((PetscObject)dm, &comm));
4628:   PetscCallMPI(MPI_Comm_size(comm, &size));
4629:   PetscCallMPI(MPI_Comm_rank(comm, &rank));
4630:   PetscCall(PetscSectionGetChart(globalSection, &pStart, &pEnd));
4631:   PetscCall(PetscSectionGetConstrainedStorageSize(globalSection, &nroots));
4632:   PetscCall(PetscLayoutCreate(comm, &layout));
4633:   PetscCall(PetscLayoutSetBlockSize(layout, 1));
4634:   PetscCall(PetscLayoutSetLocalSize(layout, nroots));
4635:   PetscCall(PetscLayoutSetUp(layout));
4636:   PetscCall(PetscLayoutGetRanges(layout, &ranges));
4637:   for (p = pStart; p < pEnd; ++p) {
4638:     PetscInt dof, cdof, off, gdof, gcdof, goff, gsize, d;

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

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

4681: PetscErrorCode DMGetIsoperiodicPointSF_Internal(DM dm, PetscSF *sf)
4682: {
4683:   PetscErrorCode (*f)(DM, PetscSF *);

4685:   PetscFunctionBegin;
4687:   PetscAssertPointer(sf, 2);
4688:   PetscCall(PetscObjectQueryFunction((PetscObject)dm, "DMGetIsoperiodicPointSF_C", &f));
4689:   if (f) PetscCall(f(dm, sf));
4690:   else *sf = dm->sf;
4691:   PetscFunctionReturn(PETSC_SUCCESS);
4692: }

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

4697:   Collective

4699:   Input Parameter:
4700: . dm - The `DM`

4702:   Output Parameter:
4703: . section - The `PetscSection`

4705:   Level: intermediate

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

4710: .seealso: [](ch_dmbase), `DM`, `DMSetLocalSection()`, `DMGetLocalSection()`
4711: @*/
4712: PetscErrorCode DMGetGlobalSection(DM dm, PetscSection *section)
4713: {
4714:   PetscFunctionBegin;
4716:   PetscAssertPointer(section, 2);
4717:   if (!dm->globalSection) {
4718:     PetscSection s;
4719:     PetscSF      sf;

4721:     PetscCall(DMGetLocalSection(dm, &s));
4722:     PetscCheck(s, PetscObjectComm((PetscObject)dm), PETSC_ERR_ARG_WRONGSTATE, "DM must have a default PetscSection in order to create a global PetscSection");
4723:     PetscCheck(dm->sf, PetscObjectComm((PetscObject)dm), PETSC_ERR_ARG_WRONGSTATE, "DM must have a point PetscSF in order to create a global PetscSection");
4724:     PetscCall(DMGetIsoperiodicPointSF_Internal(dm, &sf));
4725:     PetscCall(PetscSectionCreateGlobalSection(s, sf, PETSC_TRUE, PETSC_FALSE, PETSC_FALSE, &dm->globalSection));
4726:     PetscCall(PetscLayoutDestroy(&dm->map));
4727:     PetscCall(PetscSectionGetValueLayout(PetscObjectComm((PetscObject)dm), dm->globalSection, &dm->map));
4728:     PetscCall(PetscSectionViewFromOptions(dm->globalSection, NULL, "-global_section_view"));
4729:   }
4730:   *section = dm->globalSection;
4731:   PetscFunctionReturn(PETSC_SUCCESS);
4732: }

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

4737:   Input Parameters:
4738: + dm      - The `DM`
4739: - section - The PetscSection, or `NULL`

4741:   Level: intermediate

4743:   Note:
4744:   Any existing `PetscSection` will be destroyed

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

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

4771:   Input Parameter:
4772: . dm - The `DM`

4774:   Output Parameter:
4775: . sf - The `PetscSF`

4777:   Level: intermediate

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

4782: .seealso: [](ch_dmbase), `DM`, `DMSetSectionSF()`, `DMCreateSectionSF()`
4783: @*/
4784: PetscErrorCode DMGetSectionSF(DM dm, PetscSF *sf)
4785: {
4786:   PetscInt nroots;

4788:   PetscFunctionBegin;
4790:   PetscAssertPointer(sf, 2);
4791:   if (!dm->sectionSF) PetscCall(PetscSFCreate(PetscObjectComm((PetscObject)dm), &dm->sectionSF));
4792:   PetscCall(PetscSFGetGraph(dm->sectionSF, &nroots, NULL, NULL, NULL));
4793:   if (nroots < 0) {
4794:     PetscSection section, gSection;

4796:     PetscCall(DMGetLocalSection(dm, &section));
4797:     if (section) {
4798:       PetscCall(DMGetGlobalSection(dm, &gSection));
4799:       PetscCall(DMCreateSectionSF(dm, section, gSection));
4800:     } else {
4801:       *sf = NULL;
4802:       PetscFunctionReturn(PETSC_SUCCESS);
4803:     }
4804:   }
4805:   *sf = dm->sectionSF;
4806:   PetscFunctionReturn(PETSC_SUCCESS);
4807: }

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

4812:   Input Parameters:
4813: + dm - The `DM`
4814: - sf - The `PetscSF`

4816:   Level: intermediate

4818:   Note:
4819:   Any previous `PetscSF` is destroyed

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

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

4838:   Input Parameters:
4839: + dm            - The `DM`
4840: . localSection  - `PetscSection` describing the local data layout
4841: - globalSection - `PetscSection` describing the global data layout

4843:   Level: developer

4845:   Note:
4846:   One usually uses `DMGetSectionSF()` to obtain the `PetscSF`

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

4854: .seealso: [](ch_dmbase), `DM`, `DMGetSectionSF()`, `DMSetSectionSF()`, `DMGetLocalSection()`, `DMGetGlobalSection()`
4855: @*/
4856: PetscErrorCode DMCreateSectionSF(DM dm, PetscSection localSection, PetscSection globalSection)
4857: {
4858:   PetscFunctionBegin;
4860:   PetscCall(PetscSFSetGraphSection(dm->sectionSF, localSection, globalSection));
4861:   PetscFunctionReturn(PETSC_SUCCESS);
4862: }

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

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

4869:   Input Parameter:
4870: . dm - The `DM`

4872:   Output Parameter:
4873: . sf - The `PetscSF`

4875:   Level: intermediate

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

4880: .seealso: [](ch_dmbase), `DM`, `DMSetPointSF()`, `DMGetSectionSF()`, `DMSetSectionSF()`, `DMCreateSectionSF()`
4881: @*/
4882: PetscErrorCode DMGetPointSF(DM dm, PetscSF *sf)
4883: {
4884:   PetscFunctionBegin;
4886:   PetscAssertPointer(sf, 2);
4887:   *sf = dm->sf;
4888:   PetscFunctionReturn(PETSC_SUCCESS);
4889: }

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

4894:   Collective

4896:   Input Parameters:
4897: + dm - The `DM`
4898: - sf - The `PetscSF`

4900:   Level: intermediate

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

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

4918:   Input Parameter:
4919: . dm - The `DM`

4921:   Output Parameter:
4922: . sf - The `PetscSF`

4924:   Level: intermediate

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

4929: .seealso: [](ch_dmbase), `DM`, `DMSetNaturalSF()`, `DMSetUseNatural()`, `DMGetUseNatural()`, `DMPlexCreateGlobalToNaturalSF()`, `DMPlexDistribute()`
4930: @*/
4931: PetscErrorCode DMGetNaturalSF(DM dm, PetscSF *sf)
4932: {
4933:   PetscFunctionBegin;
4935:   PetscAssertPointer(sf, 2);
4936:   *sf = dm->sfNatural;
4937:   PetscFunctionReturn(PETSC_SUCCESS);
4938: }

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

4943:   Input Parameters:
4944: + dm - The DM
4945: - sf - The PetscSF

4947:   Level: intermediate

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

4962: static PetscErrorCode DMSetDefaultAdjacency_Private(DM dm, PetscInt f, PetscObject disc)
4963: {
4964:   PetscClassId id;

4966:   PetscFunctionBegin;
4967:   PetscCall(PetscObjectGetClassId(disc, &id));
4968:   if (id == PETSCFE_CLASSID) PetscCall(DMSetAdjacency(dm, f, PETSC_FALSE, PETSC_TRUE));
4969:   else if (id == PETSCFV_CLASSID) PetscCall(DMSetAdjacency(dm, f, PETSC_TRUE, PETSC_FALSE));
4970:   else PetscCall(DMSetAdjacency(dm, f, PETSC_FALSE, PETSC_TRUE));
4971:   PetscFunctionReturn(PETSC_SUCCESS);
4972: }

4974: static PetscErrorCode DMFieldEnlarge_Static(DM dm, PetscInt NfNew)
4975: {
4976:   RegionField *tmpr;
4977:   PetscInt     Nf = dm->Nf, f;

4979:   PetscFunctionBegin;
4980:   if (Nf >= NfNew) PetscFunctionReturn(PETSC_SUCCESS);
4981:   PetscCall(PetscMalloc1(NfNew, &tmpr));
4982:   for (f = 0; f < Nf; ++f) tmpr[f] = dm->fields[f];
4983:   for (f = Nf; f < NfNew; ++f) {
4984:     tmpr[f].disc        = NULL;
4985:     tmpr[f].label       = NULL;
4986:     tmpr[f].avoidTensor = PETSC_FALSE;
4987:   }
4988:   PetscCall(PetscFree(dm->fields));
4989:   dm->Nf     = NfNew;
4990:   dm->fields = tmpr;
4991:   PetscFunctionReturn(PETSC_SUCCESS);
4992: }

4994: /*@
4995:   DMClearFields - Remove all fields from the `DM`

4997:   Logically Collective

4999:   Input Parameter:
5000: . dm - The `DM`

5002:   Level: intermediate

5004: .seealso: [](ch_dmbase), `DM`, `DMGetNumFields()`, `DMSetNumFields()`, `DMSetField()`
5005: @*/
5006: PetscErrorCode DMClearFields(DM dm)
5007: {
5008:   PetscInt f;

5010:   PetscFunctionBegin;
5012:   if (!dm->fields) PetscFunctionReturn(PETSC_SUCCESS); // DMDA does not use fields field in DM
5013:   for (f = 0; f < dm->Nf; ++f) {
5014:     PetscCall(PetscObjectDestroy(&dm->fields[f].disc));
5015:     PetscCall(DMLabelDestroy(&dm->fields[f].label));
5016:   }
5017:   PetscCall(PetscFree(dm->fields));
5018:   dm->fields = NULL;
5019:   dm->Nf     = 0;
5020:   PetscFunctionReturn(PETSC_SUCCESS);
5021: }

5023: /*@
5024:   DMGetNumFields - Get the number of fields in the `DM`

5026:   Not Collective

5028:   Input Parameter:
5029: . dm - The `DM`

5031:   Output Parameter:
5032: . numFields - The number of fields

5034:   Level: intermediate

5036: .seealso: [](ch_dmbase), `DM`, `DMSetNumFields()`, `DMSetField()`
5037: @*/
5038: PetscErrorCode DMGetNumFields(DM dm, PetscInt *numFields)
5039: {
5040:   PetscFunctionBegin;
5042:   PetscAssertPointer(numFields, 2);
5043:   *numFields = dm->Nf;
5044:   PetscFunctionReturn(PETSC_SUCCESS);
5045: }

5047: /*@
5048:   DMSetNumFields - Set the number of fields in the `DM`

5050:   Logically Collective

5052:   Input Parameters:
5053: + dm        - The `DM`
5054: - numFields - The number of fields

5056:   Level: intermediate

5058: .seealso: [](ch_dmbase), `DM`, `DMGetNumFields()`, `DMSetField()`
5059: @*/
5060: PetscErrorCode DMSetNumFields(DM dm, PetscInt numFields)
5061: {
5062:   PetscInt Nf;

5064:   PetscFunctionBegin;
5066:   PetscCall(DMGetNumFields(dm, &Nf));
5067:   for (PetscInt f = Nf; f < numFields; ++f) {
5068:     PetscContainer obj;

5070:     PetscCall(PetscContainerCreate(PetscObjectComm((PetscObject)dm), &obj));
5071:     PetscCall(DMAddField(dm, NULL, (PetscObject)obj));
5072:     PetscCall(PetscContainerDestroy(&obj));
5073:   }
5074:   PetscFunctionReturn(PETSC_SUCCESS);
5075: }

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

5080:   Not Collective

5082:   Input Parameters:
5083: + dm - The `DM`
5084: - f  - The field number

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

5090:   Level: intermediate

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

5110: /* Does not clear the DS */
5111: PetscErrorCode DMSetField_Internal(DM dm, PetscInt f, DMLabel label, PetscObject disc)
5112: {
5113:   PetscFunctionBegin;
5114:   PetscCall(DMFieldEnlarge_Static(dm, f + 1));
5115:   PetscCall(DMLabelDestroy(&dm->fields[f].label));
5116:   PetscCall(PetscObjectDestroy(&dm->fields[f].disc));
5117:   dm->fields[f].label = label;
5118:   dm->fields[f].disc  = disc;
5119:   PetscCall(PetscObjectReference((PetscObject)label));
5120:   PetscCall(PetscObjectReference(disc));
5121:   PetscFunctionReturn(PETSC_SUCCESS);
5122: }

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

5128:   Logically Collective

5130:   Input Parameters:
5131: + dm    - The `DM`
5132: . f     - The field number
5133: . label - The label indicating the support of the field, or `NULL` for the entire mesh
5134: - disc  - The discretization object

5136:   Level: intermediate

5138: .seealso: [](ch_dmbase), `DM`, `DMAddField()`, `DMGetField()`
5139: @*/
5140: PetscErrorCode DMSetField(DM dm, PetscInt f, DMLabel label, PetscObject disc)
5141: {
5142:   PetscFunctionBegin;
5146:   PetscCheck(f >= 0, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Field number %" PetscInt_FMT " must be non-negative", f);
5147:   PetscCall(DMSetField_Internal(dm, f, label, disc));
5148:   PetscCall(DMSetDefaultAdjacency_Private(dm, f, disc));
5149:   PetscCall(DMClearDS(dm));
5150:   PetscFunctionReturn(PETSC_SUCCESS);
5151: }

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

5157:   Logically Collective

5159:   Input Parameters:
5160: + dm    - The `DM`
5161: . label - The label indicating the support of the field, or `NULL` for the entire mesh
5162: - disc  - The discretization object

5164:   Level: intermediate

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

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

5173:   Fortran Note:
5174:   Use the argument `PetscObjectCast(disc)` as the second argument

5176: .seealso: [](ch_dmbase), `DM`, `DMSetLabel()`, `DMSetField()`, `DMGetField()`, `PetscFE`
5177: @*/
5178: PetscErrorCode DMAddField(DM dm, DMLabel label, PetscObject disc)
5179: {
5180:   PetscInt Nf = dm->Nf;

5182:   PetscFunctionBegin;
5186:   PetscCall(DMFieldEnlarge_Static(dm, Nf + 1));
5187:   dm->fields[Nf].label = label;
5188:   dm->fields[Nf].disc  = disc;
5189:   PetscCall(PetscObjectReference((PetscObject)label));
5190:   PetscCall(PetscObjectReference(disc));
5191:   PetscCall(DMSetDefaultAdjacency_Private(dm, Nf, disc));
5192:   PetscCall(DMClearDS(dm));
5193:   PetscFunctionReturn(PETSC_SUCCESS);
5194: }

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

5199:   Logically Collective

5201:   Input Parameters:
5202: + dm          - The `DM`
5203: . f           - The field index
5204: - avoidTensor - `PETSC_TRUE` to skip defining the field on tensor cells

5206:   Level: intermediate

5208: .seealso: [](ch_dmbase), `DM`, `DMGetFieldAvoidTensor()`, `DMSetField()`, `DMGetField()`
5209: @*/
5210: PetscErrorCode DMSetFieldAvoidTensor(DM dm, PetscInt f, PetscBool avoidTensor)
5211: {
5212:   PetscFunctionBegin;
5213:   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);
5214:   dm->fields[f].avoidTensor = avoidTensor;
5215:   PetscFunctionReturn(PETSC_SUCCESS);
5216: }

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

5221:   Not Collective

5223:   Input Parameters:
5224: + dm - The `DM`
5225: - f  - The field index

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

5230:   Level: intermediate

5232: .seealso: [](ch_dmbase), `DM`, `DMAddField()`, `DMSetField()`, `DMGetField()`, `DMSetFieldAvoidTensor()`
5233: @*/
5234: PetscErrorCode DMGetFieldAvoidTensor(DM dm, PetscInt f, PetscBool *avoidTensor)
5235: {
5236:   PetscFunctionBegin;
5237:   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);
5238:   *avoidTensor = dm->fields[f].avoidTensor;
5239:   PetscFunctionReturn(PETSC_SUCCESS);
5240: }

5242: /*@
5243:   DMCopyFields - Copy the discretizations for the `DM` into another `DM`

5245:   Collective

5247:   Input Parameters:
5248: + dm        - The `DM`
5249: . minDegree - Minimum degree for a discretization, or `PETSC_DETERMINE` for no limit
5250: - maxDegree - Maximum degree for a discretization, or `PETSC_DETERMINE` for no limit

5252:   Output Parameter:
5253: . newdm - The `DM`

5255:   Level: advanced

5257: .seealso: [](ch_dmbase), `DM`, `DMGetField()`, `DMSetField()`, `DMAddField()`, `DMCopyDS()`, `DMGetDS()`, `DMGetCellDS()`
5258: @*/
5259: PetscErrorCode DMCopyFields(DM dm, PetscInt minDegree, PetscInt maxDegree, DM newdm)
5260: {
5261:   PetscInt Nf;

5263:   PetscFunctionBegin;
5264:   if (dm == newdm) PetscFunctionReturn(PETSC_SUCCESS);
5265:   PetscCall(DMGetNumFields(dm, &Nf));
5266:   PetscCall(DMClearFields(newdm));
5267:   for (PetscInt f = 0; f < Nf; ++f) {
5268:     DMLabel      label;
5269:     PetscObject  field;
5270:     PetscClassId id;
5271:     PetscBool    useCone, useClosure;

5273:     PetscCall(DMGetField(dm, f, &label, &field));
5274:     PetscCall(PetscObjectGetClassId(field, &id));
5275:     if (id == PETSCFE_CLASSID) {
5276:       PetscFE newfe;

5278:       PetscCall(PetscFELimitDegree((PetscFE)field, minDegree, maxDegree, &newfe));
5279:       PetscCall(DMSetField(newdm, f, label, (PetscObject)newfe));
5280:       PetscCall(PetscFEDestroy(&newfe));
5281:     } else {
5282:       PetscCall(DMSetField(newdm, f, label, field));
5283:     }
5284:     PetscCall(DMGetAdjacency(dm, f, &useCone, &useClosure));
5285:     PetscCall(DMSetAdjacency(newdm, f, useCone, useClosure));
5286:   }
5287:   // Create nullspace constructor slots
5288:   if (dm->nullspaceConstructors) {
5289:     PetscCall(PetscFree2(newdm->nullspaceConstructors, newdm->nearnullspaceConstructors));
5290:     PetscCall(PetscCalloc2(Nf, &newdm->nullspaceConstructors, Nf, &newdm->nearnullspaceConstructors));
5291:   }
5292:   PetscFunctionReturn(PETSC_SUCCESS);
5293: }

5295: /*@
5296:   DMGetAdjacency - Returns the flags for determining variable influence

5298:   Not Collective

5300:   Input Parameters:
5301: + dm - The `DM` object
5302: - f  - The field number, or `PETSC_DEFAULT` for the default adjacency

5304:   Output Parameters:
5305: + useCone    - Flag for variable influence starting with the cone operation
5306: - useClosure - Flag for variable influence using transitive closure

5308:   Level: developer

5310:   Notes:
5311: .vb
5312:      FEM:   Two points p and q are adjacent if q \in closure(star(p)),   useCone = PETSC_FALSE, useClosure = PETSC_TRUE
5313:      FVM:   Two points p and q are adjacent if q \in support(p+cone(p)), useCone = PETSC_TRUE,  useClosure = PETSC_FALSE
5314:      FVM++: Two points p and q are adjacent if q \in star(closure(p)),   useCone = PETSC_TRUE,  useClosure = PETSC_TRUE
5315: .ve
5316:   Further explanation can be found in the User's Manual Section on the Influence of Variables on One Another.

5318: .seealso: [](ch_dmbase), `DM`, `DMSetAdjacency()`, `DMGetField()`, `DMSetField()`
5319: @*/
5320: PetscErrorCode DMGetAdjacency(DM dm, PetscInt f, PetscBool *useCone, PetscBool *useClosure)
5321: {
5322:   PetscFunctionBegin;
5324:   if (useCone) PetscAssertPointer(useCone, 3);
5325:   if (useClosure) PetscAssertPointer(useClosure, 4);
5326:   if (f < 0) {
5327:     if (useCone) *useCone = dm->adjacency[0];
5328:     if (useClosure) *useClosure = dm->adjacency[1];
5329:   } else {
5330:     PetscInt Nf;

5332:     PetscCall(DMGetNumFields(dm, &Nf));
5333:     PetscCheck(f < Nf, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Field number %" PetscInt_FMT " must be in [0, %" PetscInt_FMT ")", f, Nf);
5334:     if (useCone) *useCone = dm->fields[f].adjacency[0];
5335:     if (useClosure) *useClosure = dm->fields[f].adjacency[1];
5336:   }
5337:   PetscFunctionReturn(PETSC_SUCCESS);
5338: }

5340: /*@
5341:   DMSetAdjacency - Set the flags for determining variable influence

5343:   Not Collective

5345:   Input Parameters:
5346: + dm         - The `DM` object
5347: . f          - The field number
5348: . useCone    - Flag for variable influence starting with the cone operation
5349: - useClosure - Flag for variable influence using transitive closure

5351:   Level: developer

5353:   Notes:
5354: .vb
5355:      FEM:   Two points p and q are adjacent if q \in closure(star(p)),   useCone = PETSC_FALSE, useClosure = PETSC_TRUE
5356:      FVM:   Two points p and q are adjacent if q \in support(p+cone(p)), useCone = PETSC_TRUE,  useClosure = PETSC_FALSE
5357:      FVM++: Two points p and q are adjacent if q \in star(closure(p)),   useCone = PETSC_TRUE,  useClosure = PETSC_TRUE
5358: .ve
5359:   Further explanation can be found in the User's Manual Section on the Influence of Variables on One Another.

5361: .seealso: [](ch_dmbase), `DM`, `DMGetAdjacency()`, `DMGetField()`, `DMSetField()`
5362: @*/
5363: PetscErrorCode DMSetAdjacency(DM dm, PetscInt f, PetscBool useCone, PetscBool useClosure)
5364: {
5365:   PetscFunctionBegin;
5367:   if (f < 0) {
5368:     dm->adjacency[0] = useCone;
5369:     dm->adjacency[1] = useClosure;
5370:   } else {
5371:     PetscInt Nf;

5373:     PetscCall(DMGetNumFields(dm, &Nf));
5374:     PetscCheck(f < Nf, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Field number %" PetscInt_FMT " must be in [0, %" PetscInt_FMT ")", f, Nf);
5375:     dm->fields[f].adjacency[0] = useCone;
5376:     dm->fields[f].adjacency[1] = useClosure;
5377:   }
5378:   PetscFunctionReturn(PETSC_SUCCESS);
5379: }

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

5384:   Not collective

5386:   Input Parameter:
5387: . dm - The `DM` object

5389:   Output Parameters:
5390: + useCone    - Flag for variable influence starting with the cone operation
5391: - useClosure - Flag for variable influence using transitive closure

5393:   Level: developer

5395:   Notes:
5396: .vb
5397:      FEM:   Two points p and q are adjacent if q \in closure(star(p)),   useCone = PETSC_FALSE, useClosure = PETSC_TRUE
5398:      FVM:   Two points p and q are adjacent if q \in support(p+cone(p)), useCone = PETSC_TRUE,  useClosure = PETSC_FALSE
5399:      FVM++: Two points p and q are adjacent if q \in star(closure(p)),   useCone = PETSC_TRUE,  useClosure = PETSC_TRUE
5400: .ve

5402: .seealso: [](ch_dmbase), `DM`, `DMSetBasicAdjacency()`, `DMGetField()`, `DMSetField()`
5403: @*/
5404: PetscErrorCode DMGetBasicAdjacency(DM dm, PetscBool *useCone, PetscBool *useClosure)
5405: {
5406:   PetscInt Nf;

5408:   PetscFunctionBegin;
5410:   if (useCone) PetscAssertPointer(useCone, 2);
5411:   if (useClosure) PetscAssertPointer(useClosure, 3);
5412:   PetscCall(DMGetNumFields(dm, &Nf));
5413:   if (!Nf) {
5414:     PetscCall(DMGetAdjacency(dm, PETSC_DEFAULT, useCone, useClosure));
5415:   } else {
5416:     PetscCall(DMGetAdjacency(dm, 0, useCone, useClosure));
5417:   }
5418:   PetscFunctionReturn(PETSC_SUCCESS);
5419: }

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

5424:   Not Collective

5426:   Input Parameters:
5427: + dm         - The `DM` object
5428: . useCone    - Flag for variable influence starting with the cone operation
5429: - useClosure - Flag for variable influence using transitive closure

5431:   Level: developer

5433:   Notes:
5434: .vb
5435:      FEM:   Two points p and q are adjacent if q \in closure(star(p)),   useCone = PETSC_FALSE, useClosure = PETSC_TRUE
5436:      FVM:   Two points p and q are adjacent if q \in support(p+cone(p)), useCone = PETSC_TRUE,  useClosure = PETSC_FALSE
5437:      FVM++: Two points p and q are adjacent if q \in star(closure(p)),   useCone = PETSC_TRUE,  useClosure = PETSC_TRUE
5438: .ve

5440: .seealso: [](ch_dmbase), `DM`, `DMGetBasicAdjacency()`, `DMGetField()`, `DMSetField()`
5441: @*/
5442: PetscErrorCode DMSetBasicAdjacency(DM dm, PetscBool useCone, PetscBool useClosure)
5443: {
5444:   PetscInt Nf;

5446:   PetscFunctionBegin;
5448:   PetscCall(DMGetNumFields(dm, &Nf));
5449:   if (!Nf) {
5450:     PetscCall(DMSetAdjacency(dm, PETSC_DEFAULT, useCone, useClosure));
5451:   } else {
5452:     PetscCall(DMSetAdjacency(dm, 0, useCone, useClosure));
5453:   }
5454:   PetscFunctionReturn(PETSC_SUCCESS);
5455: }

5457: PetscErrorCode DMCompleteBCLabels_Internal(DM dm)
5458: {
5459:   DM           plex;
5460:   DMLabel     *labels, *glabels;
5461:   const char **names;
5462:   char        *sendNames, *recvNames;
5463:   PetscInt     Nds, s, maxLabels = 0, maxLen = 0, gmaxLen, Nl = 0, gNl, l, gl, m;
5464:   size_t       len;
5465:   MPI_Comm     comm;
5466:   PetscMPIInt  rank, size, p, *counts, *displs;

5468:   PetscFunctionBegin;
5469:   PetscCall(PetscObjectGetComm((PetscObject)dm, &comm));
5470:   PetscCallMPI(MPI_Comm_size(comm, &size));
5471:   PetscCallMPI(MPI_Comm_rank(comm, &rank));
5472:   PetscCall(DMGetNumDS(dm, &Nds));
5473:   for (s = 0; s < Nds; ++s) {
5474:     PetscDS  dsBC;
5475:     PetscInt numBd;

5477:     PetscCall(DMGetRegionNumDS(dm, s, NULL, NULL, &dsBC, NULL));
5478:     PetscCall(PetscDSGetNumBoundary(dsBC, &numBd));
5479:     maxLabels += numBd;
5480:   }
5481:   PetscCall(PetscCalloc1(maxLabels, &labels));
5482:   /* Get list of labels to be completed */
5483:   for (s = 0; s < Nds; ++s) {
5484:     PetscDS  dsBC;
5485:     PetscInt numBd;

5487:     PetscCall(DMGetRegionNumDS(dm, s, NULL, NULL, &dsBC, NULL));
5488:     PetscCall(PetscDSGetNumBoundary(dsBC, &numBd));
5489:     for (PetscInt bd = 0; bd < numBd; ++bd) {
5490:       DMLabel      label;
5491:       PetscInt     field;
5492:       PetscObject  obj;
5493:       PetscClassId id;

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

5545: static PetscErrorCode DMDSEnlarge_Static(DM dm, PetscInt NdsNew)
5546: {
5547:   DMSpace *tmpd;
5548:   PetscInt Nds = dm->Nds, s;

5550:   PetscFunctionBegin;
5551:   if (Nds >= NdsNew) PetscFunctionReturn(PETSC_SUCCESS);
5552:   PetscCall(PetscMalloc1(NdsNew, &tmpd));
5553:   for (s = 0; s < Nds; ++s) tmpd[s] = dm->probs[s];
5554:   for (s = Nds; s < NdsNew; ++s) {
5555:     tmpd[s].ds     = NULL;
5556:     tmpd[s].label  = NULL;
5557:     tmpd[s].fields = NULL;
5558:   }
5559:   PetscCall(PetscFree(dm->probs));
5560:   dm->Nds   = NdsNew;
5561:   dm->probs = tmpd;
5562:   PetscFunctionReturn(PETSC_SUCCESS);
5563: }

5565: /*@
5566:   DMGetNumDS - Get the number of discrete systems in the `DM`

5568:   Not Collective

5570:   Input Parameter:
5571: . dm - The `DM`

5573:   Output Parameter:
5574: . Nds - The number of `PetscDS` objects

5576:   Level: intermediate

5578: .seealso: [](ch_dmbase), `DM`, `DMGetDS()`, `DMGetCellDS()`
5579: @*/
5580: PetscErrorCode DMGetNumDS(DM dm, PetscInt *Nds)
5581: {
5582:   PetscFunctionBegin;
5584:   PetscAssertPointer(Nds, 2);
5585:   *Nds = dm->Nds;
5586:   PetscFunctionReturn(PETSC_SUCCESS);
5587: }

5589: /*@
5590:   DMClearDS - Remove all discrete systems from the `DM`

5592:   Logically Collective

5594:   Input Parameter:
5595: . dm - The `DM`

5597:   Level: intermediate

5599: .seealso: [](ch_dmbase), `DM`, `DMGetNumDS()`, `DMGetDS()`, `DMSetField()`
5600: @*/
5601: PetscErrorCode DMClearDS(DM dm)
5602: {
5603:   PetscInt s;

5605:   PetscFunctionBegin;
5607:   for (s = 0; s < dm->Nds; ++s) {
5608:     PetscCall(PetscDSDestroy(&dm->probs[s].ds));
5609:     PetscCall(PetscDSDestroy(&dm->probs[s].dsIn));
5610:     PetscCall(DMLabelDestroy(&dm->probs[s].label));
5611:     PetscCall(ISDestroy(&dm->probs[s].fields));
5612:   }
5613:   PetscCall(PetscFree(dm->probs));
5614:   dm->probs = NULL;
5615:   dm->Nds   = 0;
5616:   PetscFunctionReturn(PETSC_SUCCESS);
5617: }

5619: /*@
5620:   DMGetDS - Get the default `PetscDS`

5622:   Not Collective

5624:   Input Parameter:
5625: . dm - The `DM`

5627:   Output Parameter:
5628: . ds - The default `PetscDS`

5630:   Level: intermediate

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

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

5647: /*@
5648:   DMGetCellDS - Get the `PetscDS` defined on a given cell

5650:   Not Collective

5652:   Input Parameters:
5653: + dm    - The `DM`
5654: - point - Cell for the `PetscDS`

5656:   Output Parameters:
5657: + ds   - The `PetscDS` defined on the given cell
5658: - dsIn - The `PetscDS` for input on the given cell, or `NULL` if the same ds

5660:   Level: developer

5662: .seealso: [](ch_dmbase), `DM`, `DMGetDS()`, `DMSetRegionDS()`
5663: @*/
5664: PetscErrorCode DMGetCellDS(DM dm, PetscInt point, PetscDS *ds, PetscDS *dsIn)
5665: {
5666:   PetscDS  dsDef = NULL;
5667:   PetscInt s;

5669:   PetscFunctionBeginHot;
5671:   if (ds) PetscAssertPointer(ds, 3);
5672:   if (dsIn) PetscAssertPointer(dsIn, 4);
5673:   PetscCheck(point >= 0, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Mesh point cannot be negative: %" PetscInt_FMT, point);
5674:   if (ds) *ds = NULL;
5675:   if (dsIn) *dsIn = NULL;
5676:   for (s = 0; s < dm->Nds; ++s) {
5677:     PetscInt val;

5679:     if (!dm->probs[s].label) {
5680:       dsDef = dm->probs[s].ds;
5681:     } else {
5682:       PetscCall(DMLabelGetValue(dm->probs[s].label, point, &val));
5683:       if (val >= 0) {
5684:         if (ds) *ds = dm->probs[s].ds;
5685:         if (dsIn) *dsIn = dm->probs[s].dsIn;
5686:         break;
5687:       }
5688:     }
5689:   }
5690:   if (ds && !*ds) *ds = dsDef;
5691:   PetscFunctionReturn(PETSC_SUCCESS);
5692: }

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

5697:   Not Collective

5699:   Input Parameters:
5700: + dm    - The `DM`
5701: - label - The `DMLabel` defining the mesh region, or `NULL` for the entire mesh

5703:   Output Parameters:
5704: + fields - The `IS` containing the `DM` field numbers for the fields in this `PetscDS`, or `NULL`
5705: . ds     - The `PetscDS` defined on the given region, or `NULL`
5706: - dsIn   - The `PetscDS` for input in the given region, or `NULL`

5708:   Level: advanced

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

5715: .seealso: [](ch_dmbase), `DM`, `DMGetRegionNumDS()`, `DMSetRegionDS()`, `DMGetDS()`, `DMGetCellDS()`
5716: @*/
5717: PetscErrorCode DMGetRegionDS(DM dm, DMLabel label, IS *fields, PetscDS *ds, PetscDS *dsIn)
5718: {
5719:   PetscInt Nds = dm->Nds, s;

5721:   PetscFunctionBegin;
5724:   if (fields) {
5725:     PetscAssertPointer(fields, 3);
5726:     *fields = NULL;
5727:   }
5728:   if (ds) {
5729:     PetscAssertPointer(ds, 4);
5730:     *ds = NULL;
5731:   }
5732:   if (dsIn) {
5733:     PetscAssertPointer(dsIn, 5);
5734:     *dsIn = NULL;
5735:   }
5736:   for (s = 0; s < Nds; ++s) {
5737:     if (dm->probs[s].label == label || !dm->probs[s].label) {
5738:       if (fields) *fields = dm->probs[s].fields;
5739:       if (ds) *ds = dm->probs[s].ds;
5740:       if (dsIn) *dsIn = dm->probs[s].dsIn;
5741:       if (dm->probs[s].label) PetscFunctionReturn(PETSC_SUCCESS);
5742:     }
5743:   }
5744:   PetscFunctionReturn(PETSC_SUCCESS);
5745: }

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

5750:   Collective

5752:   Input Parameters:
5753: + dm     - The `DM`
5754: . label  - The `DMLabel` defining the mesh region, or `NULL` for the entire mesh
5755: . fields - The `IS` containing the `DM` field numbers for the fields in this `PetscDS`, or `NULL` for all fields
5756: . ds     - The `PetscDS` defined on the given region
5757: - dsIn   - The `PetscDS` for input on the given cell, or `NULL` if it is the same `PetscDS`

5759:   Level: advanced

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

5765: .seealso: [](ch_dmbase), `DM`, `DMGetRegionDS()`, `DMSetRegionNumDS()`, `DMGetDS()`, `DMGetCellDS()`
5766: @*/
5767: PetscErrorCode DMSetRegionDS(DM dm, DMLabel label, IS fields, PetscDS ds, PetscDS dsIn)
5768: {
5769:   PetscInt Nds = dm->Nds, s;

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

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

5806:   Not Collective

5808:   Input Parameters:
5809: + dm  - The `DM`
5810: - num - The region number, in [0, Nds)

5812:   Output Parameters:
5813: + label  - The region label, or `NULL`
5814: . fields - The `IS` containing the `DM` field numbers for the fields in this `PetscDS`, or `NULL`
5815: . ds     - The `PetscDS` defined on the given region, or `NULL`
5816: - dsIn   - The `PetscDS` for input in the given region, or `NULL`

5818:   Level: advanced

5820: .seealso: [](ch_dmbase), `DM`, `DMGetRegionDS()`, `DMSetRegionDS()`, `DMGetDS()`, `DMGetCellDS()`
5821: @*/
5822: PetscErrorCode DMGetRegionNumDS(DM dm, PetscInt num, DMLabel *label, IS *fields, PetscDS *ds, PetscDS *dsIn)
5823: {
5824:   PetscInt Nds;

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

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

5852:   Not Collective

5854:   Input Parameters:
5855: + dm     - The `DM`
5856: . num    - The region number, in [0, Nds)
5857: . label  - The region label, or `NULL`
5858: . fields - The `IS` containing the `DM` field numbers for the fields in this `PetscDS`, or `NULL` to prevent setting
5859: . ds     - The `PetscDS` defined on the given region, or `NULL` to prevent setting
5860: - dsIn   - The `PetscDS` for input on the given cell, or `NULL` if it is the same `PetscDS`

5862:   Level: advanced

5864: .seealso: [](ch_dmbase), `DM`, `DMGetRegionDS()`, `DMSetRegionDS()`, `DMGetDS()`, `DMGetCellDS()`
5865: @*/
5866: PetscErrorCode DMSetRegionNumDS(DM dm, PetscInt num, DMLabel label, IS fields, PetscDS ds, PetscDS dsIn)
5867: {
5868:   PetscInt Nds;

5870:   PetscFunctionBegin;
5873:   PetscCall(DMGetNumDS(dm, &Nds));
5874:   PetscCheck((num >= 0) && (num < Nds), PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Region number %" PetscInt_FMT " is not in [0, %" PetscInt_FMT ")", num, Nds);
5875:   PetscCall(PetscObjectReference((PetscObject)label));
5876:   PetscCall(DMLabelDestroy(&dm->probs[num].label));
5877:   dm->probs[num].label = label;
5878:   if (fields) {
5880:     PetscCall(PetscObjectReference((PetscObject)fields));
5881:     PetscCall(ISDestroy(&dm->probs[num].fields));
5882:     dm->probs[num].fields = fields;
5883:   }
5884:   if (ds) {
5886:     PetscCall(PetscObjectReference((PetscObject)ds));
5887:     PetscCall(PetscDSDestroy(&dm->probs[num].ds));
5888:     dm->probs[num].ds = ds;
5889:   }
5890:   if (dsIn) {
5892:     PetscCall(PetscObjectReference((PetscObject)dsIn));
5893:     PetscCall(PetscDSDestroy(&dm->probs[num].dsIn));
5894:     dm->probs[num].dsIn = dsIn;
5895:   }
5896:   PetscFunctionReturn(PETSC_SUCCESS);
5897: }

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

5902:   Not Collective

5904:   Input Parameters:
5905: + dm - The `DM`
5906: - ds - The `PetscDS` defined on the given region

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

5911:   Level: advanced

5913: .seealso: [](ch_dmbase), `DM`, `DMGetRegionNumDS()`, `DMGetRegionDS()`, `DMSetRegionDS()`, `DMGetDS()`, `DMGetCellDS()`
5914: @*/
5915: PetscErrorCode DMFindRegionNum(DM dm, PetscDS ds, PetscInt *num)
5916: {
5917:   PetscInt Nds, n;

5919:   PetscFunctionBegin;
5922:   PetscAssertPointer(num, 3);
5923:   PetscCall(DMGetNumDS(dm, &Nds));
5924:   for (n = 0; n < Nds; ++n)
5925:     if (ds == dm->probs[n].ds) break;
5926:   if (n >= Nds) *num = -1;
5927:   else *num = n;
5928:   PetscFunctionReturn(PETSC_SUCCESS);
5929: }

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

5934:   Not Collective

5936:   Input Parameters:
5937: + dm     - The `DM`
5938: . Nc     - The number of components for the field
5939: . prefix - The options prefix for the output `PetscFE`, or `NULL`
5940: - qorder - The quadrature order or `PETSC_DETERMINE` to use `PetscSpace` polynomial degree

5942:   Output Parameter:
5943: . fem - The `PetscFE`

5945:   Level: intermediate

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

5950: .seealso: [](ch_dmbase), `DM`, `PetscFECreateByCell()`, `DMAddField()`, `DMCreateDS()`, `DMGetCellDS()`, `DMGetRegionDS()`
5951: @*/
5952: PetscErrorCode DMCreateFEDefault(DM dm, PetscInt Nc, const char prefix[], PetscInt qorder, PetscFE *fem)
5953: {
5954:   DMPolytopeType ct;
5955:   PetscInt       dim, cStart;

5957:   PetscFunctionBegin;
5960:   if (prefix) PetscAssertPointer(prefix, 3);
5962:   PetscAssertPointer(fem, 5);
5963:   PetscCall(DMGetDimension(dm, &dim));
5964:   PetscCall(DMPlexGetHeightStratum(dm, 0, &cStart, NULL));
5965:   PetscCall(DMPlexGetCellType(dm, cStart, &ct));
5966:   PetscCall(PetscFECreateByCell(PETSC_COMM_SELF, dim, Nc, ct, prefix, qorder, fem));
5967:   PetscFunctionReturn(PETSC_SUCCESS);
5968: }

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

5973:   Collective

5975:   Input Parameter:
5976: . dm - The `DM`

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

5981:   Level: intermediate

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

5986: .seealso: [](ch_dmbase), `DM`, `DMSetField`, `DMAddField()`, `DMGetDS()`, `DMGetCellDS()`, `DMGetRegionDS()`, `DMSetRegionDS()`
5987: @*/
5988: PetscErrorCode DMCreateDS(DM dm)
5989: {
5990:   MPI_Comm  comm;
5991:   PetscDS   dsDef;
5992:   DMLabel  *labelSet;
5993:   PetscInt  dE, Nf = dm->Nf, f, s, Nl, l, Ndef, k;
5994:   PetscBool doSetup = PETSC_TRUE, flg;

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

6012: #ifdef PETSC_HAVE_LIBCEED
6013:     /* Move CEED context to discretizations */
6014:     {
6015:       PetscClassId id;

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

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

6041:     for (f = 0, nf = 0; f < Nf; ++f)
6042:       if (!dm->fields[f].label) ++nf;
6043:     PetscCheck(nf, comm, PETSC_ERR_PLIB, "All fields have labels, but we are trying to create a default DS");
6044:     PetscCall(PetscMalloc1(nf, &fld));
6045:     for (f = 0, nf = 0; f < Nf; ++f)
6046:       if (!dm->fields[f].label) fld[nf++] = f;
6047:     PetscCall(ISCreate(PETSC_COMM_SELF, &fields));
6048:     PetscCall(PetscObjectSetOptionsPrefix((PetscObject)fields, "dm_fields_"));
6049:     PetscCall(ISSetType(fields, ISGENERAL));
6050:     PetscCall(ISGeneralSetIndices(fields, nf, fld, PETSC_OWN_POINTER));

6052:     PetscCall(PetscDSCreate(PETSC_COMM_SELF, &dsDef));
6053:     PetscCall(DMSetRegionDS(dm, NULL, fields, dsDef, NULL));
6054:     PetscCall(PetscDSDestroy(&dsDef));
6055:     PetscCall(ISDestroy(&fields));
6056:   }
6057:   PetscCall(DMGetRegionDS(dm, NULL, NULL, &dsDef, NULL));
6058:   if (dsDef) PetscCall(PetscDSSetCoordinateDimension(dsDef, dE));
6059:   /* Intersect labels with default fields */
6060:   if (Ndef && Nl) {
6061:     DM              plex;
6062:     DMLabel         cellLabel;
6063:     IS              fieldIS, allcellIS, defcellIS = NULL;
6064:     PetscInt       *fields;
6065:     const PetscInt *cells;
6066:     PetscInt        depth, nf = 0, n, c;

6068:     PetscCall(DMConvert(dm, DMPLEX, &plex));
6069:     PetscCall(DMPlexGetDepth(plex, &depth));
6070:     PetscCall(DMGetStratumIS(plex, "dim", depth, &allcellIS));
6071:     if (!allcellIS) PetscCall(DMGetStratumIS(plex, "depth", depth, &allcellIS));
6072:     /* TODO This looks like it only works for one label */
6073:     for (l = 0; l < Nl; ++l) {
6074:       DMLabel label = labelSet[l];
6075:       IS      pointIS;

6077:       PetscCall(ISDestroy(&defcellIS));
6078:       PetscCall(DMLabelGetStratumIS(label, 1, &pointIS));
6079:       PetscCall(ISDifference(allcellIS, pointIS, &defcellIS));
6080:       PetscCall(ISDestroy(&pointIS));
6081:     }
6082:     PetscCall(ISDestroy(&allcellIS));

6084:     PetscCall(DMLabelCreate(PETSC_COMM_SELF, "defaultCells", &cellLabel));
6085:     PetscCall(ISGetLocalSize(defcellIS, &n));
6086:     PetscCall(ISGetIndices(defcellIS, &cells));
6087:     for (c = 0; c < n; ++c) PetscCall(DMLabelSetValue(cellLabel, cells[c], 1));
6088:     PetscCall(ISRestoreIndices(defcellIS, &cells));
6089:     PetscCall(ISDestroy(&defcellIS));
6090:     PetscCall(DMPlexLabelComplete(plex, cellLabel));

6092:     PetscCall(PetscMalloc1(Ndef, &fields));
6093:     for (f = 0; f < Nf; ++f)
6094:       if (!dm->fields[f].label) fields[nf++] = f;
6095:     PetscCall(ISCreate(PETSC_COMM_SELF, &fieldIS));
6096:     PetscCall(PetscObjectSetOptionsPrefix((PetscObject)fieldIS, "dm_fields_"));
6097:     PetscCall(ISSetType(fieldIS, ISGENERAL));
6098:     PetscCall(ISGeneralSetIndices(fieldIS, nf, fields, PETSC_OWN_POINTER));

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

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

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

6182:     PetscCall(PetscDSGetNumFields(ds, &dsnf));
6183:     PetscCall(PetscDSIsCohesive(ds, &isCohesive));
6184:     PetscCall(ISGetLocalSize(fields, &nf));
6185:     PetscCall(ISGetIndices(fields, &fld));
6186:     for (f = 0; f < nf; ++f) {
6187:       PetscObject  disc = dm->fields[fld[f]].disc;
6188:       PetscBool    isCohesiveField;
6189:       PetscClassId id;

6191:       /* Handle DS with no fields */
6192:       if (dsnf) PetscCall(PetscDSGetCohesive(ds, f, &isCohesiveField));
6193:       /* If this is a cohesive cell, then regular fields need the lower dimensional discretization */
6194:       if (isCohesive) {
6195:         if (!isCohesiveField) {
6196:           PetscObject bdDisc;

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

6222:       PetscCall(PetscDSGetNumFields(ds, &Nf));
6223:       for (PetscInt f = 0; f < Nf; ++f) {
6224:         PetscCall(PetscDSSetJetDegree(ds, f, k));
6225:         if (dsIn) PetscCall(PetscDSSetJetDegree(dsIn, f, k));
6226:       }
6227:     }
6228:   }
6229:   /* Setup DSes */
6230:   if (doSetup) {
6231:     for (s = 0; s < dm->Nds; ++s) {
6232:       if (dm->setfromoptionscalled) {
6233:         PetscCall(PetscDSSetFromOptions(dm->probs[s].ds));
6234:         if (dm->probs[s].dsIn) PetscCall(PetscDSSetFromOptions(dm->probs[s].dsIn));
6235:       }
6236:       PetscCall(PetscDSSetUp(dm->probs[s].ds));
6237:       if (dm->probs[s].dsIn) PetscCall(PetscDSSetUp(dm->probs[s].dsIn));
6238:     }
6239:   }
6240:   PetscFunctionReturn(PETSC_SUCCESS);
6241: }

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

6246:   Input Parameters:
6247: + dm     - The DM
6248: - tensor - Flag for tensor order

6250:   Level: developer

6252: .seealso: `DMPlexSetClosurePermutationTensor()`, `PetscSectionResetClosurePermutation()`
6253: @*/
6254: PetscErrorCode DMUseTensorOrder(DM dm, PetscBool tensor)
6255: {
6256:   PetscInt  Nf;
6257:   PetscBool reorder = PETSC_TRUE, isPlex;

6259:   PetscFunctionBegin;
6260:   PetscCall(PetscObjectTypeCompare((PetscObject)dm, DMPLEX, &isPlex));
6261:   PetscCall(DMGetNumFields(dm, &Nf));
6262:   for (PetscInt f = 0; f < Nf; ++f) {
6263:     PetscObject  obj;
6264:     PetscClassId id;

6266:     PetscCall(DMGetField(dm, f, NULL, &obj));
6267:     PetscCall(PetscObjectGetClassId(obj, &id));
6268:     if (id == PETSCFE_CLASSID) {
6269:       PetscSpace sp;
6270:       PetscBool  tensor;

6272:       PetscCall(PetscFEGetBasisSpace((PetscFE)obj, &sp));
6273:       PetscCall(PetscSpacePolynomialGetTensor(sp, &tensor));
6274:       reorder = reorder && tensor ? PETSC_TRUE : PETSC_FALSE;
6275:     } else reorder = PETSC_FALSE;
6276:   }
6277:   if (tensor) {
6278:     if (reorder && isPlex) PetscCall(DMPlexSetClosurePermutationTensor(dm, PETSC_DETERMINE, NULL));
6279:   } else {
6280:     PetscSection s;

6282:     PetscCall(DMGetLocalSection(dm, &s));
6283:     if (s) PetscCall(PetscSectionResetClosurePermutation(s));
6284:   }
6285:   PetscFunctionReturn(PETSC_SUCCESS);
6286: }

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

6291:   Collective

6293:   Input Parameters:
6294: + dm   - The `DM`
6295: - time - The time

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

6301:   Level: developer

6303:   Note:
6304:   The user must call `PetscDSSetExactSolution()` before using this routine

6306: .seealso: [](ch_dmbase), `DM`, `PetscDSSetExactSolution()`
6307: @*/
6308: PetscErrorCode DMComputeExactSolution(DM dm, PetscReal time, Vec u, Vec u_t)
6309: {
6310:   PetscErrorCode (**exacts)(PetscInt, PetscReal, const PetscReal x[], PetscInt, PetscScalar *u, PetscCtx ctx);
6311:   void   **ectxs;
6312:   Vec      locu, locu_t;
6313:   PetscInt Nf, Nds, s;

6315:   PetscFunctionBegin;
6317:   if (u) {
6319:     PetscCall(DMGetLocalVector(dm, &locu));
6320:     PetscCall(VecSet(locu, 0.));
6321:   }
6322:   if (u_t) {
6324:     PetscCall(DMGetLocalVector(dm, &locu_t));
6325:     PetscCall(VecSet(locu_t, 0.));
6326:   }
6327:   PetscCall(DMGetNumFields(dm, &Nf));
6328:   PetscCall(PetscMalloc2(Nf, &exacts, Nf, &ectxs));
6329:   PetscCall(DMGetNumDS(dm, &Nds));
6330:   for (s = 0; s < Nds; ++s) {
6331:     PetscDS         ds;
6332:     DMLabel         label;
6333:     IS              fieldIS;
6334:     const PetscInt *fields, id = 1;
6335:     PetscInt        dsNf;

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

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

6382:   PetscFunctionBegin;
6383:   PetscCall(PetscDSCreate(PetscObjectComm((PetscObject)ds), &dsNew));
6384:   PetscCall(PetscDSCopy(ds, minDegree, maxDegree, dm, dsNew));
6385:   if (dsIn) {
6386:     PetscCall(PetscDSCreate(PetscObjectComm((PetscObject)dsIn), &dsInNew));
6387:     PetscCall(PetscDSCopy(dsIn, minDegree, maxDegree, dm, dsInNew));
6388:   }
6389:   PetscCall(DMSetRegionDS(dm, label, fields, dsNew, dsInNew));
6390:   PetscCall(PetscDSDestroy(&dsNew));
6391:   PetscCall(PetscDSDestroy(&dsInNew));
6392:   PetscFunctionReturn(PETSC_SUCCESS);
6393: }

6395: /*@
6396:   DMCopyDS - Copy the discrete systems for the `DM` into another `DM`

6398:   Collective

6400:   Input Parameters:
6401: + dm        - The `DM`
6402: . minDegree - Minimum degree for a discretization, or `PETSC_DETERMINE` for no limit
6403: - maxDegree - Maximum degree for a discretization, or `PETSC_DETERMINE` for no limit

6405:   Output Parameter:
6406: . newdm - The `DM`

6408:   Level: advanced

6410: .seealso: [](ch_dmbase), `DM`, `DMCopyFields()`, `DMAddField()`, `DMGetDS()`, `DMGetCellDS()`, `DMGetRegionDS()`, `DMSetRegionDS()`
6411: @*/
6412: PetscErrorCode DMCopyDS(DM dm, PetscInt minDegree, PetscInt maxDegree, DM newdm)
6413: {
6414:   PetscInt Nds;

6416:   PetscFunctionBegin;
6417:   if (dm == newdm) PetscFunctionReturn(PETSC_SUCCESS);
6418:   PetscCall(DMGetNumDS(dm, &Nds));
6419:   PetscCall(DMClearDS(newdm));
6420:   for (PetscInt s = 0; s < Nds; ++s) {
6421:     DMLabel  label;
6422:     IS       fields;
6423:     PetscDS  ds, dsIn, newds;
6424:     PetscInt Nbd;

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

6437:       PetscCall(PetscDSGetBoundary(newds, bd, &wf, NULL, NULL, &label, NULL, NULL, &field, NULL, NULL, NULL, NULL, NULL));
6438:       PetscCall(PetscWeakFormReplaceLabel(wf, label));
6439:     }
6440:   }
6441:   PetscCall(DMCompleteBCLabels_Internal(newdm));
6442:   PetscFunctionReturn(PETSC_SUCCESS);
6443: }

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

6448:   Collective

6450:   Input Parameter:
6451: . dm - The `DM`

6453:   Output Parameter:
6454: . newdm - The `DM`

6456:   Level: advanced

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

6461: .seealso: [](ch_dmbase), `DM`, `DMCopyFields()`, `DMCopyDS()`
6462: @*/
6463: PetscErrorCode DMCopyDisc(DM dm, DM newdm)
6464: {
6465:   PetscFunctionBegin;
6466:   PetscCall(DMCopyFields(dm, PETSC_DETERMINE, PETSC_DETERMINE, newdm));
6467:   PetscCall(DMCopyDS(dm, PETSC_DETERMINE, PETSC_DETERMINE, newdm));
6468:   PetscFunctionReturn(PETSC_SUCCESS);
6469: }

6471: /*@
6472:   DMGetDimension - Return the topological dimension of the `DM`

6474:   Not Collective

6476:   Input Parameter:
6477: . dm - The `DM`

6479:   Output Parameter:
6480: . dim - The topological dimension

6482:   Level: beginner

6484: .seealso: [](ch_dmbase), `DM`, `DMSetDimension()`, `DMCreate()`
6485: @*/
6486: PetscErrorCode DMGetDimension(DM dm, PetscInt *dim)
6487: {
6488:   PetscFunctionBegin;
6490:   PetscAssertPointer(dim, 2);
6491:   *dim = dm->dim;
6492:   PetscFunctionReturn(PETSC_SUCCESS);
6493: }

6495: /*@
6496:   DMSetDimension - Set the topological dimension of the `DM`

6498:   Collective

6500:   Input Parameters:
6501: + dm  - The `DM`
6502: - dim - The topological dimension

6504:   Level: beginner

6506: .seealso: [](ch_dmbase), `DM`, `DMGetDimension()`, `DMCreate()`
6507: @*/
6508: PetscErrorCode DMSetDimension(DM dm, PetscInt dim)
6509: {
6510:   PetscDS  ds;
6511:   PetscInt Nds;

6513:   PetscFunctionBegin;
6516:   if (dm->dim != dim) PetscCall(DMSetPeriodicity(dm, NULL, NULL, NULL));
6517:   dm->dim = dim;
6518:   if (dm->dim >= 0) {
6519:     PetscCall(DMGetNumDS(dm, &Nds));
6520:     for (PetscInt n = 0; n < Nds; ++n) {
6521:       PetscCall(DMGetRegionNumDS(dm, n, NULL, NULL, &ds, NULL));
6522:       if (ds->dimEmbed < 0) PetscCall(PetscDSSetCoordinateDimension(ds, dim));
6523:     }
6524:   }
6525:   PetscFunctionReturn(PETSC_SUCCESS);
6526: }

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

6531:   Collective

6533:   Input Parameters:
6534: + dm  - the `DM`
6535: - dim - the dimension

6537:   Output Parameters:
6538: + pStart - The first point of the given dimension
6539: - pEnd   - The first point following points of the given dimension

6541:   Level: intermediate

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

6548: .seealso: [](ch_dmbase), `DM`, `DMPLEX`, `DMPlexGetDepthStratum()`, `DMPlexGetHeightStratum()`
6549: @*/
6550: PetscErrorCode DMGetDimPoints(DM dm, PetscInt dim, PetscInt *pStart, PetscInt *pEnd)
6551: {
6552:   PetscInt d;

6554:   PetscFunctionBegin;
6556:   PetscCall(DMGetDimension(dm, &d));
6557:   PetscCheck((dim >= 0) && (dim <= d), PetscObjectComm((PetscObject)dm), PETSC_ERR_ARG_OUTOFRANGE, "Invalid dimension %" PetscInt_FMT, dim);
6558:   PetscUseTypeMethod(dm, getdimpoints, dim, pStart, pEnd);
6559:   PetscFunctionReturn(PETSC_SUCCESS);
6560: }

6562: /*@
6563:   DMGetOutputDM - Retrieve the `DM` associated with the layout for output

6565:   Collective

6567:   Input Parameter:
6568: . dm - The original `DM`

6570:   Output Parameter:
6571: . odm - The `DM` which provides the layout for output

6573:   Level: intermediate

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

6580: .seealso: [](ch_dmbase), `DM`, `VecView()`, `DMGetGlobalSection()`, `DMCreateGlobalVector()`, `PetscSectionHasConstraints()`, `DMSetGlobalSection()`
6581: @*/
6582: PetscErrorCode DMGetOutputDM(DM dm, DM *odm)
6583: {
6584:   PetscSection section;
6585:   IS           perm;
6586:   PetscBool    hasConstraints, newDM, gnewDM;
6587:   PetscInt     num_face_sfs = 0;

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

6607:     PetscCall(DMClone(dm, &dm->dmBC));
6608:     PetscCall(DMCopyDisc(dm, dm->dmBC));
6609:     PetscCall(PetscSectionClone(section, &newSection));
6610:     PetscCall(DMSetLocalSection(dm->dmBC, newSection));
6611:     PetscCall(PetscSectionDestroy(&newSection));
6612:     PetscCall(DMGetNaturalSF(dm, &sfNatural));
6613:     PetscCall(DMSetNaturalSF(dm->dmBC, sfNatural));
6614:     PetscCall(DMGetPointSF(dm->dmBC, &sf));
6615:     PetscCall(PetscSectionCreateGlobalSection(section, sf, usePerm, PETSC_TRUE, PETSC_FALSE, &gsection));
6616:     PetscCall(DMSetGlobalSection(dm->dmBC, gsection));
6617:     PetscCall(PetscSectionDestroy(&gsection));
6618:   }
6619:   *odm = dm->dmBC;
6620:   PetscFunctionReturn(PETSC_SUCCESS);
6621: }

6623: /*@
6624:   DMGetOutputSequenceNumber - Retrieve the sequence number/value for output

6626:   Input Parameter:
6627: . dm - The original `DM`

6629:   Output Parameters:
6630: + num - The output sequence number
6631: - val - The output sequence value

6633:   Level: intermediate

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

6639:   Developer Note:
6640:   The `DM` serves as a convenient place to store the current iteration value. The iteration is not
6641:   not directly related to the `DM`.

6643: .seealso: [](ch_dmbase), `DM`, `VecView()`
6644: @*/
6645: PetscErrorCode DMGetOutputSequenceNumber(DM dm, PetscInt *num, PetscReal *val)
6646: {
6647:   PetscFunctionBegin;
6649:   if (num) {
6650:     PetscAssertPointer(num, 2);
6651:     *num = dm->outputSequenceNum;
6652:   }
6653:   if (val) {
6654:     PetscAssertPointer(val, 3);
6655:     *val = dm->outputSequenceVal;
6656:   }
6657:   PetscFunctionReturn(PETSC_SUCCESS);
6658: }

6660: /*@
6661:   DMSetOutputSequenceNumber - Set the sequence number/value for output

6663:   Input Parameters:
6664: + dm  - The original `DM`
6665: . num - The output sequence number
6666: - val - The output sequence value

6668:   Level: intermediate

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

6674: .seealso: [](ch_dmbase), `DM`, `VecView()`
6675: @*/
6676: PetscErrorCode DMSetOutputSequenceNumber(DM dm, PetscInt num, PetscReal val)
6677: {
6678:   PetscFunctionBegin;
6680:   dm->outputSequenceNum = num;
6681:   dm->outputSequenceVal = val;
6682:   PetscFunctionReturn(PETSC_SUCCESS);
6683: }

6685: /*@
6686:   DMOutputSequenceLoad - Retrieve the sequence value from a `PetscViewer`

6688:   Input Parameters:
6689: + dm     - The original `DM`
6690: . viewer - The `PetscViewer` to get it from
6691: . name   - The sequence name
6692: - num    - The output sequence number

6694:   Output Parameter:
6695: . val - The output sequence value

6697:   Level: intermediate

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

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

6706: .seealso: [](ch_dmbase), `DM`, `DMGetOutputSequenceNumber()`, `DMSetOutputSequenceNumber()`, `VecView()`
6707: @*/
6708: PetscErrorCode DMOutputSequenceLoad(DM dm, PetscViewer viewer, const char name[], PetscInt num, PetscReal *val)
6709: {
6710:   PetscBool ishdf5;

6712:   PetscFunctionBegin;
6715:   PetscAssertPointer(name, 3);
6716:   PetscAssertPointer(val, 5);
6717:   PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERHDF5, &ishdf5));
6718:   PetscCheck(ishdf5, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Invalid viewer; open viewer with PetscViewerHDF5Open()");
6719: #if defined(PETSC_HAVE_HDF5)
6720:   PetscScalar value;

6722:   PetscCall(DMSequenceLoad_HDF5_Internal(dm, name, num, &value, viewer));
6723:   *val = PetscRealPart(value);
6724: #endif
6725:   PetscFunctionReturn(PETSC_SUCCESS);
6726: }

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

6731:   Input Parameters:
6732: + dm     - The original `DM`
6733: . viewer - The `PetscViewer` to get it from
6734: - name   - The sequence name

6736:   Output Parameter:
6737: . len - The length of the output sequence

6739:   Level: intermediate

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

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

6748: .seealso: [](ch_dmbase), `DM`, `DMGetOutputSequenceNumber()`, `DMSetOutputSequenceNumber()`, `VecView()`
6749: @*/
6750: PetscErrorCode DMGetOutputSequenceLength(DM dm, PetscViewer viewer, const char name[], PetscInt *len)
6751: {
6752:   PetscBool ishdf5;

6754:   PetscFunctionBegin;
6757:   PetscAssertPointer(name, 3);
6758:   PetscAssertPointer(len, 4);
6759:   PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERHDF5, &ishdf5));
6760:   PetscCheck(ishdf5, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Invalid viewer; open viewer with PetscViewerHDF5Open()");
6761: #if defined(PETSC_HAVE_HDF5)
6762:   PetscCall(DMSequenceGetLength_HDF5_Internal(dm, name, len, viewer));
6763: #endif
6764:   PetscFunctionReturn(PETSC_SUCCESS);
6765: }

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

6770:   Not Collective

6772:   Input Parameter:
6773: . dm - The `DM`

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

6778:   Level: beginner

6780: .seealso: [](ch_dmbase), `DM`, `DMSetUseNatural()`, `DMCreate()`
6781: @*/
6782: PetscErrorCode DMGetUseNatural(DM dm, PetscBool *useNatural)
6783: {
6784:   PetscFunctionBegin;
6786:   PetscAssertPointer(useNatural, 2);
6787:   *useNatural = dm->useNatural;
6788:   PetscFunctionReturn(PETSC_SUCCESS);
6789: }

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

6794:   Collective

6796:   Input Parameters:
6797: + dm         - The `DM`
6798: - useNatural - `PETSC_TRUE` to build the mapping to a natural order during distribution

6800:   Level: beginner

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

6805: .seealso: [](ch_dmbase), `DM`, `DMGetUseNatural()`, `DMCreate()`, `DMPlexDistribute()`, `DMCreateSubDM()`, `DMCreateSuperDM()`
6806: @*/
6807: PetscErrorCode DMSetUseNatural(DM dm, PetscBool useNatural)
6808: {
6809:   PetscFunctionBegin;
6812:   dm->useNatural = useNatural;
6813:   PetscFunctionReturn(PETSC_SUCCESS);
6814: }

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

6819:   Not Collective

6821:   Input Parameters:
6822: + dm   - The `DM` object
6823: - name - The label name

6825:   Level: intermediate

6827: .seealso: [](ch_dmbase), `DM`, `DMLabelCreate()`, `DMHasLabel()`, `DMGetLabelValue()`, `DMSetLabelValue()`, `DMGetStratumIS()`
6828: @*/
6829: PetscErrorCode DMCreateLabel(DM dm, const char name[])
6830: {
6831:   PetscBool flg;
6832:   DMLabel   label;

6834:   PetscFunctionBegin;
6836:   PetscAssertPointer(name, 2);
6837:   PetscCall(DMHasLabel(dm, name, &flg));
6838:   if (!flg) {
6839:     PetscCall(DMLabelCreate(PETSC_COMM_SELF, name, &label));
6840:     PetscCall(DMAddLabel(dm, label));
6841:     PetscCall(DMLabelDestroy(&label));
6842:   }
6843:   PetscFunctionReturn(PETSC_SUCCESS);
6844: }

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

6849:   Not Collective

6851:   Input Parameters:
6852: + dm   - The `DM` object
6853: . l    - The index for the label
6854: - name - The label name

6856:   Level: intermediate

6858: .seealso: [](ch_dmbase), `DM`, `DMCreateLabel()`, `DMLabelCreate()`, `DMHasLabel()`, `DMGetLabelValue()`, `DMSetLabelValue()`, `DMGetStratumIS()`
6859: @*/
6860: PetscErrorCode DMCreateLabelAtIndex(DM dm, PetscInt l, const char name[])
6861: {
6862:   DMLabelLink orig, prev = NULL;
6863:   DMLabel     label;
6864:   PetscInt    Nl, m;
6865:   PetscBool   flg, match;
6866:   const char *lname;

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

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

6901:   Not Collective

6903:   Input Parameters:
6904: + dm    - The `DM` object
6905: . name  - The label name
6906: - point - The mesh point

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

6911:   Level: beginner

6913: .seealso: [](ch_dmbase), `DM`, `DMLabelGetValue()`, `DMSetLabelValue()`, `DMGetStratumIS()`
6914: @*/
6915: PetscErrorCode DMGetLabelValue(DM dm, const char name[], PetscInt point, PetscInt *value)
6916: {
6917:   DMLabel label;

6919:   PetscFunctionBegin;
6921:   PetscAssertPointer(name, 2);
6922:   PetscCall(DMGetLabel(dm, name, &label));
6923:   PetscCheck(label, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "No label named %s was found", name);
6924:   PetscCall(DMLabelGetValue(label, point, value));
6925:   PetscFunctionReturn(PETSC_SUCCESS);
6926: }

6928: /*@
6929:   DMSetLabelValue - Add a point to a `DMLabel` with given value

6931:   Not Collective

6933:   Input Parameters:
6934: + dm    - The `DM` object
6935: . name  - The label name
6936: . point - The mesh point
6937: - value - The label value for this point

6939:   Output Parameter:

6941:   Level: beginner

6943: .seealso: [](ch_dmbase), `DM`, `DMLabelSetValue()`, `DMGetStratumIS()`, `DMClearLabelValue()`
6944: @*/
6945: PetscErrorCode DMSetLabelValue(DM dm, const char name[], PetscInt point, PetscInt value)
6946: {
6947:   DMLabel label;

6949:   PetscFunctionBegin;
6951:   PetscAssertPointer(name, 2);
6952:   PetscCall(DMGetLabel(dm, name, &label));
6953:   if (!label) {
6954:     PetscCall(DMCreateLabel(dm, name));
6955:     PetscCall(DMGetLabel(dm, name, &label));
6956:   }
6957:   PetscCall(DMLabelSetValue(label, point, value));
6958:   PetscFunctionReturn(PETSC_SUCCESS);
6959: }

6961: /*@
6962:   DMClearLabelValue - Remove a point from a `DMLabel` with given value

6964:   Not Collective

6966:   Input Parameters:
6967: + dm    - The `DM` object
6968: . name  - The label name
6969: . point - The mesh point
6970: - value - The label value for this point

6972:   Level: beginner

6974: .seealso: [](ch_dmbase), `DM`, `DMLabelClearValue()`, `DMSetLabelValue()`, `DMGetStratumIS()`
6975: @*/
6976: PetscErrorCode DMClearLabelValue(DM dm, const char name[], PetscInt point, PetscInt value)
6977: {
6978:   DMLabel label;

6980:   PetscFunctionBegin;
6982:   PetscAssertPointer(name, 2);
6983:   PetscCall(DMGetLabel(dm, name, &label));
6984:   if (!label) PetscFunctionReturn(PETSC_SUCCESS);
6985:   PetscCall(DMLabelClearValue(label, point, value));
6986:   PetscFunctionReturn(PETSC_SUCCESS);
6987: }

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

6992:   Not Collective

6994:   Input Parameters:
6995: + dm   - The `DM` object
6996: - name - The label name

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

7001:   Level: beginner

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

7006: .seealso: [](ch_dmbase), `DM`, `DMLabelGetNumValues()`, `DMSetLabelValue()`, `DMGetLabel()`
7007: @*/
7008: PetscErrorCode DMGetLabelSize(DM dm, const char name[], PetscInt *size)
7009: {
7010:   DMLabel label;

7012:   PetscFunctionBegin;
7014:   PetscAssertPointer(name, 2);
7015:   PetscAssertPointer(size, 3);
7016:   PetscCall(DMGetLabel(dm, name, &label));
7017:   *size = 0;
7018:   if (!label) PetscFunctionReturn(PETSC_SUCCESS);
7019:   PetscCall(DMLabelGetNumValues(label, size));
7020:   PetscFunctionReturn(PETSC_SUCCESS);
7021: }

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

7026:   Not Collective

7028:   Input Parameters:
7029: + dm   - The `DM` object
7030: - name - The label name

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

7035:   Level: beginner

7037: .seealso: [](ch_dmbase), `DM`, `DMLabelGetValueIS()`, `DMGetLabelSize()`
7038: @*/
7039: PetscErrorCode DMGetLabelIdIS(DM dm, const char name[], IS *ids)
7040: {
7041:   DMLabel label;

7043:   PetscFunctionBegin;
7045:   PetscAssertPointer(name, 2);
7046:   PetscAssertPointer(ids, 3);
7047:   PetscCall(DMGetLabel(dm, name, &label));
7048:   *ids = NULL;
7049:   if (label) PetscCall(DMLabelGetValueIS(label, ids));
7050:   else {
7051:     /* returning an empty IS */
7052:     PetscCall(ISCreateGeneral(PETSC_COMM_SELF, 0, NULL, PETSC_USE_POINTER, ids));
7053:   }
7054:   PetscFunctionReturn(PETSC_SUCCESS);
7055: }

7057: /*@
7058:   DMGetStratumSize - Get the number of points in a label stratum

7060:   Not Collective

7062:   Input Parameters:
7063: + dm    - The `DM` object
7064: . name  - The label name of the stratum
7065: - value - The stratum value

7067:   Output Parameter:
7068: . size - The number of points, also called the stratum size

7070:   Level: beginner

7072: .seealso: [](ch_dmbase), `DM`, `DMLabelGetStratumSize()`, `DMGetLabelSize()`, `DMGetLabelIds()`
7073: @*/
7074: PetscErrorCode DMGetStratumSize(DM dm, const char name[], PetscInt value, PetscInt *size)
7075: {
7076:   DMLabel label;

7078:   PetscFunctionBegin;
7080:   PetscAssertPointer(name, 2);
7081:   PetscAssertPointer(size, 4);
7082:   PetscCall(DMGetLabel(dm, name, &label));
7083:   *size = 0;
7084:   if (!label) PetscFunctionReturn(PETSC_SUCCESS);
7085:   PetscCall(DMLabelGetStratumSize(label, value, size));
7086:   PetscFunctionReturn(PETSC_SUCCESS);
7087: }

7089: /*@
7090:   DMGetStratumIS - Get the points in a label stratum

7092:   Not Collective

7094:   Input Parameters:
7095: + dm    - The `DM` object
7096: . name  - The label name
7097: - value - The stratum value

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

7102:   Level: beginner

7104: .seealso: [](ch_dmbase), `DM`, `DMLabelGetStratumIS()`, `DMGetStratumSize()`
7105: @*/
7106: PetscErrorCode DMGetStratumIS(DM dm, const char name[], PetscInt value, IS *points)
7107: {
7108:   DMLabel label;

7110:   PetscFunctionBegin;
7112:   PetscAssertPointer(name, 2);
7113:   PetscAssertPointer(points, 4);
7114:   PetscCall(DMGetLabel(dm, name, &label));
7115:   *points = NULL;
7116:   if (!label) PetscFunctionReturn(PETSC_SUCCESS);
7117:   PetscCall(DMLabelGetStratumIS(label, value, points));
7118:   PetscFunctionReturn(PETSC_SUCCESS);
7119: }

7121: /*@
7122:   DMSetStratumIS - Set the points in a label stratum

7124:   Not Collective

7126:   Input Parameters:
7127: + dm     - The `DM` object
7128: . name   - The label name
7129: . value  - The stratum value
7130: - points - The stratum points

7132:   Level: beginner

7134: .seealso: [](ch_dmbase), `DM`, `DMLabel`, `DMClearLabelStratum()`, `DMLabelClearStratum()`, `DMLabelSetStratumIS()`, `DMGetStratumSize()`
7135: @*/
7136: PetscErrorCode DMSetStratumIS(DM dm, const char name[], PetscInt value, IS points)
7137: {
7138:   DMLabel label;

7140:   PetscFunctionBegin;
7142:   PetscAssertPointer(name, 2);
7144:   PetscCall(DMGetLabel(dm, name, &label));
7145:   if (!label) PetscFunctionReturn(PETSC_SUCCESS);
7146:   PetscCall(DMLabelSetStratumIS(label, value, points));
7147:   PetscFunctionReturn(PETSC_SUCCESS);
7148: }

7150: /*@
7151:   DMClearLabelStratum - Remove all points from a stratum from a `DMLabel`

7153:   Not Collective

7155:   Input Parameters:
7156: + dm    - The `DM` object
7157: . name  - The label name
7158: - value - The label value for this point

7160:   Output Parameter:

7162:   Level: beginner

7164: .seealso: [](ch_dmbase), `DM`, `DMLabel`, `DMLabelClearStratum()`, `DMSetLabelValue()`, `DMGetStratumIS()`, `DMClearLabelValue()`
7165: @*/
7166: PetscErrorCode DMClearLabelStratum(DM dm, const char name[], PetscInt value)
7167: {
7168:   DMLabel label;

7170:   PetscFunctionBegin;
7172:   PetscAssertPointer(name, 2);
7173:   PetscCall(DMGetLabel(dm, name, &label));
7174:   if (!label) PetscFunctionReturn(PETSC_SUCCESS);
7175:   PetscCall(DMLabelClearStratum(label, value));
7176:   PetscFunctionReturn(PETSC_SUCCESS);
7177: }

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

7182:   Not Collective

7184:   Input Parameter:
7185: . dm - The `DM` object

7187:   Output Parameter:
7188: . numLabels - the number of Labels

7190:   Level: intermediate

7192: .seealso: [](ch_dmbase), `DM`, `DMLabel`, `DMGetLabelByNum()`, `DMGetLabelName()`, `DMGetLabelValue()`, `DMSetLabelValue()`, `DMGetStratumIS()`
7193: @*/
7194: PetscErrorCode DMGetNumLabels(DM dm, PetscInt *numLabels)
7195: {
7196:   DMLabelLink next = dm->labels;
7197:   PetscInt    n    = 0;

7199:   PetscFunctionBegin;
7201:   PetscAssertPointer(numLabels, 2);
7202:   while (next) {
7203:     ++n;
7204:     next = next->next;
7205:   }
7206:   *numLabels = n;
7207:   PetscFunctionReturn(PETSC_SUCCESS);
7208: }

7210: /*@
7211:   DMGetLabelName - Return the name of nth label

7213:   Not Collective

7215:   Input Parameters:
7216: + dm - The `DM` object
7217: - n  - the label number

7219:   Output Parameter:
7220: . name - the label name

7222:   Level: intermediate

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

7227: .seealso: [](ch_dmbase), `DM`, `DMLabel`, `DMGetLabelByNum()`, `DMGetLabel()`, `DMGetLabelValue()`, `DMSetLabelValue()`, `DMGetStratumIS()`
7228: @*/
7229: PetscErrorCode DMGetLabelName(DM dm, PetscInt n, const char *name[])
7230: {
7231:   DMLabelLink next = dm->labels;
7232:   PetscInt    l    = 0;

7234:   PetscFunctionBegin;
7236:   PetscAssertPointer(name, 3);
7237:   while (next) {
7238:     if (l == n) {
7239:       PetscCall(PetscObjectGetName((PetscObject)next->label, name));
7240:       PetscFunctionReturn(PETSC_SUCCESS);
7241:     }
7242:     ++l;
7243:     next = next->next;
7244:   }
7245:   SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Label %" PetscInt_FMT " does not exist in this DM", n);
7246: }

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

7251:   Not Collective

7253:   Input Parameters:
7254: + dm   - The `DM` object
7255: - name - The label name

7257:   Output Parameter:
7258: . hasLabel - `PETSC_TRUE` if the label is present

7260:   Level: intermediate

7262: .seealso: [](ch_dmbase), `DM`, `DMLabel`, `DMGetLabel()`, `DMGetLabelByNum()`, `DMCreateLabel()`, `DMGetLabelValue()`, `DMSetLabelValue()`, `DMGetStratumIS()`
7263: @*/
7264: PetscErrorCode DMHasLabel(DM dm, const char name[], PetscBool *hasLabel)
7265: {
7266:   DMLabelLink next = dm->labels;
7267:   const char *lname;

7269:   PetscFunctionBegin;
7271:   PetscAssertPointer(name, 2);
7272:   PetscAssertPointer(hasLabel, 3);
7273:   *hasLabel = PETSC_FALSE;
7274:   while (next) {
7275:     PetscCall(PetscObjectGetName((PetscObject)next->label, &lname));
7276:     PetscCall(PetscStrcmp(name, lname, hasLabel));
7277:     if (*hasLabel) break;
7278:     next = next->next;
7279:   }
7280:   PetscFunctionReturn(PETSC_SUCCESS);
7281: }

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

7287:   Not Collective

7289:   Input Parameters:
7290: + dm   - The `DM` object
7291: - name - The label name

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

7296:   Default labels in a `DMPLEX`:
7297: + "depth"       - Holds the depth (co-dimension) of each mesh point
7298: . "celltype"    - Holds the topological type of each cell
7299: . "ghost"       - If the DM is distributed with overlap, this marks the cells and faces in the overlap
7300: . "Cell Sets"   - Mirrors the cell sets defined by GMsh and ExodusII
7301: . "Face Sets"   - Mirrors the face sets defined by GMsh and ExodusII
7302: - "Vertex Sets" - Mirrors the vertex sets defined by GMsh

7304:   Level: intermediate

7306: .seealso: [](ch_dmbase), `DM`, `DMLabel`, `DMHasLabel()`, `DMGetLabelByNum()`, `DMAddLabel()`, `DMCreateLabel()`, `DMPlexGetDepthLabel()`, `DMPlexGetCellType()`
7307: @*/
7308: PetscErrorCode DMGetLabel(DM dm, const char name[], DMLabel *label)
7309: {
7310:   DMLabelLink next = dm->labels;
7311:   PetscBool   hasLabel;
7312:   const char *lname;

7314:   PetscFunctionBegin;
7316:   PetscAssertPointer(name, 2);
7317:   PetscAssertPointer(label, 3);
7318:   *label = NULL;
7319:   while (next) {
7320:     PetscCall(PetscObjectGetName((PetscObject)next->label, &lname));
7321:     PetscCall(PetscStrcmp(name, lname, &hasLabel));
7322:     if (hasLabel) {
7323:       *label = next->label;
7324:       break;
7325:     }
7326:     next = next->next;
7327:   }
7328:   PetscFunctionReturn(PETSC_SUCCESS);
7329: }

7331: /*@
7332:   DMGetLabelByNum - Return the nth label on a `DM`

7334:   Not Collective

7336:   Input Parameters:
7337: + dm - The `DM` object
7338: - n  - the label number

7340:   Output Parameter:
7341: . label - the label

7343:   Level: intermediate

7345: .seealso: [](ch_dmbase), `DM`, `DMLabel`, `DMAddLabel()`, `DMGetLabelValue()`, `DMSetLabelValue()`, `DMGetStratumIS()`
7346: @*/
7347: PetscErrorCode DMGetLabelByNum(DM dm, PetscInt n, DMLabel *label)
7348: {
7349:   DMLabelLink next = dm->labels;
7350:   PetscInt    l    = 0;

7352:   PetscFunctionBegin;
7354:   PetscAssertPointer(label, 3);
7355:   while (next) {
7356:     if (l == n) {
7357:       *label = next->label;
7358:       PetscFunctionReturn(PETSC_SUCCESS);
7359:     }
7360:     ++l;
7361:     next = next->next;
7362:   }
7363:   SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Label %" PetscInt_FMT " does not exist in this DM", n);
7364: }

7366: /*@
7367:   DMAddLabel - Add the label to this `DM`

7369:   Not Collective

7371:   Input Parameters:
7372: + dm    - The `DM` object
7373: - label - The `DMLabel`

7375:   Level: developer

7377: .seealso: [](ch_dmbase), `DM`, `DMLabel`, `DMCreateLabel()`, `DMHasLabel()`, `DMGetLabelValue()`, `DMSetLabelValue()`, `DMGetStratumIS()`
7378: @*/
7379: PetscErrorCode DMAddLabel(DM dm, DMLabel label)
7380: {
7381:   DMLabelLink l, *p, tmpLabel;
7382:   PetscBool   hasLabel;
7383:   const char *lname;
7384:   PetscBool   flg;

7386:   PetscFunctionBegin;
7388:   PetscCall(PetscObjectGetName((PetscObject)label, &lname));
7389:   PetscCall(DMHasLabel(dm, lname, &hasLabel));
7390:   PetscCheck(!hasLabel, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Label %s already exists in this DM", lname);
7391:   PetscCall(PetscCalloc1(1, &tmpLabel));
7392:   tmpLabel->label  = label;
7393:   tmpLabel->output = PETSC_TRUE;
7394:   for (p = &dm->labels; (l = *p); p = &l->next) { }
7395:   *p = tmpLabel;
7396:   PetscCall(PetscObjectReference((PetscObject)label));
7397:   PetscCall(PetscStrcmp(lname, "depth", &flg));
7398:   if (flg) dm->depthLabel = label;
7399:   PetscCall(PetscStrcmp(lname, "celltype", &flg));
7400:   if (flg) dm->celltypeLabel = label;
7401:   PetscFunctionReturn(PETSC_SUCCESS);
7402: }

7404: // PetscClangLinter pragma ignore: -fdoc-section-header-unknown
7405: /*@
7406:   DMSetLabel - Replaces the label of a given name, or ignores it if the name is not present

7408:   Not Collective

7410:   Input Parameters:
7411: + dm    - The `DM` object
7412: - label - The `DMLabel`, having the same name, to substitute

7414:   Default labels in a `DMPLEX`:
7415: + "depth"       - Holds the depth (co-dimension) of each mesh point
7416: . "celltype"    - Holds the topological type of each cell
7417: . "ghost"       - If the DM is distributed with overlap, this marks the cells and faces in the overlap
7418: . "Cell Sets"   - Mirrors the cell sets defined by GMsh and ExodusII
7419: . "Face Sets"   - Mirrors the face sets defined by GMsh and ExodusII
7420: - "Vertex Sets" - Mirrors the vertex sets defined by GMsh

7422:   Level: intermediate

7424: .seealso: [](ch_dmbase), `DM`, `DMLabel`, `DMCreateLabel()`, `DMHasLabel()`, `DMPlexGetDepthLabel()`, `DMPlexGetCellType()`
7425: @*/
7426: PetscErrorCode DMSetLabel(DM dm, DMLabel label)
7427: {
7428:   DMLabelLink next = dm->labels;
7429:   PetscBool   hasLabel, flg;
7430:   const char *name, *lname;

7432:   PetscFunctionBegin;
7435:   PetscCall(PetscObjectGetName((PetscObject)label, &name));
7436:   while (next) {
7437:     PetscCall(PetscObjectGetName((PetscObject)next->label, &lname));
7438:     PetscCall(PetscStrcmp(name, lname, &hasLabel));
7439:     if (hasLabel) {
7440:       PetscCall(PetscObjectReference((PetscObject)label));
7441:       PetscCall(PetscStrcmp(lname, "depth", &flg));
7442:       if (flg) dm->depthLabel = label;
7443:       PetscCall(PetscStrcmp(lname, "celltype", &flg));
7444:       if (flg) dm->celltypeLabel = label;
7445:       PetscCall(DMLabelDestroy(&next->label));
7446:       next->label = label;
7447:       break;
7448:     }
7449:     next = next->next;
7450:   }
7451:   PetscFunctionReturn(PETSC_SUCCESS);
7452: }

7454: /*@
7455:   DMRemoveLabel - Remove the label given by name from this `DM`

7457:   Not Collective

7459:   Input Parameters:
7460: + dm   - The `DM` object
7461: - name - The label name

7463:   Output Parameter:
7464: . label - The `DMLabel`, or `NULL` if the label is absent. Pass in `NULL` to call `DMLabelDestroy()` on the label, otherwise the
7465:           caller is responsible for calling `DMLabelDestroy()`.

7467:   Level: developer

7469: .seealso: [](ch_dmbase), `DM`, `DMLabel`, `DMCreateLabel()`, `DMHasLabel()`, `DMGetLabel()`, `DMGetLabelValue()`, `DMSetLabelValue()`, `DMLabelDestroy()`, `DMRemoveLabelBySelf()`
7470: @*/
7471: PetscErrorCode DMRemoveLabel(DM dm, const char name[], DMLabel *label)
7472: {
7473:   DMLabelLink link, *pnext;
7474:   PetscBool   hasLabel;
7475:   const char *lname;

7477:   PetscFunctionBegin;
7479:   PetscAssertPointer(name, 2);
7480:   if (label) {
7481:     PetscAssertPointer(label, 3);
7482:     *label = NULL;
7483:   }
7484:   for (pnext = &dm->labels; (link = *pnext); pnext = &link->next) {
7485:     PetscCall(PetscObjectGetName((PetscObject)link->label, &lname));
7486:     PetscCall(PetscStrcmp(name, lname, &hasLabel));
7487:     if (hasLabel) {
7488:       *pnext = link->next; /* Remove from list */
7489:       PetscCall(PetscStrcmp(name, "depth", &hasLabel));
7490:       if (hasLabel) dm->depthLabel = NULL;
7491:       PetscCall(PetscStrcmp(name, "celltype", &hasLabel));
7492:       if (hasLabel) dm->celltypeLabel = NULL;
7493:       if (label) *label = link->label;
7494:       else PetscCall(DMLabelDestroy(&link->label));
7495:       PetscCall(PetscFree(link));
7496:       break;
7497:     }
7498:   }
7499:   PetscFunctionReturn(PETSC_SUCCESS);
7500: }

7502: /*@
7503:   DMRemoveLabelBySelf - Remove the label from this `DM`

7505:   Not Collective

7507:   Input Parameters:
7508: + dm           - The `DM` object
7509: . label        - The `DMLabel` to be removed from the `DM`
7510: - failNotFound - Should it fail if the label is not found in the `DM`?

7512:   Level: developer

7514:   Note:
7515:   Only exactly the same instance is removed if found, name match is ignored.
7516:   If the `DM` has an exclusive reference to the label, the label gets destroyed and
7517:   *label nullified.

7519: .seealso: [](ch_dmbase), `DM`, `DMLabel`, `DMCreateLabel()`, `DMHasLabel()`, `DMGetLabel()`, `DMGetLabelValue()`, `DMSetLabelValue()`, `DMLabelDestroy()`, `DMRemoveLabel()`
7520: @*/
7521: PetscErrorCode DMRemoveLabelBySelf(DM dm, DMLabel *label, PetscBool failNotFound)
7522: {
7523:   DMLabelLink link, *pnext;
7524:   PetscBool   hasLabel = PETSC_FALSE;

7526:   PetscFunctionBegin;
7528:   PetscAssertPointer(label, 2);
7529:   if (!*label && !failNotFound) PetscFunctionReturn(PETSC_SUCCESS);
7532:   for (pnext = &dm->labels; (link = *pnext); pnext = &link->next) {
7533:     if (*label == link->label) {
7534:       hasLabel = PETSC_TRUE;
7535:       *pnext   = link->next; /* Remove from list */
7536:       if (*label == dm->depthLabel) dm->depthLabel = NULL;
7537:       if (*label == dm->celltypeLabel) dm->celltypeLabel = NULL;
7538:       if (((PetscObject)link->label)->refct < 2) *label = NULL; /* nullify if exclusive reference */
7539:       PetscCall(DMLabelDestroy(&link->label));
7540:       PetscCall(PetscFree(link));
7541:       break;
7542:     }
7543:   }
7544:   PetscCheck(hasLabel || !failNotFound, PetscObjectComm((PetscObject)dm), PETSC_ERR_ARG_WRONG, "Given label not found in DM");
7545:   PetscFunctionReturn(PETSC_SUCCESS);
7546: }

7548: /*@
7549:   DMGetLabelOutput - Get the output flag for a given label

7551:   Not Collective

7553:   Input Parameters:
7554: + dm   - The `DM` object
7555: - name - The label name

7557:   Output Parameter:
7558: . output - The flag for output

7560:   Level: developer

7562: .seealso: [](ch_dmbase), `DM`, `DMLabel`, `DMSetLabelOutput()`, `DMCreateLabel()`, `DMHasLabel()`, `DMGetLabelValue()`, `DMSetLabelValue()`, `DMGetStratumIS()`
7563: @*/
7564: PetscErrorCode DMGetLabelOutput(DM dm, const char name[], PetscBool *output)
7565: {
7566:   DMLabelLink next = dm->labels;
7567:   const char *lname;

7569:   PetscFunctionBegin;
7571:   PetscAssertPointer(name, 2);
7572:   PetscAssertPointer(output, 3);
7573:   while (next) {
7574:     PetscBool flg;

7576:     PetscCall(PetscObjectGetName((PetscObject)next->label, &lname));
7577:     PetscCall(PetscStrcmp(name, lname, &flg));
7578:     if (flg) {
7579:       *output = next->output;
7580:       PetscFunctionReturn(PETSC_SUCCESS);
7581:     }
7582:     next = next->next;
7583:   }
7584:   SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "No label named %s was present in this dm", name);
7585: }

7587: /*@
7588:   DMSetLabelOutput - Set if a given label should be saved to a `PetscViewer` in calls to `DMView()`

7590:   Not Collective

7592:   Input Parameters:
7593: + dm     - The `DM` object
7594: . name   - The label name
7595: - output - `PETSC_TRUE` to save the label to the viewer

7597:   Level: developer

7599: .seealso: [](ch_dmbase), `DM`, `DMLabel`, `DMGetOutputFlag()`, `DMGetLabelOutput()`, `DMCreateLabel()`, `DMHasLabel()`, `DMGetLabelValue()`, `DMSetLabelValue()`, `DMGetStratumIS()`
7600: @*/
7601: PetscErrorCode DMSetLabelOutput(DM dm, const char name[], PetscBool output)
7602: {
7603:   DMLabelLink next = dm->labels;
7604:   const char *lname;

7606:   PetscFunctionBegin;
7608:   PetscAssertPointer(name, 2);
7609:   while (next) {
7610:     PetscBool flg;

7612:     PetscCall(PetscObjectGetName((PetscObject)next->label, &lname));
7613:     PetscCall(PetscStrcmp(name, lname, &flg));
7614:     if (flg) {
7615:       next->output = output;
7616:       PetscFunctionReturn(PETSC_SUCCESS);
7617:     }
7618:     next = next->next;
7619:   }
7620:   SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "No label named %s was present in this dm", name);
7621: }

7623: /*@
7624:   DMCopyLabels - Copy labels from one `DM` mesh to another `DM` with a superset of the points

7626:   Collective

7628:   Input Parameters:
7629: + dmA   - The `DM` object with initial labels
7630: . dmB   - The `DM` object to which labels are copied
7631: . mode  - Copy labels by pointers (`PETSC_OWN_POINTER`) or duplicate them (`PETSC_COPY_VALUES`)
7632: . all   - Copy all labels including "depth", "dim", and "celltype" (`PETSC_TRUE`) which are otherwise ignored (`PETSC_FALSE`)
7633: - emode - How to behave when a `DMLabel` in the source and destination `DM`s with the same name is encountered (see `DMCopyLabelsMode`)

7635:   Level: intermediate

7637:   Note:
7638:   This is typically used when interpolating or otherwise adding to a mesh, or testing.

7640: .seealso: [](ch_dmbase), `DM`, `DMLabel`, `DMAddLabel()`, `DMCopyLabelsMode`
7641: @*/
7642: PetscErrorCode DMCopyLabels(DM dmA, DM dmB, PetscCopyMode mode, PetscBool all, DMCopyLabelsMode emode)
7643: {
7644:   DMLabel     label, labelNew, labelOld;
7645:   const char *name;
7646:   PetscBool   flg;
7647:   DMLabelLink link;

7649:   PetscFunctionBegin;
7654:   PetscCheck(mode != PETSC_USE_POINTER, PetscObjectComm((PetscObject)dmA), PETSC_ERR_SUP, "PETSC_USE_POINTER not supported for objects");
7655:   if (dmA == dmB) PetscFunctionReturn(PETSC_SUCCESS);
7656:   for (link = dmA->labels; link; link = link->next) {
7657:     label = link->label;
7658:     PetscCall(PetscObjectGetName((PetscObject)label, &name));
7659:     if (!all) {
7660:       PetscCall(PetscStrcmp(name, "depth", &flg));
7661:       if (flg) continue;
7662:       PetscCall(PetscStrcmp(name, "dim", &flg));
7663:       if (flg) continue;
7664:       PetscCall(PetscStrcmp(name, "celltype", &flg));
7665:       if (flg) continue;
7666:     }
7667:     PetscCall(DMGetLabel(dmB, name, &labelOld));
7668:     if (labelOld) {
7669:       switch (emode) {
7670:       case DM_COPY_LABELS_KEEP:
7671:         continue;
7672:       case DM_COPY_LABELS_REPLACE:
7673:         PetscCall(DMRemoveLabelBySelf(dmB, &labelOld, PETSC_TRUE));
7674:         break;
7675:       case DM_COPY_LABELS_FAIL:
7676:         SETERRQ(PetscObjectComm((PetscObject)dmA), PETSC_ERR_ARG_OUTOFRANGE, "Label %s already exists in destination DM", name);
7677:       default:
7678:         SETERRQ(PetscObjectComm((PetscObject)dmA), PETSC_ERR_ARG_OUTOFRANGE, "Unhandled DMCopyLabelsMode %d", (int)emode);
7679:       }
7680:     }
7681:     if (mode == PETSC_COPY_VALUES) PetscCall(DMLabelDuplicate(label, &labelNew));
7682:     else labelNew = label;
7683:     PetscCall(DMAddLabel(dmB, labelNew));
7684:     if (mode == PETSC_COPY_VALUES) PetscCall(DMLabelDestroy(&labelNew));
7685:   }
7686:   PetscFunctionReturn(PETSC_SUCCESS);
7687: }

7689: /*@C
7690:   DMCompareLabels - Compare labels between two `DM` objects

7692:   Collective; No Fortran Support

7694:   Input Parameters:
7695: + dm0 - First `DM` object
7696: - dm1 - Second `DM` object

7698:   Output Parameters:
7699: + equal   - (Optional) Flag whether labels of `dm0` and `dm1` are the same
7700: - message - (Optional) Message describing the difference, or `NULL` if there is no difference

7702:   Level: intermediate

7704:   Notes:
7705:   The output flag equal will be the same on all processes.

7707:   If equal is passed as `NULL` and difference is found, an error is thrown on all processes.

7709:   Make sure to pass equal is `NULL` on all processes or none of them.

7711:   The output message is set independently on each rank.

7713:   message must be freed with `PetscFree()`

7715:   If message is passed as `NULL` and a difference is found, the difference description is printed to `stderr` in synchronized manner.

7717:   Make sure to pass message as `NULL` on all processes or no processes.

7719:   Labels are matched by name. If the number of labels and their names are equal,
7720:   `DMLabelCompare()` is used to compare each pair of labels with the same name.

7722:   Developer Note:
7723:   Cannot automatically generate the Fortran stub because `message` must be freed with `PetscFree()`

7725: .seealso: [](ch_dmbase), `DM`, `DMLabel`, `DMAddLabel()`, `DMCopyLabelsMode`, `DMLabelCompare()`
7726: @*/
7727: PetscErrorCode DMCompareLabels(DM dm0, DM dm1, PetscBool *equal, char *message[]) PeNS
7728: {
7729:   PetscInt    n;
7730:   char        msg[PETSC_MAX_PATH_LEN] = "";
7731:   PetscBool   eq;
7732:   MPI_Comm    comm;
7733:   PetscMPIInt rank;

7735:   PetscFunctionBegin;
7738:   PetscCheckSameComm(dm0, 1, dm1, 2);
7739:   if (equal) PetscAssertPointer(equal, 3);
7740:   if (message) PetscAssertPointer(message, 4);
7741:   PetscCall(PetscObjectGetComm((PetscObject)dm0, &comm));
7742:   PetscCallMPI(MPI_Comm_rank(comm, &rank));
7743:   {
7744:     PetscInt n1;

7746:     PetscCall(DMGetNumLabels(dm0, &n));
7747:     PetscCall(DMGetNumLabels(dm1, &n1));
7748:     eq = (PetscBool)(n == n1);
7749:     if (!eq) PetscCall(PetscSNPrintf(msg, sizeof(msg), "Number of labels in dm0 = %" PetscInt_FMT " != %" PetscInt_FMT " = Number of labels in dm1", n, n1));
7750:     PetscCallMPI(MPIU_Allreduce(MPI_IN_PLACE, &eq, 1, MPI_C_BOOL, MPI_LAND, comm));
7751:     if (!eq) goto finish;
7752:   }
7753:   for (PetscInt i = 0; i < n; i++) {
7754:     DMLabel     l0, l1;
7755:     const char *name;
7756:     char       *msgInner;

7758:     /* Ignore label order */
7759:     PetscCall(DMGetLabelByNum(dm0, i, &l0));
7760:     PetscCall(PetscObjectGetName((PetscObject)l0, &name));
7761:     PetscCall(DMGetLabel(dm1, name, &l1));
7762:     if (!l1) {
7763:       PetscCall(PetscSNPrintf(msg, sizeof(msg), "Label \"%s\" (#%" PetscInt_FMT " in dm0) not found in dm1", name, i));
7764:       eq = PETSC_FALSE;
7765:       break;
7766:     }
7767:     PetscCall(DMLabelCompare(comm, l0, l1, &eq, &msgInner));
7768:     PetscCall(PetscStrncpy(msg, msgInner, sizeof(msg)));
7769:     PetscCall(PetscFree(msgInner));
7770:     if (!eq) break;
7771:   }
7772:   PetscCallMPI(MPIU_Allreduce(MPI_IN_PLACE, &eq, 1, MPI_C_BOOL, MPI_LAND, comm));
7773: finish:
7774:   /* If message output arg not set, print to stderr */
7775:   if (message) {
7776:     *message = NULL;
7777:     if (msg[0]) PetscCall(PetscStrallocpy(msg, message));
7778:   } else {
7779:     if (msg[0]) PetscCall(PetscSynchronizedFPrintf(comm, PETSC_STDERR, "[%d] %s\n", rank, msg));
7780:     PetscCall(PetscSynchronizedFlush(comm, PETSC_STDERR));
7781:   }
7782:   /* If same output arg not ser and labels are not equal, throw error */
7783:   if (equal) *equal = eq;
7784:   else PetscCheck(eq, comm, PETSC_ERR_ARG_INCOMP, "DMLabels are not the same in dm0 and dm1");
7785:   PetscFunctionReturn(PETSC_SUCCESS);
7786: }

7788: PetscErrorCode DMSetLabelValue_Fast(DM dm, DMLabel *label, const char name[], PetscInt point, PetscInt value)
7789: {
7790:   PetscFunctionBegin;
7791:   PetscAssertPointer(label, 2);
7792:   if (!*label) {
7793:     PetscCall(DMCreateLabel(dm, name));
7794:     PetscCall(DMGetLabel(dm, name, label));
7795:   }
7796:   PetscCall(DMLabelSetValue(*label, point, value));
7797:   PetscFunctionReturn(PETSC_SUCCESS);
7798: }

7800: /*
7801:   Many mesh programs, such as Triangle and TetGen, allow only a single label for each mesh point. Therefore, we would
7802:   like to encode all label IDs using a single, universal label. We can do this by assigning an integer to every
7803:   (label, id) pair in the DM.

7805:   However, a mesh point can have multiple labels, so we must separate all these values. We will assign a bit range to
7806:   each label.
7807: */
7808: PetscErrorCode DMUniversalLabelCreate(DM dm, DMUniversalLabel *universal)
7809: {
7810:   DMUniversalLabel ul;
7811:   PetscBool       *active;
7812:   PetscInt         pStart, pEnd, p, Nl, l, m;

7814:   PetscFunctionBegin;
7815:   PetscCall(PetscMalloc1(1, &ul));
7816:   PetscCall(DMLabelCreate(PETSC_COMM_SELF, "universal", &ul->label));
7817:   PetscCall(DMGetNumLabels(dm, &Nl));
7818:   PetscCall(PetscCalloc1(Nl, &active));
7819:   ul->Nl = 0;
7820:   for (l = 0; l < Nl; ++l) {
7821:     PetscBool   isdepth, iscelltype;
7822:     const char *name;

7824:     PetscCall(DMGetLabelName(dm, l, &name));
7825:     PetscCall(PetscStrncmp(name, "depth", 6, &isdepth));
7826:     PetscCall(PetscStrncmp(name, "celltype", 9, &iscelltype));
7827:     active[l] = !(isdepth || iscelltype) ? PETSC_TRUE : PETSC_FALSE;
7828:     if (active[l]) ++ul->Nl;
7829:   }
7830:   PetscCall(PetscCalloc5(ul->Nl, &ul->names, ul->Nl, &ul->indices, ul->Nl + 1, &ul->offsets, ul->Nl + 1, &ul->bits, ul->Nl, &ul->masks));
7831:   ul->Nv = 0;
7832:   for (l = 0, m = 0; l < Nl; ++l) {
7833:     DMLabel     label;
7834:     PetscInt    nv;
7835:     const char *name;

7837:     if (!active[l]) continue;
7838:     PetscCall(DMGetLabelName(dm, l, &name));
7839:     PetscCall(DMGetLabelByNum(dm, l, &label));
7840:     PetscCall(DMLabelGetNumValues(label, &nv));
7841:     PetscCall(PetscStrallocpy(name, &ul->names[m]));
7842:     ul->indices[m] = l;
7843:     ul->Nv += nv;
7844:     ul->offsets[m + 1] = nv;
7845:     ul->bits[m + 1]    = PetscCeilReal(PetscLog2Real(nv + 1));
7846:     ++m;
7847:   }
7848:   for (l = 1; l <= ul->Nl; ++l) {
7849:     ul->offsets[l] = ul->offsets[l - 1] + ul->offsets[l];
7850:     ul->bits[l]    = ul->bits[l - 1] + ul->bits[l];
7851:   }
7852:   for (l = 0; l < ul->Nl; ++l) {
7853:     ul->masks[l] = 0;
7854:     for (PetscInt b = ul->bits[l]; b < ul->bits[l + 1]; ++b) ul->masks[l] |= 1 << b;
7855:   }
7856:   PetscCall(PetscMalloc1(ul->Nv, &ul->values));
7857:   for (l = 0, m = 0; l < Nl; ++l) {
7858:     DMLabel         label;
7859:     IS              valueIS;
7860:     const PetscInt *varr;
7861:     PetscInt        nv;

7863:     if (!active[l]) continue;
7864:     PetscCall(DMGetLabelByNum(dm, l, &label));
7865:     PetscCall(DMLabelGetNumValues(label, &nv));
7866:     PetscCall(DMLabelGetValueIS(label, &valueIS));
7867:     PetscCall(ISGetIndices(valueIS, &varr));
7868:     for (PetscInt v = 0; v < nv; ++v) ul->values[ul->offsets[m] + v] = varr[v];
7869:     PetscCall(ISRestoreIndices(valueIS, &varr));
7870:     PetscCall(ISDestroy(&valueIS));
7871:     PetscCall(PetscSortInt(nv, &ul->values[ul->offsets[m]]));
7872:     ++m;
7873:   }
7874:   PetscCall(DMPlexGetChart(dm, &pStart, &pEnd));
7875:   for (p = pStart; p < pEnd; ++p) {
7876:     PetscInt  uval   = 0;
7877:     PetscBool marked = PETSC_FALSE;

7879:     for (l = 0, m = 0; l < Nl; ++l) {
7880:       DMLabel  label;
7881:       PetscInt val, defval, loc, nv;

7883:       if (!active[l]) continue;
7884:       PetscCall(DMGetLabelByNum(dm, l, &label));
7885:       PetscCall(DMLabelGetValue(label, p, &val));
7886:       PetscCall(DMLabelGetDefaultValue(label, &defval));
7887:       if (val == defval) {
7888:         ++m;
7889:         continue;
7890:       }
7891:       nv     = ul->offsets[m + 1] - ul->offsets[m];
7892:       marked = PETSC_TRUE;
7893:       PetscCall(PetscFindInt(val, nv, &ul->values[ul->offsets[m]], &loc));
7894:       PetscCheck(loc >= 0, PETSC_COMM_SELF, PETSC_ERR_PLIB, "Label value %" PetscInt_FMT " not found in compression array", val);
7895:       uval += (loc + 1) << ul->bits[m];
7896:       ++m;
7897:     }
7898:     if (marked) PetscCall(DMLabelSetValue(ul->label, p, uval));
7899:   }
7900:   PetscCall(PetscFree(active));
7901:   *universal = ul;
7902:   PetscFunctionReturn(PETSC_SUCCESS);
7903: }

7905: PetscErrorCode DMUniversalLabelDestroy(DMUniversalLabel *universal)
7906: {
7907:   PetscInt l;

7909:   PetscFunctionBegin;
7910:   for (l = 0; l < (*universal)->Nl; ++l) PetscCall(PetscFree((*universal)->names[l]));
7911:   PetscCall(DMLabelDestroy(&(*universal)->label));
7912:   PetscCall(PetscFree5((*universal)->names, (*universal)->indices, (*universal)->offsets, (*universal)->bits, (*universal)->masks));
7913:   PetscCall(PetscFree((*universal)->values));
7914:   PetscCall(PetscFree(*universal));
7915:   *universal = NULL;
7916:   PetscFunctionReturn(PETSC_SUCCESS);
7917: }

7919: PetscErrorCode DMUniversalLabelGetLabel(DMUniversalLabel ul, DMLabel *ulabel)
7920: {
7921:   PetscFunctionBegin;
7922:   PetscAssertPointer(ulabel, 2);
7923:   *ulabel = ul->label;
7924:   PetscFunctionReturn(PETSC_SUCCESS);
7925: }

7927: PetscErrorCode DMUniversalLabelCreateLabels(DMUniversalLabel ul, PetscBool preserveOrder, DM dm)
7928: {
7929:   PetscInt Nl = ul->Nl, l;

7931:   PetscFunctionBegin;
7933:   for (l = 0; l < Nl; ++l) {
7934:     if (preserveOrder) PetscCall(DMCreateLabelAtIndex(dm, ul->indices[l], ul->names[l]));
7935:     else PetscCall(DMCreateLabel(dm, ul->names[l]));
7936:   }
7937:   if (preserveOrder) {
7938:     for (l = 0; l < ul->Nl; ++l) {
7939:       const char *name;
7940:       PetscBool   match;

7942:       PetscCall(DMGetLabelName(dm, ul->indices[l], &name));
7943:       PetscCall(PetscStrcmp(name, ul->names[l], &match));
7944:       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]);
7945:     }
7946:   }
7947:   PetscFunctionReturn(PETSC_SUCCESS);
7948: }

7950: PetscErrorCode DMUniversalLabelSetLabelValue(DMUniversalLabel ul, DM dm, PetscBool useIndex, PetscInt p, PetscInt value)
7951: {
7952:   PetscFunctionBegin;
7953:   for (PetscInt l = 0; l < ul->Nl; ++l) {
7954:     DMLabel  label;
7955:     PetscInt lval = (value & ul->masks[l]) >> ul->bits[l];

7957:     if (lval) {
7958:       if (useIndex) PetscCall(DMGetLabelByNum(dm, ul->indices[l], &label));
7959:       else PetscCall(DMGetLabel(dm, ul->names[l], &label));
7960:       PetscCall(DMLabelSetValue(label, p, ul->values[ul->offsets[l] + lval - 1]));
7961:     }
7962:   }
7963:   PetscFunctionReturn(PETSC_SUCCESS);
7964: }

7966: /*@
7967:   DMGetCoarseDM - Get the coarse `DM`from which this `DM` was obtained by refinement

7969:   Not Collective

7971:   Input Parameter:
7972: . dm - The `DM` object

7974:   Output Parameter:
7975: . cdm - The coarse `DM`

7977:   Level: intermediate

7979: .seealso: [](ch_dmbase), `DM`, `DMSetCoarseDM()`, `DMCoarsen()`
7980: @*/
7981: PetscErrorCode DMGetCoarseDM(DM dm, DM *cdm)
7982: {
7983:   PetscFunctionBegin;
7985:   PetscAssertPointer(cdm, 2);
7986:   *cdm = dm->coarseMesh;
7987:   PetscFunctionReturn(PETSC_SUCCESS);
7988: }

7990: /*@
7991:   DMSetCoarseDM - Set the coarse `DM` from which this `DM` was obtained by refinement

7993:   Input Parameters:
7994: + dm  - The `DM` object
7995: - cdm - The coarse `DM`

7997:   Level: intermediate

7999:   Note:
8000:   Normally this is set automatically by `DMRefine()`

8002: .seealso: [](ch_dmbase), `DM`, `DMGetCoarseDM()`, `DMCoarsen()`, `DMSetRefine()`, `DMSetFineDM()`
8003: @*/
8004: PetscErrorCode DMSetCoarseDM(DM dm, DM cdm)
8005: {
8006:   PetscFunctionBegin;
8009:   if (dm == cdm) cdm = NULL;
8010:   PetscCall(PetscObjectReference((PetscObject)cdm));
8011:   PetscCall(DMDestroy(&dm->coarseMesh));
8012:   dm->coarseMesh = cdm;
8013:   PetscFunctionReturn(PETSC_SUCCESS);
8014: }

8016: /*@
8017:   DMGetFineDM - Get the fine mesh from which this `DM` was obtained by coarsening

8019:   Input Parameter:
8020: . dm - The `DM` object

8022:   Output Parameter:
8023: . fdm - The fine `DM`

8025:   Level: intermediate

8027: .seealso: [](ch_dmbase), `DM`, `DMSetFineDM()`, `DMCoarsen()`, `DMRefine()`
8028: @*/
8029: PetscErrorCode DMGetFineDM(DM dm, DM *fdm)
8030: {
8031:   PetscFunctionBegin;
8033:   PetscAssertPointer(fdm, 2);
8034:   *fdm = dm->fineMesh;
8035:   PetscFunctionReturn(PETSC_SUCCESS);
8036: }

8038: /*@
8039:   DMSetFineDM - Set the fine mesh from which this was obtained by coarsening

8041:   Input Parameters:
8042: + dm  - The `DM` object
8043: - fdm - The fine `DM`

8045:   Level: developer

8047:   Note:
8048:   Normally this is set automatically by `DMCoarsen()`

8050: .seealso: [](ch_dmbase), `DM`, `DMGetFineDM()`, `DMCoarsen()`, `DMRefine()`
8051: @*/
8052: PetscErrorCode DMSetFineDM(DM dm, DM fdm)
8053: {
8054:   PetscFunctionBegin;
8057:   if (dm == fdm) fdm = NULL;
8058:   PetscCall(PetscObjectReference((PetscObject)fdm));
8059:   PetscCall(DMDestroy(&dm->fineMesh));
8060:   dm->fineMesh = fdm;
8061:   PetscFunctionReturn(PETSC_SUCCESS);
8062: }

8064: /*@C
8065:   DMAddBoundary - Add a boundary condition, for a single field, to a model represented by a `DM`

8067:   Collective

8069:   Input Parameters:
8070: + dm       - The `DM`, with a `PetscDS` that matches the problem being constrained
8071: . type     - The type of condition, e.g. `DM_BC_ESSENTIAL_ANALYTIC`, `DM_BC_ESSENTIAL_FIELD` (Dirichlet), or `DM_BC_NATURAL` (Neumann)
8072: . name     - The BC name
8073: . label    - The label defining constrained points
8074: . Nv       - The number of `DMLabel` values for constrained points
8075: . values   - An array of values for constrained points
8076: . field    - The field to constrain
8077: . Nc       - The number of constrained field components (0 will constrain all components)
8078: . comps    - An array of constrained component numbers
8079: . bcFunc   - A pointwise function giving boundary values
8080: . bcFunc_t - A pointwise function giving the time derivative of the boundary values, or `NULL`
8081: - ctx      - An optional user context for bcFunc

8083:   Output Parameter:
8084: . bd - (Optional) Boundary number

8086:   Options Database Keys:
8087: + -bc_NAME values     - Overrides the boundary ids for boundary named NAME
8088: - -bc_NAME_comp comps - Overrides the boundary components for boundary named NAME

8090:   Level: intermediate

8092:   Notes:
8093:   If the `DM` is of type `DMPLEX` and the field is of type `PetscFE`, then this function completes the label using `DMPlexLabelComplete()`.

8095:   Both bcFunc and bcFunc_t will depend on the boundary condition type. If the type if `DM_BC_ESSENTIAL`, then the calling sequence is\:
8096: .vb
8097:  void bcFunc(PetscInt dim, PetscReal time, const PetscReal x[], PetscInt Nc, PetscScalar bcval[])
8098: .ve

8100:   If the type is `DM_BC_ESSENTIAL_FIELD` or other _FIELD value, then the calling sequence is\:

8102: .vb
8103:   void bcFunc(PetscInt dim, PetscInt Nf, PetscInt NfAux,
8104:               const PetscInt uOff[], const PetscInt uOff_x[], const PetscScalar u[], const PetscScalar u_t[], const PetscScalar u_x[],
8105:               const PetscInt aOff[], const PetscInt aOff_x[], const PetscScalar a[], const PetscScalar a_t[], const PetscScalar a_x[],
8106:               PetscReal time, const PetscReal x[], PetscScalar bcval[])
8107: .ve
8108: + dim - the spatial dimension
8109: . Nf - the number of fields
8110: . uOff - the offset into u[] and u_t[] for each field
8111: . uOff_x - the offset into u_x[] for each field
8112: . u - each field evaluated at the current point
8113: . u_t - the time derivative of each field evaluated at the current point
8114: . u_x - the gradient of each field evaluated at the current point
8115: . aOff - the offset into a[] and a_t[] for each auxiliary field
8116: . aOff_x - the offset into a_x[] for each auxiliary field
8117: . a - each auxiliary field evaluated at the current point
8118: . a_t - the time derivative of each auxiliary field evaluated at the current point
8119: . a_x - the gradient of auxiliary each field evaluated at the current point
8120: . t - current time
8121: . x - coordinates of the current point
8122: . numConstants - number of constant parameters
8123: . constants - constant parameters
8124: - bcval - output values at the current point

8126: .seealso: [](ch_dmbase), `DM`, `DSGetBoundary()`, `PetscDSAddBoundary()`
8127: @*/
8128: 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)
8129: {
8130:   PetscDS ds;

8132:   PetscFunctionBegin;
8139:   PetscCheck(!dm->localSection, PetscObjectComm((PetscObject)dm), PETSC_ERR_ARG_WRONGSTATE, "Cannot add boundary to DM after creating local section");
8140:   PetscCall(DMGetDS(dm, &ds));
8141:   /* Complete label */
8142:   if (label) {
8143:     PetscObject  obj;
8144:     PetscClassId id;

8146:     PetscCall(DMGetField(dm, field, NULL, &obj));
8147:     PetscCall(PetscObjectGetClassId(obj, &id));
8148:     if (id == PETSCFE_CLASSID) {
8149:       DM plex;

8151:       PetscCall(DMConvert(dm, DMPLEX, &plex));
8152:       if (plex) PetscCall(DMPlexLabelComplete(plex, label));
8153:       PetscCall(DMDestroy(&plex));
8154:     }
8155:   }
8156:   PetscCall(PetscDSAddBoundary(ds, type, name, label, Nv, values, field, Nc, comps, bcFunc, bcFunc_t, ctx, bd));
8157:   PetscFunctionReturn(PETSC_SUCCESS);
8158: }

8160: /* TODO Remove this since now the structures are the same */
8161: static PetscErrorCode DMPopulateBoundary(DM dm)
8162: {
8163:   PetscDS     ds;
8164:   DMBoundary *lastnext;
8165:   DSBoundary  dsbound;

8167:   PetscFunctionBegin;
8168:   PetscCall(DMGetDS(dm, &ds));
8169:   dsbound = ds->boundary;
8170:   if (dm->boundary) {
8171:     DMBoundary next = dm->boundary;

8173:     /* quick check to see if the PetscDS has changed */
8174:     if (next->dsboundary == dsbound) PetscFunctionReturn(PETSC_SUCCESS);
8175:     /* the PetscDS has changed: tear down and rebuild */
8176:     while (next) {
8177:       DMBoundary b = next;

8179:       next = b->next;
8180:       PetscCall(PetscFree(b));
8181:     }
8182:     dm->boundary = NULL;
8183:   }

8185:   lastnext = &dm->boundary;
8186:   while (dsbound) {
8187:     DMBoundary dmbound;

8189:     PetscCall(PetscNew(&dmbound));
8190:     dmbound->dsboundary = dsbound;
8191:     dmbound->label      = dsbound->label;
8192:     /* push on the back instead of the front so that it is in the same order as in the PetscDS */
8193:     *lastnext = dmbound;
8194:     lastnext  = &dmbound->next;
8195:     dsbound   = dsbound->next;
8196:   }
8197:   PetscFunctionReturn(PETSC_SUCCESS);
8198: }

8200: /* TODO: missing manual page */
8201: PetscErrorCode DMIsBoundaryPoint(DM dm, PetscInt point, PetscBool *isBd)
8202: {
8203:   DMBoundary b;

8205:   PetscFunctionBegin;
8207:   PetscAssertPointer(isBd, 3);
8208:   *isBd = PETSC_FALSE;
8209:   PetscCall(DMPopulateBoundary(dm));
8210:   b = dm->boundary;
8211:   while (b && !*isBd) {
8212:     DMLabel    label = b->label;
8213:     DSBoundary dsb   = b->dsboundary;

8215:     if (label) {
8216:       for (PetscInt i = 0; i < dsb->Nv && !*isBd; ++i) PetscCall(DMLabelStratumHasPoint(label, dsb->values[i], point, isBd));
8217:     }
8218:     b = b->next;
8219:   }
8220:   PetscFunctionReturn(PETSC_SUCCESS);
8221: }

8223: /*@
8224:   DMHasBound - Determine whether a bound condition was specified

8226:   Logically collective

8228:   Input Parameter:
8229: . dm - The `DM`, with a `PetscDS` that matches the problem being constrained

8231:   Output Parameter:
8232: . hasBound - Flag indicating if a bound condition was specified

8234:   Level: intermediate

8236: .seealso: [](ch_dmbase), `DM`, `DSAddBoundary()`, `PetscDSAddBoundary()`
8237: @*/
8238: PetscErrorCode DMHasBound(DM dm, PetscBool *hasBound)
8239: {
8240:   PetscDS  ds;
8241:   PetscInt Nf, numBd;

8243:   PetscFunctionBegin;
8244:   *hasBound = PETSC_FALSE;
8245:   PetscCall(DMGetDS(dm, &ds));
8246:   PetscCall(PetscDSGetNumFields(ds, &Nf));
8247:   for (PetscInt f = 0; f < Nf; ++f) {
8248:     PetscSimplePointFn *lfunc, *ufunc;

8250:     PetscCall(PetscDSGetLowerBound(ds, f, &lfunc, NULL));
8251:     PetscCall(PetscDSGetUpperBound(ds, f, &ufunc, NULL));
8252:     if (lfunc || ufunc) *hasBound = PETSC_TRUE;
8253:   }

8255:   PetscCall(PetscDSGetNumBoundary(ds, &numBd));
8256:   PetscCall(PetscDSUpdateBoundaryLabels(ds, dm));
8257:   for (PetscInt b = 0; b < numBd; ++b) {
8258:     PetscWeakForm           wf;
8259:     DMBoundaryConditionType type;
8260:     const char             *name;
8261:     DMLabel                 label;
8262:     PetscInt                numids;
8263:     const PetscInt         *ids;
8264:     PetscInt                field, Nc;
8265:     const PetscInt         *comps;
8266:     PetscVoidFn            *bvfunc;
8267:     void                   *ctx;

8269:     PetscCall(PetscDSGetBoundary(ds, b, &wf, &type, &name, &label, &numids, &ids, &field, &Nc, &comps, &bvfunc, NULL, &ctx));
8270:     if (type == DM_BC_LOWER_BOUND || type == DM_BC_UPPER_BOUND) *hasBound = PETSC_TRUE;
8271:   }
8272:   PetscFunctionReturn(PETSC_SUCCESS);
8273: }

8275: /*@C
8276:   DMProjectFunction - This projects the given function into the function space provided by a `DM`, putting the coefficients in a global vector.

8278:   Collective

8280:   Input Parameters:
8281: + dm    - The `DM`
8282: . time  - The time
8283: . funcs - The coordinate functions to evaluate, one per field
8284: . ctxs  - Optional array of contexts to pass to each coordinate function.  ctxs itself may be null.
8285: - mode  - The insertion mode for values

8287:   Output Parameter:
8288: . X - vector

8290:   Calling sequence of `funcs`:
8291: + dim  - The spatial dimension
8292: . time - The time at which to sample
8293: . x    - The coordinates
8294: . Nc   - The number of components
8295: . u    - The output field values
8296: - ctx  - optional function context

8298:   Level: developer

8300:   Developer Notes:
8301:   This API is specific to only particular usage of `DM`

8303:   The notes need to provide some information about what has to be provided to the `DM` to be able to perform the computation.

8305: .seealso: [](ch_dmbase), `DM`, `DMProjectFunctionLocal()`, `DMProjectFunctionLabel()`, `DMComputeL2Diff()`
8306: @*/
8307: 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)
8308: {
8309:   Vec localX;

8311:   PetscFunctionBegin;
8313:   PetscCall(PetscLogEventBegin(DM_ProjectFunction, dm, X, 0, 0));
8314:   PetscCall(DMGetLocalVector(dm, &localX));
8315:   PetscCall(VecSet(localX, 0.));
8316:   PetscCall(DMProjectFunctionLocal(dm, time, funcs, ctxs, mode, localX));
8317:   PetscCall(DMLocalToGlobalBegin(dm, localX, mode, X));
8318:   PetscCall(DMLocalToGlobalEnd(dm, localX, mode, X));
8319:   PetscCall(DMRestoreLocalVector(dm, &localX));
8320:   PetscCall(PetscLogEventEnd(DM_ProjectFunction, dm, X, 0, 0));
8321:   PetscFunctionReturn(PETSC_SUCCESS);
8322: }

8324: /*@C
8325:   DMProjectFunctionLocal - This projects the given function into the function space provided by a `DM`, putting the coefficients in a local vector.

8327:   Not Collective

8329:   Input Parameters:
8330: + dm    - The `DM`
8331: . time  - The time
8332: . funcs - The coordinate functions to evaluate, one per field
8333: . ctxs  - Optional array of contexts to pass to each coordinate function.  ctxs itself may be null.
8334: - mode  - The insertion mode for values

8336:   Output Parameter:
8337: . localX - vector

8339:   Calling sequence of `funcs`:
8340: + dim  - The spatial dimension
8341: . time - The current timestep
8342: . x    - The coordinates
8343: . Nc   - The number of components
8344: . u    - The output field values
8345: - ctx  - optional function context

8347:   Level: developer

8349:   Developer Notes:
8350:   This API is specific to only particular usage of `DM`

8352:   The notes need to provide some information about what has to be provided to the `DM` to be able to perform the computation.

8354: .seealso: [](ch_dmbase), `DM`, `DMProjectFunction()`, `DMProjectFunctionLabel()`, `DMComputeL2Diff()`
8355: @*/
8356: 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)
8357: {
8358:   PetscFunctionBegin;
8361:   PetscUseTypeMethod(dm, projectfunctionlocal, time, funcs, ctxs, mode, localX);
8362:   PetscFunctionReturn(PETSC_SUCCESS);
8363: }

8365: /*@C
8366:   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.

8368:   Collective

8370:   Input Parameters:
8371: + dm     - The `DM`
8372: . time   - The time
8373: . numIds - The number of ids
8374: . ids    - The ids
8375: . Nc     - The number of components
8376: . comps  - The components
8377: . label  - The `DMLabel` selecting the portion of the mesh for projection
8378: . funcs  - The coordinate functions to evaluate, one per field
8379: . ctxs   - Optional array of contexts to pass to each coordinate function.  ctxs may be null.
8380: - mode   - The insertion mode for values

8382:   Output Parameter:
8383: . X - vector

8385:   Calling sequence of `funcs`:
8386: + dim  - The spatial dimension
8387: . time - The current timestep
8388: . x    - The coordinates
8389: . Nc   - The number of components
8390: . u    - The output field values
8391: - ctx  - optional function context

8393:   Level: developer

8395:   Developer Notes:
8396:   This API is specific to only particular usage of `DM`

8398:   The notes need to provide some information about what has to be provided to the `DM` to be able to perform the computation.

8400: .seealso: [](ch_dmbase), `DM`, `DMProjectFunction()`, `DMProjectFunctionLocal()`, `DMProjectFunctionLabelLocal()`, `DMComputeL2Diff()`
8401: @*/
8402: 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)
8403: {
8404:   Vec localX;

8406:   PetscFunctionBegin;
8408:   PetscCall(DMGetLocalVector(dm, &localX));
8409:   PetscCall(VecSet(localX, 0.));
8410:   PetscCall(DMProjectFunctionLabelLocal(dm, time, label, numIds, ids, Nc, comps, funcs, ctxs, mode, localX));
8411:   PetscCall(DMLocalToGlobalBegin(dm, localX, mode, X));
8412:   PetscCall(DMLocalToGlobalEnd(dm, localX, mode, X));
8413:   PetscCall(DMRestoreLocalVector(dm, &localX));
8414:   PetscFunctionReturn(PETSC_SUCCESS);
8415: }

8417: /*@C
8418:   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.

8420:   Not Collective

8422:   Input Parameters:
8423: + dm     - The `DM`
8424: . time   - The time
8425: . label  - The `DMLabel` selecting the portion of the mesh for projection
8426: . numIds - The number of ids
8427: . ids    - The ids
8428: . Nc     - The number of components
8429: . comps  - The components
8430: . funcs  - The coordinate functions to evaluate, one per field
8431: . ctxs   - Optional array of contexts to pass to each coordinate function.  ctxs itself may be null.
8432: - mode   - The insertion mode for values

8434:   Output Parameter:
8435: . localX - vector

8437:   Calling sequence of `funcs`:
8438: + dim  - The spatial dimension
8439: . time - The current time
8440: . x    - The coordinates
8441: . Nc   - The number of components
8442: . u    - The output field values
8443: - ctx  - optional function context

8445:   Level: developer

8447:   Developer Notes:
8448:   This API is specific to only particular usage of `DM`

8450:   The notes need to provide some information about what has to be provided to the `DM` to be able to perform the computation.

8452: .seealso: [](ch_dmbase), `DM`, `DMProjectFunction()`, `DMProjectFunctionLocal()`, `DMProjectFunctionLabel()`, `DMComputeL2Diff()`
8453: @*/
8454: 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)
8455: {
8456:   PetscFunctionBegin;
8459:   PetscUseTypeMethod(dm, projectfunctionlabellocal, time, label, numIds, ids, Nc, comps, funcs, ctxs, mode, localX);
8460:   PetscFunctionReturn(PETSC_SUCCESS);
8461: }

8463: /*@C
8464:   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.

8466:   Not Collective

8468:   Input Parameters:
8469: + dm     - The `DM`
8470: . time   - The time
8471: . localU - The input field vector; may be `NULL` if projection is defined purely by coordinates
8472: . funcs  - The functions to evaluate, one per field
8473: - mode   - The insertion mode for values

8475:   Output Parameter:
8476: . localX - The output vector

8478:   Calling sequence of `funcs`:
8479: + dim          - The spatial dimension
8480: . Nf           - The number of input fields
8481: . NfAux        - The number of input auxiliary fields
8482: . uOff         - The offset of each field in u[]
8483: . uOff_x       - The offset of each field in u_x[]
8484: . u            - The field values at this point in space
8485: . u_t          - The field time derivative at this point in space (or `NULL`)
8486: . u_x          - The field derivatives at this point in space
8487: . aOff         - The offset of each auxiliary field in u[]
8488: . aOff_x       - The offset of each auxiliary field in u_x[]
8489: . a            - The auxiliary field values at this point in space
8490: . a_t          - The auxiliary field time derivative at this point in space (or `NULL`)
8491: . a_x          - The auxiliary field derivatives at this point in space
8492: . t            - The current time
8493: . x            - The coordinates of this point
8494: . numConstants - The number of constants
8495: . constants    - The value of each constant
8496: - f            - The value of the function at this point in space

8498:   Level: intermediate

8500:   Note:
8501:   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.
8502:   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
8503:   a subdomain. You can also output a different number of fields than the input, with different discretizations. Last the auxiliary `DM`, attached to the
8504:   auxiliary field vector, which is attached to dm, can also be different. It can have a different topology, number of fields, and discretizations.

8506:   Developer Notes:
8507:   This API is specific to only particular usage of `DM`

8509:   The notes need to provide some information about what has to be provided to the `DM` to be able to perform the computation.

8511: .seealso: [](ch_dmbase), `DM`, `DMProjectField()`, `DMProjectFieldLabelLocal()`,
8512: `DMProjectFunction()`, `DMComputeL2Diff()`
8513: @*/
8514: 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)
8515: {
8516:   PetscFunctionBegin;
8520:   PetscUseTypeMethod(dm, projectfieldlocal, time, localU, funcs, mode, localX);
8521:   PetscFunctionReturn(PETSC_SUCCESS);
8522: }

8524: /*@C
8525:   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.

8527:   Not Collective

8529:   Input Parameters:
8530: + dm     - The `DM`
8531: . time   - The time
8532: . label  - The `DMLabel` marking the portion of the domain to output
8533: . numIds - The number of label ids to use
8534: . ids    - The label ids to use for marking
8535: . Nc     - The number of components to set in the output, or `PETSC_DETERMINE` for all components
8536: . comps  - The components to set in the output, or `NULL` for all components
8537: . localU - The input field vector
8538: . funcs  - The functions to evaluate, one per field
8539: - mode   - The insertion mode for values

8541:   Output Parameter:
8542: . localX - The output vector

8544:   Calling sequence of `funcs`:
8545: + dim          - The spatial dimension
8546: . Nf           - The number of input fields
8547: . NfAux        - The number of input auxiliary fields
8548: . uOff         - The offset of each field in u[]
8549: . uOff_x       - The offset of each field in u_x[]
8550: . u            - The field values at this point in space
8551: . u_t          - The field time derivative at this point in space (or `NULL`)
8552: . u_x          - The field derivatives at this point in space
8553: . aOff         - The offset of each auxiliary field in u[]
8554: . aOff_x       - The offset of each auxiliary field in u_x[]
8555: . a            - The auxiliary field values at this point in space
8556: . a_t          - The auxiliary field time derivative at this point in space (or `NULL`)
8557: . a_x          - The auxiliary field derivatives at this point in space
8558: . t            - The current time
8559: . x            - The coordinates of this point
8560: . numConstants - The number of constants
8561: . constants    - The value of each constant
8562: - f            - The value of the function at this point in space

8564:   Level: intermediate

8566:   Note:
8567:   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.
8568:   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
8569:   a subdomain. You can also output a different number of fields than the input, with different discretizations. Last the auxiliary `DM`, attached to the
8570:   auxiliary field vector, which is attached to dm, can also be different. It can have a different topology, number of fields, and discretizations.

8572:   Developer Notes:
8573:   This API is specific to only particular usage of `DM`

8575:   The notes need to provide some information about what has to be provided to the `DM` to be able to perform the computation.

8577: .seealso: [](ch_dmbase), `DM`, `DMProjectField()`, `DMProjectFieldLabel()`, `DMProjectFunction()`, `DMComputeL2Diff()`
8578: @*/
8579: 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)
8580: {
8581:   PetscFunctionBegin;
8585:   PetscUseTypeMethod(dm, projectfieldlabellocal, time, label, numIds, ids, Nc, comps, localU, funcs, mode, localX);
8586:   PetscFunctionReturn(PETSC_SUCCESS);
8587: }

8589: /*@C
8590:   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.

8592:   Not Collective

8594:   Input Parameters:
8595: + dm     - The `DM`
8596: . time   - The time
8597: . label  - The `DMLabel` marking the portion of the domain to output
8598: . numIds - The number of label ids to use
8599: . ids    - The label ids to use for marking
8600: . Nc     - The number of components to set in the output, or `PETSC_DETERMINE` for all components
8601: . comps  - The components to set in the output, or `NULL` for all components
8602: . U      - The input field vector
8603: . funcs  - The functions to evaluate, one per field
8604: - mode   - The insertion mode for values

8606:   Output Parameter:
8607: . X - The output vector

8609:   Calling sequence of `funcs`:
8610: + dim          - The spatial dimension
8611: . Nf           - The number of input fields
8612: . NfAux        - The number of input auxiliary fields
8613: . uOff         - The offset of each field in u[]
8614: . uOff_x       - The offset of each field in u_x[]
8615: . u            - The field values at this point in space
8616: . u_t          - The field time derivative at this point in space (or `NULL`)
8617: . u_x          - The field derivatives at this point in space
8618: . aOff         - The offset of each auxiliary field in u[]
8619: . aOff_x       - The offset of each auxiliary field in u_x[]
8620: . a            - The auxiliary field values at this point in space
8621: . a_t          - The auxiliary field time derivative at this point in space (or `NULL`)
8622: . a_x          - The auxiliary field derivatives at this point in space
8623: . t            - The current time
8624: . x            - The coordinates of this point
8625: . numConstants - The number of constants
8626: . constants    - The value of each constant
8627: - f            - The value of the function at this point in space

8629:   Level: intermediate

8631:   Note:
8632:   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.
8633:   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
8634:   a subdomain. You can also output a different number of fields than the input, with different discretizations. Last the auxiliary `DM`, attached to the
8635:   auxiliary field vector, which is attached to dm, can also be different. It can have a different topology, number of fields, and discretizations.

8637:   Developer Notes:
8638:   This API is specific to only particular usage of `DM`

8640:   The notes need to provide some information about what has to be provided to the `DM` to be able to perform the computation.

8642: .seealso: [](ch_dmbase), `DM`, `DMProjectField()`, `DMProjectFieldLabelLocal()`, `DMProjectFunction()`, `DMComputeL2Diff()`
8643: @*/
8644: 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)
8645: {
8646:   DM  dmIn;
8647:   Vec localU, localX;

8649:   PetscFunctionBegin;
8651:   PetscCall(VecGetDM(U, &dmIn));
8652:   PetscCall(DMGetLocalVector(dmIn, &localU));
8653:   PetscCall(DMGetLocalVector(dm, &localX));
8654:   PetscCall(VecSet(localX, 0.));
8655:   PetscCall(DMGlobalToLocalBegin(dmIn, U, mode, localU));
8656:   PetscCall(DMGlobalToLocalEnd(dmIn, U, mode, localU));
8657:   PetscCall(DMProjectFieldLabelLocal(dm, time, label, numIds, ids, Nc, comps, localU, funcs, mode, localX));
8658:   PetscCall(DMLocalToGlobalBegin(dm, localX, mode, X));
8659:   PetscCall(DMLocalToGlobalEnd(dm, localX, mode, X));
8660:   PetscCall(DMRestoreLocalVector(dm, &localX));
8661:   PetscCall(DMRestoreLocalVector(dmIn, &localU));
8662:   PetscFunctionReturn(PETSC_SUCCESS);
8663: }

8665: /*@C
8666:   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.

8668:   Not Collective

8670:   Input Parameters:
8671: + dm     - The `DM`
8672: . time   - The time
8673: . label  - The `DMLabel` marking the portion of the domain boundary to output
8674: . numIds - The number of label ids to use
8675: . ids    - The label ids to use for marking
8676: . Nc     - The number of components to set in the output, or `PETSC_DETERMINE` for all components
8677: . comps  - The components to set in the output, or `NULL` for all components
8678: . localU - The input field vector
8679: . funcs  - The functions to evaluate, one per field
8680: - mode   - The insertion mode for values

8682:   Output Parameter:
8683: . localX - The output vector

8685:   Calling sequence of `funcs`:
8686: + dim          - The spatial dimension
8687: . Nf           - The number of input fields
8688: . NfAux        - The number of input auxiliary fields
8689: . uOff         - The offset of each field in u[]
8690: . uOff_x       - The offset of each field in u_x[]
8691: . u            - The field values at this point in space
8692: . u_t          - The field time derivative at this point in space (or `NULL`)
8693: . u_x          - The field derivatives at this point in space
8694: . aOff         - The offset of each auxiliary field in u[]
8695: . aOff_x       - The offset of each auxiliary field in u_x[]
8696: . a            - The auxiliary field values at this point in space
8697: . a_t          - The auxiliary field time derivative at this point in space (or `NULL`)
8698: . a_x          - The auxiliary field derivatives at this point in space
8699: . t            - The current time
8700: . x            - The coordinates of this point
8701: . n            - The face normal
8702: . numConstants - The number of constants
8703: . constants    - The value of each constant
8704: - f            - The value of the function at this point in space

8706:   Level: intermediate

8708:   Note:
8709:   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.
8710:   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
8711:   a subdomain. You can also output a different number of fields than the input, with different discretizations. Last the auxiliary `DM`, attached to the
8712:   auxiliary field vector, which is attached to dm, can also be different. It can have a different topology, number of fields, and discretizations.

8714:   Developer Notes:
8715:   This API is specific to only particular usage of `DM`

8717:   The notes need to provide some information about what has to be provided to the `DM` to be able to perform the computation.

8719: .seealso: [](ch_dmbase), `DM`, `DMProjectField()`, `DMProjectFieldLabelLocal()`, `DMProjectFunction()`, `DMComputeL2Diff()`
8720: @*/
8721: 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)
8722: {
8723:   PetscFunctionBegin;
8727:   PetscUseTypeMethod(dm, projectbdfieldlabellocal, time, label, numIds, ids, Nc, comps, localU, funcs, mode, localX);
8728:   PetscFunctionReturn(PETSC_SUCCESS);
8729: }

8731: /*@C
8732:   DMComputeL2Diff - This function computes the L_2 difference between a function u and an FEM interpolant solution u_h.

8734:   Collective

8736:   Input Parameters:
8737: + dm    - The `DM`
8738: . time  - The time
8739: . funcs - The functions to evaluate for each field component
8740: . ctxs  - Optional array of contexts to pass to each function, or `NULL`.
8741: - X     - The coefficient vector u_h, a global vector

8743:   Output Parameter:
8744: . diff - The diff ||u - u_h||_2

8746:   Level: developer

8748:   Developer Notes:
8749:   This API is specific to only particular usage of `DM`

8751:   The notes need to provide some information about what has to be provided to the `DM` to be able to perform the computation.

8753: .seealso: [](ch_dmbase), `DM`, `DMProjectFunction()`, `DMComputeL2FieldDiff()`, `DMComputeL2GradientDiff()`
8754: @*/
8755: PetscErrorCode DMComputeL2Diff(DM dm, PetscReal time, PetscErrorCode (**funcs)(PetscInt, PetscReal, const PetscReal[], PetscInt, PetscScalar *, void *), void **ctxs, Vec X, PetscReal *diff)
8756: {
8757:   PetscFunctionBegin;
8760:   PetscUseTypeMethod(dm, computel2diff, time, funcs, ctxs, X, diff);
8761:   PetscFunctionReturn(PETSC_SUCCESS);
8762: }

8764: /*@C
8765:   DMComputeL2GradientDiff - This function computes the L_2 difference between the gradient of a function u and an FEM interpolant solution grad u_h.

8767:   Collective

8769:   Input Parameters:
8770: + dm    - The `DM`
8771: . time  - The time
8772: . funcs - The gradient functions to evaluate for each field component
8773: . ctxs  - Optional array of contexts to pass to each function, or `NULL`.
8774: . X     - The coefficient vector u_h, a global vector
8775: - n     - The vector to project along

8777:   Output Parameter:
8778: . diff - The diff ||(grad u - grad u_h) . n||_2

8780:   Level: developer

8782:   Developer Notes:
8783:   This API is specific to only particular usage of `DM`

8785:   The notes need to provide some information about what has to be provided to the `DM` to be able to perform the computation.

8787: .seealso: [](ch_dmbase), `DM`, `DMProjectFunction()`, `DMComputeL2Diff()`, `DMComputeL2FieldDiff()`
8788: @*/
8789: 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)
8790: {
8791:   PetscFunctionBegin;
8794:   PetscUseTypeMethod(dm, computel2gradientdiff, time, funcs, ctxs, X, n, diff);
8795:   PetscFunctionReturn(PETSC_SUCCESS);
8796: }

8798: /*@C
8799:   DMComputeL2FieldDiff - This function computes the L_2 difference between a function u and an FEM interpolant solution u_h, separated into field components.

8801:   Collective

8803:   Input Parameters:
8804: + dm    - The `DM`
8805: . time  - The time
8806: . funcs - The functions to evaluate for each field component
8807: . ctxs  - Optional array of contexts to pass to each function, or `NULL`.
8808: - X     - The coefficient vector u_h, a global vector

8810:   Output Parameter:
8811: . diff - The array of differences, ||u^f - u^f_h||_2

8813:   Level: developer

8815:   Developer Notes:
8816:   This API is specific to only particular usage of `DM`

8818:   The notes need to provide some information about what has to be provided to the `DM` to be able to perform the computation.

8820: .seealso: [](ch_dmbase), `DM`, `DMProjectFunction()`, `DMComputeL2GradientDiff()`
8821: @*/
8822: PetscErrorCode DMComputeL2FieldDiff(DM dm, PetscReal time, PetscErrorCode (**funcs)(PetscInt, PetscReal, const PetscReal[], PetscInt, PetscScalar *, void *), void **ctxs, Vec X, PetscReal diff[])
8823: {
8824:   PetscFunctionBegin;
8827:   PetscUseTypeMethod(dm, computel2fielddiff, time, funcs, ctxs, X, diff);
8828:   PetscFunctionReturn(PETSC_SUCCESS);
8829: }

8831: /*@C
8832:   DMGetNeighbors - Gets an array containing the MPI ranks of all the processes neighbors

8834:   Not Collective

8836:   Input Parameter:
8837: . dm - The `DM`

8839:   Output Parameters:
8840: + nranks - the number of neighbours
8841: - ranks  - the neighbors ranks

8843:   Level: beginner

8845:   Note:
8846:   Do not free the array, it is freed when the `DM` is destroyed.

8848: .seealso: [](ch_dmbase), `DM`, `DMDAGetNeighbors()`, `PetscSFGetRootRanks()`
8849: @*/
8850: PetscErrorCode DMGetNeighbors(DM dm, PetscInt *nranks, const PetscMPIInt *ranks[])
8851: {
8852:   PetscFunctionBegin;
8854:   PetscUseTypeMethod(dm, getneighbors, nranks, ranks);
8855:   PetscFunctionReturn(PETSC_SUCCESS);
8856: }

8858: #include <petsc/private/matimpl.h>

8860: /*
8861:     Converts the input vector to a ghosted vector and then calls the standard coloring code.
8862:     This must be a different function because it requires DM which is not defined in the Mat library
8863: */
8864: static PetscErrorCode MatFDColoringApply_AIJDM(Mat J, MatFDColoring coloring, Vec x1, void *sctx)
8865: {
8866:   PetscFunctionBegin;
8867:   if (coloring->ctype == IS_COLORING_LOCAL) {
8868:     Vec x1local;
8869:     DM  dm;
8870:     PetscCall(MatGetDM(J, &dm));
8871:     PetscCheck(dm, PetscObjectComm((PetscObject)J), PETSC_ERR_ARG_INCOMP, "IS_COLORING_LOCAL requires a DM");
8872:     PetscCall(DMGetLocalVector(dm, &x1local));
8873:     PetscCall(DMGlobalToLocalBegin(dm, x1, INSERT_VALUES, x1local));
8874:     PetscCall(DMGlobalToLocalEnd(dm, x1, INSERT_VALUES, x1local));
8875:     x1 = x1local;
8876:   }
8877:   PetscCall(MatFDColoringApply_AIJ(J, coloring, x1, sctx));
8878:   if (coloring->ctype == IS_COLORING_LOCAL) {
8879:     DM dm;
8880:     PetscCall(MatGetDM(J, &dm));
8881:     PetscCall(DMRestoreLocalVector(dm, &x1));
8882:   }
8883:   PetscFunctionReturn(PETSC_SUCCESS);
8884: }

8886: /*@
8887:   MatFDColoringUseDM - allows a `MatFDColoring` object to use the `DM` associated with the matrix to compute a `IS_COLORING_LOCAL` coloring

8889:   Input Parameters:
8890: + coloring   - The matrix to get the `DM` from
8891: - fdcoloring - the `MatFDColoring` object

8893:   Level: advanced

8895:   Developer Note:
8896:   This routine exists because the PETSc `Mat` library does not know about the `DM` objects

8898: .seealso: [](ch_dmbase), `DM`, `MatFDColoring`, `MatFDColoringCreate()`, `ISColoringType`
8899: @*/
8900: PetscErrorCode MatFDColoringUseDM(Mat coloring, MatFDColoring fdcoloring)
8901: {
8902:   PetscFunctionBegin;
8903:   coloring->ops->fdcoloringapply = MatFDColoringApply_AIJDM;
8904:   PetscFunctionReturn(PETSC_SUCCESS);
8905: }

8907: /*@
8908:   DMGetCompatibility - determine if two `DM`s are compatible

8910:   Collective

8912:   Input Parameters:
8913: + dm1 - the first `DM`
8914: - dm2 - the second `DM`

8916:   Output Parameters:
8917: + compatible - whether or not the two `DM`s are compatible
8918: - set        - whether or not the compatible value was actually determined and set

8920:   Level: advanced

8922:   Notes:
8923:   Two `DM`s are deemed compatible if they represent the same parallel decomposition
8924:   of the same topology. This implies that the section (field data) on one
8925:   "makes sense" with respect to the topology and parallel decomposition of the other.
8926:   Loosely speaking, compatible `DM`s represent the same domain and parallel
8927:   decomposition, but hold different data.

8929:   Typically, one would confirm compatibility if intending to simultaneously iterate
8930:   over a pair of vectors obtained from different `DM`s.

8932:   For example, two `DMDA` objects are compatible if they have the same local
8933:   and global sizes and the same stencil width. They can have different numbers
8934:   of degrees of freedom per node. Thus, one could use the node numbering from
8935:   either `DM` in bounds for a loop over vectors derived from either `DM`.

8937:   Consider the operation of summing data living on a 2-dof `DMDA` to data living
8938:   on a 1-dof `DMDA`, which should be compatible, as in the following snippet.
8939: .vb
8940:   ...
8941:   PetscCall(DMGetCompatibility(da1,da2,&compatible,&set));
8942:   if (set && compatible)  {
8943:     PetscCall(DMDAVecGetArrayDOF(da1,vec1,&arr1));
8944:     PetscCall(DMDAVecGetArrayDOF(da2,vec2,&arr2));
8945:     PetscCall(DMDAGetCorners(da1,&x,&y,NULL,&m,&n,NULL));
8946:     for (j=y; j<y+n; ++j) {
8947:       for (i=x; i<x+m, ++i) {
8948:         arr1[j][i][0] = arr2[j][i][0] + arr2[j][i][1];
8949:       }
8950:     }
8951:     PetscCall(DMDAVecRestoreArrayDOF(da1,vec1,&arr1));
8952:     PetscCall(DMDAVecRestoreArrayDOF(da2,vec2,&arr2));
8953:   } else {
8954:     SETERRQ(PetscObjectComm((PetscObject)da1,PETSC_ERR_ARG_INCOMP,"DMDA objects incompatible");
8955:   }
8956:   ...
8957: .ve

8959:   Checking compatibility might be expensive for a given implementation of `DM`,
8960:   or might be impossible to unambiguously confirm or deny. For this reason,
8961:   this function may decline to determine compatibility, and hence users should
8962:   always check the "set" output parameter.

8964:   A `DM` is always compatible with itself.

8966:   In the current implementation, `DM`s which live on "unequal" communicators
8967:   (MPI_UNEQUAL in the terminology of MPI_Comm_compare()) are always deemed
8968:   incompatible.

8970:   This function is labeled "Collective," as information about all subdomains
8971:   is required on each rank. However, in `DM` implementations which store all this
8972:   information locally, this function may be merely "Logically Collective".

8974:   Developer Note:
8975:   Compatibility is assumed to be a symmetric concept; `DM` A is compatible with `DM` B
8976:   iff B is compatible with A. Thus, this function checks the implementations
8977:   of both dm and dmc (if they are of different types), attempting to determine
8978:   compatibility. It is left to `DM` implementers to ensure that symmetry is
8979:   preserved. The simplest way to do this is, when implementing type-specific
8980:   logic for this function, is to check for existing logic in the implementation
8981:   of other `DM` types and let *set = PETSC_FALSE if found.

8983: .seealso: [](ch_dmbase), `DM`, `DMDACreateCompatibleDMDA()`, `DMStagCreateCompatibleDMStag()`
8984: @*/
8985: PetscErrorCode DMGetCompatibility(DM dm1, DM dm2, PetscBool *compatible, PetscBool *set)
8986: {
8987:   PetscMPIInt compareResult;
8988:   DMType      type, type2;
8989:   PetscBool   sameType;

8991:   PetscFunctionBegin;

8995:   /* Declare a DM compatible with itself */
8996:   if (dm1 == dm2) {
8997:     *set        = PETSC_TRUE;
8998:     *compatible = PETSC_TRUE;
8999:     PetscFunctionReturn(PETSC_SUCCESS);
9000:   }

9002:   /* Declare a DM incompatible with a DM that lives on an "unequal"
9003:      communicator. Note that this does not preclude compatibility with
9004:      DMs living on "congruent" or "similar" communicators, but this must be
9005:      determined by the implementation-specific logic */
9006:   PetscCallMPI(MPI_Comm_compare(PetscObjectComm((PetscObject)dm1), PetscObjectComm((PetscObject)dm2), &compareResult));
9007:   if (compareResult == MPI_UNEQUAL) {
9008:     *set        = PETSC_TRUE;
9009:     *compatible = PETSC_FALSE;
9010:     PetscFunctionReturn(PETSC_SUCCESS);
9011:   }

9013:   /* Pass to the implementation-specific routine, if one exists. */
9014:   if (dm1->ops->getcompatibility) {
9015:     PetscUseTypeMethod(dm1, getcompatibility, dm2, compatible, set);
9016:     if (*set) PetscFunctionReturn(PETSC_SUCCESS);
9017:   }

9019:   /* If dm1 and dm2 are of different types, then attempt to check compatibility
9020:      with an implementation of this function from dm2 */
9021:   PetscCall(DMGetType(dm1, &type));
9022:   PetscCall(DMGetType(dm2, &type2));
9023:   PetscCall(PetscStrcmp(type, type2, &sameType));
9024:   if (!sameType && dm2->ops->getcompatibility) {
9025:     PetscUseTypeMethod(dm2, getcompatibility, dm1, compatible, set); /* Note argument order */
9026:   } else {
9027:     *set = PETSC_FALSE;
9028:   }
9029:   PetscFunctionReturn(PETSC_SUCCESS);
9030: }

9032: /*@C
9033:   DMMonitorSet - Sets an additional monitor function that is to be used after a solve to monitor discretization performance.

9035:   Logically Collective

9037:   Input Parameters:
9038: + dm             - the `DM`
9039: . f              - the monitor function
9040: . mctx           - [optional] context for private data for the monitor routine (use `NULL` if no context is desired)
9041: - monitordestroy - [optional] routine that frees monitor context (may be `NULL`), see `PetscCtxDestroyFn` for the calling sequence

9043:   Options Database Key:
9044: . -dm_monitor_cancel - cancels all monitors that have been hardwired into a code by calls to `DMMonitorSet()`, but
9045:                        does not cancel those set via the options database.

9047:   Level: intermediate

9049:   Note:
9050:   Several different monitoring routines may be set by calling
9051:   `DMMonitorSet()` multiple times or with `DMMonitorSetFromOptions()`; all will be called in the
9052:   order in which they were set.

9054:   Fortran Note:
9055:   Only a single monitor function can be set for each `DM` object

9057:   Developer Note:
9058:   This API has a generic name but seems specific to a very particular aspect of the use of `DM`

9060: .seealso: [](ch_dmbase), `DM`, `DMMonitorCancel()`, `DMMonitorSetFromOptions()`, `DMMonitor()`, `PetscCtxDestroyFn`
9061: @*/
9062: PetscErrorCode DMMonitorSet(DM dm, PetscErrorCode (*f)(DM, void *), void *mctx, PetscCtxDestroyFn *monitordestroy)
9063: {
9064:   PetscFunctionBegin;
9066:   for (PetscInt m = 0; m < dm->numbermonitors; ++m) {
9067:     PetscBool identical;

9069:     PetscCall(PetscMonitorCompare((PetscErrorCode (*)(void))(PetscVoidFn *)f, mctx, monitordestroy, (PetscErrorCode (*)(void))(PetscVoidFn *)dm->monitor[m], dm->monitorcontext[m], dm->monitordestroy[m], &identical));
9070:     if (identical) PetscFunctionReturn(PETSC_SUCCESS);
9071:   }
9072:   PetscCheck(dm->numbermonitors < MAXDMMONITORS, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Too many monitors set");
9073:   dm->monitor[dm->numbermonitors]          = f;
9074:   dm->monitordestroy[dm->numbermonitors]   = monitordestroy;
9075:   dm->monitorcontext[dm->numbermonitors++] = mctx;
9076:   PetscFunctionReturn(PETSC_SUCCESS);
9077: }

9079: /*@
9080:   DMMonitorCancel - Clears all the monitor functions for a `DM` object.

9082:   Logically Collective

9084:   Input Parameter:
9085: . dm - the DM

9087:   Options Database Key:
9088: . -dm_monitor_cancel - cancels all monitors that have been hardwired
9089:   into a code by calls to `DMonitorSet()`, but does not cancel those
9090:   set via the options database

9092:   Level: intermediate

9094:   Note:
9095:   There is no way to clear one specific monitor from a `DM` object.

9097: .seealso: [](ch_dmbase), `DM`, `DMMonitorSet()`, `DMMonitorSetFromOptions()`, `DMMonitor()`
9098: @*/
9099: PetscErrorCode DMMonitorCancel(DM dm)
9100: {
9101:   PetscFunctionBegin;
9103:   for (PetscInt 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:   PetscFunctionBegin;
9183:   if (!dm) PetscFunctionReturn(PETSC_SUCCESS);
9185:   for (PetscInt m = 0; m < dm->numbermonitors; ++m) PetscCall((*dm->monitor[m])(dm, dm->monitorcontext[m]));
9186:   PetscFunctionReturn(PETSC_SUCCESS);
9187: }

9189: /*@
9190:   DMComputeError - Computes the error assuming the user has provided the exact solution functions

9192:   Collective

9194:   Input Parameters:
9195: + dm  - The `DM`
9196: - sol - The solution vector

9198:   Input/Output Parameter:
9199: . errors - An array of length Nf, the number of fields, or `NULL` for no output; on output
9200:            contains the error in each field

9202:   Output Parameter:
9203: . errorVec - A vector to hold the cellwise error (may be `NULL`)

9205:   Level: developer

9207:   Note:
9208:   The exact solutions come from the `PetscDS` object, and the time comes from `DMGetOutputSequenceNumber()`.

9210: .seealso: [](ch_dmbase), `DM`, `DMMonitorSet()`, `DMGetRegionNumDS()`, `PetscDSGetExactSolution()`, `DMGetOutputSequenceNumber()`
9211: @*/
9212: PetscErrorCode DMComputeError(DM dm, Vec sol, PetscReal errors[], Vec *errorVec)
9213: {
9214:   PetscErrorCode (**exactSol)(PetscInt, PetscReal, const PetscReal[], PetscInt, PetscScalar[], void *);
9215:   void    **ctxs;
9216:   PetscReal time;
9217:   PetscInt  Nf, f, Nds, s;

9219:   PetscFunctionBegin;
9220:   PetscCall(DMGetNumFields(dm, &Nf));
9221:   PetscCall(PetscCalloc2(Nf, &exactSol, Nf, &ctxs));
9222:   PetscCall(DMGetNumDS(dm, &Nds));
9223:   for (s = 0; s < Nds; ++s) {
9224:     PetscDS         ds;
9225:     DMLabel         label;
9226:     IS              fieldIS;
9227:     const PetscInt *fields;
9228:     PetscInt        dsNf;

9230:     PetscCall(DMGetRegionNumDS(dm, s, &label, &fieldIS, &ds, NULL));
9231:     PetscCall(PetscDSGetNumFields(ds, &dsNf));
9232:     if (fieldIS) PetscCall(ISGetIndices(fieldIS, &fields));
9233:     for (f = 0; f < dsNf; ++f) {
9234:       const PetscInt field = fields[f];
9235:       PetscCall(PetscDSGetExactSolution(ds, field, &exactSol[field], &ctxs[field]));
9236:     }
9237:     if (fieldIS) PetscCall(ISRestoreIndices(fieldIS, &fields));
9238:   }
9239:   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);
9240:   PetscCall(DMGetOutputSequenceNumber(dm, NULL, &time));
9241:   if (errors) PetscCall(DMComputeL2FieldDiff(dm, time, exactSol, ctxs, sol, errors));
9242:   if (errorVec) {
9243:     DM             edm;
9244:     DMPolytopeType ct;
9245:     PetscBool      simplex;
9246:     PetscInt       dim, cStart, Nf;

9248:     PetscCall(DMClone(dm, &edm));
9249:     PetscCall(DMGetDimension(edm, &dim));
9250:     PetscCall(DMPlexGetHeightStratum(dm, 0, &cStart, NULL));
9251:     PetscCall(DMPlexGetCellType(dm, cStart, &ct));
9252:     simplex = DMPolytopeTypeGetNumVertices(ct) == DMPolytopeTypeGetDim(ct) + 1 ? PETSC_TRUE : PETSC_FALSE;
9253:     PetscCall(DMGetNumFields(dm, &Nf));
9254:     for (f = 0; f < Nf; ++f) {
9255:       PetscFE         fe, efe;
9256:       PetscQuadrature q;
9257:       const char     *name;

9259:       PetscCall(DMGetField(dm, f, NULL, (PetscObject *)&fe));
9260:       PetscCall(PetscFECreateLagrange(PETSC_COMM_SELF, dim, Nf, simplex, 0, PETSC_DETERMINE, &efe));
9261:       PetscCall(PetscObjectGetName((PetscObject)fe, &name));
9262:       PetscCall(PetscObjectSetName((PetscObject)efe, name));
9263:       PetscCall(PetscFEGetQuadrature(fe, &q));
9264:       PetscCall(PetscFESetQuadrature(efe, q));
9265:       PetscCall(DMSetField(edm, f, NULL, (PetscObject)efe));
9266:       PetscCall(PetscFEDestroy(&efe));
9267:     }
9268:     PetscCall(DMCreateDS(edm));

9270:     PetscCall(DMCreateGlobalVector(edm, errorVec));
9271:     PetscCall(PetscObjectSetName((PetscObject)*errorVec, "Error"));
9272:     PetscCall(DMPlexComputeL2DiffVec(dm, time, exactSol, ctxs, sol, *errorVec));
9273:     PetscCall(DMDestroy(&edm));
9274:   }
9275:   PetscCall(PetscFree2(exactSol, ctxs));
9276:   PetscFunctionReturn(PETSC_SUCCESS);
9277: }

9279: /*@
9280:   DMGetNumAuxiliaryVec - Get the number of auxiliary vectors associated with this `DM`

9282:   Not Collective

9284:   Input Parameter:
9285: . dm - The `DM`

9287:   Output Parameter:
9288: . numAux - The number of auxiliary data vectors

9290:   Level: advanced

9292: .seealso: [](ch_dmbase), `DM`, `DMClearAuxiliaryVec()`, `DMSetAuxiliaryVec()`, `DMGetAuxiliaryLabels()`, `DMGetAuxiliaryVec()`
9293: @*/
9294: PetscErrorCode DMGetNumAuxiliaryVec(DM dm, PetscInt *numAux)
9295: {
9296:   PetscFunctionBegin;
9298:   PetscCall(PetscHMapAuxGetSize(dm->auxData, numAux));
9299:   PetscFunctionReturn(PETSC_SUCCESS);
9300: }

9302: /*@
9303:   DMGetAuxiliaryVec - Get the auxiliary vector for region specified by the given label and value, and equation part

9305:   Not Collective

9307:   Input Parameters:
9308: + dm    - The `DM`
9309: . label - The `DMLabel`
9310: . value - The label value indicating the region
9311: - part  - The equation part, or 0 if unused

9313:   Output Parameter:
9314: . aux - The `Vec` holding auxiliary field data

9316:   Level: advanced

9318:   Note:
9319:   If no auxiliary vector is found for this (label, value), (`NULL`, 0, 0) is checked as well.

9321: .seealso: [](ch_dmbase), `DM`, `DMClearAuxiliaryVec()`, `DMSetAuxiliaryVec()`, `DMGetNumAuxiliaryVec()`, `DMGetAuxiliaryLabels()`
9322: @*/
9323: PetscErrorCode DMGetAuxiliaryVec(DM dm, DMLabel label, PetscInt value, PetscInt part, Vec *aux)
9324: {
9325:   PetscHashAuxKey key, wild = {NULL, 0, 0};
9326:   PetscBool       has;

9328:   PetscFunctionBegin;
9331:   key.label = label;
9332:   key.value = value;
9333:   key.part  = part;
9334:   PetscCall(PetscHMapAuxHas(dm->auxData, key, &has));
9335:   if (has) PetscCall(PetscHMapAuxGet(dm->auxData, key, aux));
9336:   else PetscCall(PetscHMapAuxGet(dm->auxData, wild, aux));
9337:   PetscFunctionReturn(PETSC_SUCCESS);
9338: }

9340: /*@
9341:   DMSetAuxiliaryVec - Set an auxiliary vector for region specified by the given label and value, and equation part

9343:   Not Collective because auxiliary vectors are not parallel

9345:   Input Parameters:
9346: + dm    - The `DM`
9347: . label - The `DMLabel`
9348: . value - The label value indicating the region
9349: . part  - The equation part, or 0 if unused
9350: - aux   - The `Vec` holding auxiliary field data

9352:   Level: advanced

9354: .seealso: [](ch_dmbase), `DM`, `DMClearAuxiliaryVec()`, `DMGetAuxiliaryVec()`, `DMGetAuxiliaryLabels()`, `DMCopyAuxiliaryVec()`
9355: @*/
9356: PetscErrorCode DMSetAuxiliaryVec(DM dm, DMLabel label, PetscInt value, PetscInt part, Vec aux)
9357: {
9358:   Vec             old;
9359:   PetscHashAuxKey key;

9361:   PetscFunctionBegin;
9364:   key.label = label;
9365:   key.value = value;
9366:   key.part  = part;
9367:   PetscCall(PetscHMapAuxGet(dm->auxData, key, &old));
9368:   PetscCall(PetscObjectReference((PetscObject)aux));
9369:   if (!aux) PetscCall(PetscHMapAuxDel(dm->auxData, key));
9370:   else PetscCall(PetscHMapAuxSet(dm->auxData, key, aux));
9371:   PetscCall(VecDestroy(&old));
9372:   PetscFunctionReturn(PETSC_SUCCESS);
9373: }

9375: /*@
9376:   DMGetAuxiliaryLabels - Get the labels, values, and parts for all auxiliary vectors in this `DM`

9378:   Not Collective

9380:   Input Parameter:
9381: . dm - The `DM`

9383:   Output Parameters:
9384: + labels - The `DMLabel`s for each `Vec`
9385: . values - The label values for each `Vec`
9386: - parts  - The equation parts for each `Vec`

9388:   Level: advanced

9390:   Note:
9391:   The arrays passed in must be at least as large as `DMGetNumAuxiliaryVec()`.

9393: .seealso: [](ch_dmbase), `DM`, `DMClearAuxiliaryVec()`, `DMGetNumAuxiliaryVec()`, `DMGetAuxiliaryVec()`, `DMSetAuxiliaryVec()`, `DMCopyAuxiliaryVec()`
9394: @*/
9395: PetscErrorCode DMGetAuxiliaryLabels(DM dm, DMLabel labels[], PetscInt values[], PetscInt parts[])
9396: {
9397:   PetscHashAuxKey *keys;
9398:   PetscInt         n, i, off = 0;

9400:   PetscFunctionBegin;
9402:   PetscAssertPointer(labels, 2);
9403:   PetscAssertPointer(values, 3);
9404:   PetscAssertPointer(parts, 4);
9405:   PetscCall(DMGetNumAuxiliaryVec(dm, &n));
9406:   PetscCall(PetscMalloc1(n, &keys));
9407:   PetscCall(PetscHMapAuxGetKeys(dm->auxData, &off, keys));
9408:   for (i = 0; i < n; ++i) {
9409:     labels[i] = keys[i].label;
9410:     values[i] = keys[i].value;
9411:     parts[i]  = keys[i].part;
9412:   }
9413:   PetscCall(PetscFree(keys));
9414:   PetscFunctionReturn(PETSC_SUCCESS);
9415: }

9417: /*@
9418:   DMCopyAuxiliaryVec - Copy the auxiliary vector data on a `DM` to a new `DM`

9420:   Not Collective

9422:   Input Parameter:
9423: . dm - The `DM`

9425:   Output Parameter:
9426: . dmNew - The new `DM`, now with the same auxiliary data

9428:   Level: advanced

9430:   Note:
9431:   This is a shallow copy of the auxiliary vectors

9433: .seealso: [](ch_dmbase), `DM`, `DMClearAuxiliaryVec()`, `DMGetNumAuxiliaryVec()`, `DMGetAuxiliaryVec()`, `DMSetAuxiliaryVec()`
9434: @*/
9435: PetscErrorCode DMCopyAuxiliaryVec(DM dm, DM dmNew)
9436: {
9437:   PetscFunctionBegin;
9440:   if (dm == dmNew) PetscFunctionReturn(PETSC_SUCCESS);
9441:   PetscCall(DMClearAuxiliaryVec(dmNew));

9443:   PetscCall(PetscHMapAuxDestroy(&dmNew->auxData));
9444:   PetscCall(PetscHMapAuxDuplicate(dm->auxData, &dmNew->auxData));
9445:   {
9446:     Vec     *auxData;
9447:     PetscInt n, i, off = 0;

9449:     PetscCall(PetscHMapAuxGetSize(dmNew->auxData, &n));
9450:     PetscCall(PetscMalloc1(n, &auxData));
9451:     PetscCall(PetscHMapAuxGetVals(dmNew->auxData, &off, auxData));
9452:     for (i = 0; i < n; ++i) PetscCall(PetscObjectReference((PetscObject)auxData[i]));
9453:     PetscCall(PetscFree(auxData));
9454:   }
9455:   PetscFunctionReturn(PETSC_SUCCESS);
9456: }

9458: /*@
9459:   DMClearAuxiliaryVec - Destroys the auxiliary vector information and creates a new empty one

9461:   Not Collective

9463:   Input Parameter:
9464: . dm - The `DM`

9466:   Level: advanced

9468: .seealso: [](ch_dmbase), `DM`, `DMCopyAuxiliaryVec()`, `DMGetNumAuxiliaryVec()`, `DMGetAuxiliaryVec()`, `DMSetAuxiliaryVec()`
9469: @*/
9470: PetscErrorCode DMClearAuxiliaryVec(DM dm)
9471: {
9472:   Vec     *auxData;
9473:   PetscInt n, i, off = 0;

9475:   PetscFunctionBegin;
9476:   PetscCall(PetscHMapAuxGetSize(dm->auxData, &n));
9477:   PetscCall(PetscMalloc1(n, &auxData));
9478:   PetscCall(PetscHMapAuxGetVals(dm->auxData, &off, auxData));
9479:   for (i = 0; i < n; ++i) PetscCall(VecDestroy(&auxData[i]));
9480:   PetscCall(PetscFree(auxData));
9481:   PetscCall(PetscHMapAuxDestroy(&dm->auxData));
9482:   PetscCall(PetscHMapAuxCreate(&dm->auxData));
9483:   PetscFunctionReturn(PETSC_SUCCESS);
9484: }

9486: /*@
9487:   DMPolytopeMatchOrientation - Determine an orientation (transformation) that takes the source face arrangement to the target face arrangement

9489:   Not Collective

9491:   Input Parameters:
9492: + ct         - The `DMPolytopeType`
9493: . sourceCone - The source arrangement of faces
9494: - targetCone - The target arrangement of faces

9496:   Output Parameters:
9497: + ornt  - The orientation (transformation) which will take the source arrangement to the target arrangement
9498: - found - Flag indicating that a suitable orientation was found

9500:   Level: advanced

9502:   Note:
9503:   An arrangement is a face order combined with an orientation for each face

9505:   Each orientation (transformation) is labeled with an integer from negative `DMPolytopeTypeGetNumArrangements(ct)`/2 to `DMPolytopeTypeGetNumArrangements(ct)`/2
9506:   that labels each arrangement (face ordering plus orientation for each face).

9508:   See `DMPolytopeMatchVertexOrientation()` to find a new vertex orientation that takes the source vertex arrangement to the target vertex arrangement

9510: .seealso: [](ch_dmbase), `DM`, `DMPolytopeGetOrientation()`, `DMPolytopeMatchVertexOrientation()`, `DMPolytopeGetVertexOrientation()`
9511: @*/
9512: PetscErrorCode DMPolytopeMatchOrientation(DMPolytopeType ct, const PetscInt sourceCone[], const PetscInt targetCone[], PetscInt *ornt, PetscBool *found)
9513: {
9514:   const PetscInt cS = DMPolytopeTypeGetConeSize(ct);
9515:   const PetscInt nO = DMPolytopeTypeGetNumArrangements(ct) / 2;
9516:   PetscInt       o, c;

9518:   PetscFunctionBegin;
9519:   if (!nO) {
9520:     *ornt  = 0;
9521:     *found = PETSC_TRUE;
9522:     PetscFunctionReturn(PETSC_SUCCESS);
9523:   }
9524:   for (o = -nO; o < nO; ++o) {
9525:     const PetscInt *arr = DMPolytopeTypeGetArrangement(ct, o);

9527:     for (c = 0; c < cS; ++c)
9528:       if (sourceCone[arr[c * 2]] != targetCone[c]) break;
9529:     if (c == cS) {
9530:       *ornt = o;
9531:       break;
9532:     }
9533:   }
9534:   *found = o == nO ? PETSC_FALSE : PETSC_TRUE;
9535:   PetscFunctionReturn(PETSC_SUCCESS);
9536: }

9538: /*@
9539:   DMPolytopeGetOrientation - Determine an orientation (transformation) that takes the source face arrangement to the target face arrangement

9541:   Not Collective

9543:   Input Parameters:
9544: + ct         - The `DMPolytopeType`
9545: . sourceCone - The source arrangement of faces
9546: - targetCone - The target arrangement of faces

9548:   Output Parameter:
9549: . ornt - The orientation (transformation) which will take the source arrangement to the target arrangement

9551:   Level: advanced

9553:   Note:
9554:   This function is the same as `DMPolytopeMatchOrientation()` except it will generate an error if no suitable orientation can be found.

9556:   Developer Note:
9557:   It is unclear why this function needs to exist since one can simply call `DMPolytopeMatchOrientation()` and error if none is found

9559: .seealso: [](ch_dmbase), `DM`, `DMPolytopeType`, `DMPolytopeMatchOrientation()`, `DMPolytopeGetVertexOrientation()`, `DMPolytopeMatchVertexOrientation()`
9560: @*/
9561: PetscErrorCode DMPolytopeGetOrientation(DMPolytopeType ct, const PetscInt sourceCone[], const PetscInt targetCone[], PetscInt *ornt)
9562: {
9563:   PetscBool found;

9565:   PetscFunctionBegin;
9566:   PetscCall(DMPolytopeMatchOrientation(ct, sourceCone, targetCone, ornt, &found));
9567:   PetscCheck(found, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Could not find orientation for %s", DMPolytopeTypes[ct]);
9568:   PetscFunctionReturn(PETSC_SUCCESS);
9569: }

9571: /*@
9572:   DMPolytopeMatchVertexOrientation - Determine an orientation (transformation) that takes the source vertex arrangement to the target vertex arrangement

9574:   Not Collective

9576:   Input Parameters:
9577: + ct         - The `DMPolytopeType`
9578: . sourceVert - The source arrangement of vertices
9579: - targetVert - The target arrangement of vertices

9581:   Output Parameters:
9582: + ornt  - The orientation (transformation) which will take the source arrangement to the target arrangement
9583: - found - Flag indicating that a suitable orientation was found

9585:   Level: advanced

9587:   Notes:
9588:   An arrangement is a vertex order

9590:   Each orientation (transformation) is labeled with an integer from negative `DMPolytopeTypeGetNumArrangements(ct)`/2 to `DMPolytopeTypeGetNumArrangements(ct)`/2
9591:   that labels each arrangement (vertex ordering).

9593:   See `DMPolytopeMatchOrientation()` to find a new face orientation that takes the source face arrangement to the target face arrangement

9595: .seealso: [](ch_dmbase), `DM`, `DMPolytopeType`, `DMPolytopeGetOrientation()`, `DMPolytopeMatchOrientation()`, `DMPolytopeTypeGetNumVertices()`, `DMPolytopeTypeGetVertexArrangement()`
9596: @*/
9597: PetscErrorCode DMPolytopeMatchVertexOrientation(DMPolytopeType ct, const PetscInt sourceVert[], const PetscInt targetVert[], PetscInt *ornt, PetscBool *found)
9598: {
9599:   const PetscInt cS = DMPolytopeTypeGetNumVertices(ct);
9600:   const PetscInt nO = DMPolytopeTypeGetNumArrangements(ct) / 2;
9601:   PetscInt       o, c;

9603:   PetscFunctionBegin;
9604:   if (!nO) {
9605:     *ornt  = 0;
9606:     *found = PETSC_TRUE;
9607:     PetscFunctionReturn(PETSC_SUCCESS);
9608:   }
9609:   for (o = -nO; o < nO; ++o) {
9610:     const PetscInt *arr = DMPolytopeTypeGetVertexArrangement(ct, o);

9612:     for (c = 0; c < cS; ++c)
9613:       if (sourceVert[arr[c]] != targetVert[c]) break;
9614:     if (c == cS) {
9615:       *ornt = o;
9616:       break;
9617:     }
9618:   }
9619:   *found = o == nO ? PETSC_FALSE : PETSC_TRUE;
9620:   PetscFunctionReturn(PETSC_SUCCESS);
9621: }

9623: /*@
9624:   DMPolytopeGetVertexOrientation - Determine an orientation (transformation) that takes the source vertex arrangement to the target vertex arrangement

9626:   Not Collective

9628:   Input Parameters:
9629: + ct         - The `DMPolytopeType`
9630: . sourceCone - The source arrangement of vertices
9631: - targetCone - The target arrangement of vertices

9633:   Output Parameter:
9634: . ornt - The orientation (transformation) which will take the source arrangement to the target arrangement

9636:   Level: advanced

9638:   Note:
9639:   This function is the same as `DMPolytopeMatchVertexOrientation()` except it errors if not orientation is possible.

9641:   Developer Note:
9642:   It is unclear why this function needs to exist since one can simply call `DMPolytopeMatchVertexOrientation()` and error if none is found

9644: .seealso: [](ch_dmbase), `DM`, `DMPolytopeType`, `DMPolytopeMatchVertexOrientation()`, `DMPolytopeGetOrientation()`
9645: @*/
9646: PetscErrorCode DMPolytopeGetVertexOrientation(DMPolytopeType ct, const PetscInt sourceCone[], const PetscInt targetCone[], PetscInt *ornt)
9647: {
9648:   PetscBool found;

9650:   PetscFunctionBegin;
9651:   PetscCall(DMPolytopeMatchVertexOrientation(ct, sourceCone, targetCone, ornt, &found));
9652:   PetscCheck(found, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Could not find orientation for %s", DMPolytopeTypes[ct]);
9653:   PetscFunctionReturn(PETSC_SUCCESS);
9654: }

9656: /*@
9657:   DMPolytopeInCellTest - Check whether a point lies inside the reference cell of given type

9659:   Not Collective

9661:   Input Parameters:
9662: + ct    - The `DMPolytopeType`
9663: - point - Coordinates of the point

9665:   Output Parameter:
9666: . inside - Flag indicating whether the point is inside the reference cell of given type

9668:   Level: advanced

9670: .seealso: [](ch_dmbase), `DM`, `DMPolytopeType`, `DMLocatePoints()`
9671: @*/
9672: PetscErrorCode DMPolytopeInCellTest(DMPolytopeType ct, const PetscReal point[], PetscBool *inside)
9673: {
9674:   PetscReal sum = 0.0;

9676:   PetscFunctionBegin;
9677:   *inside = PETSC_TRUE;
9678:   switch (ct) {
9679:   case DM_POLYTOPE_TRIANGLE:
9680:   case DM_POLYTOPE_TETRAHEDRON:
9681:     for (PetscInt d = 0; d < DMPolytopeTypeGetDim(ct); ++d) {
9682:       if (point[d] < -1.0) {
9683:         *inside = PETSC_FALSE;
9684:         break;
9685:       }
9686:       sum += point[d];
9687:     }
9688:     if (sum > PETSC_SMALL) {
9689:       *inside = PETSC_FALSE;
9690:       break;
9691:     }
9692:     break;
9693:   case DM_POLYTOPE_QUADRILATERAL:
9694:   case DM_POLYTOPE_HEXAHEDRON:
9695:     for (PetscInt d = 0; d < DMPolytopeTypeGetDim(ct); ++d)
9696:       if (PetscAbsReal(point[d]) > 1. + PETSC_SMALL) {
9697:         *inside = PETSC_FALSE;
9698:         break;
9699:       }
9700:     break;
9701:   default:
9702:     SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Unsupported polytope type %s", DMPolytopeTypes[ct]);
9703:   }
9704:   PetscFunctionReturn(PETSC_SUCCESS);
9705: }

9707: /*@
9708:   DMReorderSectionSetDefault - Set flag indicating whether the local section should be reordered by default

9710:   Logically collective

9712:   Input Parameters:
9713: + dm      - The DM
9714: - reorder - Flag for reordering

9716:   Level: intermediate

9718: .seealso: `DMReorderSectionGetDefault()`
9719: @*/
9720: PetscErrorCode DMReorderSectionSetDefault(DM dm, DMReorderDefaultFlag reorder)
9721: {
9722:   PetscFunctionBegin;
9724:   PetscTryMethod(dm, "DMReorderSectionSetDefault_C", (DM, DMReorderDefaultFlag), (dm, reorder));
9725:   PetscFunctionReturn(PETSC_SUCCESS);
9726: }

9728: /*@
9729:   DMReorderSectionGetDefault - Get flag indicating whether the local section should be reordered by default

9731:   Not collective

9733:   Input Parameter:
9734: . dm - The DM

9736:   Output Parameter:
9737: . reorder - Flag for reordering

9739:   Level: intermediate

9741: .seealso: `DMReorderSetDefault()`
9742: @*/
9743: PetscErrorCode DMReorderSectionGetDefault(DM dm, DMReorderDefaultFlag *reorder)
9744: {
9745:   PetscFunctionBegin;
9747:   PetscAssertPointer(reorder, 2);
9748:   *reorder = DM_REORDER_DEFAULT_NOTSET;
9749:   PetscTryMethod(dm, "DMReorderSectionGetDefault_C", (DM, DMReorderDefaultFlag *), (dm, reorder));
9750:   PetscFunctionReturn(PETSC_SUCCESS);
9751: }

9753: /*@
9754:   DMReorderSectionSetType - Set the type of local section reordering

9756:   Logically collective

9758:   Input Parameters:
9759: + dm      - The DM
9760: - reorder - The reordering method

9762:   Level: intermediate

9764: .seealso: `DMReorderSectionGetType()`, `DMReorderSectionSetDefault()`
9765: @*/
9766: PetscErrorCode DMReorderSectionSetType(DM dm, MatOrderingType reorder)
9767: {
9768:   PetscFunctionBegin;
9770:   PetscTryMethod(dm, "DMReorderSectionSetType_C", (DM, MatOrderingType), (dm, reorder));
9771:   PetscFunctionReturn(PETSC_SUCCESS);
9772: }

9774: /*@
9775:   DMReorderSectionGetType - Get the reordering type for the local section

9777:   Not collective

9779:   Input Parameter:
9780: . dm - The DM

9782:   Output Parameter:
9783: . reorder - The reordering method

9785:   Level: intermediate

9787: .seealso: `DMReorderSetDefault()`, `DMReorderSectionGetDefault()`
9788: @*/
9789: PetscErrorCode DMReorderSectionGetType(DM dm, MatOrderingType *reorder)
9790: {
9791:   PetscFunctionBegin;
9793:   PetscAssertPointer(reorder, 2);
9794:   *reorder = NULL;
9795:   PetscTryMethod(dm, "DMReorderSectionGetType_C", (DM, MatOrderingType *), (dm, reorder));
9796:   PetscFunctionReturn(PETSC_SUCCESS);
9797: }