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: .seealso: [](ch_dmbase), `DM`, `Vec`, `DMCreateLocalVector()`, `DMGetGlobalVector()`, `DMDestroy()`, `DMView()`, `DMCreateInterpolation()`, `DMCreateColoring()`, `DMCreateMatrix()`,
1032:          `DMGlobalToLocalBegin()`, `DMGlobalToLocalEnd()`
1033: @*/
1034: PetscErrorCode DMCreateGlobalVector(DM dm, Vec *vec)
1035: {
1036:   PetscFunctionBegin;
1038:   PetscAssertPointer(vec, 2);
1039:   PetscUseTypeMethod(dm, createglobalvector, vec);
1040:   if (PetscDefined(USE_DEBUG)) {
1041:     DM vdm;

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

1049: /*@
1050:   DMCreateLocalVector - Creates a local vector from a `DM` object.

1052:   Not Collective

1054:   Input Parameter:
1055: . dm - the `DM` object

1057:   Output Parameter:
1058: . vec - the local vector

1060:   Level: beginner

1062:   Note:
1063:   A local vector usually has ghost locations that contain values that are owned by different MPI ranks. A global vector has no ghost locations.

1065: .seealso: [](ch_dmbase), `DM`, `Vec`, `DMCreateGlobalVector()`, `DMGetLocalVector()`, `DMDestroy()`, `DMView()`, `DMCreateInterpolation()`, `DMCreateColoring()`, `DMCreateMatrix()`,
1066:          `DMGlobalToLocalBegin()`, `DMGlobalToLocalEnd()`
1067: @*/
1068: PetscErrorCode DMCreateLocalVector(DM dm, Vec *vec)
1069: {
1070:   PetscFunctionBegin;
1072:   PetscAssertPointer(vec, 2);
1073:   PetscUseTypeMethod(dm, createlocalvector, vec);
1074:   if (PetscDefined(USE_DEBUG)) {
1075:     DM vdm;

1077:     PetscCall(VecGetDM(*vec, &vdm));
1078:     PetscCheck(vdm, PETSC_COMM_SELF, PETSC_ERR_LIB, "DM type '%s' did not attach the DM to the vector", ((PetscObject)dm)->type_name);
1079:   }
1080:   PetscFunctionReturn(PETSC_SUCCESS);
1081: }

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

1086:   Collective

1088:   Input Parameter:
1089: . dm - the `DM` that provides the mapping

1091:   Output Parameter:
1092: . ltog - the mapping

1094:   Level: advanced

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

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

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

1104: .seealso: [](ch_dmbase), `DM`, `DMCreateLocalVector()`, `DMCreateGlobalVector()`, `VecSetLocalToGlobalMapping()`, `MatSetLocalToGlobalMapping()`,
1105:           `DMCreateMatrix()`
1106: @*/
1107: PetscErrorCode DMGetLocalToGlobalMapping(DM dm, ISLocalToGlobalMapping *ltog)
1108: {
1109:   PetscInt bs = -1, bsLocal[2], bsMinMax[2];

1111:   PetscFunctionBegin;
1113:   PetscAssertPointer(ltog, 2);
1114:   if (!dm->ltogmap) {
1115:     PetscSection section, sectionGlobal;

1117:     PetscCall(DMGetLocalSection(dm, &section));
1118:     if (section) {
1119:       const PetscInt *cdofs;
1120:       PetscInt       *ltog;
1121:       PetscInt        pStart, pEnd, n, p, k, l;

1123:       PetscCall(DMGetGlobalSection(dm, &sectionGlobal));
1124:       PetscCall(PetscSectionGetChart(section, &pStart, &pEnd));
1125:       PetscCall(PetscSectionGetStorageSize(section, &n));
1126:       PetscCall(PetscMalloc1(n, &ltog)); /* We want the local+overlap size */
1127:       for (p = pStart, l = 0; p < pEnd; ++p) {
1128:         PetscInt bdof, cdof, dof, off, c, cind;

1130:         /* Should probably use constrained dofs */
1131:         PetscCall(PetscSectionGetDof(section, p, &dof));
1132:         PetscCall(PetscSectionGetConstraintDof(section, p, &cdof));
1133:         PetscCall(PetscSectionGetConstraintIndices(section, p, &cdofs));
1134:         PetscCall(PetscSectionGetOffset(sectionGlobal, p, &off));
1135:         /* If you have dofs, and constraints, and they are unequal, we set the blocksize to 1 */
1136:         bdof = cdof && (dof - cdof) ? 1 : dof;
1137:         if (dof) bs = bs < 0 ? bdof : PetscGCD(bs, bdof);

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

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

1173:   Not Collective

1175:   Input Parameter:
1176: . dm - the `DM` with block structure

1178:   Output Parameter:
1179: . bs - the block size, 1 implies no exploitable block structure

1181:   Level: intermediate

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

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

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

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

1205:   Collective

1207:   Input Parameters:
1208: + dmc - the `DM` object
1209: - dmf - the second, finer `DM` object

1211:   Output Parameters:
1212: + mat - the interpolation
1213: - vec - the scaling (optional, pass `NULL` if not needed), see `DMCreateInterpolationScale()`

1215:   Level: developer

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

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

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

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

1242:   Input Parameters:
1243: + dac - `DM` that defines a coarse mesh
1244: . daf - `DM` that defines a fine mesh
1245: - mat - the restriction (or interpolation operator) from fine to coarse

1247:   Output Parameter:
1248: . scale - the scaled vector

1250:   Level: advanced

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

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

1260: .seealso: [](ch_dmbase), `DM`, `MatRestrict()`, `MatInterpolate()`, `DMCreateInterpolation()`, `DMCreateRestriction()`, `DMCreateGlobalVector()`
1261: @*/
1262: PetscErrorCode DMCreateInterpolationScale(DM dac, DM daf, Mat mat, Vec *scale)
1263: {
1264:   Vec         fine;
1265:   PetscScalar one = 1.0;
1266: #if defined(PETSC_HAVE_CUDA)
1267:   PetscBool bindingpropagates, isbound;
1268: #endif

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

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

1295:   Collective

1297:   Input Parameters:
1298: + dmc - the `DM` object
1299: - dmf - the second, finer `DM` object

1301:   Output Parameter:
1302: . mat - the restriction

1304:   Level: developer

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

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

1324: /*@
1325:   DMCreateInjection - Gets injection matrix between two `DM` objects.

1327:   Collective

1329:   Input Parameters:
1330: + dac - the `DM` object
1331: - daf - the second, finer `DM` object

1333:   Output Parameter:
1334: . mat - the injection

1336:   Level: developer

1338:   Notes:
1339:   This is an operator that applied to a vector obtained with `DMCreateGlobalVector()` on the
1340:   fine grid maps the values to a vector on the vector on the coarse `DM` by simply selecting
1341:   the values on the coarse grid points. This compares to the operator obtained by
1342:   `DMCreateRestriction()` or the transpose of the operator obtained by
1343:   `DMCreateInterpolation()` that uses a "local weighted average" of the values around the
1344:   coarse grid point as the coarse grid value.

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

1349: .seealso: [](ch_dmbase), `DM`, `DMDestroy()`, `DMView()`, `DMCreateGlobalVector()`, `DMCreateColoring()`, `DMCreateMatrix()`, `DMCreateMassMatrix()`, `DMCreateInterpolation()`,
1350:           `DMCreateRestriction()`, `MatRestrict()`, `MatInterpolate()`
1351: @*/
1352: PetscErrorCode DMCreateInjection(DM dac, DM daf, Mat *mat)
1353: {
1354:   PetscFunctionBegin;
1357:   PetscAssertPointer(mat, 3);
1358:   PetscCall(PetscLogEventBegin(DM_CreateInjection, dac, daf, 0, 0));
1359:   PetscUseTypeMethod(dac, createinjection, daf, mat);
1360:   PetscCall(PetscLogEventEnd(DM_CreateInjection, dac, daf, 0, 0));
1361:   PetscFunctionReturn(PETSC_SUCCESS);
1362: }

1364: /*@
1365:   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
1366:   a Galerkin finite element model on the `DM`

1368:   Collective

1370:   Input Parameters:
1371: + dmc - the target `DM` object
1372: - dmf - the source `DM` object, can be `NULL`

1374:   Output Parameter:
1375: . mat - the mass matrix

1377:   Level: developer

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

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

1384: .seealso: [](ch_dmbase), `DM`, `DMCreateMassMatrixLumped()`, `DMCreateMatrix()`, `DMRefine()`, `DMCoarsen()`, `DMCreateRestriction()`, `DMCreateInterpolation()`, `DMCreateInjection()`
1385: @*/
1386: PetscErrorCode DMCreateMassMatrix(DM dmc, DM dmf, Mat *mat)
1387: {
1388:   PetscFunctionBegin;
1390:   if (!dmf) dmf = dmc;
1392:   PetscAssertPointer(mat, 3);
1393:   PetscCall(PetscLogEventBegin(DM_CreateMassMatrix, dmc, dmf, 0, 0));
1394:   PetscUseTypeMethod(dmc, createmassmatrix, dmf, mat);
1395:   PetscCall(PetscLogEventEnd(DM_CreateMassMatrix, dmc, dmf, 0, 0));
1396:   PetscFunctionReturn(PETSC_SUCCESS);
1397: }

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

1402:   Collective

1404:   Input Parameter:
1405: . dm - the `DM` object

1407:   Output Parameters:
1408: + llm - the local lumped mass matrix, which is a diagonal matrix, represented as a vector
1409: - lm  - the global lumped mass matrix, which is a diagonal matrix, represented as a vector

1411:   Level: developer

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

1416: .seealso: [](ch_dmbase), `DM`, `DMCreateMassMatrix()`, `DMCreateMatrix()`, `DMRefine()`, `DMCoarsen()`, `DMCreateRestriction()`, `DMCreateInterpolation()`, `DMCreateInjection()`
1417: @*/
1418: PetscErrorCode DMCreateMassMatrixLumped(DM dm, Vec *llm, Vec *lm)
1419: {
1420:   PetscFunctionBegin;
1422:   if (llm) PetscAssertPointer(llm, 2);
1423:   if (lm) PetscAssertPointer(lm, 3);
1424:   if (llm || lm) PetscUseTypeMethod(dm, createmassmatrixlumped, llm, lm);
1425:   PetscFunctionReturn(PETSC_SUCCESS);
1426: }

1428: /*@
1429:   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`

1431:   Collective

1433:   Input Parameters:
1434: + dmc - the target `DM` object
1435: - dmf - the source `DM` object, can be `NULL`

1437:   Output Parameter:
1438: . mat - the gradient matrix

1440:   Level: developer

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

1445: .seealso: [](ch_dmbase), `DM`, `DMCreateMassMatrix()`, `DMCreateMassMatrixLumped()`, `DMCreateMatrix()`, `DMRefine()`, `DMCoarsen()`, `DMCreateRestriction()`, `DMCreateInterpolation()`, `DMCreateInjection()`
1446: @*/
1447: PetscErrorCode DMCreateGradientMatrix(DM dmc, DM dmf, Mat *mat)
1448: {
1449:   PetscFunctionBegin;
1451:   if (!dmf) dmf = dmc;
1453:   PetscAssertPointer(mat, 3);
1454:   PetscUseTypeMethod(dmc, creategradientmatrix, dmf, mat);
1455:   PetscFunctionReturn(PETSC_SUCCESS);
1456: }

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

1462:   Collective

1464:   Input Parameters:
1465: + dm    - the `DM` object
1466: - ctype - `IS_COLORING_LOCAL` or `IS_COLORING_GLOBAL`

1468:   Output Parameter:
1469: . coloring - the coloring

1471:   Level: developer

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

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

1481: .seealso: [](ch_dmbase), `DM`, `ISColoring`, `DMDestroy()`, `DMView()`, `DMCreateGlobalVector()`, `DMCreateInterpolation()`, `DMCreateMatrix()`, `DMCreateMassMatrix()`, `DMSetMatType()`, `MatColoring`, `MatFDColoringCreate()`
1482: @*/
1483: PetscErrorCode DMCreateColoring(DM dm, ISColoringType ctype, ISColoring *coloring)
1484: {
1485:   PetscFunctionBegin;
1487:   PetscAssertPointer(coloring, 3);
1488:   PetscUseTypeMethod(dm, getcoloring, ctype, coloring);
1489:   PetscFunctionReturn(PETSC_SUCCESS);
1490: }

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

1495:   Collective

1497:   Input Parameter:
1498: . dm - the `DM` object

1500:   Output Parameter:
1501: . mat - the empty Jacobian

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

1506:   Level: beginner

1508:   Notes:
1509:   This properly preallocates the number of nonzeros in the sparse matrix so you
1510:   do not need to do it yourself.

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

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

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

1521: .seealso: [](ch_dmbase), `DM`, `DMDestroy()`, `DMView()`, `DMCreateGlobalVector()`, `DMCreateInterpolation()`, `DMSetMatType()`, `DMCreateMassMatrix()`
1522: @*/
1523: PetscErrorCode DMCreateMatrix(DM dm, Mat *mat)
1524: {
1525:   PetscFunctionBegin;
1527:   PetscAssertPointer(mat, 2);
1528:   PetscCall(MatInitializePackage());
1529:   PetscCall(PetscLogEventBegin(DM_CreateMatrix, 0, 0, 0, 0));
1530:   PetscUseTypeMethod(dm, creatematrix, mat);
1531:   if (PetscDefined(USE_DEBUG)) {
1532:     DM mdm;

1534:     PetscCall(MatGetDM(*mat, &mdm));
1535:     PetscCheck(mdm, PETSC_COMM_SELF, PETSC_ERR_PLIB, "DM type '%s' did not attach the DM to the matrix", ((PetscObject)dm)->type_name);
1536:   }
1537:   /* Handle nullspace and near nullspace */
1538:   if (dm->Nf) {
1539:     MatNullSpace nullSpace;
1540:     PetscInt     Nf;

1542:     PetscCall(DMGetNumFields(dm, &Nf));
1543:     for (PetscInt f = 0; f < Nf; ++f) {
1544:       if (dm->nullspaceConstructors && dm->nullspaceConstructors[f]) {
1545:         PetscCall((*dm->nullspaceConstructors[f])(dm, f, f, &nullSpace));
1546:         PetscCall(MatSetNullSpace(*mat, nullSpace));
1547:         PetscCall(MatNullSpaceDestroy(&nullSpace));
1548:         break;
1549:       }
1550:     }
1551:     for (PetscInt f = 0; f < Nf; ++f) {
1552:       if (dm->nearnullspaceConstructors && dm->nearnullspaceConstructors[f]) {
1553:         PetscCall((*dm->nearnullspaceConstructors[f])(dm, f, f, &nullSpace));
1554:         PetscCall(MatSetNearNullSpace(*mat, nullSpace));
1555:         PetscCall(MatNullSpaceDestroy(&nullSpace));
1556:       }
1557:     }
1558:   }
1559:   PetscCall(PetscLogEventEnd(DM_CreateMatrix, 0, 0, 0, 0));
1560:   PetscFunctionReturn(PETSC_SUCCESS);
1561: }

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

1568:   Logically Collective

1570:   Input Parameters:
1571: + dm   - the `DM`
1572: - skip - `PETSC_TRUE` to skip preallocation

1574:   Level: developer

1576:   Note:
1577:   This is most useful to reduce initialization costs when `MatSetPreallocationCOO()` and
1578:   `MatSetValuesCOO()` will be used.

1580: .seealso: [](ch_dmbase), `DM`, `DMCreateMatrix()`, `DMSetMatrixStructureOnly()`, `DMSetMatrixPreallocateOnly()`
1581: @*/
1582: PetscErrorCode DMSetMatrixPreallocateSkip(DM dm, PetscBool skip)
1583: {
1584:   PetscFunctionBegin;
1586:   dm->prealloc_skip = skip;
1587:   PetscFunctionReturn(PETSC_SUCCESS);
1588: }

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

1594:   Logically Collective

1596:   Input Parameters:
1597: + dm   - the `DM`
1598: - only - `PETSC_TRUE` if only want preallocation

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

1603:   Level: developer

1605: .seealso: [](ch_dmbase), `DM`, `DMCreateMatrix()`, `DMCreateMassMatrix()`, `DMSetMatrixStructureOnly()`, `DMSetMatrixPreallocateSkip()`
1606: @*/
1607: PetscErrorCode DMSetMatrixPreallocateOnly(DM dm, PetscBool only)
1608: {
1609:   PetscFunctionBegin;
1611:   dm->prealloc_only = only;
1612:   PetscFunctionReturn(PETSC_SUCCESS);
1613: }

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

1619:   Logically Collective

1621:   Input Parameters:
1622: + dm   - the `DM`
1623: - only - `PETSC_TRUE` if you only want matrix nonzero structure

1625:   Level: developer

1627: .seealso: [](ch_dmbase), `DM`, `DMCreateMatrix()`, `DMSetMatrixPreallocateOnly()`, `DMSetMatrixPreallocateSkip()`
1628: @*/
1629: PetscErrorCode DMSetMatrixStructureOnly(DM dm, PetscBool only)
1630: {
1631:   PetscFunctionBegin;
1633:   dm->structure_only = only;
1634:   PetscFunctionReturn(PETSC_SUCCESS);
1635: }

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

1640:   Logically Collective

1642:   Input Parameters:
1643: + dm    - the `DM`
1644: - btype - block by topological point or field node

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

1649:   Level: advanced

1651: .seealso: [](ch_dmbase), `DM`, `DMCreateMatrix()`, `MatSetVariableBlockSizes()`
1652: @*/
1653: PetscErrorCode DMSetBlockingType(DM dm, DMBlockingType btype)
1654: {
1655:   PetscFunctionBegin;
1657:   dm->blocking_type = btype;
1658:   PetscFunctionReturn(PETSC_SUCCESS);
1659: }

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

1664:   Not Collective

1666:   Input Parameter:
1667: . dm - the `DM`

1669:   Output Parameter:
1670: . btype - block by topological point or field node

1672:   Level: advanced

1674: .seealso: [](ch_dmbase), `DM`, `DMCreateMatrix()`, `MatSetVariableBlockSizes()`
1675: @*/
1676: PetscErrorCode DMGetBlockingType(DM dm, DMBlockingType *btype)
1677: {
1678:   PetscFunctionBegin;
1680:   PetscAssertPointer(btype, 2);
1681:   *btype = dm->blocking_type;
1682:   PetscFunctionReturn(PETSC_SUCCESS);
1683: }

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

1688:   Not Collective

1690:   Input Parameters:
1691: + dm    - the `DM` object
1692: . count - The minimum size
1693: - dtype - MPI data type, often `MPIU_REAL`, `MPIU_SCALAR`, or `MPIU_INT`)

1695:   Output Parameter:
1696: . mem - the work array

1698:   Level: developer

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

1703:   The array may contain nonzero values

1705: .seealso: [](ch_dmbase), `DM`, `DMDestroy()`, `DMCreate()`, `DMRestoreWorkArray()`, `PetscMalloc()`
1706: @*/
1707: PetscErrorCode DMGetWorkArray(DM dm, PetscInt count, MPI_Datatype dtype, void *mem)
1708: {
1709:   DMWorkLink  link;
1710:   PetscMPIInt dsize;

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

1737:   if (((size_t)dsize * count) > link->bytes) {
1738:     PetscCall(PetscFree(link->mem));
1739:     PetscCall(PetscMalloc(dsize * count, &link->mem));
1740:     link->bytes = dsize * count;
1741:   }
1742:   link->next    = dm->workout;
1743:   dm->workout   = link;
1744:   *(void **)mem = link->mem;
1745:   PetscFunctionReturn(PETSC_SUCCESS);
1746: }

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

1751:   Not Collective

1753:   Input Parameters:
1754: + dm    - the `DM` object
1755: . count - The minimum size
1756: - dtype - MPI data type, often `MPIU_REAL`, `MPIU_SCALAR`, `MPIU_INT`

1758:   Output Parameter:
1759: . mem - the work array

1761:   Level: developer

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

1766: .seealso: [](ch_dmbase), `DM`, `DMDestroy()`, `DMCreate()`, `DMGetWorkArray()`
1767: @*/
1768: PetscErrorCode DMRestoreWorkArray(DM dm, PetscInt count, MPI_Datatype dtype, void *mem)
1769: {
1770:   DMWorkLink *p, link;

1772:   PetscFunctionBegin;
1773:   PetscAssertPointer(mem, 4);
1774:   (void)count;
1775:   (void)dtype;
1776:   if (!*(void **)mem) PetscFunctionReturn(PETSC_SUCCESS);
1777:   for (p = &dm->workout; (link = *p); p = &link->next) {
1778:     if (link->mem == *(void **)mem) {
1779:       *p            = link->next;
1780:       link->next    = dm->workin;
1781:       dm->workin    = link;
1782:       *(void **)mem = NULL;
1783:       PetscFunctionReturn(PETSC_SUCCESS);
1784:     }
1785:   }
1786:   SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Array was not checked out");
1787: }

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

1793:   Logically Collective; No Fortran Support

1795:   Input Parameters:
1796: + dm     - The `DM`
1797: . field  - The field number for the nullspace
1798: - nullsp - A callback to create the nullspace

1800:   Calling sequence of `nullsp`:
1801: + dm        - The present `DM`
1802: . origField - The field number given above, in the original `DM`
1803: . field     - The field number in dm
1804: - nullSpace - The nullspace for the given field

1806:   Level: intermediate

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

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

1823:   Not Collective; No Fortran Support

1825:   Input Parameters:
1826: + dm    - The `DM`
1827: - field - The field number for the nullspace

1829:   Output Parameter:
1830: . nullsp - A callback to create the nullspace

1832:   Calling sequence of `nullsp`:
1833: + dm        - The present DM
1834: . origField - The field number given above, in the original DM
1835: . field     - The field number in dm
1836: - nullSpace - The nullspace for the given field

1838:   Level: intermediate

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

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

1856:   Logically Collective; No Fortran Support

1858:   Input Parameters:
1859: + dm     - The `DM`
1860: . field  - The field number for the nullspace
1861: - nullsp - A callback to create the near-nullspace

1863:   Calling sequence of `nullsp`:
1864: + dm        - The present `DM`
1865: . origField - The field number given above, in the original `DM`
1866: . field     - The field number in dm
1867: - nullSpace - The nullspace for the given field

1869:   Level: intermediate

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

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

1887:   Not Collective; No Fortran Support

1889:   Input Parameters:
1890: + dm    - The `DM`
1891: - field - The field number for the nullspace

1893:   Output Parameter:
1894: . nullsp - A callback to create the near-nullspace

1896:   Calling sequence of `nullsp`:
1897: + dm        - The present `DM`
1898: . origField - The field number given above, in the original `DM`
1899: . field     - The field number in dm
1900: - nullSpace - The nullspace for the given field

1902:   Level: intermediate

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

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

1921:   Not Collective; No Fortran Support

1923:   Input Parameter:
1924: . dm - the `DM` object

1926:   Output Parameters:
1927: + numFields  - The number of fields (or `NULL` if not requested)
1928: . fieldNames - The name of each field (or `NULL` if not requested)
1929: - fields     - The global indices for each field (or `NULL` if not requested)

1931:   Level: intermediate

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

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

1942: .seealso: [](ch_dmbase), `DM`, `DMAddField()`, `DMGetField()`, `DMDestroy()`, `DMView()`, `DMCreateInterpolation()`, `DMCreateColoring()`, `DMCreateMatrix()`,
1943:           `DMCreateFieldDecomposition()`
1944: @*/
1945: PetscErrorCode DMCreateFieldIS(DM dm, PetscInt *numFields, char ***fieldNames, IS *fields[])
1946: {
1947:   PetscSection section, sectionGlobal;

1949:   PetscFunctionBegin;
1951:   if (numFields) {
1952:     PetscAssertPointer(numFields, 2);
1953:     *numFields = 0;
1954:   }
1955:   if (fieldNames) {
1956:     PetscAssertPointer(fieldNames, 3);
1957:     *fieldNames = NULL;
1958:   }
1959:   if (fields) {
1960:     PetscAssertPointer(fields, 4);
1961:     *fields = NULL;
1962:   }
1963:   PetscCall(DMGetLocalSection(dm, &section));
1964:   if (section) {
1965:     PetscInt *fieldSizes, *fieldNc, **fieldIndices;
1966:     PetscInt  nF, f, pStart, pEnd, p;

1968:     PetscCall(DMGetGlobalSection(dm, &sectionGlobal));
1969:     PetscCall(PetscSectionGetNumFields(section, &nF));
1970:     PetscCall(PetscMalloc3(nF, &fieldSizes, nF, &fieldNc, nF, &fieldIndices));
1971:     PetscCall(PetscSectionGetChart(sectionGlobal, &pStart, &pEnd));
1972:     for (f = 0; f < nF; ++f) {
1973:       fieldSizes[f] = 0;
1974:       PetscCall(PetscSectionGetFieldComponents(section, f, &fieldNc[f]));
1975:     }
1976:     for (p = pStart; p < pEnd; ++p) {
1977:       PetscInt gdof;

1979:       PetscCall(PetscSectionGetDof(sectionGlobal, p, &gdof));
1980:       if (gdof > 0) {
1981:         for (f = 0; f < nF; ++f) {
1982:           PetscInt fdof, fcdof, fpdof;

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

2002:       PetscCall(PetscSectionGetDof(sectionGlobal, p, &gdof));
2003:       if (gdof > 0) {
2004:         PetscCall(PetscSectionGetOffset(sectionGlobal, p, &goff));
2005:         for (f = 0; f < nF; ++f) {
2006:           PetscInt fdof, fcdof, fc;

2008:           PetscCall(PetscSectionGetFieldDof(section, p, f, &fdof));
2009:           PetscCall(PetscSectionGetFieldConstraintDof(section, p, f, &fcdof));
2010:           for (fc = 0; fc < fdof - fcdof; ++fc, ++fieldSizes[f]) fieldIndices[f][fieldSizes[f]] = goff++;
2011:         }
2012:       }
2013:     }
2014:     if (numFields) *numFields = nF;
2015:     if (fieldNames) {
2016:       PetscCall(PetscMalloc1(nF, fieldNames));
2017:       for (f = 0; f < nF; ++f) {
2018:         const char *fieldName;

2020:         PetscCall(PetscSectionGetFieldName(section, f, &fieldName));
2021:         PetscCall(PetscStrallocpy(fieldName, &(*fieldNames)[f]));
2022:       }
2023:     }
2024:     if (fields) {
2025:       PetscCall(PetscMalloc1(nF, fields));
2026:       for (f = 0; f < nF; ++f) {
2027:         PetscInt bs, in[2], out[2];

2029:         PetscCall(ISCreateGeneral(PetscObjectComm((PetscObject)dm), fieldSizes[f], fieldIndices[f], PETSC_OWN_POINTER, &(*fields)[f]));
2030:         in[0] = -fieldNc[f];
2031:         in[1] = fieldNc[f];
2032:         PetscCallMPI(MPIU_Allreduce(in, out, 2, MPIU_INT, MPI_MAX, PetscObjectComm((PetscObject)dm)));
2033:         bs = (-out[0] == out[1]) ? out[1] : 1;
2034:         PetscCall(ISSetBlockSize((*fields)[f], bs));
2035:       }
2036:     }
2037:     PetscCall(PetscFree3(fieldSizes, fieldNc, fieldIndices));
2038:   } else PetscTryTypeMethod(dm, createfieldis, numFields, fieldNames, fields);
2039:   PetscFunctionReturn(PETSC_SUCCESS);
2040: }

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

2046:   Not Collective; No Fortran Support

2048:   Input Parameter:
2049: . dm - the `DM` object

2051:   Output Parameters:
2052: + len      - The number of fields (or `NULL` if not requested)
2053: . namelist - The name for each field (or `NULL` if not requested)
2054: . islist   - The global indices for each field (or `NULL` if not requested)
2055: - dmlist   - The `DM`s for each field subproblem (or `NULL`, if not requested; if `NULL` is returned, no `DM`s are defined)

2057:   Level: intermediate

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

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

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

2069:   Fortran Notes:
2070:   Use the declarations
2071: .vb
2072:   character(80), pointer :: namelist(:)
2073:   IS, pointer :: islist(:)
2074:   DM, pointer :: dmlist(:)
2075: .ve

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

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

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

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

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

2119:     PetscCall(DMGetLocalSection(dm, &section));
2120:     if (section) PetscCall(PetscSectionGetNumFields(section, &numFields));
2121:     if (section && numFields && dm->ops->createsubdm) {
2122:       if (len) *len = numFields;
2123:       if (namelist) PetscCall(PetscMalloc1(numFields, namelist));
2124:       if (islist) PetscCall(PetscMalloc1(numFields, islist));
2125:       if (dmlist) PetscCall(PetscMalloc1(numFields, dmlist));
2126:       for (PetscInt f = 0; f < numFields; ++f) {
2127:         const char *fieldName;

2129:         PetscCall(DMCreateSubDM(dm, 1, &f, islist ? &(*islist)[f] : NULL, dmlist ? &(*dmlist)[f] : NULL));
2130:         if (namelist) {
2131:           PetscCall(PetscSectionGetFieldName(section, f, &fieldName));
2132:           PetscCall(PetscStrallocpy(fieldName, &(*namelist)[f]));
2133:         }
2134:       }
2135:     } else {
2136:       PetscCall(DMCreateFieldIS(dm, len, namelist, islist));
2137:       /* By default there are no DMs associated with subproblems. */
2138:       if (dmlist) *dmlist = NULL;
2139:     }
2140:   } else PetscUseTypeMethod(dm, createfielddecomposition, len, namelist, islist, dmlist);
2141:   PetscFunctionReturn(PETSC_SUCCESS);
2142: }

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

2148:   Not collective

2150:   Input Parameters:
2151: + dm        - The `DM` object
2152: . numFields - The number of fields to select
2153: - fields    - The field numbers of the selected fields

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

2159:   Level: intermediate

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

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

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

2180:   Not collective

2182:   Input Parameters:
2183: + dms - The `DM` objects
2184: - n   - The number of `DM`s

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

2190:   Level: intermediate

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

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

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

2217:   Not Collective

2219:   Input Parameter:
2220: . dm - the `DM` object

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

2229:   Level: intermediate

2231:   Notes:
2232:   Each `IS` contains the global indices of the dofs of the corresponding subdomains with in the
2233:   dofs of the original `DM`. The inner subdomains conceptually define a nonoverlapping
2234:   covering, while outer subdomains can overlap.

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

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

2242:   Developer Notes:
2243:   The `dmlist` is for the inner subdomains or the outer subdomains or all subdomains?

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

2247: .seealso: [](ch_dmbase), `DM`, `DMCreateFieldDecomposition()`, `DMDestroy()`, `DMCreateDomainDecompositionScatters()`, `DMView()`, `DMCreateInterpolation()`,
2248:           `DMSubDomainHookAdd()`, `DMSubDomainHookRemove()`, `DMCreateColoring()`, `DMCreateMatrix()`, `DMCreateMassMatrix()`, `DMRefine()`, `DMCoarsen()`
2249: @*/
2250: PetscErrorCode DMCreateDomainDecomposition(DM dm, PetscInt *n, char **namelist[], IS *innerislist[], IS *outerislist[], DM *dmlist[])
2251: {
2252:   DMSubDomainHookLink link;
2253:   PetscInt            l;

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

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

2303:   Not Collective

2305:   Input Parameters:
2306: + dm     - the `DM` object
2307: . n      - the number of subdomains
2308: - subdms - the local subdomains

2310:   Output Parameters:
2311: + iscat - scatter from global vector to nonoverlapping global vector entries on subdomain
2312: . oscat - scatter from global vector to overlapping global vector entries on subdomain
2313: - gscat - scatter from global vector to local vector on subdomain (fills in ghosts)

2315:   Level: developer

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

2323:   Developer Note:
2324:   Can the `subdms` input be anything or are they exactly the `DM` obtained from
2325:   `DMCreateDomainDecomposition()`?

2327: .seealso: [](ch_dmbase), `DM`, `DMCreateDomainDecomposition()`, `DMDestroy()`, `DMView()`, `DMCreateInterpolation()`, `DMCreateColoring()`, `DMCreateMatrix()`, `DMCreateMassMatrix()`, `DMCreateFieldIS()`
2328: @*/
2329: PetscErrorCode DMCreateDomainDecompositionScatters(DM dm, PetscInt n, DM subdms[], VecScatter *iscat[], VecScatter *oscat[], VecScatter *gscat[])
2330: {
2331:   PetscFunctionBegin;
2333:   PetscAssertPointer(subdms, 3);
2334:   PetscUseTypeMethod(dm, createddscatters, n, subdms, iscat, oscat, gscat);
2335:   PetscFunctionReturn(PETSC_SUCCESS);
2336: }

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

2341:   Collective

2343:   Input Parameters:
2344: + dm   - the `DM` object
2345: - comm - the communicator to contain the new `DM` object (or `MPI_COMM_NULL`)

2347:   Output Parameter:
2348: . dmf - the refined `DM`, or `NULL`

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

2353:   Level: developer

2355:   Note:
2356:   If no refinement was done, the return value is `NULL`

2358: .seealso: [](ch_dmbase), `DM`, `DMCoarsen()`, `DMDestroy()`, `DMView()`, `DMCreateGlobalVector()`, `DMCreateInterpolation()`, `DMCreateDomainDecomposition()`,
2359:           `DMRefineHookAdd()`, `DMRefineHookRemove()`
2360: @*/
2361: PetscErrorCode DMRefine(DM dm, MPI_Comm comm, DM *dmf)
2362: {
2363:   DMRefineHookLink link;

2365:   PetscFunctionBegin;
2367:   PetscCall(PetscLogEventBegin(DM_Refine, dm, 0, 0, 0));
2368:   PetscUseTypeMethod(dm, refine, comm, dmf);
2369:   if (*dmf) {
2370:     (*dmf)->ops->creatematrix = dm->ops->creatematrix;

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

2374:     (*dmf)->ctx       = dm->ctx;
2375:     (*dmf)->leveldown = dm->leveldown;
2376:     (*dmf)->levelup   = dm->levelup + 1;

2378:     PetscCall(DMSetMatType(*dmf, dm->mattype));
2379:     for (link = dm->refinehook; link; link = link->next) {
2380:       if (link->refinehook) PetscCall((*link->refinehook)(dm, *dmf, link->ctx));
2381:     }
2382:   }
2383:   PetscCall(PetscLogEventEnd(DM_Refine, dm, 0, 0, 0));
2384:   PetscFunctionReturn(PETSC_SUCCESS);
2385: }

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

2390:   Logically Collective; No Fortran Support

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

2398:   Calling sequence of `refinehook`:
2399: + coarse - coarse level `DM`
2400: . fine   - fine level `DM` to interpolate problem to
2401: - ctx    - optional function context

2403:   Calling sequence of `interphook`:
2404: + coarse - coarse level `DM`
2405: . interp - matrix interpolating a coarse-level solution to the finer grid
2406: . fine   - fine level `DM` to update
2407: - ctx    - optional function context

2409:   Level: advanced

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

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

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

2419: .seealso: [](ch_dmbase), `DM`, `DMCoarsenHookAdd()`, `DMInterpolate()`, `SNESFASGetInterpolation()`, `SNESFASGetInjection()`, `PetscObjectCompose()`, `PetscContainerCreate()`
2420: @*/
2421: PetscErrorCode DMRefineHookAdd(DM coarse, PetscErrorCode (*refinehook)(DM coarse, DM fine, PetscCtx ctx), PetscErrorCode (*interphook)(DM coarse, Mat interp, DM fine, PetscCtx ctx), PetscCtx ctx)
2422: {
2423:   DMRefineHookLink link, *p;

2425:   PetscFunctionBegin;
2427:   for (p = &coarse->refinehook; *p; p = &(*p)->next) { /* Scan to the end of the current list of hooks */
2428:     if ((*p)->refinehook == refinehook && (*p)->interphook == interphook && (*p)->ctx == ctx) PetscFunctionReturn(PETSC_SUCCESS);
2429:   }
2430:   PetscCall(PetscNew(&link));
2431:   link->refinehook = refinehook;
2432:   link->interphook = interphook;
2433:   link->ctx        = ctx;
2434:   link->next       = NULL;
2435:   *p               = link;
2436:   PetscFunctionReturn(PETSC_SUCCESS);
2437: }

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

2443:   Logically Collective; No Fortran Support

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

2451:   Calling sequence of refinehook:
2452: + coarse - the coarse `DM`
2453: . fine   - the fine `DM`
2454: - ctx    - context for the function

2456:   Calling sequence of interphook:
2457: + coarse - the coarse `DM`
2458: . interp - the interpolation `Mat` from coarse to fine
2459: . fine   - the fine `DM`
2460: - ctx    - context for the function

2462:   Level: advanced

2464:   Note:
2465:   This function does nothing if the hook is not in the list.

2467: .seealso: [](ch_dmbase), `DM`, `DMRefineHookAdd()`, `DMCoarsenHookRemove()`, `DMInterpolate()`, `SNESFASGetInterpolation()`, `SNESFASGetInjection()`, `PetscObjectCompose()`, `PetscContainerCreate()`
2468: @*/
2469: PetscErrorCode DMRefineHookRemove(DM coarse, PetscErrorCode (*refinehook)(DM coarse, DM fine, PetscCtx ctx), PetscErrorCode (*interphook)(DM coarse, Mat interp, DM fine, PetscCtx ctx), PetscCtx ctx)
2470: {
2471:   DMRefineHookLink link, *p;

2473:   PetscFunctionBegin;
2475:   for (p = &coarse->refinehook; *p; p = &(*p)->next) { /* Search the list of current hooks */
2476:     if ((*p)->refinehook == refinehook && (*p)->interphook == interphook && (*p)->ctx == ctx) {
2477:       link = *p;
2478:       *p   = link->next;
2479:       PetscCall(PetscFree(link));
2480:       break;
2481:     }
2482:   }
2483:   PetscFunctionReturn(PETSC_SUCCESS);
2484: }

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

2489:   Collective if any hooks are

2491:   Input Parameters:
2492: + coarse - coarser `DM` to use as a base
2493: . interp - interpolation matrix, apply using `MatInterpolate()`
2494: - fine   - finer `DM` to update

2496:   Level: developer

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

2502: .seealso: [](ch_dmbase), `DM`, `DMRefineHookAdd()`, `MatInterpolate()`
2503: @*/
2504: PetscErrorCode DMInterpolate(DM coarse, Mat interp, DM fine)
2505: {
2506:   DMRefineHookLink link;

2508:   PetscFunctionBegin;
2509:   for (link = fine->refinehook; link; link = link->next) {
2510:     if (link->interphook) PetscCall((*link->interphook)(coarse, interp, fine, link->ctx));
2511:   }
2512:   PetscFunctionReturn(PETSC_SUCCESS);
2513: }

2515: /*@
2516:   DMInterpolateSolution - Interpolates a solution from a coarse mesh to a fine mesh.

2518:   Collective

2520:   Input Parameters:
2521: + coarse    - coarse `DM`
2522: . fine      - fine `DM`
2523: . interp    - (optional) the matrix computed by `DMCreateInterpolation()`.  Implementations may not need this, but if it
2524:             is available it can avoid some recomputation.  If it is provided, `MatInterpolate()` will be used if
2525:             the coarse `DM` does not have a specialized implementation.
2526: - coarseSol - solution on the coarse mesh

2528:   Output Parameter:
2529: . fineSol - the interpolation of coarseSol to the fine mesh

2531:   Level: developer

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

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

2542: .seealso: [](ch_dmbase), `DM`, `DMInterpolate()`, `DMCreateInterpolation()`
2543: @*/
2544: PetscErrorCode DMInterpolateSolution(DM coarse, DM fine, Mat interp, Vec coarseSol, Vec fineSol)
2545: {
2546:   PetscErrorCode (*interpsol)(DM, DM, Mat, Vec, Vec) = NULL;

2548:   PetscFunctionBegin;

2554:   PetscCall(PetscObjectQueryFunction((PetscObject)coarse, "DMInterpolateSolution_C", &interpsol));
2555:   if (interpsol) {
2556:     PetscCall((*interpsol)(coarse, fine, interp, coarseSol, fineSol));
2557:   } else if (interp) {
2558:     PetscCall(MatInterpolate(interp, coarseSol, fineSol));
2559:   } else SETERRQ(PetscObjectComm((PetscObject)coarse), PETSC_ERR_SUP, "DM %s does not implement DMInterpolateSolution()", ((PetscObject)coarse)->type_name);
2560:   PetscFunctionReturn(PETSC_SUCCESS);
2561: }

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

2566:   Not Collective

2568:   Input Parameter:
2569: . dm - the `DM` object

2571:   Output Parameter:
2572: . level - number of refinements

2574:   Level: developer

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

2579: .seealso: [](ch_dmbase), `DM`, `DMRefine()`, `DMCoarsen()`, `DMGetCoarsenLevel()`, `DMDestroy()`, `DMView()`, `DMCreateGlobalVector()`, `DMCreateInterpolation()`
2580: @*/
2581: PetscErrorCode DMGetRefineLevel(DM dm, PetscInt *level)
2582: {
2583:   PetscFunctionBegin;
2585:   *level = dm->levelup;
2586:   PetscFunctionReturn(PETSC_SUCCESS);
2587: }

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

2592:   Not Collective

2594:   Input Parameters:
2595: + dm    - the `DM` object
2596: - level - number of refinements

2598:   Level: advanced

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

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

2605: .seealso: [](ch_dmbase), `DM`, `DMGetRefineLevel()`, `DMCoarsen()`, `DMGetCoarsenLevel()`, `DMDestroy()`, `DMView()`, `DMCreateGlobalVector()`, `DMCreateInterpolation()`
2606: @*/
2607: PetscErrorCode DMSetRefineLevel(DM dm, PetscInt level)
2608: {
2609:   PetscFunctionBegin;
2611:   dm->levelup = level;
2612:   PetscFunctionReturn(PETSC_SUCCESS);
2613: }

2615: /*@
2616:   DMExtrude - Extrude a `DM` object from a surface

2618:   Collective

2620:   Input Parameters:
2621: + dm     - the `DM` object
2622: - layers - the number of extruded cell layers

2624:   Output Parameter:
2625: . dme - the extruded `DM`, or `NULL`

2627:   Level: developer

2629:   Note:
2630:   If no extrusion was done, the return value is `NULL`

2632: .seealso: [](ch_dmbase), `DM`, `DMRefine()`, `DMCoarsen()`, `DMDestroy()`, `DMView()`, `DMCreateGlobalVector()`
2633: @*/
2634: PetscErrorCode DMExtrude(DM dm, PetscInt layers, DM *dme)
2635: {
2636:   PetscFunctionBegin;
2638:   PetscUseTypeMethod(dm, extrude, layers, dme);
2639:   if (*dme) {
2640:     (*dme)->ops->creatematrix = dm->ops->creatematrix;
2641:     PetscCall(PetscObjectCopyFortranFunctionPointers((PetscObject)dm, (PetscObject)*dme));
2642:     (*dme)->ctx = dm->ctx;
2643:     PetscCall(DMSetMatType(*dme, dm->mattype));
2644:   }
2645:   PetscFunctionReturn(PETSC_SUCCESS);
2646: }

2648: PetscErrorCode DMGetBasisTransformDM_Internal(DM dm, DM *tdm)
2649: {
2650:   PetscFunctionBegin;
2652:   PetscAssertPointer(tdm, 2);
2653:   *tdm = dm->transformDM;
2654:   PetscFunctionReturn(PETSC_SUCCESS);
2655: }

2657: PetscErrorCode DMGetBasisTransformVec_Internal(DM dm, Vec *tv)
2658: {
2659:   PetscFunctionBegin;
2661:   PetscAssertPointer(tv, 2);
2662:   *tv = dm->transform;
2663:   PetscFunctionReturn(PETSC_SUCCESS);
2664: }

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

2669:   Input Parameter:
2670: . dm - The `DM`

2672:   Output Parameter:
2673: . flg - `PETSC_TRUE` if a basis transformation should be done

2675:   Level: developer

2677: .seealso: [](ch_dmbase), `DM`, `DMPlexGlobalToLocalBasis()`, `DMPlexLocalToGlobalBasis()`, `DMPlexCreateBasisRotation()`
2678: @*/
2679: PetscErrorCode DMHasBasisTransform(DM dm, PetscBool *flg)
2680: {
2681:   Vec tv;

2683:   PetscFunctionBegin;
2685:   PetscAssertPointer(flg, 2);
2686:   PetscCall(DMGetBasisTransformVec_Internal(dm, &tv));
2687:   *flg = tv ? PETSC_TRUE : PETSC_FALSE;
2688:   PetscFunctionReturn(PETSC_SUCCESS);
2689: }

2691: PetscErrorCode DMConstructBasisTransform_Internal(DM dm)
2692: {
2693:   PetscSection s, ts;
2694:   PetscScalar *ta;
2695:   PetscInt     cdim, pStart, pEnd, p, Nf, f, Nc, dof;

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

2728:         /* TODO Get quadrature point for this dual basis vector for coordinate */
2729:         PetscCall((*dm->transformGetMatrix)(dm, x, PETSC_TRUE, &A, dm->transformCtx));
2730:         PetscCall(DMPlexPointLocalFieldRef(dm->transformDM, p, f, ta, (void *)&tva));
2731:         PetscCall(PetscArraycpy(tva, A, PetscSqr(cdim)));
2732:       }
2733:     }
2734:   }
2735:   PetscCall(VecRestoreArray(dm->transform, &ta));
2736:   PetscFunctionReturn(PETSC_SUCCESS);
2737: }

2739: PetscErrorCode DMCopyTransform(DM dm, DM newdm)
2740: {
2741:   PetscFunctionBegin;
2744:   newdm->transformCtx       = dm->transformCtx;
2745:   newdm->transformSetUp     = dm->transformSetUp;
2746:   newdm->transformDestroy   = NULL;
2747:   newdm->transformGetMatrix = dm->transformGetMatrix;
2748:   if (newdm->transformSetUp) PetscCall(DMConstructBasisTransform_Internal(newdm));
2749:   PetscFunctionReturn(PETSC_SUCCESS);
2750: }

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

2755:   Logically Collective

2757:   Input Parameters:
2758: + dm        - the `DM`
2759: . beginhook - function to run at the beginning of `DMGlobalToLocalBegin()`
2760: . endhook   - function to run after `DMGlobalToLocalEnd()` has completed
2761: - ctx       - [optional] context for provide data for the hooks (may be `NULL`)

2763:   Calling sequence of `beginhook`:
2764: + dm   - global `DM`
2765: . g    - global vector
2766: . mode - mode
2767: . l    - local vector
2768: - ctx  - optional function context

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

2777:   Level: advanced

2779:   Note:
2780:   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.

2782: .seealso: [](ch_dmbase), `DM`, `DMGlobalToLocal()`, `DMRefineHookAdd()`, `SNESFASGetInterpolation()`, `SNESFASGetInjection()`, `PetscObjectCompose()`, `PetscContainerCreate()`
2783: @*/
2784: 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)
2785: {
2786:   DMGlobalToLocalHookLink link, *p;

2788:   PetscFunctionBegin;
2790:   for (p = &dm->gtolhook; *p; p = &(*p)->next) { } /* Scan to the end of the current list of hooks */
2791:   PetscCall(PetscNew(&link));
2792:   link->beginhook = beginhook;
2793:   link->endhook   = endhook;
2794:   link->ctx       = ctx;
2795:   link->next      = NULL;
2796:   *p              = link;
2797:   PetscFunctionReturn(PETSC_SUCCESS);
2798: }

2800: static PetscErrorCode DMGlobalToLocalHook_Constraints(DM dm, Vec g, InsertMode mode, Vec l, PetscCtx ctx)
2801: {
2802:   Mat          cMat;
2803:   Vec          cVec, cBias;
2804:   PetscSection section, cSec;
2805:   PetscInt     pStart, pEnd, p, dof;

2807:   PetscFunctionBegin;
2808:   (void)g;
2809:   (void)ctx;
2811:   PetscCall(DMGetDefaultConstraints(dm, &cSec, &cMat, &cBias));
2812:   if (cMat && (mode == INSERT_VALUES || mode == INSERT_ALL_VALUES || mode == INSERT_BC_VALUES)) {
2813:     PetscInt nRows;

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

2835: /*@
2836:   DMGlobalToLocal - update local vectors from global vector

2838:   Neighbor-wise Collective

2840:   Input Parameters:
2841: + dm   - the `DM` object
2842: . g    - the global vector
2843: . mode - `INSERT_VALUES` or `ADD_VALUES`
2844: - l    - the local vector

2846:   Level: beginner

2848:   Notes:
2849:   The communication involved in this update can be overlapped with computation by instead using
2850:   `DMGlobalToLocalBegin()` and `DMGlobalToLocalEnd()`.

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

2854: .seealso: [](ch_dmbase), `DM`, `DMGlobalToLocalHookAdd()`, `DMCoarsen()`, `DMDestroy()`, `DMView()`, `DMCreateGlobalVector()`, `DMCreateInterpolation()`,
2855:           `DMLocalToGlobalBegin()`, `DMLocalToGlobal()`, `DMLocalToGlobalEnd()`,
2856:           `DMGlobalToLocalBegin()`, `DMGlobalToLocalEnd()`
2857: @*/
2858: PetscErrorCode DMGlobalToLocal(DM dm, Vec g, InsertMode mode, Vec l)
2859: {
2860:   PetscFunctionBegin;
2861:   PetscCall(DMGlobalToLocalBegin(dm, g, mode, l));
2862:   PetscCall(DMGlobalToLocalEnd(dm, g, mode, l));
2863:   PetscFunctionReturn(PETSC_SUCCESS);
2864: }

2866: /*@
2867:   DMGlobalToLocalBegin - Begins updating local vectors from global vector

2869:   Neighbor-wise Collective

2871:   Input Parameters:
2872: + dm   - the `DM` object
2873: . g    - the global vector
2874: . mode - `INSERT_VALUES` or `ADD_VALUES`
2875: - l    - the local vector

2877:   Level: intermediate

2879:   Notes:
2880:   The operation is completed with `DMGlobalToLocalEnd()`

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

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

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

2888: .seealso: [](ch_dmbase), `DM`, `DMCoarsen()`, `DMDestroy()`, `DMView()`, `DMCreateGlobalVector()`, `DMCreateInterpolation()`, `DMGlobalToLocal()`, `DMGlobalToLocalEnd()`, `DMLocalToGlobalBegin()`, `DMLocalToGlobal()`, `DMLocalToGlobalEnd()`
2889: @*/
2890: PetscErrorCode DMGlobalToLocalBegin(DM dm, Vec g, InsertMode mode, Vec l)
2891: {
2892:   PetscSF                 sf;
2893:   DMGlobalToLocalHookLink link;

2895:   PetscFunctionBegin;
2897:   for (link = dm->gtolhook; link; link = link->next) {
2898:     if (link->beginhook) PetscCall((*link->beginhook)(dm, g, mode, l, link->ctx));
2899:   }
2900:   PetscCall(DMGetSectionSF(dm, &sf));
2901:   if (sf) {
2902:     const PetscScalar *gArray;
2903:     PetscScalar       *lArray;
2904:     PetscMemType       lmtype, gmtype;

2906:     PetscCheck(mode != ADD_VALUES, PetscObjectComm((PetscObject)dm), PETSC_ERR_ARG_OUTOFRANGE, "Invalid insertion mode %d", (int)mode);
2907:     PetscCall(VecGetArrayAndMemType(l, &lArray, &lmtype));
2908:     PetscCall(VecGetArrayReadAndMemType(g, &gArray, &gmtype));
2909:     PetscCall(PetscSFBcastWithMemTypeBegin(sf, MPIU_SCALAR, gmtype, gArray, lmtype, lArray, MPI_REPLACE));
2910:     PetscCall(VecRestoreArrayAndMemType(l, &lArray));
2911:     PetscCall(VecRestoreArrayReadAndMemType(g, &gArray));
2912:   } else {
2913:     PetscUseTypeMethod(dm, globaltolocalbegin, g, mode == INSERT_ALL_VALUES ? INSERT_VALUES : (mode == ADD_ALL_VALUES ? ADD_VALUES : mode), l);
2914:   }
2915:   PetscFunctionReturn(PETSC_SUCCESS);
2916: }

2918: /*@
2919:   DMGlobalToLocalEnd - Ends updating local vectors from global vector

2921:   Neighbor-wise Collective

2923:   Input Parameters:
2924: + dm   - the `DM` object
2925: . g    - the global vector
2926: . mode - `INSERT_VALUES` or `ADD_VALUES`
2927: - l    - the local vector

2929:   Level: intermediate

2931:   Note:
2932:   See `DMGlobalToLocalBegin()` for details.

2934: .seealso: [](ch_dmbase), `DM`, `DMCoarsen()`, `DMDestroy()`, `DMView()`, `DMCreateGlobalVector()`, `DMCreateInterpolation()`, `DMGlobalToLocal()`, `DMLocalToGlobalBegin()`, `DMLocalToGlobal()`, `DMLocalToGlobalEnd()`
2935: @*/
2936: PetscErrorCode DMGlobalToLocalEnd(DM dm, Vec g, InsertMode mode, Vec l)
2937: {
2938:   PetscSF                 sf;
2939:   const PetscScalar      *gArray;
2940:   PetscScalar            *lArray;
2941:   PetscBool               transform;
2942:   DMGlobalToLocalHookLink link;
2943:   PetscMemType            lmtype, gmtype;

2945:   PetscFunctionBegin;
2947:   PetscCall(DMGetSectionSF(dm, &sf));
2948:   PetscCall(DMHasBasisTransform(dm, &transform));
2949:   if (sf) {
2950:     PetscCheck(mode != ADD_VALUES, PetscObjectComm((PetscObject)dm), PETSC_ERR_ARG_OUTOFRANGE, "Invalid insertion mode %d", (int)mode);

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

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

2971:   Logically Collective

2973:   Input Parameters:
2974: + dm        - the `DM`
2975: . beginhook - function to run at the beginning of `DMLocalToGlobalBegin()`
2976: . endhook   - function to run after `DMLocalToGlobalEnd()` has completed
2977: - ctx       - [optional] context for provide data for the hooks (may be `NULL`)

2979:   Calling sequence of `beginhook`:
2980: + global - global `DM`
2981: . l      - local vector
2982: . mode   - mode
2983: . g      - global vector
2984: - ctx    - optional function context

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

2993:   Level: advanced

2995: .seealso: [](ch_dmbase), `DM`, `DMLocalToGlobal()`, `DMRefineHookAdd()`, `DMGlobalToLocalHookAdd()`, `SNESFASGetInterpolation()`, `SNESFASGetInjection()`, `PetscObjectCompose()`, `PetscContainerCreate()`
2996: @*/
2997: 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)
2998: {
2999:   DMLocalToGlobalHookLink link, *p;

3001:   PetscFunctionBegin;
3003:   for (p = &dm->ltoghook; *p; p = &(*p)->next) { } /* Scan to the end of the current list of hooks */
3004:   PetscCall(PetscNew(&link));
3005:   link->beginhook = beginhook;
3006:   link->endhook   = endhook;
3007:   link->ctx       = ctx;
3008:   link->next      = NULL;
3009:   *p              = link;
3010:   PetscFunctionReturn(PETSC_SUCCESS);
3011: }

3013: static PetscErrorCode DMLocalToGlobalHook_Constraints(DM dm, Vec l, InsertMode mode, Vec g, PetscCtx ctx)
3014: {
3015:   PetscFunctionBegin;
3016:   (void)g;
3017:   (void)ctx;
3019:   if (mode == ADD_VALUES || mode == ADD_ALL_VALUES || mode == ADD_BC_VALUES) {
3020:     Mat          cMat;
3021:     Vec          cVec;
3022:     PetscInt     nRows;
3023:     PetscSection section, cSec;
3024:     PetscInt     pStart, pEnd, p, dof;

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

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

3054:   Neighbor-wise Collective

3056:   Input Parameters:
3057: + dm   - the `DM` object
3058: . l    - the local vector
3059: . 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.
3060: - g    - the global vector

3062:   Level: beginner

3064:   Notes:
3065:   The communication involved in this update can be overlapped with computation by using
3066:   `DMLocalToGlobalBegin()` and `DMLocalToGlobalEnd()`.

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

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

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

3074: .seealso: [](ch_dmbase), `DM`, `DMLocalToGlobalBegin()`, `DMLocalToGlobalEnd()`, `DMCoarsen()`, `DMDestroy()`, `DMView()`, `DMCreateGlobalVector()`, `DMCreateInterpolation()`, `DMGlobalToLocal()`, `DMGlobalToLocalEnd()`, `DMGlobalToLocalBegin()`, `DMLocalToGlobalHookAdd()`, `DMGlobaToLocallHookAdd()`
3075: @*/
3076: PetscErrorCode DMLocalToGlobal(DM dm, Vec l, InsertMode mode, Vec g)
3077: {
3078:   PetscFunctionBegin;
3079:   PetscCall(DMLocalToGlobalBegin(dm, l, mode, g));
3080:   PetscCall(DMLocalToGlobalEnd(dm, l, mode, g));
3081:   PetscFunctionReturn(PETSC_SUCCESS);
3082: }

3084: /*@
3085:   DMLocalToGlobalBegin - begins updating global vectors from local vectors

3087:   Neighbor-wise Collective

3089:   Input Parameters:
3090: + dm   - the `DM` object
3091: . l    - the local vector
3092: . 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.
3093: - g    - the global vector

3095:   Level: intermediate

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

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

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

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

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

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

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

3167:       PetscCall(DMGetGlobalSection(dm, &gs));
3168:       PetscCall(PetscSectionGetChart(s, &pStart, &pEnd));
3169:       PetscCall(VecGetOwnershipRange(g, &gStart, NULL));
3170:       for (p = pStart; p < pEnd; ++p) {
3171:         PetscInt dof, gdof, cdof, gcdof, off, goff, d, e;

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

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

3220: /*@
3221:   DMLocalToGlobalEnd - updates global vectors from local vectors

3223:   Neighbor-wise Collective

3225:   Input Parameters:
3226: + dm   - the `DM` object
3227: . l    - the local vector
3228: . mode - `INSERT_VALUES` or `ADD_VALUES`
3229: - g    - the global vector

3231:   Level: intermediate

3233:   Note:
3234:   See `DMLocalToGlobalBegin()` for full details

3236: .seealso: [](ch_dmbase), `DM`, `DMLocalToGlobalBegin()`, `DMCoarsen()`, `DMDestroy()`, `DMView()`, `DMCreateGlobalVector()`, `DMCreateInterpolation()`, `DMGlobalToLocalEnd()`
3237: @*/
3238: PetscErrorCode DMLocalToGlobalEnd(DM dm, Vec l, InsertMode mode, Vec g)
3239: {
3240:   PetscSF                 sf;
3241:   PetscSection            s;
3242:   DMLocalToGlobalHookLink link;
3243:   PetscBool               isInsert, transform;

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

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

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

3297:   Neighbor-wise Collective

3299:   Input Parameters:
3300: + dm   - the `DM` object
3301: . g    - the original local vector
3302: - mode - one of `INSERT_VALUES` or `ADD_VALUES`

3304:   Output Parameter:
3305: . l - the local vector with correct ghost values

3307:   Level: intermediate

3309:   Note:
3310:   Must be followed by `DMLocalToLocalEnd()`.

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

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

3328:   Neighbor-wise Collective

3330:   Input Parameters:
3331: + dm   - the `DM` object
3332: . g    - the original local vector
3333: - mode - one of `INSERT_VALUES` or `ADD_VALUES`

3335:   Output Parameter:
3336: . l - the local vector with correct ghost values

3338:   Level: intermediate

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

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

3355:   Collective

3357:   Input Parameters:
3358: + dm   - the `DM` object
3359: - comm - the communicator to contain the new `DM` object (or `MPI_COMM_NULL`)

3361:   Output Parameter:
3362: . dmc - the coarsened `DM`

3364:   Level: developer

3366: .seealso: [](ch_dmbase), `DM`, `DMRefine()`, `DMDestroy()`, `DMView()`, `DMCreateGlobalVector()`, `DMCreateInterpolation()`, `DMCreateDomainDecomposition()`,
3367:           `DMCoarsenHookAdd()`, `DMCoarsenHookRemove()`
3368: @*/
3369: PetscErrorCode DMCoarsen(DM dm, MPI_Comm comm, DM *dmc)
3370: {
3371:   DMCoarsenHookLink link;

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

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

3398:   Logically Collective; No Fortran Support

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

3406:   Calling sequence of `coarsenhook`:
3407: + fine   - fine level `DM`
3408: . coarse - coarse level `DM` to restrict problem to
3409: - ctx    - optional application function context

3411:   Calling sequence of `restricthook`:
3412: + fine      - fine level `DM`
3413: . mrestrict - matrix restricting a fine-level solution to the coarse grid, usually the transpose of the interpolation
3414: . rscale    - scaling vector for restriction
3415: . inject    - matrix restricting by injection
3416: . coarse    - coarse level DM to update
3417: - ctx       - optional application function context

3419:   Level: advanced

3421:   Notes:
3422:   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`.

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

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

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

3431: .seealso: [](ch_dmbase), `DM`, `DMCoarsenHookRemove()`, `DMRefineHookAdd()`, `SNESFASGetInterpolation()`, `SNESFASGetInjection()`, `PetscObjectCompose()`, `PetscContainerCreate()`
3432: @*/
3433: 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)
3434: {
3435:   DMCoarsenHookLink link, *p;

3437:   PetscFunctionBegin;
3439:   for (p = &fine->coarsenhook; *p; p = &(*p)->next) { /* Scan to the end of the current list of hooks */
3440:     if ((*p)->coarsenhook == coarsenhook && (*p)->restricthook == restricthook && (*p)->ctx == ctx) PetscFunctionReturn(PETSC_SUCCESS);
3441:   }
3442:   PetscCall(PetscNew(&link));
3443:   link->coarsenhook  = coarsenhook;
3444:   link->restricthook = restricthook;
3445:   link->ctx          = ctx;
3446:   link->next         = NULL;
3447:   *p                 = link;
3448:   PetscFunctionReturn(PETSC_SUCCESS);
3449: }

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

3454:   Logically Collective; No Fortran Support

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

3462:   Calling sequence of `coarsenhook`:
3463: + fine   - fine level `DM`
3464: . coarse - coarse level `DM` to restrict problem to
3465: - ctx    - optional application function context

3467:   Calling sequence of `restricthook`:
3468: + fine    - fine level `DM`
3469: . rstrict - matrix restricting a fine-level solution to the coarse grid, usually the transpose of the interpolation
3470: . rscale  - scaling vector for restriction
3471: . inject  - matrix restricting by injection
3472: . coarse  - coarse level DM to update
3473: - ctx     - optional application function context

3475:   Level: advanced

3477:   Notes:
3478:   This function does nothing if the `coarsenhook` is not in the list.

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

3482: .seealso: [](ch_dmbase), `DM`, `DMCoarsenHookAdd()`, `DMRefineHookAdd()`, `SNESFASGetInterpolation()`, `SNESFASGetInjection()`, `PetscObjectCompose()`, `PetscContainerCreate()`
3483: @*/
3484: 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)
3485: {
3486:   DMCoarsenHookLink link, *p;

3488:   PetscFunctionBegin;
3490:   for (p = &fine->coarsenhook; *p; p = &(*p)->next) { /* Search the list of current hooks */
3491:     if ((*p)->coarsenhook == coarsenhook && (*p)->restricthook == restricthook && (*p)->ctx == ctx) {
3492:       link = *p;
3493:       *p   = link->next;
3494:       PetscCall(PetscFree(link));
3495:       break;
3496:     }
3497:   }
3498:   PetscFunctionReturn(PETSC_SUCCESS);
3499: }

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

3504:   Collective if any hooks are

3506:   Input Parameters:
3507: + fine    - finer `DM` from which the data is obtained
3508: . restrct - restriction matrix, apply using `MatRestrict()`, usually the transpose of the interpolation
3509: . rscale  - scaling vector for restriction
3510: . inject  - injection matrix, also use `MatRestrict()`
3511: - coarse  - coarser `DM` to update

3513:   Level: developer

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

3518: .seealso: [](ch_dmbase), `DM`, `DMCoarsenHookAdd()`, `MatRestrict()`, `DMInterpolate()`, `DMRefineHookAdd()`
3519: @*/
3520: PetscErrorCode DMRestrict(DM fine, Mat restrct, Vec rscale, Mat inject, DM coarse)
3521: {
3522:   DMCoarsenHookLink link;

3524:   PetscFunctionBegin;
3525:   for (link = fine->coarsenhook; link; link = link->next) {
3526:     if (link->restricthook) PetscCall((*link->restricthook)(fine, restrct, rscale, inject, coarse, link->ctx));
3527:   }
3528:   PetscFunctionReturn(PETSC_SUCCESS);
3529: }

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

3534:   Logically Collective; No Fortran Support

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

3542:   Calling sequence of `ddhook`:
3543: + global - global `DM`
3544: . block  - subdomain `DM`
3545: - ctx    - optional application function context

3547:   Calling sequence of `restricthook`:
3548: + global - global `DM`
3549: . out    - scatter to the outer (with ghost and overlap points) sub vector
3550: . in     - scatter to sub vector values only owned locally
3551: . block  - subdomain `DM`
3552: - ctx    - optional application function context

3554:   Level: advanced

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

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

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

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

3567: .seealso: [](ch_dmbase), `DM`, `DMSubDomainHookRemove()`, `DMRefineHookAdd()`, `SNESFASGetInterpolation()`, `SNESFASGetInjection()`, `PetscObjectCompose()`, `PetscContainerCreate()`, `DMCreateDomainDecomposition()`
3568: @*/
3569: 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)
3570: {
3571:   DMSubDomainHookLink link, *p;

3573:   PetscFunctionBegin;
3575:   for (p = &global->subdomainhook; *p; p = &(*p)->next) { /* Scan to the end of the current list of hooks */
3576:     if ((*p)->ddhook == ddhook && (*p)->restricthook == restricthook && (*p)->ctx == ctx) PetscFunctionReturn(PETSC_SUCCESS);
3577:   }
3578:   PetscCall(PetscNew(&link));
3579:   link->restricthook = restricthook;
3580:   link->ddhook       = ddhook;
3581:   link->ctx          = ctx;
3582:   link->next         = NULL;
3583:   *p                 = link;
3584:   PetscFunctionReturn(PETSC_SUCCESS);
3585: }

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

3590:   Logically Collective; No Fortran Support

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

3598:   Calling sequence of `ddhook`:
3599: + dm    - global `DM`
3600: . block - subdomain `DM`
3601: - ctx   - optional application function context

3603:   Calling sequence of `restricthook`:
3604: + dm       - global `DM`
3605: . oscatter - scatter to the outer (with ghost and overlap points) sub vector
3606: . gscatter - scatter to sub vector values only owned locally
3607: . block    - subdomain `DM`
3608: - ctx      - optional application function context

3610:   Level: advanced

3612: .seealso: [](ch_dmbase), `DM`, `DMSubDomainHookAdd()`, `SNESFASGetInterpolation()`, `SNESFASGetInjection()`, `PetscObjectCompose()`, `PetscContainerCreate()`,
3613:           `DMCreateDomainDecomposition()`
3614: @*/
3615: 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)
3616: {
3617:   DMSubDomainHookLink link, *p;

3619:   PetscFunctionBegin;
3621:   for (p = &global->subdomainhook; *p; p = &(*p)->next) { /* Search the list of current hooks */
3622:     if ((*p)->ddhook == ddhook && (*p)->restricthook == restricthook && (*p)->ctx == ctx) {
3623:       link = *p;
3624:       *p   = link->next;
3625:       PetscCall(PetscFree(link));
3626:       break;
3627:     }
3628:   }
3629:   PetscFunctionReturn(PETSC_SUCCESS);
3630: }

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

3635:   Collective if any hooks are

3637:   Input Parameters:
3638: + global   - The global `DM` to use as a base
3639: . oscatter - The scatter from domain global vector filling subdomain global vector with overlap
3640: . gscatter - The scatter from domain global vector filling subdomain local vector with ghosts
3641: - subdm    - The subdomain `DM` to update

3643:   Level: developer

3645: .seealso: [](ch_dmbase), `DM`, `DMCoarsenHookAdd()`, `MatRestrict()`, `DMCreateDomainDecomposition()`
3646: @*/
3647: PetscErrorCode DMSubDomainRestrict(DM global, VecScatter oscatter, VecScatter gscatter, DM subdm)
3648: {
3649:   DMSubDomainHookLink link;

3651:   PetscFunctionBegin;
3652:   for (link = global->subdomainhook; link; link = link->next) {
3653:     if (link->restricthook) PetscCall((*link->restricthook)(global, oscatter, gscatter, subdm, link->ctx));
3654:   }
3655:   PetscFunctionReturn(PETSC_SUCCESS);
3656: }

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

3661:   Not Collective

3663:   Input Parameter:
3664: . dm - the `DM` object

3666:   Output Parameter:
3667: . level - number of coarsenings

3669:   Level: developer

3671: .seealso: [](ch_dmbase), `DM`, `DMCoarsen()`, `DMSetCoarsenLevel()`, `DMGetRefineLevel()`, `DMDestroy()`, `DMView()`, `DMCreateGlobalVector()`, `DMCreateInterpolation()`
3672: @*/
3673: PetscErrorCode DMGetCoarsenLevel(DM dm, PetscInt *level)
3674: {
3675:   PetscFunctionBegin;
3677:   PetscAssertPointer(level, 2);
3678:   *level = dm->leveldown;
3679:   PetscFunctionReturn(PETSC_SUCCESS);
3680: }

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

3685:   Collective

3687:   Input Parameters:
3688: + dm    - the `DM` object
3689: - level - number of coarsenings

3691:   Level: developer

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

3696: .seealso: [](ch_dmbase), `DM`, `DMCoarsen()`, `DMGetCoarsenLevel()`, `DMGetRefineLevel()`, `DMDestroy()`, `DMView()`, `DMCreateGlobalVector()`, `DMCreateInterpolation()`
3697: @*/
3698: PetscErrorCode DMSetCoarsenLevel(DM dm, PetscInt level)
3699: {
3700:   PetscFunctionBegin;
3702:   dm->leveldown = level;
3703:   PetscFunctionReturn(PETSC_SUCCESS);
3704: }

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

3709:   Collective

3711:   Input Parameters:
3712: + dm      - the `DM` object
3713: - nlevels - the number of levels of refinement

3715:   Output Parameter:
3716: . dmf - the refined `DM` hierarchy

3718:   Level: developer

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

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

3739:   Collective

3741:   Input Parameters:
3742: + dm      - the `DM` object
3743: - nlevels - the number of levels of coarsening

3745:   Output Parameter:
3746: . dmc - the coarsened `DM` hierarchy

3748:   Level: developer

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

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

3769:   Logically Collective if the function is collective

3771:   Input Parameters:
3772: + dm      - the `DM` object
3773: - destroy - the destroy function, see `PetscCtxDestroyFn` for the calling sequence

3775:   Level: intermediate

3777: .seealso: [](ch_dmbase), `DM`, `DMSetApplicationContext()`, `DMView()`, `DMCreateGlobalVector()`, `DMCreateInterpolation()`, `DMCreateColoring()`, `DMCreateMatrix()`, `DMCreateMassMatrix()`,
3778:           `DMGetApplicationContext()`, `PetscCtxDestroyFn`
3779: @*/
3780: PetscErrorCode DMSetApplicationContextDestroy(DM dm, PetscCtxDestroyFn *destroy)
3781: {
3782:   PetscFunctionBegin;
3784:   dm->ctxdestroy = destroy;
3785:   PetscFunctionReturn(PETSC_SUCCESS);
3786: }

3788: /*@
3789:   DMSetApplicationContext - Set a user context into a `DM` object

3791:   Not Collective

3793:   Input Parameters:
3794: + dm  - the `DM` object
3795: - ctx - the user context

3797:   Level: intermediate

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

3804:   Fortran Notes:
3805:   This only works when the context is a Fortran derived type or a `PetscObject`. Declare `ctx` with
3806: .vb
3807:   type(tUsertype), pointer :: ctx
3808: .ve

3810: .seealso: [](ch_dmbase), `DM`, `DMGetApplicationContext()`, `DMView()`, `DMCreateGlobalVector()`, `DMCreateInterpolation()`, `DMCreateColoring()`, `DMCreateMatrix()`, `DMCreateMassMatrix()`
3811: @*/
3812: PetscErrorCode DMSetApplicationContext(DM dm, PetscCtx ctx)
3813: {
3814:   PetscFunctionBegin;
3816:   dm->ctx = ctx;
3817:   PetscFunctionReturn(PETSC_SUCCESS);
3818: }

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

3823:   Not Collective

3825:   Input Parameter:
3826: . dm - the `DM` object

3828:   Output Parameter:
3829: . ctx - a pointer to the user context

3831:   Level: intermediate

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

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

3851:   The prototype for `ctx` must be
3852: .vb
3853:   type(tUsertype), pointer :: ctx
3854: .ve

3856: .seealso: [](ch_dmbase), `DM`, `DMView()`, `DMCreateGlobalVector()`, `DMCreateInterpolation()`, `DMCreateColoring()`, `DMCreateMatrix()`, `DMCreateMassMatrix()`
3857: @*/
3858: PetscErrorCode DMGetApplicationContext(DM dm, PetscCtxRt ctx)
3859: {
3860:   PetscFunctionBegin;
3862:   *(void **)ctx = dm->ctx;
3863:   PetscFunctionReturn(PETSC_SUCCESS);
3864: }

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

3869:   Logically Collective

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

3875:   Calling sequence of f:
3876: + dm    - the `DM`
3877: . lower - the vector to hold the lower bounds
3878: - upper - the vector to hold the upper bounds

3880:   Level: intermediate

3882:   Developer Note:
3883:   Should be called `DMSetComputeVIBounds()` or something similar

3885: .seealso: [](ch_dmbase), `DM`, `DMComputeVariableBounds()`, `DMHasVariableBounds()`, `DMView()`, `DMCreateGlobalVector()`, `DMCreateInterpolation()`, `DMCreateColoring()`, `DMCreateMatrix()`, `DMCreateMassMatrix()`, `DMGetApplicationContext()`,
3886:          `DMSetJacobian()`
3887: @*/
3888: PetscErrorCode DMSetVariableBounds(DM dm, PetscErrorCode (*f)(DM dm, Vec lower, Vec upper))
3889: {
3890:   PetscFunctionBegin;
3892:   dm->ops->computevariablebounds = f;
3893:   PetscFunctionReturn(PETSC_SUCCESS);
3894: }

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

3899:   Not Collective

3901:   Input Parameter:
3902: . dm - the `DM` object to destroy

3904:   Output Parameter:
3905: . flg - `PETSC_TRUE` if the variable bounds function exists

3907:   Level: developer

3909: .seealso: [](ch_dmbase), `DM`, `DMComputeVariableBounds()`, `DMView()`, `DMCreateGlobalVector()`, `DMCreateInterpolation()`, `DMCreateColoring()`, `DMCreateMatrix()`, `DMCreateMassMatrix()`, `DMGetApplicationContext()`
3910: @*/
3911: PetscErrorCode DMHasVariableBounds(DM dm, PetscBool *flg)
3912: {
3913:   PetscFunctionBegin;
3915:   PetscAssertPointer(flg, 2);
3916:   *flg = (dm->ops->computevariablebounds) ? PETSC_TRUE : PETSC_FALSE;
3917:   PetscFunctionReturn(PETSC_SUCCESS);
3918: }

3920: /*@
3921:   DMComputeVariableBounds - compute variable bounds used by `SNESVI`.

3923:   Logically Collective

3925:   Input Parameter:
3926: . dm - the `DM` object

3928:   Output Parameters:
3929: + xl - lower bound
3930: - xu - upper bound

3932:   Level: advanced

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

3937: .seealso: [](ch_dmbase), `DM`, `DMHasVariableBounds()`, `DMView()`, `DMCreateGlobalVector()`, `DMCreateInterpolation()`, `DMCreateColoring()`, `DMCreateMatrix()`, `DMCreateMassMatrix()`, `DMGetApplicationContext()`
3938: @*/
3939: PetscErrorCode DMComputeVariableBounds(DM dm, Vec xl, Vec xu)
3940: {
3941:   PetscFunctionBegin;
3945:   PetscUseTypeMethod(dm, computevariablebounds, xl, xu);
3946:   PetscFunctionReturn(PETSC_SUCCESS);
3947: }

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

3952:   Not Collective

3954:   Input Parameter:
3955: . dm - the DM object

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

3960:   Level: developer

3962: .seealso: [](ch_dmbase), `DM`, `DMCreateColoring()`
3963: @*/
3964: PetscErrorCode DMHasColoring(DM dm, PetscBool *flg)
3965: {
3966:   PetscFunctionBegin;
3968:   PetscAssertPointer(flg, 2);
3969:   *flg = (dm->ops->getcoloring) ? PETSC_TRUE : PETSC_FALSE;
3970:   PetscFunctionReturn(PETSC_SUCCESS);
3971: }

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

3976:   Not Collective

3978:   Input Parameter:
3979: . dm - the `DM` object

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

3984:   Level: developer

3986: .seealso: [](ch_dmbase), `DM`, `DMCreateRestriction()`, `DMHasCreateInterpolation()`, `DMHasCreateInjection()`
3987: @*/
3988: PetscErrorCode DMHasCreateRestriction(DM dm, PetscBool *flg)
3989: {
3990:   PetscFunctionBegin;
3992:   PetscAssertPointer(flg, 2);
3993:   *flg = (dm->ops->createrestriction) ? PETSC_TRUE : PETSC_FALSE;
3994:   PetscFunctionReturn(PETSC_SUCCESS);
3995: }

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

4000:   Not Collective

4002:   Input Parameter:
4003: . dm - the `DM` object

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

4008:   Level: developer

4010: .seealso: [](ch_dmbase), `DM`, `DMCreateInjection()`, `DMHasCreateRestriction()`, `DMHasCreateInterpolation()`
4011: @*/
4012: PetscErrorCode DMHasCreateInjection(DM dm, PetscBool *flg)
4013: {
4014:   PetscFunctionBegin;
4016:   PetscAssertPointer(flg, 2);
4017:   if (dm->ops->hascreateinjection) PetscUseTypeMethod(dm, hascreateinjection, flg);
4018:   else *flg = (dm->ops->createinjection) ? PETSC_TRUE : PETSC_FALSE;
4019:   PetscFunctionReturn(PETSC_SUCCESS);
4020: }

4022: PetscFunctionList DMList              = NULL;
4023: PetscBool         DMRegisterAllCalled = PETSC_FALSE;

4025: /*@
4026:   DMSetType - Builds a `DM`, for a particular `DM` implementation.

4028:   Collective

4030:   Input Parameters:
4031: + dm     - The `DM` object
4032: - method - The name of the `DMType`, for example `DMDA`, `DMPLEX`

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

4037:   Level: intermediate

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

4042: .seealso: [](ch_dmbase), `DM`, `DMType`, `DMDA`, `DMPLEX`, `DMGetType()`, `DMCreate()`, `DMDACreate2d()`
4043: @*/
4044: PetscErrorCode DMSetType(DM dm, DMType method)
4045: {
4046:   PetscErrorCode (*r)(DM);
4047:   PetscBool match;

4049:   PetscFunctionBegin;
4051:   PetscCall(PetscObjectTypeCompare((PetscObject)dm, method, &match));
4052:   if (match) PetscFunctionReturn(PETSC_SUCCESS);

4054:   PetscCall(DMRegisterAll());
4055:   PetscCall(PetscFunctionListFind(DMList, method, &r));
4056:   PetscCheck(r, PetscObjectComm((PetscObject)dm), PETSC_ERR_ARG_UNKNOWN_TYPE, "Unknown DM type: %s", method);

4058:   PetscTryTypeMethod(dm, destroy);
4059:   PetscCall(PetscMemzero(dm->ops, sizeof(*dm->ops)));
4060:   PetscCall(PetscObjectChangeTypeName((PetscObject)dm, method));
4061:   PetscCall((*r)(dm));
4062:   PetscFunctionReturn(PETSC_SUCCESS);
4063: }

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

4068:   Not Collective

4070:   Input Parameter:
4071: . dm - The `DM`

4073:   Output Parameter:
4074: . type - The `DMType` name

4076:   Level: intermediate

4078: .seealso: [](ch_dmbase), `DM`, `DMType`, `DMDA`, `DMPLEX`, `DMSetType()`, `DMCreate()`
4079: @*/
4080: PetscErrorCode DMGetType(DM dm, DMType *type)
4081: {
4082:   PetscFunctionBegin;
4084:   PetscAssertPointer(type, 2);
4085:   PetscCall(DMRegisterAll());
4086:   *type = ((PetscObject)dm)->type_name;
4087:   PetscFunctionReturn(PETSC_SUCCESS);
4088: }

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

4093:   Collective

4095:   Input Parameters:
4096: + dm      - the `DM`
4097: - newtype - new `DM` type (use "same" for the same type)

4099:   Output Parameter:
4100: . M - pointer to new `DM`

4102:   Level: intermediate

4104:   Note:
4105:   Cannot be used to convert a sequential `DM` to a parallel or a parallel to sequential,
4106:   the MPI communicator of the generated `DM` is always the same as the communicator
4107:   of the input `DM`.

4109: .seealso: [](ch_dmbase), `DM`, `DMSetType()`, `DMCreate()`, `DMClone()`
4110: @*/
4111: PetscErrorCode DMConvert(DM dm, DMType newtype, DM *M)
4112: {
4113:   DM        B;
4114:   char      convname[256];
4115:   PetscBool sametype /*, issame */;

4117:   PetscFunctionBegin;
4120:   PetscAssertPointer(M, 3);
4121:   PetscCall(PetscObjectTypeCompare((PetscObject)dm, newtype, &sametype));
4122:   /* PetscCall(PetscStrcmp(newtype, "same", &issame)); */
4123:   if (sametype) {
4124:     *M = dm;
4125:     PetscCall(PetscObjectReference((PetscObject)dm));
4126:     PetscFunctionReturn(PETSC_SUCCESS);
4127:   } else {
4128:     PetscErrorCode (*conv)(DM, DMType, DM *) = NULL;

4130:     /*
4131:        Order of precedence:
4132:        1) See if a specialized converter is known to the current DM.
4133:        2) See if a specialized converter is known to the desired DM class.
4134:        3) See if a good general converter is registered for the desired class
4135:        4) See if a good general converter is known for the current matrix.
4136:        5) Use a really basic converter.
4137:     */

4139:     /* 1) See if a specialized converter is known to the current DM and the desired class */
4140:     PetscCall(PetscStrncpy(convname, "DMConvert_", sizeof(convname)));
4141:     PetscCall(PetscStrlcat(convname, ((PetscObject)dm)->type_name, sizeof(convname)));
4142:     PetscCall(PetscStrlcat(convname, "_", sizeof(convname)));
4143:     PetscCall(PetscStrlcat(convname, newtype, sizeof(convname)));
4144:     PetscCall(PetscStrlcat(convname, "_C", sizeof(convname)));
4145:     PetscCall(PetscObjectQueryFunction((PetscObject)dm, convname, &conv));
4146:     if (conv) goto foundconv;

4148:     /* 2)  See if a specialized converter is known to the desired DM class. */
4149:     PetscCall(DMCreate(PetscObjectComm((PetscObject)dm), &B));
4150:     PetscCall(DMSetType(B, newtype));
4151:     PetscCall(PetscStrncpy(convname, "DMConvert_", sizeof(convname)));
4152:     PetscCall(PetscStrlcat(convname, ((PetscObject)dm)->type_name, sizeof(convname)));
4153:     PetscCall(PetscStrlcat(convname, "_", sizeof(convname)));
4154:     PetscCall(PetscStrlcat(convname, newtype, sizeof(convname)));
4155:     PetscCall(PetscStrlcat(convname, "_C", sizeof(convname)));
4156:     PetscCall(PetscObjectQueryFunction((PetscObject)B, convname, &conv));
4157:     if (conv) {
4158:       PetscCall(DMDestroy(&B));
4159:       goto foundconv;
4160:     }

4162: #if 0
4163:     /* 3) See if a good general converter is registered for the desired class */
4164:     conv = B->ops->convertfrom;
4165:     PetscCall(DMDestroy(&B));
4166:     if (conv) goto foundconv;

4168:     /* 4) See if a good general converter is known for the current matrix */
4169:     if (dm->ops->convert) conv = dm->ops->convert;
4170:     if (conv) goto foundconv;
4171: #endif

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

4176:   foundconv:
4177:     PetscCall(PetscLogEventBegin(DM_Convert, dm, 0, 0, 0));
4178:     PetscCall((*conv)(dm, newtype, M));
4179:     /* Things that are independent of DM type: We should consult DMClone() here */
4180:     {
4181:       const PetscReal *maxCell, *Lstart, *L;

4183:       PetscCall(DMGetPeriodicity(dm, &maxCell, &Lstart, &L));
4184:       PetscCall(DMSetPeriodicity(*M, maxCell, Lstart, L));
4185:       (*M)->prealloc_only = dm->prealloc_only;
4186:       PetscCall(PetscFree((*M)->vectype));
4187:       PetscCall(PetscStrallocpy(dm->vectype, (char **)&(*M)->vectype));
4188:       PetscCall(PetscFree((*M)->mattype));
4189:       PetscCall(PetscStrallocpy(dm->mattype, (char **)&(*M)->mattype));
4190:     }
4191:     PetscCall(PetscLogEventEnd(DM_Convert, dm, 0, 0, 0));
4192:   }
4193:   PetscCall(PetscObjectStateIncrease((PetscObject)*M));
4194:   PetscFunctionReturn(PETSC_SUCCESS);
4195: }

4197: /*@C
4198:   DMRegister -  Adds a new `DM` type implementation

4200:   Not Collective, No Fortran Support

4202:   Input Parameters:
4203: + sname    - The name of a new user-defined creation routine
4204: - function - The creation routine itself

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

4209:   Level: advanced

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

4214:   Example Usage:
4215: .vb
4216:     DMRegister("my_da", MyDMCreate);
4217: .ve

4219:   Then, your `DM` type can be chosen with the procedural interface via
4220: .vb
4221:     DMCreate(MPI_Comm, DM *);
4222:     DMSetType(DM,"my_da");
4223: .ve
4224:   or at runtime via the option
4225: .vb
4226:     -da_type my_da
4227: .ve

4229: .seealso: [](ch_dmbase), `DM`, `DMType`, `DMSetType()`, `DMRegisterAll()`, `DMRegisterDestroy()`
4230: @*/
4231: PetscErrorCode DMRegister(const char sname[], PetscErrorCode (*function)(DM dm))
4232: {
4233:   PetscFunctionBegin;
4234:   PetscCall(DMInitializePackage());
4235:   PetscCall(PetscFunctionListAdd(&DMList, sname, function));
4236:   PetscFunctionReturn(PETSC_SUCCESS);
4237: }

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

4242:   Collective

4244:   Input Parameters:
4245: + newdm  - the newly loaded `DM`, this needs to have been created with `DMCreate()` or
4246:            some related function before a call to `DMLoad()`.
4247: - viewer - binary file viewer, obtained from `PetscViewerBinaryOpen()` or
4248:            `PETSCVIEWERHDF5` file viewer, obtained from `PetscViewerHDF5Open()`

4250:   Level: intermediate

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

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

4259: .seealso: [](ch_dmbase), `DM`, `PetscViewerBinaryOpen()`, `DMView()`, `MatLoad()`, `VecLoad()`
4260: @*/
4261: PetscErrorCode DMLoad(DM newdm, PetscViewer viewer)
4262: {
4263:   PetscBool isbinary, ishdf5;

4265:   PetscFunctionBegin;
4268:   PetscCall(PetscViewerCheckReadable(viewer));
4269:   PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERBINARY, &isbinary));
4270:   PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERHDF5, &ishdf5));
4271:   PetscCall(PetscLogEventBegin(DM_Load, viewer, 0, 0, 0));
4272:   if (isbinary) {
4273:     PetscInt classid;
4274:     char     type[256];

4276:     PetscCall(PetscViewerBinaryRead(viewer, &classid, 1, NULL, PETSC_INT));
4277:     PetscCheck(classid == DM_FILE_CLASSID, PetscObjectComm((PetscObject)newdm), PETSC_ERR_ARG_WRONG, "Not DM next in file, classid found %" PetscInt_FMT, classid);
4278:     PetscCall(PetscViewerBinaryRead(viewer, type, 256, NULL, PETSC_CHAR));
4279:     PetscCall(DMSetType(newdm, type));
4280:     PetscTryTypeMethod(newdm, load, viewer);
4281:   } else if (ishdf5) {
4282:     PetscTryTypeMethod(newdm, load, viewer);
4283:   } else SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Invalid viewer; open viewer with PetscViewerBinaryOpen() or PetscViewerHDF5Open()");
4284:   PetscCall(PetscLogEventEnd(DM_Load, viewer, 0, 0, 0));
4285:   PetscFunctionReturn(PETSC_SUCCESS);
4286: }

4288: /* FEM Support */

4290: PetscErrorCode DMPrintCellIndices(PetscInt c, const char name[], PetscInt len, const PetscInt x[])
4291: {
4292:   PetscInt f;

4294:   PetscFunctionBegin;
4295:   PetscCall(PetscPrintf(PETSC_COMM_SELF, "Cell %" PetscInt_FMT " Element %s\n", c, name));
4296:   for (f = 0; f < len; ++f) PetscCall(PetscPrintf(PETSC_COMM_SELF, "  | %" PetscInt_FMT " |\n", x[f]));
4297:   PetscFunctionReturn(PETSC_SUCCESS);
4298: }

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

4310: PetscErrorCode DMPrintCellVectorReal(PetscInt c, const char name[], PetscInt len, const PetscReal x[])
4311: {
4312:   PetscFunctionBegin;
4313:   PetscCall(PetscPrintf(PETSC_COMM_SELF, "Cell %" PetscInt_FMT " Element %s\n", c, name));
4314:   for (PetscInt f = 0; f < len; ++f) PetscCall(PetscPrintf(PETSC_COMM_SELF, "  | %g |\n", (double)x[f]));
4315:   PetscFunctionReturn(PETSC_SUCCESS);
4316: }

4318: PetscErrorCode DMPrintCellMatrix(PetscInt c, const char name[], PetscInt rows, PetscInt cols, const PetscScalar A[])
4319: {
4320:   PetscFunctionBegin;
4321:   PetscCall(PetscPrintf(PETSC_COMM_SELF, "Cell %" PetscInt_FMT " Element %s\n", c, name));
4322:   for (PetscInt f = 0; f < rows; ++f) {
4323:     PetscCall(PetscPrintf(PETSC_COMM_SELF, "  |"));
4324:     for (PetscInt g = 0; g < cols; ++g) PetscCall(PetscPrintf(PETSC_COMM_SELF, " % 9.5g", (double)PetscRealPart(A[f * cols + g])));
4325:     PetscCall(PetscPrintf(PETSC_COMM_SELF, " |\n"));
4326:   }
4327:   PetscFunctionReturn(PETSC_SUCCESS);
4328: }

4330: PetscErrorCode DMPrintLocalVec(DM dm, const char name[], PetscReal tol, Vec X)
4331: {
4332:   PetscInt           localSize, bs;
4333:   PetscMPIInt        size;
4334:   Vec                x, xglob;
4335:   const PetscScalar *xarray;

4337:   PetscFunctionBegin;
4338:   PetscCallMPI(MPI_Comm_size(PetscObjectComm((PetscObject)dm), &size));
4339:   PetscCall(VecDuplicate(X, &x));
4340:   PetscCall(VecCopy(X, x));
4341:   PetscCall(VecFilter(x, tol));
4342:   PetscCall(PetscPrintf(PetscObjectComm((PetscObject)dm), "%s:\n", name));
4343:   if (size > 1) {
4344:     PetscCall(VecGetLocalSize(x, &localSize));
4345:     PetscCall(VecGetArrayRead(x, &xarray));
4346:     PetscCall(VecGetBlockSize(x, &bs));
4347:     PetscCall(VecCreateMPIWithArray(PetscObjectComm((PetscObject)dm), bs, localSize, PETSC_DETERMINE, xarray, &xglob));
4348:   } else {
4349:     xglob = x;
4350:   }
4351:   PetscCall(VecView(xglob, PETSC_VIEWER_STDOUT_(PetscObjectComm((PetscObject)dm))));
4352:   if (size > 1) {
4353:     PetscCall(VecDestroy(&xglob));
4354:     PetscCall(VecRestoreArrayRead(x, &xarray));
4355:   }
4356:   PetscCall(VecDestroy(&x));
4357:   PetscFunctionReturn(PETSC_SUCCESS);
4358: }

4360: PetscErrorCode DMViewDSFromOptions_Internal(DM dm, const char opt[])
4361: {
4362:   PetscObject       obj = (PetscObject)dm;
4363:   PetscViewer       viewer;
4364:   PetscViewerFormat format;
4365:   PetscBool         flg;

4367:   PetscFunctionBegin;
4368:   PetscCall(PetscOptionsCreateViewer(PetscObjectComm(obj), obj->options, obj->prefix, opt, &viewer, &format, &flg));
4369:   if (flg) {
4370:     PetscCall(PetscViewerPushFormat(viewer, format));
4371:     for (PetscInt d = 0; d < dm->Nds; ++d) PetscCall(PetscDSView(dm->probs[d].ds, viewer));
4372:     PetscCall(PetscViewerFlush(viewer));
4373:     PetscCall(PetscViewerPopFormat(viewer));
4374:     PetscCall(PetscViewerDestroy(&viewer));
4375:   }
4376:   PetscFunctionReturn(PETSC_SUCCESS);
4377: }

4379: PetscErrorCode DMViewSectionFromOptions_Internal(DM dm, const char opt[])
4380: {
4381:   PetscObject       obj = (PetscObject)dm;
4382:   PetscViewer       viewer;
4383:   PetscViewerFormat format;
4384:   PetscBool         flg;

4386:   PetscFunctionBegin;
4387:   PetscCall(PetscOptionsCreateViewer(PetscObjectComm(obj), obj->options, obj->prefix, opt, &viewer, &format, &flg));
4388:   if (flg) {
4389:     PetscCall(PetscViewerPushFormat(viewer, format));
4390:     if (dm->localSection) PetscCall(PetscSectionView(dm->localSection, viewer));
4391:     PetscCall(PetscViewerFlush(viewer));
4392:     PetscCall(PetscViewerPopFormat(viewer));
4393:     PetscCall(PetscViewerDestroy(&viewer));
4394:   }
4395:   PetscFunctionReturn(PETSC_SUCCESS);
4396: }

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

4401:   Input Parameter:
4402: . dm - The `DM`

4404:   Output Parameter:
4405: . section - The `PetscSection`

4407:   Options Database Key:
4408: . -dm_petscsection_view - View the section created by the `DM`

4410:   Level: intermediate

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

4415: .seealso: [](ch_dmbase), `DM`, `DMSetLocalSection()`, `DMGetGlobalSection()`
4416: @*/
4417: PetscErrorCode DMGetLocalSection(DM dm, PetscSection *section)
4418: {
4419:   PetscFunctionBegin;
4421:   PetscAssertPointer(section, 2);
4422:   if (!dm->localSection && dm->ops->createlocalsection) {
4423:     if (dm->setfromoptionscalled) {
4424:       for (PetscInt d = 0; d < dm->Nds; ++d) PetscCall(PetscDSSetFromOptions(dm->probs[d].ds));
4425:       PetscCall(DMViewDSFromOptions_Internal(dm, "-dm_petscds_view"));
4426:     }
4427:     PetscUseTypeMethod(dm, createlocalsection);
4428:     if (dm->localSection) PetscCall(PetscObjectViewFromOptions((PetscObject)dm->localSection, NULL, "-dm_petscsection_view"));
4429:   }
4430:   *section = dm->localSection;
4431:   PetscFunctionReturn(PETSC_SUCCESS);
4432: }

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

4437:   Input Parameters:
4438: + dm      - The `DM`
4439: - section - The `PetscSection`

4441:   Level: intermediate

4443:   Note:
4444:   Any existing Section will be destroyed

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

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

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

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

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

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

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

4494:   Level: developer

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

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

4510:   not Collective

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

4515:   Output Parameters:
4516: + 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.
4517: . 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.
4518: - bias    - Vector containing bias to be added to constrained dofs

4520:   Level: advanced

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

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

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

4541:   Collective

4543:   Input Parameters:
4544: + dm      - The `DM`
4545: . 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).
4546: . 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).
4547: - 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).

4549:   Level: advanced

4551:   Notes:
4552:   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()`.

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

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

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

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

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

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

4602:   Level: intermediate

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

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

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

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

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

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

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

4687:   Collective

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

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

4695:   Level: intermediate

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

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

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

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

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

4731:   Level: intermediate

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

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

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

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

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

4767:   Level: intermediate

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

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

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

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

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

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

4806:   Level: intermediate

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

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

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

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

4833:   Level: developer

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

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

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

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

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

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

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

4865:   Level: intermediate

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

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

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

4884:   Collective

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

4890:   Level: intermediate

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

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

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

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

4914:   Level: intermediate

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

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

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

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

4937:   Level: intermediate

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

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

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

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

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

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

4987:   Logically Collective

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

4992:   Level: intermediate

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

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

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

5016:   Not Collective

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

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

5024:   Level: intermediate

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

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

5040:   Logically Collective

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

5046:   Level: intermediate

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

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

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

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

5070:   Not Collective

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

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

5080:   Level: intermediate

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

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

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

5118:   Logically Collective

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

5126:   Level: intermediate

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

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

5147:   Logically Collective

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

5154:   Level: intermediate

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

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

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

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

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

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

5189:   Logically Collective

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

5196:   Level: intermediate

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

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

5211:   Not Collective

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

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

5220:   Level: intermediate

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

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

5235:   Collective

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

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

5245:   Level: advanced

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

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

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

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

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

5288:   Not Collective

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

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

5298:   Level: developer

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

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

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

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

5333:   Not Collective

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

5341:   Level: developer

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

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

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

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

5374:   Not collective

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

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

5383:   Level: developer

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

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

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

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

5414:   Not Collective

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

5421:   Level: developer

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

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

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

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

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

5467:     PetscCall(DMGetRegionNumDS(dm, s, NULL, NULL, &dsBC, NULL));
5468:     PetscCall(PetscDSGetNumBoundary(dsBC, &numBd));
5469:     maxLabels += numBd;
5470:   }
5471:   PetscCall(PetscCalloc1(maxLabels, &labels));
5472:   /* Get list of labels to be completed */
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:     for (PetscInt bd = 0; bd < numBd; ++bd) {
5480:       DMLabel      label;
5481:       PetscInt     field;
5482:       PetscObject  obj;
5483:       PetscClassId id;

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

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

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

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

5558:   Not Collective

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

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

5566:   Level: intermediate

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

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

5582:   Logically Collective

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

5587:   Level: intermediate

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

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

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

5612:   Not Collective

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

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

5620:   Level: intermediate

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

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

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

5640:   Not Collective

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

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

5650:   Level: developer

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

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

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

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

5687:   Not Collective

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

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

5698:   Level: advanced

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

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

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

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

5740:   Collective

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

5749:   Level: advanced

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

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

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

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

5796:   Not Collective

5798:   Input Parameters:
5799: + dm  - The `DM`
5800: - num - The region number, in [0, Nds)

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

5808:   Level: advanced

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

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

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

5842:   Not Collective

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

5852:   Level: advanced

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

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

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

5892:   Not Collective

5894:   Input Parameters:
5895: + dm - The `DM`
5896: - ds - The `PetscDS` defined on the given region

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

5901:   Level: advanced

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

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

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

5924:   Not Collective

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

5932:   Output Parameter:
5933: . fem - The `PetscFE`

5935:   Level: intermediate

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

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

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

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

5963:   Collective

5965:   Input Parameter:
5966: . dm - The `DM`

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

5971:   Level: intermediate

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

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

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

6002: #ifdef PETSC_HAVE_LIBCEED
6003:     /* Move CEED context to discretizations */
6004:     {
6005:       PetscClassId id;

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

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

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

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

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

6067:       PetscCall(ISDestroy(&defcellIS));
6068:       PetscCall(DMLabelGetStratumIS(label, 1, &pointIS));
6069:       PetscCall(ISDifference(allcellIS, pointIS, &defcellIS));
6070:       PetscCall(ISDestroy(&pointIS));
6071:     }
6072:     PetscCall(ISDestroy(&allcellIS));

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

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

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

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

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

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

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

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

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

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

6236:   Input Parameters:
6237: + dm     - The DM
6238: - tensor - Flag for tensor order

6240:   Level: developer

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

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

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

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

6272:     PetscCall(DMGetLocalSection(dm, &s));
6273:     if (s) PetscCall(PetscSectionResetClosurePermutation(s));
6274:   }
6275:   PetscFunctionReturn(PETSC_SUCCESS);
6276: }

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

6281:   Collective

6283:   Input Parameters:
6284: + dm   - The `DM`
6285: - time - The time

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

6291:   Level: developer

6293:   Note:
6294:   The user must call `PetscDSSetExactSolution()` before using this routine

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

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

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

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

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

6385: /*@
6386:   DMCopyDS - Copy the discrete systems for the `DM` into another `DM`

6388:   Collective

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

6395:   Output Parameter:
6396: . newdm - The `DM`

6398:   Level: advanced

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

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

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

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

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

6438:   Collective

6440:   Input Parameter:
6441: . dm - The `DM`

6443:   Output Parameter:
6444: . newdm - The `DM`

6446:   Level: advanced

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

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

6461: /*@
6462:   DMGetDimension - Return the topological dimension of the `DM`

6464:   Not Collective

6466:   Input Parameter:
6467: . dm - The `DM`

6469:   Output Parameter:
6470: . dim - The topological dimension

6472:   Level: beginner

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

6485: /*@
6486:   DMSetDimension - Set the topological dimension of the `DM`

6488:   Collective

6490:   Input Parameters:
6491: + dm  - The `DM`
6492: - dim - The topological dimension

6494:   Level: beginner

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

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

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

6521:   Collective

6523:   Input Parameters:
6524: + dm  - the `DM`
6525: - dim - the dimension

6527:   Output Parameters:
6528: + pStart - The first point of the given dimension
6529: - pEnd   - The first point following points of the given dimension

6531:   Level: intermediate

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

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

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

6552: /*@
6553:   DMGetOutputDM - Retrieve the `DM` associated with the layout for output

6555:   Collective

6557:   Input Parameter:
6558: . dm - The original `DM`

6560:   Output Parameter:
6561: . odm - The `DM` which provides the layout for output

6563:   Level: intermediate

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

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

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

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

6613: /*@
6614:   DMGetOutputSequenceNumber - Retrieve the sequence number/value for output

6616:   Input Parameter:
6617: . dm - The original `DM`

6619:   Output Parameters:
6620: + num - The output sequence number
6621: - val - The output sequence value

6623:   Level: intermediate

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

6629:   Developer Note:
6630:   The `DM` serves as a convenient place to store the current iteration value. The iteration is not
6631:   not directly related to the `DM`.

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

6650: /*@
6651:   DMSetOutputSequenceNumber - Set the sequence number/value for output

6653:   Input Parameters:
6654: + dm  - The original `DM`
6655: . num - The output sequence number
6656: - val - The output sequence value

6658:   Level: intermediate

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

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

6675: /*@
6676:   DMOutputSequenceLoad - Retrieve the sequence value from a `PetscViewer`

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

6684:   Output Parameter:
6685: . val - The output sequence value

6687:   Level: intermediate

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

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

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

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

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

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

6721:   Input Parameters:
6722: + dm     - The original `DM`
6723: . viewer - The `PetscViewer` to get it from
6724: - name   - The sequence name

6726:   Output Parameter:
6727: . len - The length of the output sequence

6729:   Level: intermediate

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

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

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

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

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

6760:   Not Collective

6762:   Input Parameter:
6763: . dm - The `DM`

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

6768:   Level: beginner

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

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

6784:   Collective

6786:   Input Parameters:
6787: + dm         - The `DM`
6788: - useNatural - `PETSC_TRUE` to build the mapping to a natural order during distribution

6790:   Level: beginner

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

6795: .seealso: [](ch_dmbase), `DM`, `DMGetUseNatural()`, `DMCreate()`, `DMPlexDistribute()`, `DMCreateSubDM()`, `DMCreateSuperDM()`
6796: @*/
6797: PetscErrorCode DMSetUseNatural(DM dm, PetscBool useNatural)
6798: {
6799:   PetscFunctionBegin;
6802:   dm->useNatural = useNatural;
6803:   PetscFunctionReturn(PETSC_SUCCESS);
6804: }

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

6809:   Not Collective

6811:   Input Parameters:
6812: + dm   - The `DM` object
6813: - name - The label name

6815:   Level: intermediate

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

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

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

6839:   Not Collective

6841:   Input Parameters:
6842: + dm   - The `DM` object
6843: . l    - The index for the label
6844: - name - The label name

6846:   Level: intermediate

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

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

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

6891:   Not Collective

6893:   Input Parameters:
6894: + dm    - The `DM` object
6895: . name  - The label name
6896: - point - The mesh point

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

6901:   Level: beginner

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

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

6918: /*@
6919:   DMSetLabelValue - Add a point to a `DMLabel` with given value

6921:   Not Collective

6923:   Input Parameters:
6924: + dm    - The `DM` object
6925: . name  - The label name
6926: . point - The mesh point
6927: - value - The label value for this point

6929:   Output Parameter:

6931:   Level: beginner

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

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

6951: /*@
6952:   DMClearLabelValue - Remove a point from a `DMLabel` with given value

6954:   Not Collective

6956:   Input Parameters:
6957: + dm    - The `DM` object
6958: . name  - The label name
6959: . point - The mesh point
6960: - value - The label value for this point

6962:   Level: beginner

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

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

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

6982:   Not Collective

6984:   Input Parameters:
6985: + dm   - The `DM` object
6986: - name - The label name

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

6991:   Level: beginner

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

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

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

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

7016:   Not Collective

7018:   Input Parameters:
7019: + dm   - The `DM` object
7020: - name - The label name

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

7025:   Level: beginner

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

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

7047: /*@
7048:   DMGetStratumSize - Get the number of points in a label stratum

7050:   Not Collective

7052:   Input Parameters:
7053: + dm    - The `DM` object
7054: . name  - The label name of the stratum
7055: - value - The stratum value

7057:   Output Parameter:
7058: . size - The number of points, also called the stratum size

7060:   Level: beginner

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

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

7079: /*@
7080:   DMGetStratumIS - Get the points in a label stratum

7082:   Not Collective

7084:   Input Parameters:
7085: + dm    - The `DM` object
7086: . name  - The label name
7087: - value - The stratum value

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

7092:   Level: beginner

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

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

7111: /*@
7112:   DMSetStratumIS - Set the points in a label stratum

7114:   Not Collective

7116:   Input Parameters:
7117: + dm     - The `DM` object
7118: . name   - The label name
7119: . value  - The stratum value
7120: - points - The stratum points

7122:   Level: beginner

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

7130:   PetscFunctionBegin;
7132:   PetscAssertPointer(name, 2);
7134:   PetscCall(DMGetLabel(dm, name, &label));
7135:   if (!label) PetscFunctionReturn(PETSC_SUCCESS);
7136:   PetscCall(DMLabelSetStratumIS(label, value, points));
7137:   PetscFunctionReturn(PETSC_SUCCESS);
7138: }

7140: /*@
7141:   DMClearLabelStratum - Remove all points from a stratum from a `DMLabel`

7143:   Not Collective

7145:   Input Parameters:
7146: + dm    - The `DM` object
7147: . name  - The label name
7148: - value - The label value for this point

7150:   Output Parameter:

7152:   Level: beginner

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

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

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

7172:   Not Collective

7174:   Input Parameter:
7175: . dm - The `DM` object

7177:   Output Parameter:
7178: . numLabels - the number of Labels

7180:   Level: intermediate

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

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

7200: /*@
7201:   DMGetLabelName - Return the name of nth label

7203:   Not Collective

7205:   Input Parameters:
7206: + dm - The `DM` object
7207: - n  - the label number

7209:   Output Parameter:
7210: . name - the label name

7212:   Level: intermediate

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

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

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

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

7241:   Not Collective

7243:   Input Parameters:
7244: + dm   - The `DM` object
7245: - name - The label name

7247:   Output Parameter:
7248: . hasLabel - `PETSC_TRUE` if the label is present

7250:   Level: intermediate

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

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

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

7277:   Not Collective

7279:   Input Parameters:
7280: + dm   - The `DM` object
7281: - name - The label name

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

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

7294:   Level: intermediate

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

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

7321: /*@
7322:   DMGetLabelByNum - Return the nth label on a `DM`

7324:   Not Collective

7326:   Input Parameters:
7327: + dm - The `DM` object
7328: - n  - the label number

7330:   Output Parameter:
7331: . label - the label

7333:   Level: intermediate

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

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

7356: /*@
7357:   DMAddLabel - Add the label to this `DM`

7359:   Not Collective

7361:   Input Parameters:
7362: + dm    - The `DM` object
7363: - label - The `DMLabel`

7365:   Level: developer

7367: .seealso: [](ch_dmbase), `DM`, `DMLabel`, `DMCreateLabel()`, `DMHasLabel()`, `DMGetLabelValue()`, `DMSetLabelValue()`, `DMGetStratumIS()`
7368: @*/
7369: PetscErrorCode DMAddLabel(DM dm, DMLabel label)
7370: {
7371:   DMLabelLink l, *p, tmpLabel;
7372:   PetscBool   hasLabel;
7373:   const char *lname;
7374:   PetscBool   flg;

7376:   PetscFunctionBegin;
7378:   PetscCall(PetscObjectGetName((PetscObject)label, &lname));
7379:   PetscCall(DMHasLabel(dm, lname, &hasLabel));
7380:   PetscCheck(!hasLabel, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Label %s already exists in this DM", lname);
7381:   PetscCall(PetscCalloc1(1, &tmpLabel));
7382:   tmpLabel->label  = label;
7383:   tmpLabel->output = PETSC_TRUE;
7384:   for (p = &dm->labels; (l = *p); p = &l->next) { }
7385:   *p = tmpLabel;
7386:   PetscCall(PetscObjectReference((PetscObject)label));
7387:   PetscCall(PetscStrcmp(lname, "depth", &flg));
7388:   if (flg) dm->depthLabel = label;
7389:   PetscCall(PetscStrcmp(lname, "celltype", &flg));
7390:   if (flg) dm->celltypeLabel = label;
7391:   PetscFunctionReturn(PETSC_SUCCESS);
7392: }

7394: // PetscClangLinter pragma ignore: -fdoc-section-header-unknown
7395: /*@
7396:   DMSetLabel - Replaces the label of a given name, or ignores it if the name is not present

7398:   Not Collective

7400:   Input Parameters:
7401: + dm    - The `DM` object
7402: - label - The `DMLabel`, having the same name, to substitute

7404:   Default labels in a `DMPLEX`:
7405: + "depth"       - Holds the depth (co-dimension) of each mesh point
7406: . "celltype"    - Holds the topological type of each cell
7407: . "ghost"       - If the DM is distributed with overlap, this marks the cells and faces in the overlap
7408: . "Cell Sets"   - Mirrors the cell sets defined by GMsh and ExodusII
7409: . "Face Sets"   - Mirrors the face sets defined by GMsh and ExodusII
7410: - "Vertex Sets" - Mirrors the vertex sets defined by GMsh

7412:   Level: intermediate

7414: .seealso: [](ch_dmbase), `DM`, `DMLabel`, `DMCreateLabel()`, `DMHasLabel()`, `DMPlexGetDepthLabel()`, `DMPlexGetCellType()`
7415: @*/
7416: PetscErrorCode DMSetLabel(DM dm, DMLabel label)
7417: {
7418:   DMLabelLink next = dm->labels;
7419:   PetscBool   hasLabel, flg;
7420:   const char *name, *lname;

7422:   PetscFunctionBegin;
7425:   PetscCall(PetscObjectGetName((PetscObject)label, &name));
7426:   while (next) {
7427:     PetscCall(PetscObjectGetName((PetscObject)next->label, &lname));
7428:     PetscCall(PetscStrcmp(name, lname, &hasLabel));
7429:     if (hasLabel) {
7430:       PetscCall(PetscObjectReference((PetscObject)label));
7431:       PetscCall(PetscStrcmp(lname, "depth", &flg));
7432:       if (flg) dm->depthLabel = label;
7433:       PetscCall(PetscStrcmp(lname, "celltype", &flg));
7434:       if (flg) dm->celltypeLabel = label;
7435:       PetscCall(DMLabelDestroy(&next->label));
7436:       next->label = label;
7437:       break;
7438:     }
7439:     next = next->next;
7440:   }
7441:   PetscFunctionReturn(PETSC_SUCCESS);
7442: }

7444: /*@
7445:   DMRemoveLabel - Remove the label given by name from this `DM`

7447:   Not Collective

7449:   Input Parameters:
7450: + dm   - The `DM` object
7451: - name - The label name

7453:   Output Parameter:
7454: . label - The `DMLabel`, or `NULL` if the label is absent. Pass in `NULL` to call `DMLabelDestroy()` on the label, otherwise the
7455:           caller is responsible for calling `DMLabelDestroy()`.

7457:   Level: developer

7459: .seealso: [](ch_dmbase), `DM`, `DMLabel`, `DMCreateLabel()`, `DMHasLabel()`, `DMGetLabel()`, `DMGetLabelValue()`, `DMSetLabelValue()`, `DMLabelDestroy()`, `DMRemoveLabelBySelf()`
7460: @*/
7461: PetscErrorCode DMRemoveLabel(DM dm, const char name[], DMLabel *label)
7462: {
7463:   DMLabelLink link, *pnext;
7464:   PetscBool   hasLabel;
7465:   const char *lname;

7467:   PetscFunctionBegin;
7469:   PetscAssertPointer(name, 2);
7470:   if (label) {
7471:     PetscAssertPointer(label, 3);
7472:     *label = NULL;
7473:   }
7474:   for (pnext = &dm->labels; (link = *pnext); pnext = &link->next) {
7475:     PetscCall(PetscObjectGetName((PetscObject)link->label, &lname));
7476:     PetscCall(PetscStrcmp(name, lname, &hasLabel));
7477:     if (hasLabel) {
7478:       *pnext = link->next; /* Remove from list */
7479:       PetscCall(PetscStrcmp(name, "depth", &hasLabel));
7480:       if (hasLabel) dm->depthLabel = NULL;
7481:       PetscCall(PetscStrcmp(name, "celltype", &hasLabel));
7482:       if (hasLabel) dm->celltypeLabel = NULL;
7483:       if (label) *label = link->label;
7484:       else PetscCall(DMLabelDestroy(&link->label));
7485:       PetscCall(PetscFree(link));
7486:       break;
7487:     }
7488:   }
7489:   PetscFunctionReturn(PETSC_SUCCESS);
7490: }

7492: /*@
7493:   DMRemoveLabelBySelf - Remove the label from this `DM`

7495:   Not Collective

7497:   Input Parameters:
7498: + dm           - The `DM` object
7499: . label        - The `DMLabel` to be removed from the `DM`
7500: - failNotFound - Should it fail if the label is not found in the `DM`?

7502:   Level: developer

7504:   Note:
7505:   Only exactly the same instance is removed if found, name match is ignored.
7506:   If the `DM` has an exclusive reference to the label, the label gets destroyed and
7507:   *label nullified.

7509: .seealso: [](ch_dmbase), `DM`, `DMLabel`, `DMCreateLabel()`, `DMHasLabel()`, `DMGetLabel()`, `DMGetLabelValue()`, `DMSetLabelValue()`, `DMLabelDestroy()`, `DMRemoveLabel()`
7510: @*/
7511: PetscErrorCode DMRemoveLabelBySelf(DM dm, DMLabel *label, PetscBool failNotFound)
7512: {
7513:   DMLabelLink link, *pnext;
7514:   PetscBool   hasLabel = PETSC_FALSE;

7516:   PetscFunctionBegin;
7518:   PetscAssertPointer(label, 2);
7519:   if (!*label && !failNotFound) PetscFunctionReturn(PETSC_SUCCESS);
7522:   for (pnext = &dm->labels; (link = *pnext); pnext = &link->next) {
7523:     if (*label == link->label) {
7524:       hasLabel = PETSC_TRUE;
7525:       *pnext   = link->next; /* Remove from list */
7526:       if (*label == dm->depthLabel) dm->depthLabel = NULL;
7527:       if (*label == dm->celltypeLabel) dm->celltypeLabel = NULL;
7528:       if (((PetscObject)link->label)->refct < 2) *label = NULL; /* nullify if exclusive reference */
7529:       PetscCall(DMLabelDestroy(&link->label));
7530:       PetscCall(PetscFree(link));
7531:       break;
7532:     }
7533:   }
7534:   PetscCheck(hasLabel || !failNotFound, PetscObjectComm((PetscObject)dm), PETSC_ERR_ARG_WRONG, "Given label not found in DM");
7535:   PetscFunctionReturn(PETSC_SUCCESS);
7536: }

7538: /*@
7539:   DMGetLabelOutput - Get the output flag for a given label

7541:   Not Collective

7543:   Input Parameters:
7544: + dm   - The `DM` object
7545: - name - The label name

7547:   Output Parameter:
7548: . output - The flag for output

7550:   Level: developer

7552: .seealso: [](ch_dmbase), `DM`, `DMLabel`, `DMSetLabelOutput()`, `DMCreateLabel()`, `DMHasLabel()`, `DMGetLabelValue()`, `DMSetLabelValue()`, `DMGetStratumIS()`
7553: @*/
7554: PetscErrorCode DMGetLabelOutput(DM dm, const char name[], PetscBool *output)
7555: {
7556:   DMLabelLink next = dm->labels;
7557:   const char *lname;

7559:   PetscFunctionBegin;
7561:   PetscAssertPointer(name, 2);
7562:   PetscAssertPointer(output, 3);
7563:   while (next) {
7564:     PetscBool flg;

7566:     PetscCall(PetscObjectGetName((PetscObject)next->label, &lname));
7567:     PetscCall(PetscStrcmp(name, lname, &flg));
7568:     if (flg) {
7569:       *output = next->output;
7570:       PetscFunctionReturn(PETSC_SUCCESS);
7571:     }
7572:     next = next->next;
7573:   }
7574:   SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "No label named %s was present in this dm", name);
7575: }

7577: /*@
7578:   DMSetLabelOutput - Set if a given label should be saved to a `PetscViewer` in calls to `DMView()`

7580:   Not Collective

7582:   Input Parameters:
7583: + dm     - The `DM` object
7584: . name   - The label name
7585: - output - `PETSC_TRUE` to save the label to the viewer

7587:   Level: developer

7589: .seealso: [](ch_dmbase), `DM`, `DMLabel`, `DMGetOutputFlag()`, `DMGetLabelOutput()`, `DMCreateLabel()`, `DMHasLabel()`, `DMGetLabelValue()`, `DMSetLabelValue()`, `DMGetStratumIS()`
7590: @*/
7591: PetscErrorCode DMSetLabelOutput(DM dm, const char name[], PetscBool output)
7592: {
7593:   DMLabelLink next = dm->labels;
7594:   const char *lname;

7596:   PetscFunctionBegin;
7598:   PetscAssertPointer(name, 2);
7599:   while (next) {
7600:     PetscBool flg;

7602:     PetscCall(PetscObjectGetName((PetscObject)next->label, &lname));
7603:     PetscCall(PetscStrcmp(name, lname, &flg));
7604:     if (flg) {
7605:       next->output = output;
7606:       PetscFunctionReturn(PETSC_SUCCESS);
7607:     }
7608:     next = next->next;
7609:   }
7610:   SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "No label named %s was present in this dm", name);
7611: }

7613: /*@
7614:   DMCopyLabels - Copy labels from one `DM` mesh to another `DM` with a superset of the points

7616:   Collective

7618:   Input Parameters:
7619: + dmA   - The `DM` object with initial labels
7620: . dmB   - The `DM` object to which labels are copied
7621: . mode  - Copy labels by pointers (`PETSC_OWN_POINTER`) or duplicate them (`PETSC_COPY_VALUES`)
7622: . all   - Copy all labels including "depth", "dim", and "celltype" (`PETSC_TRUE`) which are otherwise ignored (`PETSC_FALSE`)
7623: - emode - How to behave when a `DMLabel` in the source and destination `DM`s with the same name is encountered (see `DMCopyLabelsMode`)

7625:   Level: intermediate

7627:   Note:
7628:   This is typically used when interpolating or otherwise adding to a mesh, or testing.

7630: .seealso: [](ch_dmbase), `DM`, `DMLabel`, `DMAddLabel()`, `DMCopyLabelsMode`
7631: @*/
7632: PetscErrorCode DMCopyLabels(DM dmA, DM dmB, PetscCopyMode mode, PetscBool all, DMCopyLabelsMode emode)
7633: {
7634:   DMLabel     label, labelNew, labelOld;
7635:   const char *name;
7636:   PetscBool   flg;
7637:   DMLabelLink link;

7639:   PetscFunctionBegin;
7644:   PetscCheck(mode != PETSC_USE_POINTER, PetscObjectComm((PetscObject)dmA), PETSC_ERR_SUP, "PETSC_USE_POINTER not supported for objects");
7645:   if (dmA == dmB) PetscFunctionReturn(PETSC_SUCCESS);
7646:   for (link = dmA->labels; link; link = link->next) {
7647:     label = link->label;
7648:     PetscCall(PetscObjectGetName((PetscObject)label, &name));
7649:     if (!all) {
7650:       PetscCall(PetscStrcmp(name, "depth", &flg));
7651:       if (flg) continue;
7652:       PetscCall(PetscStrcmp(name, "dim", &flg));
7653:       if (flg) continue;
7654:       PetscCall(PetscStrcmp(name, "celltype", &flg));
7655:       if (flg) continue;
7656:     }
7657:     PetscCall(DMGetLabel(dmB, name, &labelOld));
7658:     if (labelOld) {
7659:       switch (emode) {
7660:       case DM_COPY_LABELS_KEEP:
7661:         continue;
7662:       case DM_COPY_LABELS_REPLACE:
7663:         PetscCall(DMRemoveLabelBySelf(dmB, &labelOld, PETSC_TRUE));
7664:         break;
7665:       case DM_COPY_LABELS_FAIL:
7666:         SETERRQ(PetscObjectComm((PetscObject)dmA), PETSC_ERR_ARG_OUTOFRANGE, "Label %s already exists in destination DM", name);
7667:       default:
7668:         SETERRQ(PetscObjectComm((PetscObject)dmA), PETSC_ERR_ARG_OUTOFRANGE, "Unhandled DMCopyLabelsMode %d", (int)emode);
7669:       }
7670:     }
7671:     if (mode == PETSC_COPY_VALUES) PetscCall(DMLabelDuplicate(label, &labelNew));
7672:     else labelNew = label;
7673:     PetscCall(DMAddLabel(dmB, labelNew));
7674:     if (mode == PETSC_COPY_VALUES) PetscCall(DMLabelDestroy(&labelNew));
7675:   }
7676:   PetscFunctionReturn(PETSC_SUCCESS);
7677: }

7679: /*@C
7680:   DMCompareLabels - Compare labels between two `DM` objects

7682:   Collective; No Fortran Support

7684:   Input Parameters:
7685: + dm0 - First `DM` object
7686: - dm1 - Second `DM` object

7688:   Output Parameters:
7689: + equal   - (Optional) Flag whether labels of `dm0` and `dm1` are the same
7690: - message - (Optional) Message describing the difference, or `NULL` if there is no difference

7692:   Level: intermediate

7694:   Notes:
7695:   The output flag equal will be the same on all processes.

7697:   If equal is passed as `NULL` and difference is found, an error is thrown on all processes.

7699:   Make sure to pass equal is `NULL` on all processes or none of them.

7701:   The output message is set independently on each rank.

7703:   message must be freed with `PetscFree()`

7705:   If message is passed as `NULL` and a difference is found, the difference description is printed to `stderr` in synchronized manner.

7707:   Make sure to pass message as `NULL` on all processes or no processes.

7709:   Labels are matched by name. If the number of labels and their names are equal,
7710:   `DMLabelCompare()` is used to compare each pair of labels with the same name.

7712:   Developer Note:
7713:   Cannot automatically generate the Fortran stub because `message` must be freed with `PetscFree()`

7715: .seealso: [](ch_dmbase), `DM`, `DMLabel`, `DMAddLabel()`, `DMCopyLabelsMode`, `DMLabelCompare()`
7716: @*/
7717: PetscErrorCode DMCompareLabels(DM dm0, DM dm1, PetscBool *equal, char *message[]) PeNS
7718: {
7719:   PetscInt    n;
7720:   char        msg[PETSC_MAX_PATH_LEN] = "";
7721:   PetscBool   eq;
7722:   MPI_Comm    comm;
7723:   PetscMPIInt rank;

7725:   PetscFunctionBegin;
7728:   PetscCheckSameComm(dm0, 1, dm1, 2);
7729:   if (equal) PetscAssertPointer(equal, 3);
7730:   if (message) PetscAssertPointer(message, 4);
7731:   PetscCall(PetscObjectGetComm((PetscObject)dm0, &comm));
7732:   PetscCallMPI(MPI_Comm_rank(comm, &rank));
7733:   {
7734:     PetscInt n1;

7736:     PetscCall(DMGetNumLabels(dm0, &n));
7737:     PetscCall(DMGetNumLabels(dm1, &n1));
7738:     eq = (PetscBool)(n == n1);
7739:     if (!eq) PetscCall(PetscSNPrintf(msg, sizeof(msg), "Number of labels in dm0 = %" PetscInt_FMT " != %" PetscInt_FMT " = Number of labels in dm1", n, n1));
7740:     PetscCallMPI(MPIU_Allreduce(MPI_IN_PLACE, &eq, 1, MPI_C_BOOL, MPI_LAND, comm));
7741:     if (!eq) goto finish;
7742:   }
7743:   for (PetscInt i = 0; i < n; i++) {
7744:     DMLabel     l0, l1;
7745:     const char *name;
7746:     char       *msgInner;

7748:     /* Ignore label order */
7749:     PetscCall(DMGetLabelByNum(dm0, i, &l0));
7750:     PetscCall(PetscObjectGetName((PetscObject)l0, &name));
7751:     PetscCall(DMGetLabel(dm1, name, &l1));
7752:     if (!l1) {
7753:       PetscCall(PetscSNPrintf(msg, sizeof(msg), "Label \"%s\" (#%" PetscInt_FMT " in dm0) not found in dm1", name, i));
7754:       eq = PETSC_FALSE;
7755:       break;
7756:     }
7757:     PetscCall(DMLabelCompare(comm, l0, l1, &eq, &msgInner));
7758:     PetscCall(PetscStrncpy(msg, msgInner, sizeof(msg)));
7759:     PetscCall(PetscFree(msgInner));
7760:     if (!eq) break;
7761:   }
7762:   PetscCallMPI(MPIU_Allreduce(MPI_IN_PLACE, &eq, 1, MPI_C_BOOL, MPI_LAND, comm));
7763: finish:
7764:   /* If message output arg not set, print to stderr */
7765:   if (message) {
7766:     *message = NULL;
7767:     if (msg[0]) PetscCall(PetscStrallocpy(msg, message));
7768:   } else {
7769:     if (msg[0]) PetscCall(PetscSynchronizedFPrintf(comm, PETSC_STDERR, "[%d] %s\n", rank, msg));
7770:     PetscCall(PetscSynchronizedFlush(comm, PETSC_STDERR));
7771:   }
7772:   /* If same output arg not ser and labels are not equal, throw error */
7773:   if (equal) *equal = eq;
7774:   else PetscCheck(eq, comm, PETSC_ERR_ARG_INCOMP, "DMLabels are not the same in dm0 and dm1");
7775:   PetscFunctionReturn(PETSC_SUCCESS);
7776: }

7778: PetscErrorCode DMSetLabelValue_Fast(DM dm, DMLabel *label, const char name[], PetscInt point, PetscInt value)
7779: {
7780:   PetscFunctionBegin;
7781:   PetscAssertPointer(label, 2);
7782:   if (!*label) {
7783:     PetscCall(DMCreateLabel(dm, name));
7784:     PetscCall(DMGetLabel(dm, name, label));
7785:   }
7786:   PetscCall(DMLabelSetValue(*label, point, value));
7787:   PetscFunctionReturn(PETSC_SUCCESS);
7788: }

7790: /*
7791:   Many mesh programs, such as Triangle and TetGen, allow only a single label for each mesh point. Therefore, we would
7792:   like to encode all label IDs using a single, universal label. We can do this by assigning an integer to every
7793:   (label, id) pair in the DM.

7795:   However, a mesh point can have multiple labels, so we must separate all these values. We will assign a bit range to
7796:   each label.
7797: */
7798: PetscErrorCode DMUniversalLabelCreate(DM dm, DMUniversalLabel *universal)
7799: {
7800:   DMUniversalLabel ul;
7801:   PetscBool       *active;
7802:   PetscInt         pStart, pEnd, p, Nl, l, m;

7804:   PetscFunctionBegin;
7805:   PetscCall(PetscMalloc1(1, &ul));
7806:   PetscCall(DMLabelCreate(PETSC_COMM_SELF, "universal", &ul->label));
7807:   PetscCall(DMGetNumLabels(dm, &Nl));
7808:   PetscCall(PetscCalloc1(Nl, &active));
7809:   ul->Nl = 0;
7810:   for (l = 0; l < Nl; ++l) {
7811:     PetscBool   isdepth, iscelltype;
7812:     const char *name;

7814:     PetscCall(DMGetLabelName(dm, l, &name));
7815:     PetscCall(PetscStrncmp(name, "depth", 6, &isdepth));
7816:     PetscCall(PetscStrncmp(name, "celltype", 9, &iscelltype));
7817:     active[l] = !(isdepth || iscelltype) ? PETSC_TRUE : PETSC_FALSE;
7818:     if (active[l]) ++ul->Nl;
7819:   }
7820:   PetscCall(PetscCalloc5(ul->Nl, &ul->names, ul->Nl, &ul->indices, ul->Nl + 1, &ul->offsets, ul->Nl + 1, &ul->bits, ul->Nl, &ul->masks));
7821:   ul->Nv = 0;
7822:   for (l = 0, m = 0; l < Nl; ++l) {
7823:     DMLabel     label;
7824:     PetscInt    nv;
7825:     const char *name;

7827:     if (!active[l]) continue;
7828:     PetscCall(DMGetLabelName(dm, l, &name));
7829:     PetscCall(DMGetLabelByNum(dm, l, &label));
7830:     PetscCall(DMLabelGetNumValues(label, &nv));
7831:     PetscCall(PetscStrallocpy(name, &ul->names[m]));
7832:     ul->indices[m] = l;
7833:     ul->Nv += nv;
7834:     ul->offsets[m + 1] = nv;
7835:     ul->bits[m + 1]    = PetscCeilReal(PetscLog2Real(nv + 1));
7836:     ++m;
7837:   }
7838:   for (l = 1; l <= ul->Nl; ++l) {
7839:     ul->offsets[l] = ul->offsets[l - 1] + ul->offsets[l];
7840:     ul->bits[l]    = ul->bits[l - 1] + ul->bits[l];
7841:   }
7842:   for (l = 0; l < ul->Nl; ++l) {
7843:     ul->masks[l] = 0;
7844:     for (PetscInt b = ul->bits[l]; b < ul->bits[l + 1]; ++b) ul->masks[l] |= 1 << b;
7845:   }
7846:   PetscCall(PetscMalloc1(ul->Nv, &ul->values));
7847:   for (l = 0, m = 0; l < Nl; ++l) {
7848:     DMLabel         label;
7849:     IS              valueIS;
7850:     const PetscInt *varr;
7851:     PetscInt        nv;

7853:     if (!active[l]) continue;
7854:     PetscCall(DMGetLabelByNum(dm, l, &label));
7855:     PetscCall(DMLabelGetNumValues(label, &nv));
7856:     PetscCall(DMLabelGetValueIS(label, &valueIS));
7857:     PetscCall(ISGetIndices(valueIS, &varr));
7858:     for (PetscInt v = 0; v < nv; ++v) ul->values[ul->offsets[m] + v] = varr[v];
7859:     PetscCall(ISRestoreIndices(valueIS, &varr));
7860:     PetscCall(ISDestroy(&valueIS));
7861:     PetscCall(PetscSortInt(nv, &ul->values[ul->offsets[m]]));
7862:     ++m;
7863:   }
7864:   PetscCall(DMPlexGetChart(dm, &pStart, &pEnd));
7865:   for (p = pStart; p < pEnd; ++p) {
7866:     PetscInt  uval   = 0;
7867:     PetscBool marked = PETSC_FALSE;

7869:     for (l = 0, m = 0; l < Nl; ++l) {
7870:       DMLabel  label;
7871:       PetscInt val, defval, loc, nv;

7873:       if (!active[l]) continue;
7874:       PetscCall(DMGetLabelByNum(dm, l, &label));
7875:       PetscCall(DMLabelGetValue(label, p, &val));
7876:       PetscCall(DMLabelGetDefaultValue(label, &defval));
7877:       if (val == defval) {
7878:         ++m;
7879:         continue;
7880:       }
7881:       nv     = ul->offsets[m + 1] - ul->offsets[m];
7882:       marked = PETSC_TRUE;
7883:       PetscCall(PetscFindInt(val, nv, &ul->values[ul->offsets[m]], &loc));
7884:       PetscCheck(loc >= 0, PETSC_COMM_SELF, PETSC_ERR_PLIB, "Label value %" PetscInt_FMT " not found in compression array", val);
7885:       uval += (loc + 1) << ul->bits[m];
7886:       ++m;
7887:     }
7888:     if (marked) PetscCall(DMLabelSetValue(ul->label, p, uval));
7889:   }
7890:   PetscCall(PetscFree(active));
7891:   *universal = ul;
7892:   PetscFunctionReturn(PETSC_SUCCESS);
7893: }

7895: PetscErrorCode DMUniversalLabelDestroy(DMUniversalLabel *universal)
7896: {
7897:   PetscInt l;

7899:   PetscFunctionBegin;
7900:   for (l = 0; l < (*universal)->Nl; ++l) PetscCall(PetscFree((*universal)->names[l]));
7901:   PetscCall(DMLabelDestroy(&(*universal)->label));
7902:   PetscCall(PetscFree5((*universal)->names, (*universal)->indices, (*universal)->offsets, (*universal)->bits, (*universal)->masks));
7903:   PetscCall(PetscFree((*universal)->values));
7904:   PetscCall(PetscFree(*universal));
7905:   *universal = NULL;
7906:   PetscFunctionReturn(PETSC_SUCCESS);
7907: }

7909: PetscErrorCode DMUniversalLabelGetLabel(DMUniversalLabel ul, DMLabel *ulabel)
7910: {
7911:   PetscFunctionBegin;
7912:   PetscAssertPointer(ulabel, 2);
7913:   *ulabel = ul->label;
7914:   PetscFunctionReturn(PETSC_SUCCESS);
7915: }

7917: PetscErrorCode DMUniversalLabelCreateLabels(DMUniversalLabel ul, PetscBool preserveOrder, DM dm)
7918: {
7919:   PetscInt Nl = ul->Nl, l;

7921:   PetscFunctionBegin;
7923:   for (l = 0; l < Nl; ++l) {
7924:     if (preserveOrder) PetscCall(DMCreateLabelAtIndex(dm, ul->indices[l], ul->names[l]));
7925:     else PetscCall(DMCreateLabel(dm, ul->names[l]));
7926:   }
7927:   if (preserveOrder) {
7928:     for (l = 0; l < ul->Nl; ++l) {
7929:       const char *name;
7930:       PetscBool   match;

7932:       PetscCall(DMGetLabelName(dm, ul->indices[l], &name));
7933:       PetscCall(PetscStrcmp(name, ul->names[l], &match));
7934:       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]);
7935:     }
7936:   }
7937:   PetscFunctionReturn(PETSC_SUCCESS);
7938: }

7940: PetscErrorCode DMUniversalLabelSetLabelValue(DMUniversalLabel ul, DM dm, PetscBool useIndex, PetscInt p, PetscInt value)
7941: {
7942:   PetscFunctionBegin;
7943:   for (PetscInt l = 0; l < ul->Nl; ++l) {
7944:     DMLabel  label;
7945:     PetscInt lval = (value & ul->masks[l]) >> ul->bits[l];

7947:     if (lval) {
7948:       if (useIndex) PetscCall(DMGetLabelByNum(dm, ul->indices[l], &label));
7949:       else PetscCall(DMGetLabel(dm, ul->names[l], &label));
7950:       PetscCall(DMLabelSetValue(label, p, ul->values[ul->offsets[l] + lval - 1]));
7951:     }
7952:   }
7953:   PetscFunctionReturn(PETSC_SUCCESS);
7954: }

7956: /*@
7957:   DMGetCoarseDM - Get the coarse `DM`from which this `DM` was obtained by refinement

7959:   Not Collective

7961:   Input Parameter:
7962: . dm - The `DM` object

7964:   Output Parameter:
7965: . cdm - The coarse `DM`

7967:   Level: intermediate

7969: .seealso: [](ch_dmbase), `DM`, `DMSetCoarseDM()`, `DMCoarsen()`
7970: @*/
7971: PetscErrorCode DMGetCoarseDM(DM dm, DM *cdm)
7972: {
7973:   PetscFunctionBegin;
7975:   PetscAssertPointer(cdm, 2);
7976:   *cdm = dm->coarseMesh;
7977:   PetscFunctionReturn(PETSC_SUCCESS);
7978: }

7980: /*@
7981:   DMSetCoarseDM - Set the coarse `DM` from which this `DM` was obtained by refinement

7983:   Input Parameters:
7984: + dm  - The `DM` object
7985: - cdm - The coarse `DM`

7987:   Level: intermediate

7989:   Note:
7990:   Normally this is set automatically by `DMRefine()`

7992: .seealso: [](ch_dmbase), `DM`, `DMGetCoarseDM()`, `DMCoarsen()`, `DMSetRefine()`, `DMSetFineDM()`
7993: @*/
7994: PetscErrorCode DMSetCoarseDM(DM dm, DM cdm)
7995: {
7996:   PetscFunctionBegin;
7999:   if (dm == cdm) cdm = NULL;
8000:   PetscCall(PetscObjectReference((PetscObject)cdm));
8001:   PetscCall(DMDestroy(&dm->coarseMesh));
8002:   dm->coarseMesh = cdm;
8003:   PetscFunctionReturn(PETSC_SUCCESS);
8004: }

8006: /*@
8007:   DMGetFineDM - Get the fine mesh from which this `DM` was obtained by coarsening

8009:   Input Parameter:
8010: . dm - The `DM` object

8012:   Output Parameter:
8013: . fdm - The fine `DM`

8015:   Level: intermediate

8017: .seealso: [](ch_dmbase), `DM`, `DMSetFineDM()`, `DMCoarsen()`, `DMRefine()`
8018: @*/
8019: PetscErrorCode DMGetFineDM(DM dm, DM *fdm)
8020: {
8021:   PetscFunctionBegin;
8023:   PetscAssertPointer(fdm, 2);
8024:   *fdm = dm->fineMesh;
8025:   PetscFunctionReturn(PETSC_SUCCESS);
8026: }

8028: /*@
8029:   DMSetFineDM - Set the fine mesh from which this was obtained by coarsening

8031:   Input Parameters:
8032: + dm  - The `DM` object
8033: - fdm - The fine `DM`

8035:   Level: developer

8037:   Note:
8038:   Normally this is set automatically by `DMCoarsen()`

8040: .seealso: [](ch_dmbase), `DM`, `DMGetFineDM()`, `DMCoarsen()`, `DMRefine()`
8041: @*/
8042: PetscErrorCode DMSetFineDM(DM dm, DM fdm)
8043: {
8044:   PetscFunctionBegin;
8047:   if (dm == fdm) fdm = NULL;
8048:   PetscCall(PetscObjectReference((PetscObject)fdm));
8049:   PetscCall(DMDestroy(&dm->fineMesh));
8050:   dm->fineMesh = fdm;
8051:   PetscFunctionReturn(PETSC_SUCCESS);
8052: }

8054: /*@C
8055:   DMAddBoundary - Add a boundary condition, for a single field, to a model represented by a `DM`

8057:   Collective

8059:   Input Parameters:
8060: + dm       - The `DM`, with a `PetscDS` that matches the problem being constrained
8061: . type     - The type of condition, e.g. `DM_BC_ESSENTIAL_ANALYTIC`, `DM_BC_ESSENTIAL_FIELD` (Dirichlet), or `DM_BC_NATURAL` (Neumann)
8062: . name     - The BC name
8063: . label    - The label defining constrained points
8064: . Nv       - The number of `DMLabel` values for constrained points
8065: . values   - An array of values for constrained points
8066: . field    - The field to constrain
8067: . Nc       - The number of constrained field components (0 will constrain all components)
8068: . comps    - An array of constrained component numbers
8069: . bcFunc   - A pointwise function giving boundary values
8070: . bcFunc_t - A pointwise function giving the time derivative of the boundary values, or `NULL`
8071: - ctx      - An optional user context for bcFunc

8073:   Output Parameter:
8074: . bd - (Optional) Boundary number

8076:   Options Database Keys:
8077: + -bc_NAME values     - Overrides the boundary ids for boundary named NAME
8078: - -bc_NAME_comp comps - Overrides the boundary components for boundary named NAME

8080:   Level: intermediate

8082:   Notes:
8083:   If the `DM` is of type `DMPLEX` and the field is of type `PetscFE`, then this function completes the label using `DMPlexLabelComplete()`.

8085:   Both bcFunc and bcFunc_t will depend on the boundary condition type. If the type if `DM_BC_ESSENTIAL`, then the calling sequence is\:
8086: .vb
8087:  void bcFunc(PetscInt dim, PetscReal time, const PetscReal x[], PetscInt Nc, PetscScalar bcval[])
8088: .ve

8090:   If the type is `DM_BC_ESSENTIAL_FIELD` or other _FIELD value, then the calling sequence is\:

8092: .vb
8093:   void bcFunc(PetscInt dim, PetscInt Nf, PetscInt NfAux,
8094:               const PetscInt uOff[], const PetscInt uOff_x[], const PetscScalar u[], const PetscScalar u_t[], const PetscScalar u_x[],
8095:               const PetscInt aOff[], const PetscInt aOff_x[], const PetscScalar a[], const PetscScalar a_t[], const PetscScalar a_x[],
8096:               PetscReal time, const PetscReal x[], PetscScalar bcval[])
8097: .ve
8098: + dim - the spatial dimension
8099: . Nf - the number of fields
8100: . uOff - the offset into u[] and u_t[] for each field
8101: . uOff_x - the offset into u_x[] for each field
8102: . u - each field evaluated at the current point
8103: . u_t - the time derivative of each field evaluated at the current point
8104: . u_x - the gradient of each field evaluated at the current point
8105: . aOff - the offset into a[] and a_t[] for each auxiliary field
8106: . aOff_x - the offset into a_x[] for each auxiliary field
8107: . a - each auxiliary field evaluated at the current point
8108: . a_t - the time derivative of each auxiliary field evaluated at the current point
8109: . a_x - the gradient of auxiliary each field evaluated at the current point
8110: . t - current time
8111: . x - coordinates of the current point
8112: . numConstants - number of constant parameters
8113: . constants - constant parameters
8114: - bcval - output values at the current point

8116: .seealso: [](ch_dmbase), `DM`, `DSGetBoundary()`, `PetscDSAddBoundary()`
8117: @*/
8118: 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)
8119: {
8120:   PetscDS ds;

8122:   PetscFunctionBegin;
8129:   PetscCheck(!dm->localSection, PetscObjectComm((PetscObject)dm), PETSC_ERR_ARG_WRONGSTATE, "Cannot add boundary to DM after creating local section");
8130:   PetscCall(DMGetDS(dm, &ds));
8131:   /* Complete label */
8132:   if (label) {
8133:     PetscObject  obj;
8134:     PetscClassId id;

8136:     PetscCall(DMGetField(dm, field, NULL, &obj));
8137:     PetscCall(PetscObjectGetClassId(obj, &id));
8138:     if (id == PETSCFE_CLASSID) {
8139:       DM plex;

8141:       PetscCall(DMConvert(dm, DMPLEX, &plex));
8142:       if (plex) PetscCall(DMPlexLabelComplete(plex, label));
8143:       PetscCall(DMDestroy(&plex));
8144:     }
8145:   }
8146:   PetscCall(PetscDSAddBoundary(ds, type, name, label, Nv, values, field, Nc, comps, bcFunc, bcFunc_t, ctx, bd));
8147:   PetscFunctionReturn(PETSC_SUCCESS);
8148: }

8150: /* TODO Remove this since now the structures are the same */
8151: static PetscErrorCode DMPopulateBoundary(DM dm)
8152: {
8153:   PetscDS     ds;
8154:   DMBoundary *lastnext;
8155:   DSBoundary  dsbound;

8157:   PetscFunctionBegin;
8158:   PetscCall(DMGetDS(dm, &ds));
8159:   dsbound = ds->boundary;
8160:   if (dm->boundary) {
8161:     DMBoundary next = dm->boundary;

8163:     /* quick check to see if the PetscDS has changed */
8164:     if (next->dsboundary == dsbound) PetscFunctionReturn(PETSC_SUCCESS);
8165:     /* the PetscDS has changed: tear down and rebuild */
8166:     while (next) {
8167:       DMBoundary b = next;

8169:       next = b->next;
8170:       PetscCall(PetscFree(b));
8171:     }
8172:     dm->boundary = NULL;
8173:   }

8175:   lastnext = &dm->boundary;
8176:   while (dsbound) {
8177:     DMBoundary dmbound;

8179:     PetscCall(PetscNew(&dmbound));
8180:     dmbound->dsboundary = dsbound;
8181:     dmbound->label      = dsbound->label;
8182:     /* push on the back instead of the front so that it is in the same order as in the PetscDS */
8183:     *lastnext = dmbound;
8184:     lastnext  = &dmbound->next;
8185:     dsbound   = dsbound->next;
8186:   }
8187:   PetscFunctionReturn(PETSC_SUCCESS);
8188: }

8190: /* TODO: missing manual page */
8191: PetscErrorCode DMIsBoundaryPoint(DM dm, PetscInt point, PetscBool *isBd)
8192: {
8193:   DMBoundary b;

8195:   PetscFunctionBegin;
8197:   PetscAssertPointer(isBd, 3);
8198:   *isBd = PETSC_FALSE;
8199:   PetscCall(DMPopulateBoundary(dm));
8200:   b = dm->boundary;
8201:   while (b && !*isBd) {
8202:     DMLabel    label = b->label;
8203:     DSBoundary dsb   = b->dsboundary;

8205:     if (label) {
8206:       for (PetscInt i = 0; i < dsb->Nv && !*isBd; ++i) PetscCall(DMLabelStratumHasPoint(label, dsb->values[i], point, isBd));
8207:     }
8208:     b = b->next;
8209:   }
8210:   PetscFunctionReturn(PETSC_SUCCESS);
8211: }

8213: /*@
8214:   DMHasBound - Determine whether a bound condition was specified

8216:   Logically collective

8218:   Input Parameter:
8219: . dm - The `DM`, with a `PetscDS` that matches the problem being constrained

8221:   Output Parameter:
8222: . hasBound - Flag indicating if a bound condition was specified

8224:   Level: intermediate

8226: .seealso: [](ch_dmbase), `DM`, `DSAddBoundary()`, `PetscDSAddBoundary()`
8227: @*/
8228: PetscErrorCode DMHasBound(DM dm, PetscBool *hasBound)
8229: {
8230:   PetscDS  ds;
8231:   PetscInt Nf, numBd;

8233:   PetscFunctionBegin;
8234:   *hasBound = PETSC_FALSE;
8235:   PetscCall(DMGetDS(dm, &ds));
8236:   PetscCall(PetscDSGetNumFields(ds, &Nf));
8237:   for (PetscInt f = 0; f < Nf; ++f) {
8238:     PetscSimplePointFn *lfunc, *ufunc;

8240:     PetscCall(PetscDSGetLowerBound(ds, f, &lfunc, NULL));
8241:     PetscCall(PetscDSGetUpperBound(ds, f, &ufunc, NULL));
8242:     if (lfunc || ufunc) *hasBound = PETSC_TRUE;
8243:   }

8245:   PetscCall(PetscDSGetNumBoundary(ds, &numBd));
8246:   PetscCall(PetscDSUpdateBoundaryLabels(ds, dm));
8247:   for (PetscInt b = 0; b < numBd; ++b) {
8248:     PetscWeakForm           wf;
8249:     DMBoundaryConditionType type;
8250:     const char             *name;
8251:     DMLabel                 label;
8252:     PetscInt                numids;
8253:     const PetscInt         *ids;
8254:     PetscInt                field, Nc;
8255:     const PetscInt         *comps;
8256:     PetscVoidFn            *bvfunc;
8257:     void                   *ctx;

8259:     PetscCall(PetscDSGetBoundary(ds, b, &wf, &type, &name, &label, &numids, &ids, &field, &Nc, &comps, &bvfunc, NULL, &ctx));
8260:     if (type == DM_BC_LOWER_BOUND || type == DM_BC_UPPER_BOUND) *hasBound = PETSC_TRUE;
8261:   }
8262:   PetscFunctionReturn(PETSC_SUCCESS);
8263: }

8265: /*@C
8266:   DMProjectFunction - This projects the given function into the function space provided by a `DM`, putting the coefficients in a global vector.

8268:   Collective

8270:   Input Parameters:
8271: + dm    - The `DM`
8272: . time  - The time
8273: . funcs - The coordinate functions to evaluate, one per field
8274: . ctxs  - Optional array of contexts to pass to each coordinate function.  ctxs itself may be null.
8275: - mode  - The insertion mode for values

8277:   Output Parameter:
8278: . X - vector

8280:   Calling sequence of `funcs`:
8281: + dim  - The spatial dimension
8282: . time - The time at which to sample
8283: . x    - The coordinates
8284: . Nc   - The number of components
8285: . u    - The output field values
8286: - ctx  - optional function context

8288:   Level: developer

8290:   Developer Notes:
8291:   This API is specific to only particular usage of `DM`

8293:   The notes need to provide some information about what has to be provided to the `DM` to be able to perform the computation.

8295: .seealso: [](ch_dmbase), `DM`, `DMProjectFunctionLocal()`, `DMProjectFunctionLabel()`, `DMComputeL2Diff()`
8296: @*/
8297: 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)
8298: {
8299:   Vec localX;

8301:   PetscFunctionBegin;
8303:   PetscCall(PetscLogEventBegin(DM_ProjectFunction, dm, X, 0, 0));
8304:   PetscCall(DMGetLocalVector(dm, &localX));
8305:   PetscCall(VecSet(localX, 0.));
8306:   PetscCall(DMProjectFunctionLocal(dm, time, funcs, ctxs, mode, localX));
8307:   PetscCall(DMLocalToGlobalBegin(dm, localX, mode, X));
8308:   PetscCall(DMLocalToGlobalEnd(dm, localX, mode, X));
8309:   PetscCall(DMRestoreLocalVector(dm, &localX));
8310:   PetscCall(PetscLogEventEnd(DM_ProjectFunction, dm, X, 0, 0));
8311:   PetscFunctionReturn(PETSC_SUCCESS);
8312: }

8314: /*@C
8315:   DMProjectFunctionLocal - This projects the given function into the function space provided by a `DM`, putting the coefficients in a local vector.

8317:   Not Collective

8319:   Input Parameters:
8320: + dm    - The `DM`
8321: . time  - The time
8322: . funcs - The coordinate functions to evaluate, one per field
8323: . ctxs  - Optional array of contexts to pass to each coordinate function.  ctxs itself may be null.
8324: - mode  - The insertion mode for values

8326:   Output Parameter:
8327: . localX - vector

8329:   Calling sequence of `funcs`:
8330: + dim  - The spatial dimension
8331: . time - The current timestep
8332: . x    - The coordinates
8333: . Nc   - The number of components
8334: . u    - The output field values
8335: - ctx  - optional function context

8337:   Level: developer

8339:   Developer Notes:
8340:   This API is specific to only particular usage of `DM`

8342:   The notes need to provide some information about what has to be provided to the `DM` to be able to perform the computation.

8344: .seealso: [](ch_dmbase), `DM`, `DMProjectFunction()`, `DMProjectFunctionLabel()`, `DMComputeL2Diff()`
8345: @*/
8346: 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)
8347: {
8348:   PetscFunctionBegin;
8351:   PetscUseTypeMethod(dm, projectfunctionlocal, time, funcs, ctxs, mode, localX);
8352:   PetscFunctionReturn(PETSC_SUCCESS);
8353: }

8355: /*@C
8356:   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.

8358:   Collective

8360:   Input Parameters:
8361: + dm     - The `DM`
8362: . time   - The time
8363: . numIds - The number of ids
8364: . ids    - The ids
8365: . Nc     - The number of components
8366: . comps  - The components
8367: . label  - The `DMLabel` selecting the portion of the mesh for projection
8368: . funcs  - The coordinate functions to evaluate, one per field
8369: . ctxs   - Optional array of contexts to pass to each coordinate function.  ctxs may be null.
8370: - mode   - The insertion mode for values

8372:   Output Parameter:
8373: . X - vector

8375:   Calling sequence of `funcs`:
8376: + dim  - The spatial dimension
8377: . time - The current timestep
8378: . x    - The coordinates
8379: . Nc   - The number of components
8380: . u    - The output field values
8381: - ctx  - optional function context

8383:   Level: developer

8385:   Developer Notes:
8386:   This API is specific to only particular usage of `DM`

8388:   The notes need to provide some information about what has to be provided to the `DM` to be able to perform the computation.

8390: .seealso: [](ch_dmbase), `DM`, `DMProjectFunction()`, `DMProjectFunctionLocal()`, `DMProjectFunctionLabelLocal()`, `DMComputeL2Diff()`
8391: @*/
8392: 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)
8393: {
8394:   Vec localX;

8396:   PetscFunctionBegin;
8398:   PetscCall(DMGetLocalVector(dm, &localX));
8399:   PetscCall(VecSet(localX, 0.));
8400:   PetscCall(DMProjectFunctionLabelLocal(dm, time, label, numIds, ids, Nc, comps, funcs, ctxs, mode, localX));
8401:   PetscCall(DMLocalToGlobalBegin(dm, localX, mode, X));
8402:   PetscCall(DMLocalToGlobalEnd(dm, localX, mode, X));
8403:   PetscCall(DMRestoreLocalVector(dm, &localX));
8404:   PetscFunctionReturn(PETSC_SUCCESS);
8405: }

8407: /*@C
8408:   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.

8410:   Not Collective

8412:   Input Parameters:
8413: + dm     - The `DM`
8414: . time   - The time
8415: . label  - The `DMLabel` selecting the portion of the mesh for projection
8416: . numIds - The number of ids
8417: . ids    - The ids
8418: . Nc     - The number of components
8419: . comps  - The components
8420: . funcs  - The coordinate functions to evaluate, one per field
8421: . ctxs   - Optional array of contexts to pass to each coordinate function.  ctxs itself may be null.
8422: - mode   - The insertion mode for values

8424:   Output Parameter:
8425: . localX - vector

8427:   Calling sequence of `funcs`:
8428: + dim  - The spatial dimension
8429: . time - The current time
8430: . x    - The coordinates
8431: . Nc   - The number of components
8432: . u    - The output field values
8433: - ctx  - optional function context

8435:   Level: developer

8437:   Developer Notes:
8438:   This API is specific to only particular usage of `DM`

8440:   The notes need to provide some information about what has to be provided to the `DM` to be able to perform the computation.

8442: .seealso: [](ch_dmbase), `DM`, `DMProjectFunction()`, `DMProjectFunctionLocal()`, `DMProjectFunctionLabel()`, `DMComputeL2Diff()`
8443: @*/
8444: 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)
8445: {
8446:   PetscFunctionBegin;
8449:   PetscUseTypeMethod(dm, projectfunctionlabellocal, time, label, numIds, ids, Nc, comps, funcs, ctxs, mode, localX);
8450:   PetscFunctionReturn(PETSC_SUCCESS);
8451: }

8453: /*@C
8454:   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.

8456:   Not Collective

8458:   Input Parameters:
8459: + dm     - The `DM`
8460: . time   - The time
8461: . localU - The input field vector; may be `NULL` if projection is defined purely by coordinates
8462: . funcs  - The functions to evaluate, one per field
8463: - mode   - The insertion mode for values

8465:   Output Parameter:
8466: . localX - The output vector

8468:   Calling sequence of `funcs`:
8469: + dim          - The spatial dimension
8470: . Nf           - The number of input fields
8471: . NfAux        - The number of input auxiliary fields
8472: . uOff         - The offset of each field in u[]
8473: . uOff_x       - The offset of each field in u_x[]
8474: . u            - The field values at this point in space
8475: . u_t          - The field time derivative at this point in space (or `NULL`)
8476: . u_x          - The field derivatives at this point in space
8477: . aOff         - The offset of each auxiliary field in u[]
8478: . aOff_x       - The offset of each auxiliary field in u_x[]
8479: . a            - The auxiliary field values at this point in space
8480: . a_t          - The auxiliary field time derivative at this point in space (or `NULL`)
8481: . a_x          - The auxiliary field derivatives at this point in space
8482: . t            - The current time
8483: . x            - The coordinates of this point
8484: . numConstants - The number of constants
8485: . constants    - The value of each constant
8486: - f            - The value of the function at this point in space

8488:   Level: intermediate

8490:   Note:
8491:   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.
8492:   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
8493:   a subdomain. You can also output a different number of fields than the input, with different discretizations. Last the auxiliary `DM`, attached to the
8494:   auxiliary field vector, which is attached to dm, can also be different. It can have a different topology, number of fields, and discretizations.

8496:   Developer Notes:
8497:   This API is specific to only particular usage of `DM`

8499:   The notes need to provide some information about what has to be provided to the `DM` to be able to perform the computation.

8501: .seealso: [](ch_dmbase), `DM`, `DMProjectField()`, `DMProjectFieldLabelLocal()`,
8502: `DMProjectFunction()`, `DMComputeL2Diff()`
8503: @*/
8504: 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)
8505: {
8506:   PetscFunctionBegin;
8510:   PetscUseTypeMethod(dm, projectfieldlocal, time, localU, funcs, mode, localX);
8511:   PetscFunctionReturn(PETSC_SUCCESS);
8512: }

8514: /*@C
8515:   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.

8517:   Not Collective

8519:   Input Parameters:
8520: + dm     - The `DM`
8521: . time   - The time
8522: . label  - The `DMLabel` marking the portion of the domain to output
8523: . numIds - The number of label ids to use
8524: . ids    - The label ids to use for marking
8525: . Nc     - The number of components to set in the output, or `PETSC_DETERMINE` for all components
8526: . comps  - The components to set in the output, or `NULL` for all components
8527: . localU - The input field vector
8528: . funcs  - The functions to evaluate, one per field
8529: - mode   - The insertion mode for values

8531:   Output Parameter:
8532: . localX - The output vector

8534:   Calling sequence of `funcs`:
8535: + dim          - The spatial dimension
8536: . Nf           - The number of input fields
8537: . NfAux        - The number of input auxiliary fields
8538: . uOff         - The offset of each field in u[]
8539: . uOff_x       - The offset of each field in u_x[]
8540: . u            - The field values at this point in space
8541: . u_t          - The field time derivative at this point in space (or `NULL`)
8542: . u_x          - The field derivatives at this point in space
8543: . aOff         - The offset of each auxiliary field in u[]
8544: . aOff_x       - The offset of each auxiliary field in u_x[]
8545: . a            - The auxiliary field values at this point in space
8546: . a_t          - The auxiliary field time derivative at this point in space (or `NULL`)
8547: . a_x          - The auxiliary field derivatives at this point in space
8548: . t            - The current time
8549: . x            - The coordinates of this point
8550: . numConstants - The number of constants
8551: . constants    - The value of each constant
8552: - f            - The value of the function at this point in space

8554:   Level: intermediate

8556:   Note:
8557:   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.
8558:   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
8559:   a subdomain. You can also output a different number of fields than the input, with different discretizations. Last the auxiliary `DM`, attached to the
8560:   auxiliary field vector, which is attached to dm, can also be different. It can have a different topology, number of fields, and discretizations.

8562:   Developer Notes:
8563:   This API is specific to only particular usage of `DM`

8565:   The notes need to provide some information about what has to be provided to the `DM` to be able to perform the computation.

8567: .seealso: [](ch_dmbase), `DM`, `DMProjectField()`, `DMProjectFieldLabel()`, `DMProjectFunction()`, `DMComputeL2Diff()`
8568: @*/
8569: 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)
8570: {
8571:   PetscFunctionBegin;
8575:   PetscUseTypeMethod(dm, projectfieldlabellocal, time, label, numIds, ids, Nc, comps, localU, funcs, mode, localX);
8576:   PetscFunctionReturn(PETSC_SUCCESS);
8577: }

8579: /*@C
8580:   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.

8582:   Not Collective

8584:   Input Parameters:
8585: + dm     - The `DM`
8586: . time   - The time
8587: . label  - The `DMLabel` marking the portion of the domain to output
8588: . numIds - The number of label ids to use
8589: . ids    - The label ids to use for marking
8590: . Nc     - The number of components to set in the output, or `PETSC_DETERMINE` for all components
8591: . comps  - The components to set in the output, or `NULL` for all components
8592: . U      - The input field vector
8593: . funcs  - The functions to evaluate, one per field
8594: - mode   - The insertion mode for values

8596:   Output Parameter:
8597: . X - The output vector

8599:   Calling sequence of `funcs`:
8600: + dim          - The spatial dimension
8601: . Nf           - The number of input fields
8602: . NfAux        - The number of input auxiliary fields
8603: . uOff         - The offset of each field in u[]
8604: . uOff_x       - The offset of each field in u_x[]
8605: . u            - The field values at this point in space
8606: . u_t          - The field time derivative at this point in space (or `NULL`)
8607: . u_x          - The field derivatives at this point in space
8608: . aOff         - The offset of each auxiliary field in u[]
8609: . aOff_x       - The offset of each auxiliary field in u_x[]
8610: . a            - The auxiliary field values at this point in space
8611: . a_t          - The auxiliary field time derivative at this point in space (or `NULL`)
8612: . a_x          - The auxiliary field derivatives at this point in space
8613: . t            - The current time
8614: . x            - The coordinates of this point
8615: . numConstants - The number of constants
8616: . constants    - The value of each constant
8617: - f            - The value of the function at this point in space

8619:   Level: intermediate

8621:   Note:
8622:   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.
8623:   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
8624:   a subdomain. You can also output a different number of fields than the input, with different discretizations. Last the auxiliary `DM`, attached to the
8625:   auxiliary field vector, which is attached to dm, can also be different. It can have a different topology, number of fields, and discretizations.

8627:   Developer Notes:
8628:   This API is specific to only particular usage of `DM`

8630:   The notes need to provide some information about what has to be provided to the `DM` to be able to perform the computation.

8632: .seealso: [](ch_dmbase), `DM`, `DMProjectField()`, `DMProjectFieldLabelLocal()`, `DMProjectFunction()`, `DMComputeL2Diff()`
8633: @*/
8634: 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)
8635: {
8636:   DM  dmIn;
8637:   Vec localU, localX;

8639:   PetscFunctionBegin;
8641:   PetscCall(VecGetDM(U, &dmIn));
8642:   PetscCall(DMGetLocalVector(dmIn, &localU));
8643:   PetscCall(DMGetLocalVector(dm, &localX));
8644:   PetscCall(VecSet(localX, 0.));
8645:   PetscCall(DMGlobalToLocalBegin(dmIn, U, mode, localU));
8646:   PetscCall(DMGlobalToLocalEnd(dmIn, U, mode, localU));
8647:   PetscCall(DMProjectFieldLabelLocal(dm, time, label, numIds, ids, Nc, comps, localU, funcs, mode, localX));
8648:   PetscCall(DMLocalToGlobalBegin(dm, localX, mode, X));
8649:   PetscCall(DMLocalToGlobalEnd(dm, localX, mode, X));
8650:   PetscCall(DMRestoreLocalVector(dm, &localX));
8651:   PetscCall(DMRestoreLocalVector(dmIn, &localU));
8652:   PetscFunctionReturn(PETSC_SUCCESS);
8653: }

8655: /*@C
8656:   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.

8658:   Not Collective

8660:   Input Parameters:
8661: + dm     - The `DM`
8662: . time   - The time
8663: . label  - The `DMLabel` marking the portion of the domain boundary to output
8664: . numIds - The number of label ids to use
8665: . ids    - The label ids to use for marking
8666: . Nc     - The number of components to set in the output, or `PETSC_DETERMINE` for all components
8667: . comps  - The components to set in the output, or `NULL` for all components
8668: . localU - The input field vector
8669: . funcs  - The functions to evaluate, one per field
8670: - mode   - The insertion mode for values

8672:   Output Parameter:
8673: . localX - The output vector

8675:   Calling sequence of `funcs`:
8676: + dim          - The spatial dimension
8677: . Nf           - The number of input fields
8678: . NfAux        - The number of input auxiliary fields
8679: . uOff         - The offset of each field in u[]
8680: . uOff_x       - The offset of each field in u_x[]
8681: . u            - The field values at this point in space
8682: . u_t          - The field time derivative at this point in space (or `NULL`)
8683: . u_x          - The field derivatives at this point in space
8684: . aOff         - The offset of each auxiliary field in u[]
8685: . aOff_x       - The offset of each auxiliary field in u_x[]
8686: . a            - The auxiliary field values at this point in space
8687: . a_t          - The auxiliary field time derivative at this point in space (or `NULL`)
8688: . a_x          - The auxiliary field derivatives at this point in space
8689: . t            - The current time
8690: . x            - The coordinates of this point
8691: . n            - The face normal
8692: . numConstants - The number of constants
8693: . constants    - The value of each constant
8694: - f            - The value of the function at this point in space

8696:   Level: intermediate

8698:   Note:
8699:   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.
8700:   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
8701:   a subdomain. You can also output a different number of fields than the input, with different discretizations. Last the auxiliary `DM`, attached to the
8702:   auxiliary field vector, which is attached to dm, can also be different. It can have a different topology, number of fields, and discretizations.

8704:   Developer Notes:
8705:   This API is specific to only particular usage of `DM`

8707:   The notes need to provide some information about what has to be provided to the `DM` to be able to perform the computation.

8709: .seealso: [](ch_dmbase), `DM`, `DMProjectField()`, `DMProjectFieldLabelLocal()`, `DMProjectFunction()`, `DMComputeL2Diff()`
8710: @*/
8711: 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)
8712: {
8713:   PetscFunctionBegin;
8717:   PetscUseTypeMethod(dm, projectbdfieldlabellocal, time, label, numIds, ids, Nc, comps, localU, funcs, mode, localX);
8718:   PetscFunctionReturn(PETSC_SUCCESS);
8719: }

8721: /*@C
8722:   DMComputeL2Diff - This function computes the L_2 difference between a function u and an FEM interpolant solution u_h.

8724:   Collective

8726:   Input Parameters:
8727: + dm    - The `DM`
8728: . time  - The time
8729: . funcs - The functions to evaluate for each field component
8730: . ctxs  - Optional array of contexts to pass to each function, or `NULL`.
8731: - X     - The coefficient vector u_h, a global vector

8733:   Output Parameter:
8734: . diff - The diff ||u - u_h||_2

8736:   Level: developer

8738:   Developer Notes:
8739:   This API is specific to only particular usage of `DM`

8741:   The notes need to provide some information about what has to be provided to the `DM` to be able to perform the computation.

8743: .seealso: [](ch_dmbase), `DM`, `DMProjectFunction()`, `DMComputeL2FieldDiff()`, `DMComputeL2GradientDiff()`
8744: @*/
8745: PetscErrorCode DMComputeL2Diff(DM dm, PetscReal time, PetscErrorCode (**funcs)(PetscInt, PetscReal, const PetscReal[], PetscInt, PetscScalar *, void *), void **ctxs, Vec X, PetscReal *diff)
8746: {
8747:   PetscFunctionBegin;
8750:   PetscUseTypeMethod(dm, computel2diff, time, funcs, ctxs, X, diff);
8751:   PetscFunctionReturn(PETSC_SUCCESS);
8752: }

8754: /*@C
8755:   DMComputeL2GradientDiff - This function computes the L_2 difference between the gradient of a function u and an FEM interpolant solution grad u_h.

8757:   Collective

8759:   Input Parameters:
8760: + dm    - The `DM`
8761: . time  - The time
8762: . funcs - The gradient functions to evaluate for each field component
8763: . ctxs  - Optional array of contexts to pass to each function, or `NULL`.
8764: . X     - The coefficient vector u_h, a global vector
8765: - n     - The vector to project along

8767:   Output Parameter:
8768: . diff - The diff ||(grad u - grad u_h) . n||_2

8770:   Level: developer

8772:   Developer Notes:
8773:   This API is specific to only particular usage of `DM`

8775:   The notes need to provide some information about what has to be provided to the `DM` to be able to perform the computation.

8777: .seealso: [](ch_dmbase), `DM`, `DMProjectFunction()`, `DMComputeL2Diff()`, `DMComputeL2FieldDiff()`
8778: @*/
8779: 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)
8780: {
8781:   PetscFunctionBegin;
8784:   PetscUseTypeMethod(dm, computel2gradientdiff, time, funcs, ctxs, X, n, diff);
8785:   PetscFunctionReturn(PETSC_SUCCESS);
8786: }

8788: /*@C
8789:   DMComputeL2FieldDiff - This function computes the L_2 difference between a function u and an FEM interpolant solution u_h, separated into field components.

8791:   Collective

8793:   Input Parameters:
8794: + dm    - The `DM`
8795: . time  - The time
8796: . funcs - The functions to evaluate for each field component
8797: . ctxs  - Optional array of contexts to pass to each function, or `NULL`.
8798: - X     - The coefficient vector u_h, a global vector

8800:   Output Parameter:
8801: . diff - The array of differences, ||u^f - u^f_h||_2

8803:   Level: developer

8805:   Developer Notes:
8806:   This API is specific to only particular usage of `DM`

8808:   The notes need to provide some information about what has to be provided to the `DM` to be able to perform the computation.

8810: .seealso: [](ch_dmbase), `DM`, `DMProjectFunction()`, `DMComputeL2GradientDiff()`
8811: @*/
8812: PetscErrorCode DMComputeL2FieldDiff(DM dm, PetscReal time, PetscErrorCode (**funcs)(PetscInt, PetscReal, const PetscReal[], PetscInt, PetscScalar *, void *), void **ctxs, Vec X, PetscReal diff[])
8813: {
8814:   PetscFunctionBegin;
8817:   PetscUseTypeMethod(dm, computel2fielddiff, time, funcs, ctxs, X, diff);
8818:   PetscFunctionReturn(PETSC_SUCCESS);
8819: }

8821: /*@C
8822:   DMGetNeighbors - Gets an array containing the MPI ranks of all the processes neighbors

8824:   Not Collective

8826:   Input Parameter:
8827: . dm - The `DM`

8829:   Output Parameters:
8830: + nranks - the number of neighbours
8831: - ranks  - the neighbors ranks

8833:   Level: beginner

8835:   Note:
8836:   Do not free the array, it is freed when the `DM` is destroyed.

8838: .seealso: [](ch_dmbase), `DM`, `DMDAGetNeighbors()`, `PetscSFGetRootRanks()`
8839: @*/
8840: PetscErrorCode DMGetNeighbors(DM dm, PetscInt *nranks, const PetscMPIInt *ranks[])
8841: {
8842:   PetscFunctionBegin;
8844:   PetscUseTypeMethod(dm, getneighbors, nranks, ranks);
8845:   PetscFunctionReturn(PETSC_SUCCESS);
8846: }

8848: #include <petsc/private/matimpl.h>

8850: /*
8851:     Converts the input vector to a ghosted vector and then calls the standard coloring code.
8852:     This must be a different function because it requires DM which is not defined in the Mat library
8853: */
8854: static PetscErrorCode MatFDColoringApply_AIJDM(Mat J, MatFDColoring coloring, Vec x1, void *sctx)
8855: {
8856:   PetscFunctionBegin;
8857:   if (coloring->ctype == IS_COLORING_LOCAL) {
8858:     Vec x1local;
8859:     DM  dm;
8860:     PetscCall(MatGetDM(J, &dm));
8861:     PetscCheck(dm, PetscObjectComm((PetscObject)J), PETSC_ERR_ARG_INCOMP, "IS_COLORING_LOCAL requires a DM");
8862:     PetscCall(DMGetLocalVector(dm, &x1local));
8863:     PetscCall(DMGlobalToLocalBegin(dm, x1, INSERT_VALUES, x1local));
8864:     PetscCall(DMGlobalToLocalEnd(dm, x1, INSERT_VALUES, x1local));
8865:     x1 = x1local;
8866:   }
8867:   PetscCall(MatFDColoringApply_AIJ(J, coloring, x1, sctx));
8868:   if (coloring->ctype == IS_COLORING_LOCAL) {
8869:     DM dm;
8870:     PetscCall(MatGetDM(J, &dm));
8871:     PetscCall(DMRestoreLocalVector(dm, &x1));
8872:   }
8873:   PetscFunctionReturn(PETSC_SUCCESS);
8874: }

8876: /*@
8877:   MatFDColoringUseDM - allows a `MatFDColoring` object to use the `DM` associated with the matrix to compute a `IS_COLORING_LOCAL` coloring

8879:   Input Parameters:
8880: + coloring   - The matrix to get the `DM` from
8881: - fdcoloring - the `MatFDColoring` object

8883:   Level: advanced

8885:   Developer Note:
8886:   This routine exists because the PETSc `Mat` library does not know about the `DM` objects

8888: .seealso: [](ch_dmbase), `DM`, `MatFDColoring`, `MatFDColoringCreate()`, `ISColoringType`
8889: @*/
8890: PetscErrorCode MatFDColoringUseDM(Mat coloring, MatFDColoring fdcoloring)
8891: {
8892:   PetscFunctionBegin;
8893:   coloring->ops->fdcoloringapply = MatFDColoringApply_AIJDM;
8894:   PetscFunctionReturn(PETSC_SUCCESS);
8895: }

8897: /*@
8898:   DMGetCompatibility - determine if two `DM`s are compatible

8900:   Collective

8902:   Input Parameters:
8903: + dm1 - the first `DM`
8904: - dm2 - the second `DM`

8906:   Output Parameters:
8907: + compatible - whether or not the two `DM`s are compatible
8908: - set        - whether or not the compatible value was actually determined and set

8910:   Level: advanced

8912:   Notes:
8913:   Two `DM`s are deemed compatible if they represent the same parallel decomposition
8914:   of the same topology. This implies that the section (field data) on one
8915:   "makes sense" with respect to the topology and parallel decomposition of the other.
8916:   Loosely speaking, compatible `DM`s represent the same domain and parallel
8917:   decomposition, but hold different data.

8919:   Typically, one would confirm compatibility if intending to simultaneously iterate
8920:   over a pair of vectors obtained from different `DM`s.

8922:   For example, two `DMDA` objects are compatible if they have the same local
8923:   and global sizes and the same stencil width. They can have different numbers
8924:   of degrees of freedom per node. Thus, one could use the node numbering from
8925:   either `DM` in bounds for a loop over vectors derived from either `DM`.

8927:   Consider the operation of summing data living on a 2-dof `DMDA` to data living
8928:   on a 1-dof `DMDA`, which should be compatible, as in the following snippet.
8929: .vb
8930:   ...
8931:   PetscCall(DMGetCompatibility(da1,da2,&compatible,&set));
8932:   if (set && compatible)  {
8933:     PetscCall(DMDAVecGetArrayDOF(da1,vec1,&arr1));
8934:     PetscCall(DMDAVecGetArrayDOF(da2,vec2,&arr2));
8935:     PetscCall(DMDAGetCorners(da1,&x,&y,NULL,&m,&n,NULL));
8936:     for (j=y; j<y+n; ++j) {
8937:       for (i=x; i<x+m, ++i) {
8938:         arr1[j][i][0] = arr2[j][i][0] + arr2[j][i][1];
8939:       }
8940:     }
8941:     PetscCall(DMDAVecRestoreArrayDOF(da1,vec1,&arr1));
8942:     PetscCall(DMDAVecRestoreArrayDOF(da2,vec2,&arr2));
8943:   } else {
8944:     SETERRQ(PetscObjectComm((PetscObject)da1,PETSC_ERR_ARG_INCOMP,"DMDA objects incompatible");
8945:   }
8946:   ...
8947: .ve

8949:   Checking compatibility might be expensive for a given implementation of `DM`,
8950:   or might be impossible to unambiguously confirm or deny. For this reason,
8951:   this function may decline to determine compatibility, and hence users should
8952:   always check the "set" output parameter.

8954:   A `DM` is always compatible with itself.

8956:   In the current implementation, `DM`s which live on "unequal" communicators
8957:   (MPI_UNEQUAL in the terminology of MPI_Comm_compare()) are always deemed
8958:   incompatible.

8960:   This function is labeled "Collective," as information about all subdomains
8961:   is required on each rank. However, in `DM` implementations which store all this
8962:   information locally, this function may be merely "Logically Collective".

8964:   Developer Note:
8965:   Compatibility is assumed to be a symmetric concept; `DM` A is compatible with `DM` B
8966:   iff B is compatible with A. Thus, this function checks the implementations
8967:   of both dm and dmc (if they are of different types), attempting to determine
8968:   compatibility. It is left to `DM` implementers to ensure that symmetry is
8969:   preserved. The simplest way to do this is, when implementing type-specific
8970:   logic for this function, is to check for existing logic in the implementation
8971:   of other `DM` types and let *set = PETSC_FALSE if found.

8973: .seealso: [](ch_dmbase), `DM`, `DMDACreateCompatibleDMDA()`, `DMStagCreateCompatibleDMStag()`
8974: @*/
8975: PetscErrorCode DMGetCompatibility(DM dm1, DM dm2, PetscBool *compatible, PetscBool *set)
8976: {
8977:   PetscMPIInt compareResult;
8978:   DMType      type, type2;
8979:   PetscBool   sameType;

8981:   PetscFunctionBegin;

8985:   /* Declare a DM compatible with itself */
8986:   if (dm1 == dm2) {
8987:     *set        = PETSC_TRUE;
8988:     *compatible = PETSC_TRUE;
8989:     PetscFunctionReturn(PETSC_SUCCESS);
8990:   }

8992:   /* Declare a DM incompatible with a DM that lives on an "unequal"
8993:      communicator. Note that this does not preclude compatibility with
8994:      DMs living on "congruent" or "similar" communicators, but this must be
8995:      determined by the implementation-specific logic */
8996:   PetscCallMPI(MPI_Comm_compare(PetscObjectComm((PetscObject)dm1), PetscObjectComm((PetscObject)dm2), &compareResult));
8997:   if (compareResult == MPI_UNEQUAL) {
8998:     *set        = PETSC_TRUE;
8999:     *compatible = PETSC_FALSE;
9000:     PetscFunctionReturn(PETSC_SUCCESS);
9001:   }

9003:   /* Pass to the implementation-specific routine, if one exists. */
9004:   if (dm1->ops->getcompatibility) {
9005:     PetscUseTypeMethod(dm1, getcompatibility, dm2, compatible, set);
9006:     if (*set) PetscFunctionReturn(PETSC_SUCCESS);
9007:   }

9009:   /* If dm1 and dm2 are of different types, then attempt to check compatibility
9010:      with an implementation of this function from dm2 */
9011:   PetscCall(DMGetType(dm1, &type));
9012:   PetscCall(DMGetType(dm2, &type2));
9013:   PetscCall(PetscStrcmp(type, type2, &sameType));
9014:   if (!sameType && dm2->ops->getcompatibility) {
9015:     PetscUseTypeMethod(dm2, getcompatibility, dm1, compatible, set); /* Note argument order */
9016:   } else {
9017:     *set = PETSC_FALSE;
9018:   }
9019:   PetscFunctionReturn(PETSC_SUCCESS);
9020: }

9022: /*@C
9023:   DMMonitorSet - Sets an additional monitor function that is to be used after a solve to monitor discretization performance.

9025:   Logically Collective

9027:   Input Parameters:
9028: + dm             - the `DM`
9029: . f              - the monitor function
9030: . mctx           - [optional] context for private data for the monitor routine (use `NULL` if no context is desired)
9031: - monitordestroy - [optional] routine that frees monitor context (may be `NULL`), see `PetscCtxDestroyFn` for the calling sequence

9033:   Options Database Key:
9034: . -dm_monitor_cancel - cancels all monitors that have been hardwired into a code by calls to `DMMonitorSet()`, but
9035:                        does not cancel those set via the options database.

9037:   Level: intermediate

9039:   Note:
9040:   Several different monitoring routines may be set by calling
9041:   `DMMonitorSet()` multiple times or with `DMMonitorSetFromOptions()`; all will be called in the
9042:   order in which they were set.

9044:   Fortran Note:
9045:   Only a single monitor function can be set for each `DM` object

9047:   Developer Note:
9048:   This API has a generic name but seems specific to a very particular aspect of the use of `DM`

9050: .seealso: [](ch_dmbase), `DM`, `DMMonitorCancel()`, `DMMonitorSetFromOptions()`, `DMMonitor()`, `PetscCtxDestroyFn`
9051: @*/
9052: PetscErrorCode DMMonitorSet(DM dm, PetscErrorCode (*f)(DM, void *), void *mctx, PetscCtxDestroyFn *monitordestroy)
9053: {
9054:   PetscFunctionBegin;
9056:   for (PetscInt m = 0; m < dm->numbermonitors; ++m) {
9057:     PetscBool identical;

9059:     PetscCall(PetscMonitorCompare((PetscErrorCode (*)(void))(PetscVoidFn *)f, mctx, monitordestroy, (PetscErrorCode (*)(void))(PetscVoidFn *)dm->monitor[m], dm->monitorcontext[m], dm->monitordestroy[m], &identical));
9060:     if (identical) PetscFunctionReturn(PETSC_SUCCESS);
9061:   }
9062:   PetscCheck(dm->numbermonitors < MAXDMMONITORS, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Too many monitors set");
9063:   dm->monitor[dm->numbermonitors]          = f;
9064:   dm->monitordestroy[dm->numbermonitors]   = monitordestroy;
9065:   dm->monitorcontext[dm->numbermonitors++] = mctx;
9066:   PetscFunctionReturn(PETSC_SUCCESS);
9067: }

9069: /*@
9070:   DMMonitorCancel - Clears all the monitor functions for a `DM` object.

9072:   Logically Collective

9074:   Input Parameter:
9075: . dm - the DM

9077:   Options Database Key:
9078: . -dm_monitor_cancel - cancels all monitors that have been hardwired
9079:   into a code by calls to `DMonitorSet()`, but does not cancel those
9080:   set via the options database

9082:   Level: intermediate

9084:   Note:
9085:   There is no way to clear one specific monitor from a `DM` object.

9087: .seealso: [](ch_dmbase), `DM`, `DMMonitorSet()`, `DMMonitorSetFromOptions()`, `DMMonitor()`
9088: @*/
9089: PetscErrorCode DMMonitorCancel(DM dm)
9090: {
9091:   PetscFunctionBegin;
9093:   for (PetscInt m = 0; m < dm->numbermonitors; ++m) {
9094:     if (dm->monitordestroy[m]) PetscCall((*dm->monitordestroy[m])(&dm->monitorcontext[m]));
9095:   }
9096:   dm->numbermonitors = 0;
9097:   PetscFunctionReturn(PETSC_SUCCESS);
9098: }

9100: /*@C
9101:   DMMonitorSetFromOptions - Sets a monitor function and viewer appropriate for the type indicated by the user

9103:   Collective

9105:   Input Parameters:
9106: + dm           - `DM` object you wish to monitor
9107: . name         - the monitor type one is seeking
9108: . help         - message indicating what monitoring is done
9109: . manual       - manual page for the monitor
9110: . monitor      - the monitor function, this must use a `PetscViewerFormat` as its context
9111: - 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

9113:   Output Parameter:
9114: . flg - Flag set if the monitor was created

9116:   Calling sequence of `monitor`:
9117: + dm  - the `DM` to be monitored
9118: - ctx - monitor context

9120:   Calling sequence of `monitorsetup`:
9121: + dm - the `DM` to be monitored
9122: - vf - the `PetscViewer` and format to be used by the monitor

9124:   Level: developer

9126: .seealso: [](ch_dmbase), `DM`, `PetscOptionsCreateViewer()`, `PetscOptionsGetReal()`, `PetscOptionsHasName()`, `PetscOptionsGetString()`,
9127:           `PetscOptionsGetIntArray()`, `PetscOptionsGetRealArray()`, `PetscOptionsBool()`,
9128:           `PetscOptionsInt()`, `PetscOptionsString()`, `PetscOptionsReal()`,
9129:           `PetscOptionsName()`, `PetscOptionsBegin()`, `PetscOptionsEnd()`, `PetscOptionsHeadBegin()`,
9130:           `PetscOptionsStringArray()`, `PetscOptionsRealArray()`, `PetscOptionsScalar()`,
9131:           `PetscOptionsBoolGroupBegin()`, `PetscOptionsBoolGroup()`, `PetscOptionsBoolGroupEnd()`,
9132:           `PetscOptionsFList()`, `PetscOptionsEList()`, `DMMonitor()`, `DMMonitorSet()`
9133: @*/
9134: 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)
9135: {
9136:   PetscViewer       viewer;
9137:   PetscViewerFormat format;

9139:   PetscFunctionBegin;
9141:   PetscCall(PetscOptionsCreateViewer(PetscObjectComm((PetscObject)dm), ((PetscObject)dm)->options, ((PetscObject)dm)->prefix, name, &viewer, &format, flg));
9142:   if (*flg) {
9143:     PetscViewerAndFormat *vf;

9145:     PetscCall(PetscViewerAndFormatCreate(viewer, format, &vf));
9146:     PetscCall(PetscViewerDestroy(&viewer));
9147:     if (monitorsetup) PetscCall((*monitorsetup)(dm, vf));
9148:     PetscCall(DMMonitorSet(dm, monitor, vf, (PetscCtxDestroyFn *)PetscViewerAndFormatDestroy));
9149:   }
9150:   PetscFunctionReturn(PETSC_SUCCESS);
9151: }

9153: /*@
9154:   DMMonitor - runs the user provided monitor routines, if they exist

9156:   Collective

9158:   Input Parameter:
9159: . dm - The `DM`

9161:   Level: developer

9163:   Developer Note:
9164:   Note should indicate when during the life of the `DM` the monitor is run. It appears to be
9165:   related to the discretization process seems rather specialized since some `DM` have no
9166:   concept of discretization.

9168: .seealso: [](ch_dmbase), `DM`, `DMMonitorSet()`, `DMMonitorSetFromOptions()`
9169: @*/
9170: PetscErrorCode DMMonitor(DM dm)
9171: {
9172:   PetscFunctionBegin;
9173:   if (!dm) PetscFunctionReturn(PETSC_SUCCESS);
9175:   for (PetscInt m = 0; m < dm->numbermonitors; ++m) PetscCall((*dm->monitor[m])(dm, dm->monitorcontext[m]));
9176:   PetscFunctionReturn(PETSC_SUCCESS);
9177: }

9179: /*@
9180:   DMComputeError - Computes the error assuming the user has provided the exact solution functions

9182:   Collective

9184:   Input Parameters:
9185: + dm  - The `DM`
9186: - sol - The solution vector

9188:   Input/Output Parameter:
9189: . errors - An array of length Nf, the number of fields, or `NULL` for no output; on output
9190:            contains the error in each field

9192:   Output Parameter:
9193: . errorVec - A vector to hold the cellwise error (may be `NULL`)

9195:   Level: developer

9197:   Note:
9198:   The exact solutions come from the `PetscDS` object, and the time comes from `DMGetOutputSequenceNumber()`.

9200: .seealso: [](ch_dmbase), `DM`, `DMMonitorSet()`, `DMGetRegionNumDS()`, `PetscDSGetExactSolution()`, `DMGetOutputSequenceNumber()`
9201: @*/
9202: PetscErrorCode DMComputeError(DM dm, Vec sol, PetscReal errors[], Vec *errorVec)
9203: {
9204:   PetscErrorCode (**exactSol)(PetscInt, PetscReal, const PetscReal[], PetscInt, PetscScalar[], void *);
9205:   void    **ctxs;
9206:   PetscReal time;
9207:   PetscInt  Nf, f, Nds, s;

9209:   PetscFunctionBegin;
9210:   PetscCall(DMGetNumFields(dm, &Nf));
9211:   PetscCall(PetscCalloc2(Nf, &exactSol, Nf, &ctxs));
9212:   PetscCall(DMGetNumDS(dm, &Nds));
9213:   for (s = 0; s < Nds; ++s) {
9214:     PetscDS         ds;
9215:     DMLabel         label;
9216:     IS              fieldIS;
9217:     const PetscInt *fields;
9218:     PetscInt        dsNf;

9220:     PetscCall(DMGetRegionNumDS(dm, s, &label, &fieldIS, &ds, NULL));
9221:     PetscCall(PetscDSGetNumFields(ds, &dsNf));
9222:     if (fieldIS) PetscCall(ISGetIndices(fieldIS, &fields));
9223:     for (f = 0; f < dsNf; ++f) {
9224:       const PetscInt field = fields[f];
9225:       PetscCall(PetscDSGetExactSolution(ds, field, &exactSol[field], &ctxs[field]));
9226:     }
9227:     if (fieldIS) PetscCall(ISRestoreIndices(fieldIS, &fields));
9228:   }
9229:   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);
9230:   PetscCall(DMGetOutputSequenceNumber(dm, NULL, &time));
9231:   if (errors) PetscCall(DMComputeL2FieldDiff(dm, time, exactSol, ctxs, sol, errors));
9232:   if (errorVec) {
9233:     DM             edm;
9234:     DMPolytopeType ct;
9235:     PetscBool      simplex;
9236:     PetscInt       dim, cStart, Nf;

9238:     PetscCall(DMClone(dm, &edm));
9239:     PetscCall(DMGetDimension(edm, &dim));
9240:     PetscCall(DMPlexGetHeightStratum(dm, 0, &cStart, NULL));
9241:     PetscCall(DMPlexGetCellType(dm, cStart, &ct));
9242:     simplex = DMPolytopeTypeGetNumVertices(ct) == DMPolytopeTypeGetDim(ct) + 1 ? PETSC_TRUE : PETSC_FALSE;
9243:     PetscCall(DMGetNumFields(dm, &Nf));
9244:     for (f = 0; f < Nf; ++f) {
9245:       PetscFE         fe, efe;
9246:       PetscQuadrature q;
9247:       const char     *name;

9249:       PetscCall(DMGetField(dm, f, NULL, (PetscObject *)&fe));
9250:       PetscCall(PetscFECreateLagrange(PETSC_COMM_SELF, dim, Nf, simplex, 0, PETSC_DETERMINE, &efe));
9251:       PetscCall(PetscObjectGetName((PetscObject)fe, &name));
9252:       PetscCall(PetscObjectSetName((PetscObject)efe, name));
9253:       PetscCall(PetscFEGetQuadrature(fe, &q));
9254:       PetscCall(PetscFESetQuadrature(efe, q));
9255:       PetscCall(DMSetField(edm, f, NULL, (PetscObject)efe));
9256:       PetscCall(PetscFEDestroy(&efe));
9257:     }
9258:     PetscCall(DMCreateDS(edm));

9260:     PetscCall(DMCreateGlobalVector(edm, errorVec));
9261:     PetscCall(PetscObjectSetName((PetscObject)*errorVec, "Error"));
9262:     PetscCall(DMPlexComputeL2DiffVec(dm, time, exactSol, ctxs, sol, *errorVec));
9263:     PetscCall(DMDestroy(&edm));
9264:   }
9265:   PetscCall(PetscFree2(exactSol, ctxs));
9266:   PetscFunctionReturn(PETSC_SUCCESS);
9267: }

9269: /*@
9270:   DMGetNumAuxiliaryVec - Get the number of auxiliary vectors associated with this `DM`

9272:   Not Collective

9274:   Input Parameter:
9275: . dm - The `DM`

9277:   Output Parameter:
9278: . numAux - The number of auxiliary data vectors

9280:   Level: advanced

9282: .seealso: [](ch_dmbase), `DM`, `DMClearAuxiliaryVec()`, `DMSetAuxiliaryVec()`, `DMGetAuxiliaryLabels()`, `DMGetAuxiliaryVec()`
9283: @*/
9284: PetscErrorCode DMGetNumAuxiliaryVec(DM dm, PetscInt *numAux)
9285: {
9286:   PetscFunctionBegin;
9288:   PetscCall(PetscHMapAuxGetSize(dm->auxData, numAux));
9289:   PetscFunctionReturn(PETSC_SUCCESS);
9290: }

9292: /*@
9293:   DMGetAuxiliaryVec - Get the auxiliary vector for region specified by the given label and value, and equation part

9295:   Not Collective

9297:   Input Parameters:
9298: + dm    - The `DM`
9299: . label - The `DMLabel`
9300: . value - The label value indicating the region
9301: - part  - The equation part, or 0 if unused

9303:   Output Parameter:
9304: . aux - The `Vec` holding auxiliary field data

9306:   Level: advanced

9308:   Note:
9309:   If no auxiliary vector is found for this (label, value), (`NULL`, 0, 0) is checked as well.

9311: .seealso: [](ch_dmbase), `DM`, `DMClearAuxiliaryVec()`, `DMSetAuxiliaryVec()`, `DMGetNumAuxiliaryVec()`, `DMGetAuxiliaryLabels()`
9312: @*/
9313: PetscErrorCode DMGetAuxiliaryVec(DM dm, DMLabel label, PetscInt value, PetscInt part, Vec *aux)
9314: {
9315:   PetscHashAuxKey key, wild = {NULL, 0, 0};
9316:   PetscBool       has;

9318:   PetscFunctionBegin;
9321:   key.label = label;
9322:   key.value = value;
9323:   key.part  = part;
9324:   PetscCall(PetscHMapAuxHas(dm->auxData, key, &has));
9325:   if (has) PetscCall(PetscHMapAuxGet(dm->auxData, key, aux));
9326:   else PetscCall(PetscHMapAuxGet(dm->auxData, wild, aux));
9327:   PetscFunctionReturn(PETSC_SUCCESS);
9328: }

9330: /*@
9331:   DMSetAuxiliaryVec - Set an auxiliary vector for region specified by the given label and value, and equation part

9333:   Not Collective because auxiliary vectors are not parallel

9335:   Input Parameters:
9336: + dm    - The `DM`
9337: . label - The `DMLabel`
9338: . value - The label value indicating the region
9339: . part  - The equation part, or 0 if unused
9340: - aux   - The `Vec` holding auxiliary field data

9342:   Level: advanced

9344: .seealso: [](ch_dmbase), `DM`, `DMClearAuxiliaryVec()`, `DMGetAuxiliaryVec()`, `DMGetAuxiliaryLabels()`, `DMCopyAuxiliaryVec()`
9345: @*/
9346: PetscErrorCode DMSetAuxiliaryVec(DM dm, DMLabel label, PetscInt value, PetscInt part, Vec aux)
9347: {
9348:   Vec             old;
9349:   PetscHashAuxKey key;

9351:   PetscFunctionBegin;
9354:   key.label = label;
9355:   key.value = value;
9356:   key.part  = part;
9357:   PetscCall(PetscHMapAuxGet(dm->auxData, key, &old));
9358:   PetscCall(PetscObjectReference((PetscObject)aux));
9359:   if (!aux) PetscCall(PetscHMapAuxDel(dm->auxData, key));
9360:   else PetscCall(PetscHMapAuxSet(dm->auxData, key, aux));
9361:   PetscCall(VecDestroy(&old));
9362:   PetscFunctionReturn(PETSC_SUCCESS);
9363: }

9365: /*@
9366:   DMGetAuxiliaryLabels - Get the labels, values, and parts for all auxiliary vectors in this `DM`

9368:   Not Collective

9370:   Input Parameter:
9371: . dm - The `DM`

9373:   Output Parameters:
9374: + labels - The `DMLabel`s for each `Vec`
9375: . values - The label values for each `Vec`
9376: - parts  - The equation parts for each `Vec`

9378:   Level: advanced

9380:   Note:
9381:   The arrays passed in must be at least as large as `DMGetNumAuxiliaryVec()`.

9383: .seealso: [](ch_dmbase), `DM`, `DMClearAuxiliaryVec()`, `DMGetNumAuxiliaryVec()`, `DMGetAuxiliaryVec()`, `DMSetAuxiliaryVec()`, `DMCopyAuxiliaryVec()`
9384: @*/
9385: PetscErrorCode DMGetAuxiliaryLabels(DM dm, DMLabel labels[], PetscInt values[], PetscInt parts[])
9386: {
9387:   PetscHashAuxKey *keys;
9388:   PetscInt         n, i, off = 0;

9390:   PetscFunctionBegin;
9392:   PetscAssertPointer(labels, 2);
9393:   PetscAssertPointer(values, 3);
9394:   PetscAssertPointer(parts, 4);
9395:   PetscCall(DMGetNumAuxiliaryVec(dm, &n));
9396:   PetscCall(PetscMalloc1(n, &keys));
9397:   PetscCall(PetscHMapAuxGetKeys(dm->auxData, &off, keys));
9398:   for (i = 0; i < n; ++i) {
9399:     labels[i] = keys[i].label;
9400:     values[i] = keys[i].value;
9401:     parts[i]  = keys[i].part;
9402:   }
9403:   PetscCall(PetscFree(keys));
9404:   PetscFunctionReturn(PETSC_SUCCESS);
9405: }

9407: /*@
9408:   DMCopyAuxiliaryVec - Copy the auxiliary vector data on a `DM` to a new `DM`

9410:   Not Collective

9412:   Input Parameter:
9413: . dm - The `DM`

9415:   Output Parameter:
9416: . dmNew - The new `DM`, now with the same auxiliary data

9418:   Level: advanced

9420:   Note:
9421:   This is a shallow copy of the auxiliary vectors

9423: .seealso: [](ch_dmbase), `DM`, `DMClearAuxiliaryVec()`, `DMGetNumAuxiliaryVec()`, `DMGetAuxiliaryVec()`, `DMSetAuxiliaryVec()`
9424: @*/
9425: PetscErrorCode DMCopyAuxiliaryVec(DM dm, DM dmNew)
9426: {
9427:   PetscFunctionBegin;
9430:   if (dm == dmNew) PetscFunctionReturn(PETSC_SUCCESS);
9431:   PetscCall(DMClearAuxiliaryVec(dmNew));

9433:   PetscCall(PetscHMapAuxDestroy(&dmNew->auxData));
9434:   PetscCall(PetscHMapAuxDuplicate(dm->auxData, &dmNew->auxData));
9435:   {
9436:     Vec     *auxData;
9437:     PetscInt n, i, off = 0;

9439:     PetscCall(PetscHMapAuxGetSize(dmNew->auxData, &n));
9440:     PetscCall(PetscMalloc1(n, &auxData));
9441:     PetscCall(PetscHMapAuxGetVals(dmNew->auxData, &off, auxData));
9442:     for (i = 0; i < n; ++i) PetscCall(PetscObjectReference((PetscObject)auxData[i]));
9443:     PetscCall(PetscFree(auxData));
9444:   }
9445:   PetscFunctionReturn(PETSC_SUCCESS);
9446: }

9448: /*@
9449:   DMClearAuxiliaryVec - Destroys the auxiliary vector information and creates a new empty one

9451:   Not Collective

9453:   Input Parameter:
9454: . dm - The `DM`

9456:   Level: advanced

9458: .seealso: [](ch_dmbase), `DM`, `DMCopyAuxiliaryVec()`, `DMGetNumAuxiliaryVec()`, `DMGetAuxiliaryVec()`, `DMSetAuxiliaryVec()`
9459: @*/
9460: PetscErrorCode DMClearAuxiliaryVec(DM dm)
9461: {
9462:   Vec     *auxData;
9463:   PetscInt n, i, off = 0;

9465:   PetscFunctionBegin;
9466:   PetscCall(PetscHMapAuxGetSize(dm->auxData, &n));
9467:   PetscCall(PetscMalloc1(n, &auxData));
9468:   PetscCall(PetscHMapAuxGetVals(dm->auxData, &off, auxData));
9469:   for (i = 0; i < n; ++i) PetscCall(VecDestroy(&auxData[i]));
9470:   PetscCall(PetscFree(auxData));
9471:   PetscCall(PetscHMapAuxDestroy(&dm->auxData));
9472:   PetscCall(PetscHMapAuxCreate(&dm->auxData));
9473:   PetscFunctionReturn(PETSC_SUCCESS);
9474: }

9476: /*@
9477:   DMPolytopeMatchOrientation - Determine an orientation (transformation) that takes the source face arrangement to the target face arrangement

9479:   Not Collective

9481:   Input Parameters:
9482: + ct         - The `DMPolytopeType`
9483: . sourceCone - The source arrangement of faces
9484: - targetCone - The target arrangement of faces

9486:   Output Parameters:
9487: + ornt  - The orientation (transformation) which will take the source arrangement to the target arrangement
9488: - found - Flag indicating that a suitable orientation was found

9490:   Level: advanced

9492:   Note:
9493:   An arrangement is a face order combined with an orientation for each face

9495:   Each orientation (transformation) is labeled with an integer from negative `DMPolytopeTypeGetNumArrangements(ct)`/2 to `DMPolytopeTypeGetNumArrangements(ct)`/2
9496:   that labels each arrangement (face ordering plus orientation for each face).

9498:   See `DMPolytopeMatchVertexOrientation()` to find a new vertex orientation that takes the source vertex arrangement to the target vertex arrangement

9500: .seealso: [](ch_dmbase), `DM`, `DMPolytopeGetOrientation()`, `DMPolytopeMatchVertexOrientation()`, `DMPolytopeGetVertexOrientation()`
9501: @*/
9502: PetscErrorCode DMPolytopeMatchOrientation(DMPolytopeType ct, const PetscInt sourceCone[], const PetscInt targetCone[], PetscInt *ornt, PetscBool *found)
9503: {
9504:   const PetscInt cS = DMPolytopeTypeGetConeSize(ct);
9505:   const PetscInt nO = DMPolytopeTypeGetNumArrangements(ct) / 2;
9506:   PetscInt       o, c;

9508:   PetscFunctionBegin;
9509:   if (!nO) {
9510:     *ornt  = 0;
9511:     *found = PETSC_TRUE;
9512:     PetscFunctionReturn(PETSC_SUCCESS);
9513:   }
9514:   for (o = -nO; o < nO; ++o) {
9515:     const PetscInt *arr = DMPolytopeTypeGetArrangement(ct, o);

9517:     for (c = 0; c < cS; ++c)
9518:       if (sourceCone[arr[c * 2]] != targetCone[c]) break;
9519:     if (c == cS) {
9520:       *ornt = o;
9521:       break;
9522:     }
9523:   }
9524:   *found = o == nO ? PETSC_FALSE : PETSC_TRUE;
9525:   PetscFunctionReturn(PETSC_SUCCESS);
9526: }

9528: /*@
9529:   DMPolytopeGetOrientation - Determine an orientation (transformation) that takes the source face arrangement to the target face arrangement

9531:   Not Collective

9533:   Input Parameters:
9534: + ct         - The `DMPolytopeType`
9535: . sourceCone - The source arrangement of faces
9536: - targetCone - The target arrangement of faces

9538:   Output Parameter:
9539: . ornt - The orientation (transformation) which will take the source arrangement to the target arrangement

9541:   Level: advanced

9543:   Note:
9544:   This function is the same as `DMPolytopeMatchOrientation()` except it will generate an error if no suitable orientation can be found.

9546:   Developer Note:
9547:   It is unclear why this function needs to exist since one can simply call `DMPolytopeMatchOrientation()` and error if none is found

9549: .seealso: [](ch_dmbase), `DM`, `DMPolytopeType`, `DMPolytopeMatchOrientation()`, `DMPolytopeGetVertexOrientation()`, `DMPolytopeMatchVertexOrientation()`
9550: @*/
9551: PetscErrorCode DMPolytopeGetOrientation(DMPolytopeType ct, const PetscInt sourceCone[], const PetscInt targetCone[], PetscInt *ornt)
9552: {
9553:   PetscBool found;

9555:   PetscFunctionBegin;
9556:   PetscCall(DMPolytopeMatchOrientation(ct, sourceCone, targetCone, ornt, &found));
9557:   PetscCheck(found, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Could not find orientation for %s", DMPolytopeTypes[ct]);
9558:   PetscFunctionReturn(PETSC_SUCCESS);
9559: }

9561: /*@
9562:   DMPolytopeMatchVertexOrientation - Determine an orientation (transformation) that takes the source vertex arrangement to the target vertex arrangement

9564:   Not Collective

9566:   Input Parameters:
9567: + ct         - The `DMPolytopeType`
9568: . sourceVert - The source arrangement of vertices
9569: - targetVert - The target arrangement of vertices

9571:   Output Parameters:
9572: + ornt  - The orientation (transformation) which will take the source arrangement to the target arrangement
9573: - found - Flag indicating that a suitable orientation was found

9575:   Level: advanced

9577:   Notes:
9578:   An arrangement is a vertex order

9580:   Each orientation (transformation) is labeled with an integer from negative `DMPolytopeTypeGetNumArrangements(ct)`/2 to `DMPolytopeTypeGetNumArrangements(ct)`/2
9581:   that labels each arrangement (vertex ordering).

9583:   See `DMPolytopeMatchOrientation()` to find a new face orientation that takes the source face arrangement to the target face arrangement

9585: .seealso: [](ch_dmbase), `DM`, `DMPolytopeType`, `DMPolytopeGetOrientation()`, `DMPolytopeMatchOrientation()`, `DMPolytopeTypeGetNumVertices()`, `DMPolytopeTypeGetVertexArrangement()`
9586: @*/
9587: PetscErrorCode DMPolytopeMatchVertexOrientation(DMPolytopeType ct, const PetscInt sourceVert[], const PetscInt targetVert[], PetscInt *ornt, PetscBool *found)
9588: {
9589:   const PetscInt cS = DMPolytopeTypeGetNumVertices(ct);
9590:   const PetscInt nO = DMPolytopeTypeGetNumArrangements(ct) / 2;
9591:   PetscInt       o, c;

9593:   PetscFunctionBegin;
9594:   if (!nO) {
9595:     *ornt  = 0;
9596:     *found = PETSC_TRUE;
9597:     PetscFunctionReturn(PETSC_SUCCESS);
9598:   }
9599:   for (o = -nO; o < nO; ++o) {
9600:     const PetscInt *arr = DMPolytopeTypeGetVertexArrangement(ct, o);

9602:     for (c = 0; c < cS; ++c)
9603:       if (sourceVert[arr[c]] != targetVert[c]) break;
9604:     if (c == cS) {
9605:       *ornt = o;
9606:       break;
9607:     }
9608:   }
9609:   *found = o == nO ? PETSC_FALSE : PETSC_TRUE;
9610:   PetscFunctionReturn(PETSC_SUCCESS);
9611: }

9613: /*@
9614:   DMPolytopeGetVertexOrientation - Determine an orientation (transformation) that takes the source vertex arrangement to the target vertex arrangement

9616:   Not Collective

9618:   Input Parameters:
9619: + ct         - The `DMPolytopeType`
9620: . sourceCone - The source arrangement of vertices
9621: - targetCone - The target arrangement of vertices

9623:   Output Parameter:
9624: . ornt - The orientation (transformation) which will take the source arrangement to the target arrangement

9626:   Level: advanced

9628:   Note:
9629:   This function is the same as `DMPolytopeMatchVertexOrientation()` except it errors if not orientation is possible.

9631:   Developer Note:
9632:   It is unclear why this function needs to exist since one can simply call `DMPolytopeMatchVertexOrientation()` and error if none is found

9634: .seealso: [](ch_dmbase), `DM`, `DMPolytopeType`, `DMPolytopeMatchVertexOrientation()`, `DMPolytopeGetOrientation()`
9635: @*/
9636: PetscErrorCode DMPolytopeGetVertexOrientation(DMPolytopeType ct, const PetscInt sourceCone[], const PetscInt targetCone[], PetscInt *ornt)
9637: {
9638:   PetscBool found;

9640:   PetscFunctionBegin;
9641:   PetscCall(DMPolytopeMatchVertexOrientation(ct, sourceCone, targetCone, ornt, &found));
9642:   PetscCheck(found, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Could not find orientation for %s", DMPolytopeTypes[ct]);
9643:   PetscFunctionReturn(PETSC_SUCCESS);
9644: }

9646: /*@
9647:   DMPolytopeInCellTest - Check whether a point lies inside the reference cell of given type

9649:   Not Collective

9651:   Input Parameters:
9652: + ct    - The `DMPolytopeType`
9653: - point - Coordinates of the point

9655:   Output Parameter:
9656: . inside - Flag indicating whether the point is inside the reference cell of given type

9658:   Level: advanced

9660: .seealso: [](ch_dmbase), `DM`, `DMPolytopeType`, `DMLocatePoints()`
9661: @*/
9662: PetscErrorCode DMPolytopeInCellTest(DMPolytopeType ct, const PetscReal point[], PetscBool *inside)
9663: {
9664:   PetscReal sum = 0.0;

9666:   PetscFunctionBegin;
9667:   *inside = PETSC_TRUE;
9668:   switch (ct) {
9669:   case DM_POLYTOPE_TRIANGLE:
9670:   case DM_POLYTOPE_TETRAHEDRON:
9671:     for (PetscInt d = 0; d < DMPolytopeTypeGetDim(ct); ++d) {
9672:       if (point[d] < -1.0) {
9673:         *inside = PETSC_FALSE;
9674:         break;
9675:       }
9676:       sum += point[d];
9677:     }
9678:     if (sum > PETSC_SMALL) {
9679:       *inside = PETSC_FALSE;
9680:       break;
9681:     }
9682:     break;
9683:   case DM_POLYTOPE_QUADRILATERAL:
9684:   case DM_POLYTOPE_HEXAHEDRON:
9685:     for (PetscInt d = 0; d < DMPolytopeTypeGetDim(ct); ++d)
9686:       if (PetscAbsReal(point[d]) > 1. + PETSC_SMALL) {
9687:         *inside = PETSC_FALSE;
9688:         break;
9689:       }
9690:     break;
9691:   default:
9692:     SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Unsupported polytope type %s", DMPolytopeTypes[ct]);
9693:   }
9694:   PetscFunctionReturn(PETSC_SUCCESS);
9695: }

9697: /*@
9698:   DMReorderSectionSetDefault - Set flag indicating whether the local section should be reordered by default

9700:   Logically collective

9702:   Input Parameters:
9703: + dm      - The DM
9704: - reorder - Flag for reordering

9706:   Level: intermediate

9708: .seealso: `DMReorderSectionGetDefault()`
9709: @*/
9710: PetscErrorCode DMReorderSectionSetDefault(DM dm, DMReorderDefaultFlag reorder)
9711: {
9712:   PetscFunctionBegin;
9714:   PetscTryMethod(dm, "DMReorderSectionSetDefault_C", (DM, DMReorderDefaultFlag), (dm, reorder));
9715:   PetscFunctionReturn(PETSC_SUCCESS);
9716: }

9718: /*@
9719:   DMReorderSectionGetDefault - Get flag indicating whether the local section should be reordered by default

9721:   Not collective

9723:   Input Parameter:
9724: . dm - The DM

9726:   Output Parameter:
9727: . reorder - Flag for reordering

9729:   Level: intermediate

9731: .seealso: `DMReorderSetDefault()`
9732: @*/
9733: PetscErrorCode DMReorderSectionGetDefault(DM dm, DMReorderDefaultFlag *reorder)
9734: {
9735:   PetscFunctionBegin;
9737:   PetscAssertPointer(reorder, 2);
9738:   *reorder = DM_REORDER_DEFAULT_NOTSET;
9739:   PetscTryMethod(dm, "DMReorderSectionGetDefault_C", (DM, DMReorderDefaultFlag *), (dm, reorder));
9740:   PetscFunctionReturn(PETSC_SUCCESS);
9741: }

9743: /*@
9744:   DMReorderSectionSetType - Set the type of local section reordering

9746:   Logically collective

9748:   Input Parameters:
9749: + dm      - The DM
9750: - reorder - The reordering method

9752:   Level: intermediate

9754: .seealso: `DMReorderSectionGetType()`, `DMReorderSectionSetDefault()`
9755: @*/
9756: PetscErrorCode DMReorderSectionSetType(DM dm, MatOrderingType reorder)
9757: {
9758:   PetscFunctionBegin;
9760:   PetscTryMethod(dm, "DMReorderSectionSetType_C", (DM, MatOrderingType), (dm, reorder));
9761:   PetscFunctionReturn(PETSC_SUCCESS);
9762: }

9764: /*@
9765:   DMReorderSectionGetType - Get the reordering type for the local section

9767:   Not collective

9769:   Input Parameter:
9770: . dm - The DM

9772:   Output Parameter:
9773: . reorder - The reordering method

9775:   Level: intermediate

9777: .seealso: `DMReorderSetDefault()`, `DMReorderSectionGetDefault()`
9778: @*/
9779: PetscErrorCode DMReorderSectionGetType(DM dm, MatOrderingType *reorder)
9780: {
9781:   PetscFunctionBegin;
9783:   PetscAssertPointer(reorder, 2);
9784:   *reorder = NULL;
9785:   PetscTryMethod(dm, "DMReorderSectionGetType_C", (DM, MatOrderingType *), (dm, reorder));
9786:   PetscFunctionReturn(PETSC_SUCCESS);
9787: }