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: #if PetscDefined(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     pEndMax = -1;

165:       PetscCall(DMGetLocalSection(dm->coordinates[i].dm, &cs));
166:       if (cs) PetscCall(PetscSectionGetChart(cs, NULL, &pEndMax));
167:       PetscCallMPI(MPIU_Allreduce(MPI_IN_PLACE, &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: #if PetscDefined(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, sizeof(typeName), &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 viewer_specification - See `PetscOptionsCreateViewer()` for the values of `viewer_specification`

927:   Level: intermediate

929:   Note:
930:   This checks the options database, creates the viewer on-the-fly, uses it and then destroys it. Hence it should not be called in heavily used routines,
931:   rather `PetscOptionsCreateViewer()` should be used to construct the viewer once which can then be utilized in the heavily used routine.

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

943: /*@
944:   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
945:   save the `DM` in a binary file to be loaded later or create a visualization of the `DM`

947:   Collective

949:   Input Parameters:
950: + dm - the `DM` object to view
951: - v  - the viewer

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

960:   Level: beginner

962:   Notes:

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

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

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

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

975:   `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.
976:   The order of the mesh shall be set using `PetscViewerExodusIISetOrder()`

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

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

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

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

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

1021: /*@
1022:   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,
1023:   that is it has no ghost locations.

1025:   Collective

1027:   Input Parameter:
1028: . dm - the `DM` object

1030:   Output Parameter:
1031: . vec - the global vector

1033:   Level: beginner

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

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

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

1057: /*@
1058:   DMCreateLocalVector - Creates a local vector from a `DM` object.

1060:   Not Collective

1062:   Input Parameter:
1063: . dm - the `DM` object

1065:   Output Parameter:
1066: . vec - the local vector

1068:   Level: beginner

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

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

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

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

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

1097:   Collective

1099:   Input Parameter:
1100: . dm - the `DM` that provides the mapping

1102:   Output Parameter:
1103: . ltog - the mapping

1105:   Level: advanced

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

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

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

1115:   If the `DM` has a local section, it must have been set up with `PetscSectionSetUp()` before the mapping is built, otherwise an error is raised.

1117:   The mapping is owned by the `DM`: do not destroy it. A mapping derived from the sections is invalidated by a subsequent call to `DMSetLocalSection()` or
1118:   `DMSetGlobalSection()`.

1120: .seealso: [](ch_dmbase), `DM`, `DMCreateLocalVector()`, `DMCreateGlobalVector()`, `VecSetLocalToGlobalMapping()`, `MatSetLocalToGlobalMapping()`,
1121:           `DMCreateMatrix()`
1122: @*/
1123: PetscErrorCode DMGetLocalToGlobalMapping(DM dm, ISLocalToGlobalMapping *ltog)
1124: {
1125:   PetscInt bs = -1, bsLocal[2], bsMinMax[2];

1127:   PetscFunctionBegin;
1129:   PetscAssertPointer(ltog, 2);
1130:   if (!dm->ltogmap) {
1131:     PetscSection section, sectionGlobal;

1133:     PetscCall(DMGetLocalSection(dm, &section));
1134:     if (section) {
1135:       const PetscInt *cdofs;
1136:       PetscInt       *ltog;
1137:       PetscInt        pStart, pEnd, n, p, k, l;
1138:       PetscBT         seen;

1140:       // The loop below indexes by the local section offsets, which are uninitialized before PetscSectionSetUp()
1141:       PetscCheck(section->setup, PetscObjectComm((PetscObject)dm), PETSC_ERR_ARG_WRONGSTATE, "The local section must be set up with PetscSectionSetUp() before DMGetLocalToGlobalMapping()");
1142:       PetscCall(DMGetGlobalSection(dm, &sectionGlobal));
1143:       PetscCall(PetscSectionGetChart(section, &pStart, &pEnd));
1144:       PetscCall(PetscSectionGetStorageSize(section, &n));
1145:       PetscCall(PetscMalloc1(n, &ltog)); /* We want the local+overlap size */
1146:       PetscCall(PetscBTCreate(n, &seen));
1147:       for (p = pStart; p < pEnd; ++p) {
1148:         PetscInt bdof, cdof, dof, off, loff, c, cind;

1150:         /* Should probably use constrained dofs */
1151:         PetscCall(PetscSectionGetDof(section, p, &dof));
1152:         PetscCall(PetscSectionGetConstraintDof(section, p, &cdof));
1153:         PetscCall(PetscSectionGetConstraintIndices(section, p, &cdofs));
1154:         PetscCall(PetscSectionGetOffset(sectionGlobal, p, &off));
1155:         PetscCall(PetscSectionGetOffset(section, p, &loff));
1156:         /* A set-up section can still carry offsets that do not index the local storage, e.g. a field-major
1157:            section, whose point offsets PetscSectionSetUp() disables by setting them to -1 */
1158:         PetscCheck(!dof || (loff >= 0 && loff + dof <= n), PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Local section offset %" PetscInt_FMT " + dof %" PetscInt_FMT " of point %" PetscInt_FMT " is outside the local storage [0, %" PetscInt_FMT ")", loff, dof, p, n);
1159:         /* If you have dofs, and constraints, and they are unequal, we set the blocksize to 1 */
1160:         bdof = cdof && (dof - cdof) ? 1 : dof;
1161:         if (dof) bs = bs < 0 ? bdof : PetscGCD(bs, bdof);

1163:         for (c = 0, cind = 0; c < dof; ++c) {
1164:           l = loff + c;
1165:           /* The storage size n is the sum of the dofs, so exactly n in-range slots are written: if no slot
1166:              is written twice, the offsets tile [0, n) and every ltog[] entry is set (a non-bijective section
1167:              permutation violates this, since PetscSectionSetPermutation() does not check for duplicates) */
1168:           PetscCheck(!PetscBTLookupSet(seen, l), PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Local section offsets overlap: slot %" PetscInt_FMT " of point %" PetscInt_FMT " was already filled by another point", l, p);
1169:           if (cind < cdof && c == cdofs[cind]) {
1170:             ltog[l] = off < 0 ? off - c : -(off + c + 1);
1171:             cind++;
1172:           } else {
1173:             ltog[l] = (off < 0 ? -(off + 1) : off) + c - cind;
1174:           }
1175:         }
1176:       }
1177:       PetscCall(PetscBTDestroy(&seen));
1178:       /* Must have same blocksize on all procs (some might have no points) */
1179:       bsLocal[0] = bs < 0 ? PETSC_INT_MAX : bs;
1180:       bsLocal[1] = bs;
1181:       PetscCall(PetscGlobalMinMaxInt(PetscObjectComm((PetscObject)dm), bsLocal, bsMinMax));
1182:       if (bsMinMax[0] != bsMinMax[1]) bs = 1;
1183:       else bs = bsMinMax[0];
1184:       bs = bs < 0 ? 1 : bs;
1185:       /* Must reduce indices by blocksize */
1186:       if (bs > 1) {
1187:         for (l = 0, k = 0; l < n; l += bs, ++k) {
1188:           // Integer division of negative values truncates toward zero(!), not toward negative infinity
1189:           ltog[k] = ltog[l] >= 0 ? ltog[l] / bs : -(-(ltog[l] + 1) / bs + 1);
1190:         }
1191:         n /= bs;
1192:       }
1193:       PetscCall(ISLocalToGlobalMappingCreate(PetscObjectComm((PetscObject)dm), bs, n, ltog, PETSC_OWN_POINTER, &dm->ltogmap));
1194:       dm->ltogmapFromSection = PETSC_TRUE;
1195:     } else {
1196:       PetscUseTypeMethod(dm, getlocaltoglobalmapping);
1197:       dm->ltogmapFromSection = PETSC_FALSE;
1198:     }
1199:   }
1200:   *ltog = dm->ltogmap;
1201:   PetscFunctionReturn(PETSC_SUCCESS);
1202: }

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

1207:   Not Collective

1209:   Input Parameter:
1210: . dm - the `DM` with block structure

1212:   Output Parameter:
1213: . bs - the block size, 1 implies no exploitable block structure

1215:   Level: intermediate

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

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

1223: .seealso: [](ch_dmbase), `DM`, `ISCreateBlock()`, `VecSetBlockSize()`, `MatSetBlockSize()`, `DMGetLocalToGlobalMapping()`
1224: @*/
1225: PetscErrorCode DMGetBlockSize(DM dm, PetscInt *bs)
1226: {
1227:   PetscFunctionBegin;
1229:   PetscAssertPointer(bs, 2);
1230:   PetscCheck(dm->bs >= 1, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "DM does not have enough information to provide a block size yet");
1231:   *bs = dm->bs;
1232:   PetscFunctionReturn(PETSC_SUCCESS);
1233: }

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

1239:   Collective

1241:   Input Parameters:
1242: + dmc - the `DM` object
1243: - dmf - the second, finer `DM` object

1245:   Output Parameters:
1246: + mat - the interpolation
1247: - vec - the scaling (optional, pass `NULL` if not needed), see `DMCreateInterpolationScale()`

1249:   Level: developer

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

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

1258: .seealso: [](ch_dmbase), `DM`, `DMDestroy()`, `DMView()`, `DMCreateGlobalVector()`, `DMCreateColoring()`, `DMCreateMatrix()`, `DMCreateMassMatrix()`, `DMRefine()`, `DMCoarsen()`, `DMCreateRestriction()`, `DMCreateInterpolationScale()`
1259: @*/
1260: PetscErrorCode DMCreateInterpolation(DM dmc, DM dmf, Mat *mat, Vec *vec)
1261: {
1262:   PetscFunctionBegin;
1265:   PetscAssertPointer(mat, 3);
1266:   PetscCall(PetscLogEventBegin(DM_CreateInterpolation, dmc, dmf, 0, 0));
1267:   PetscUseTypeMethod(dmc, createinterpolation, dmf, mat, vec);
1268:   PetscCall(PetscLogEventEnd(DM_CreateInterpolation, dmc, dmf, 0, 0));
1269:   PetscFunctionReturn(PETSC_SUCCESS);
1270: }

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

1276:   Input Parameters:
1277: + dac - `DM` that defines a coarse mesh
1278: . daf - `DM` that defines a fine mesh
1279: - mat - the restriction (or interpolation operator) from fine to coarse

1281:   Output Parameter:
1282: . scale - the scaled vector

1284:   Level: advanced

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

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

1294: .seealso: [](ch_dmbase), `DM`, `MatRestrict()`, `MatInterpolate()`, `DMCreateInterpolation()`, `DMCreateRestriction()`, `DMCreateGlobalVector()`
1295: @*/
1296: PetscErrorCode DMCreateInterpolationScale(DM dac, DM daf, Mat mat, Vec *scale)
1297: {
1298:   Vec         fine;
1299:   PetscScalar one = 1.0;
1300: #if PetscDefined(HAVE_CUDA)
1301:   PetscBool bindingpropagates, isbound;
1302: #endif

1304:   PetscFunctionBegin;
1305:   PetscCall(DMCreateGlobalVector(daf, &fine));
1306:   PetscCall(DMCreateGlobalVector(dac, scale));
1307:   PetscCall(VecSet(fine, one));
1308: #if PetscDefined(HAVE_CUDA)
1309:   /* If the 'fine' Vec is bound to the CPU, it makes sense to bind 'mat' as well.
1310:    * Note that we only do this for the CUDA case, right now, but if we add support for MatMultTranspose() via ViennaCL,
1311:    * we'll need to do it for that case, too.*/
1312:   PetscCall(VecGetBindingPropagates(fine, &bindingpropagates));
1313:   if (bindingpropagates) {
1314:     PetscCall(MatSetBindingPropagates(mat, PETSC_TRUE));
1315:     PetscCall(VecBoundToCPU(fine, &isbound));
1316:     PetscCall(MatBindToCPU(mat, isbound));
1317:   }
1318: #endif
1319:   PetscCall(MatRestrict(mat, fine, *scale));
1320:   PetscCall(VecDestroy(&fine));
1321:   PetscCall(VecReciprocal(*scale));
1322:   PetscFunctionReturn(PETSC_SUCCESS);
1323: }

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

1329:   Collective

1331:   Input Parameters:
1332: + dmc - the `DM` object
1333: - dmf - the second, finer `DM` object

1335:   Output Parameter:
1336: . mat - the restriction

1338:   Level: developer

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

1344: .seealso: [](ch_dmbase), `DM`, `DMRestrict()`, `DMInterpolate()`, `DMDestroy()`, `DMView()`, `DMCreateGlobalVector()`, `DMCreateColoring()`, `DMCreateMatrix()`, `DMCreateMassMatrix()`, `DMRefine()`, `DMCoarsen()`, `DMCreateInterpolation()`
1345: @*/
1346: PetscErrorCode DMCreateRestriction(DM dmc, DM dmf, Mat *mat)
1347: {
1348:   PetscFunctionBegin;
1351:   PetscAssertPointer(mat, 3);
1352:   PetscCall(PetscLogEventBegin(DM_CreateRestriction, dmc, dmf, 0, 0));
1353:   PetscUseTypeMethod(dmc, createrestriction, dmf, mat);
1354:   PetscCall(PetscLogEventEnd(DM_CreateRestriction, dmc, dmf, 0, 0));
1355:   PetscFunctionReturn(PETSC_SUCCESS);
1356: }

1358: /*@
1359:   DMCreateInjection - Gets injection matrix between two `DM` objects.

1361:   Collective

1363:   Input Parameters:
1364: + dac - the `DM` object
1365: - daf - the second, finer `DM` object

1367:   Output Parameter:
1368: . mat - the injection

1370:   Level: developer

1372:   Notes:
1373:   This is an operator that applied to a vector obtained with `DMCreateGlobalVector()` on the
1374:   fine grid maps the values to a vector on the vector on the coarse `DM` by simply selecting
1375:   the values on the coarse grid points. This compares to the operator obtained by
1376:   `DMCreateRestriction()` or the transpose of the operator obtained by
1377:   `DMCreateInterpolation()` that uses a "local weighted average" of the values around the
1378:   coarse grid point as the coarse grid value.

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

1383: .seealso: [](ch_dmbase), `DM`, `DMDestroy()`, `DMView()`, `DMCreateGlobalVector()`, `DMCreateColoring()`, `DMCreateMatrix()`, `DMCreateMassMatrix()`, `DMCreateInterpolation()`,
1384:           `DMCreateRestriction()`, `MatRestrict()`, `MatInterpolate()`
1385: @*/
1386: PetscErrorCode DMCreateInjection(DM dac, DM daf, Mat *mat)
1387: {
1388:   PetscFunctionBegin;
1391:   PetscAssertPointer(mat, 3);
1392:   PetscCall(PetscLogEventBegin(DM_CreateInjection, dac, daf, 0, 0));
1393:   PetscUseTypeMethod(dac, createinjection, daf, mat);
1394:   PetscCall(PetscLogEventEnd(DM_CreateInjection, dac, daf, 0, 0));
1395:   PetscFunctionReturn(PETSC_SUCCESS);
1396: }

1398: /*@
1399:   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
1400:   a Galerkin finite element model on the `DM`

1402:   Collective

1404:   Input Parameters:
1405: + dmc - the target `DM` object
1406: - dmf - the source `DM` object, can be `NULL`

1408:   Output Parameter:
1409: . mat - the mass matrix

1411:   Level: developer

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

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

1418: .seealso: [](ch_dmbase), `DM`, `DMCreateMassMatrixLumped()`, `DMCreateMatrix()`, `DMRefine()`, `DMCoarsen()`, `DMCreateRestriction()`, `DMCreateInterpolation()`, `DMCreateInjection()`
1419: @*/
1420: PetscErrorCode DMCreateMassMatrix(DM dmc, DM dmf, Mat *mat)
1421: {
1422:   PetscFunctionBegin;
1424:   if (!dmf) dmf = dmc;
1426:   PetscAssertPointer(mat, 3);
1427:   PetscCall(PetscLogEventBegin(DM_CreateMassMatrix, dmc, dmf, 0, 0));
1428:   PetscUseTypeMethod(dmc, createmassmatrix, dmf, mat);
1429:   PetscCall(PetscLogEventEnd(DM_CreateMassMatrix, dmc, dmf, 0, 0));
1430:   PetscFunctionReturn(PETSC_SUCCESS);
1431: }

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

1436:   Collective

1438:   Input Parameter:
1439: . dm - the `DM` object

1441:   Output Parameters:
1442: + llm - the local lumped mass matrix, which is a diagonal matrix, represented as a vector
1443: - lm  - the global lumped mass matrix, which is a diagonal matrix, represented as a vector

1445:   Level: developer

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

1450: .seealso: [](ch_dmbase), `DM`, `DMCreateMassMatrix()`, `DMCreateMatrix()`, `DMRefine()`, `DMCoarsen()`, `DMCreateRestriction()`, `DMCreateInterpolation()`, `DMCreateInjection()`
1451: @*/
1452: PetscErrorCode DMCreateMassMatrixLumped(DM dm, Vec *llm, Vec *lm)
1453: {
1454:   PetscFunctionBegin;
1456:   if (llm) PetscAssertPointer(llm, 2);
1457:   if (lm) PetscAssertPointer(lm, 3);
1458:   if (llm || lm) PetscUseTypeMethod(dm, createmassmatrixlumped, llm, lm);
1459:   PetscFunctionReturn(PETSC_SUCCESS);
1460: }

1462: /*@
1463:   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`

1465:   Collective

1467:   Input Parameters:
1468: + dmc - the target `DM` object
1469: - dmf - the source `DM` object, can be `NULL`

1471:   Output Parameter:
1472: . mat - the gradient matrix

1474:   Level: developer

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

1479: .seealso: [](ch_dmbase), `DM`, `DMCreateMassMatrix()`, `DMCreateMassMatrixLumped()`, `DMCreateMatrix()`, `DMRefine()`, `DMCoarsen()`, `DMCreateRestriction()`, `DMCreateInterpolation()`, `DMCreateInjection()`
1480: @*/
1481: PetscErrorCode DMCreateGradientMatrix(DM dmc, DM dmf, Mat *mat)
1482: {
1483:   PetscFunctionBegin;
1485:   if (!dmf) dmf = dmc;
1487:   PetscAssertPointer(mat, 3);
1488:   PetscUseTypeMethod(dmc, creategradientmatrix, dmf, mat);
1489:   PetscFunctionReturn(PETSC_SUCCESS);
1490: }

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

1496:   Collective

1498:   Input Parameters:
1499: + dm    - the `DM` object
1500: - ctype - `IS_COLORING_LOCAL` or `IS_COLORING_GLOBAL`

1502:   Output Parameter:
1503: . coloring - the coloring

1505:   Level: developer

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

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

1515: .seealso: [](ch_dmbase), `DM`, `ISColoring`, `DMDestroy()`, `DMView()`, `DMCreateGlobalVector()`, `DMCreateInterpolation()`, `DMCreateMatrix()`, `DMCreateMassMatrix()`, `DMSetMatType()`, `MatColoring`, `MatFDColoringCreate()`
1516: @*/
1517: PetscErrorCode DMCreateColoring(DM dm, ISColoringType ctype, ISColoring *coloring)
1518: {
1519:   PetscFunctionBegin;
1521:   PetscAssertPointer(coloring, 3);
1522:   PetscUseTypeMethod(dm, getcoloring, ctype, coloring);
1523:   PetscFunctionReturn(PETSC_SUCCESS);
1524: }

1526: /*@
1527:   DMCreateMatrix - Creates a matrix of appropriate size and nonzero structure for a `DM`. The matrix is most commonly used to store the Jacobian
1528:   of a discrete PDE operator.

1530:   Collective

1532:   Input Parameter:
1533: . dm - the `DM` object

1535:   Output Parameter:
1536: . mat - the matrix

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

1541:   Level: beginner

1543:   Notes:
1544:   This properly preallocates the number of nonzeros in the sparse matrix so you
1545:   do not need to do it yourself.

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

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

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

1556: .seealso: [](ch_dmbase), `DM`, `DMDestroy()`, `DMView()`, `DMCreateGlobalVector()`, `DMCreateInterpolation()`, `DMSetMatType()`, `DMCreateMassMatrix()`
1557: @*/
1558: PetscErrorCode DMCreateMatrix(DM dm, Mat *mat)
1559: {
1560:   PetscFunctionBegin;
1562:   PetscAssertPointer(mat, 2);
1563:   PetscCall(MatInitializePackage());
1564:   PetscCall(PetscLogEventBegin(DM_CreateMatrix, 0, 0, 0, 0));
1565:   PetscUseTypeMethod(dm, creatematrix, mat);
1566:   if (PetscDefined(USE_DEBUG)) {
1567:     DM mdm;

1569:     PetscCall(MatGetDM(*mat, &mdm));
1570:     PetscCheck(mdm, PETSC_COMM_SELF, PETSC_ERR_PLIB, "DM type '%s' did not attach the DM to the matrix", ((PetscObject)dm)->type_name);
1571:   }
1572:   /* Handle nullspace and near nullspace */
1573:   if (dm->Nf) {
1574:     MatNullSpace nullSpace;
1575:     PetscInt     Nf;

1577:     PetscCall(DMGetNumFields(dm, &Nf));
1578:     for (PetscInt f = 0; f < Nf; ++f) {
1579:       if (dm->nullspaceConstructors && dm->nullspaceConstructors[f]) {
1580:         PetscCall((*dm->nullspaceConstructors[f])(dm, f, f, &nullSpace));
1581:         PetscCall(MatSetNullSpace(*mat, nullSpace));
1582:         PetscCall(MatNullSpaceDestroy(&nullSpace));
1583:         break;
1584:       }
1585:     }
1586:     for (PetscInt f = 0; f < Nf; ++f) {
1587:       if (dm->nearnullspaceConstructors && dm->nearnullspaceConstructors[f]) {
1588:         PetscCall((*dm->nearnullspaceConstructors[f])(dm, f, f, &nullSpace));
1589:         PetscCall(MatSetNearNullSpace(*mat, nullSpace));
1590:         PetscCall(MatNullSpaceDestroy(&nullSpace));
1591:       }
1592:     }
1593:   }
1594:   PetscCall(PetscLogEventEnd(DM_CreateMatrix, 0, 0, 0, 0));
1595:   PetscFunctionReturn(PETSC_SUCCESS);
1596: }

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

1603:   Logically Collective

1605:   Input Parameters:
1606: + dm   - the `DM`
1607: - skip - `PETSC_TRUE` to skip preallocation

1609:   Level: developer

1611:   Note:
1612:   This is most useful to reduce initialization costs when `MatSetPreallocationCOO()` and
1613:   `MatSetValuesCOO()` will be used.

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

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

1629:   Logically Collective

1631:   Input Parameters:
1632: + dm   - the `DM`
1633: - only - `PETSC_TRUE` if only want preallocation

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

1638:   Level: developer

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

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

1654:   Logically Collective

1656:   Input Parameters:
1657: + dm   - the `DM`
1658: - only - `PETSC_TRUE` if you only want matrix nonzero structure

1660:   Level: developer

1662: .seealso: [](ch_dmbase), `DM`, `DMCreateMatrix()`, `DMSetMatrixPreallocateOnly()`, `DMSetMatrixPreallocateSkip()`
1663: @*/
1664: PetscErrorCode DMSetMatrixStructureOnly(DM dm, PetscBool only)
1665: {
1666:   PetscFunctionBegin;
1668:   dm->structure_only = only;
1669:   PetscFunctionReturn(PETSC_SUCCESS);
1670: }

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

1675:   Logically Collective

1677:   Input Parameters:
1678: + dm    - the `DM`
1679: - btype - block by topological point or field node

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

1684:   Level: advanced

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

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

1699:   Not Collective

1701:   Input Parameter:
1702: . dm - the `DM`

1704:   Output Parameter:
1705: . btype - block by topological point or field node

1707:   Level: advanced

1709: .seealso: [](ch_dmbase), `DM`, `DMCreateMatrix()`, `MatSetVariableBlockSizes()`
1710: @*/
1711: PetscErrorCode DMGetBlockingType(DM dm, DMBlockingType *btype)
1712: {
1713:   PetscFunctionBegin;
1715:   PetscAssertPointer(btype, 2);
1716:   *btype = dm->blocking_type;
1717:   PetscFunctionReturn(PETSC_SUCCESS);
1718: }

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

1723:   Not Collective

1725:   Input Parameters:
1726: + dm    - the `DM` object
1727: . count - The minimum size
1728: - dtype - MPI data type, often `MPIU_REAL`, `MPIU_SCALAR`, or `MPIU_INT`)

1730:   Output Parameter:
1731: . mem - the work array

1733:   Level: developer

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

1738:   The array may contain nonzero values

1740: .seealso: [](ch_dmbase), `DM`, `DMDestroy()`, `DMCreate()`, `DMRestoreWorkArray()`, `PetscMalloc()`
1741: @*/
1742: PetscErrorCode DMGetWorkArray(DM dm, PetscInt count, MPI_Datatype dtype, void *mem)
1743: {
1744:   DMWorkLink  link;
1745:   PetscMPIInt dsize;

1747:   PetscFunctionBegin;
1749:   PetscAssertPointer(mem, 4);
1750:   if (!count) {
1751:     *(void **)mem = NULL;
1752:     PetscFunctionReturn(PETSC_SUCCESS);
1753:   }
1754:   if (dm->workin) {
1755:     link       = dm->workin;
1756:     dm->workin = dm->workin->next;
1757:   } else {
1758:     PetscCall(PetscNew(&link));
1759:   }
1760:   /* Avoid MPI_Type_size for most used datatypes
1761:      Get size directly */
1762:   if (dtype == MPIU_INT) dsize = sizeof(PetscInt);
1763:   else if (dtype == MPIU_REAL) dsize = sizeof(PetscReal);
1764:   else if (PetscDefined(USE_64BIT_INDICES) && dtype == MPI_INT) dsize = sizeof(int);
1765:   else if (PetscDefined(USE_COMPLEX) && dtype == MPIU_SCALAR) dsize = sizeof(PetscScalar);
1766:   else PetscCallMPI(MPI_Type_size(dtype, &dsize));

1768:   if (((size_t)dsize * count) > link->bytes) {
1769:     PetscCall(PetscFree(link->mem));
1770:     PetscCall(PetscMalloc(dsize * count, &link->mem));
1771:     link->bytes = dsize * count;
1772:   }
1773:   link->next    = dm->workout;
1774:   dm->workout   = link;
1775:   *(void **)mem = link->mem;
1776:   PetscFunctionReturn(PETSC_SUCCESS);
1777: }

1779: /*@
1780:   DMRestoreWorkArray - Restores a work array obtained with `DMCreateWorkArray()`

1782:   Not Collective

1784:   Input Parameters:
1785: + dm    - the `DM` object
1786: . count - The minimum size
1787: - dtype - MPI data type, often `MPIU_REAL`, `MPIU_SCALAR`, `MPIU_INT`

1789:   Output Parameter:
1790: . mem - the work array

1792:   Level: developer

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

1797: .seealso: [](ch_dmbase), `DM`, `DMDestroy()`, `DMCreate()`, `DMGetWorkArray()`
1798: @*/
1799: PetscErrorCode DMRestoreWorkArray(DM dm, PetscInt count, MPI_Datatype dtype, void *mem)
1800: {
1801:   DMWorkLink *p, link;

1803:   PetscFunctionBegin;
1804:   PetscAssertPointer(mem, 4);
1805:   (void)count;
1806:   (void)dtype;
1807:   if (!*(void **)mem) PetscFunctionReturn(PETSC_SUCCESS);
1808:   for (p = &dm->workout; (link = *p); p = &link->next) {
1809:     if (link->mem == *(void **)mem) {
1810:       *p            = link->next;
1811:       link->next    = dm->workin;
1812:       dm->workin    = link;
1813:       *(void **)mem = NULL;
1814:       PetscFunctionReturn(PETSC_SUCCESS);
1815:     }
1816:   }
1817:   SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Array was not checked out");
1818: }

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

1824:   Logically Collective; No Fortran Support

1826:   Input Parameters:
1827: + dm     - The `DM`
1828: . field  - The field number for the nullspace
1829: - nullsp - A callback to create the nullspace

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

1837:   Level: intermediate

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

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

1854:   Not Collective; No Fortran Support

1856:   Input Parameters:
1857: + dm    - The `DM`
1858: - field - The field number for the nullspace

1860:   Output Parameter:
1861: . nullsp - A callback to create the 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()`, `DMGetField()`, `DMSetNullSpaceConstructor()`, `DMSetNearNullSpaceConstructor()`, `DMGetNearNullSpaceConstructor()`, `DMCreateSubDM()`, `DMCreateSuperDM()`
1872: @*/
1873: PetscErrorCode DMGetNullSpaceConstructor(DM dm, PetscInt field, PetscErrorCode (**nullsp)(DM dm, PetscInt origField, PetscInt field, MatNullSpace *nullSpace))
1874: {
1875:   PetscFunctionBegin;
1877:   PetscAssertPointer(nullsp, 3);
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->nullspaceConstructors, PetscObjectComm((PetscObject)dm), PETSC_ERR_ARG_WRONG, "Must call DMCreateDS() to setup nullspaces");
1880:   *nullsp = dm->nullspaceConstructors[field];
1881:   PetscFunctionReturn(PETSC_SUCCESS);
1882: }

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

1887:   Logically Collective; No Fortran Support

1889:   Input Parameters:
1890: + dm     - The `DM`
1891: . field  - The field number for the nullspace
1892: - nullsp - A callback to create the near-nullspace

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

1900:   Level: intermediate

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

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

1918:   Not Collective; No Fortran Support

1920:   Input Parameters:
1921: + dm    - The `DM`
1922: - field - The field number for the nullspace

1924:   Output Parameter:
1925: . nullsp - A callback to create the near-nullspace

1927:   Calling sequence of `nullsp`:
1928: + dm        - The present `DM`
1929: . origField - The field number given above, in the original `DM`
1930: . field     - The field number in dm
1931: - nullSpace - The nullspace for the given field

1933:   Level: intermediate

1935: .seealso: [](ch_dmbase), `DM`, `DMAddField()`, `DMGetField()`, `DMSetNearNullSpaceConstructor()`, `DMSetNullSpaceConstructor()`, `DMGetNullSpaceConstructor()`, `DMCreateSubDM()`,
1936:           `MatNullSpace`, `DMCreateSuperDM()`
1937: @*/
1938: PetscErrorCode DMGetNearNullSpaceConstructor(DM dm, PetscInt field, PetscErrorCode (**nullsp)(DM dm, PetscInt origField, PetscInt field, MatNullSpace *nullSpace))
1939: {
1940:   PetscFunctionBegin;
1942:   PetscAssertPointer(nullsp, 3);
1943:   PetscCheck(field < dm->Nf, PetscObjectComm((PetscObject)dm), PETSC_ERR_ARG_OUTOFRANGE, "Cannot handle %" PetscInt_FMT " >= %" PetscInt_FMT " fields", field, dm->Nf);
1944:   PetscCheck(dm->nearnullspaceConstructors, PetscObjectComm((PetscObject)dm), PETSC_ERR_ARG_WRONG, "Must call DMCreateDS() to setup nullspaces");
1945:   *nullsp = dm->nearnullspaceConstructors[field];
1946:   PetscFunctionReturn(PETSC_SUCCESS);
1947: }

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

1952:   Not Collective; No Fortran Support

1954:   Input Parameter:
1955: . dm - the `DM` object

1957:   Output Parameters:
1958: + numFields  - The number of fields (or `NULL` if not requested)
1959: . fieldNames - The name of each field (or `NULL` if not requested)
1960: - fields     - The global indices for each field (or `NULL` if not requested)

1962:   Level: intermediate

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

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

1973: .seealso: [](ch_dmbase), `DM`, `DMAddField()`, `DMGetField()`, `DMDestroy()`, `DMView()`, `DMCreateInterpolation()`, `DMCreateColoring()`, `DMCreateMatrix()`,
1974:           `DMCreateFieldDecomposition()`
1975: @*/
1976: PetscErrorCode DMCreateFieldIS(DM dm, PetscInt *numFields, char ***fieldNames, IS *fields[])
1977: {
1978:   PetscSection section, sectionGlobal;

1980:   PetscFunctionBegin;
1982:   if (numFields) {
1983:     PetscAssertPointer(numFields, 2);
1984:     *numFields = 0;
1985:   }
1986:   if (fieldNames) {
1987:     PetscAssertPointer(fieldNames, 3);
1988:     *fieldNames = NULL;
1989:   }
1990:   if (fields) {
1991:     PetscAssertPointer(fields, 4);
1992:     *fields = NULL;
1993:   }
1994:   PetscCall(DMGetLocalSection(dm, &section));
1995:   if (section) {
1996:     PetscInt *fieldSizes, *fieldNc, **fieldIndices;
1997:     PetscInt  nF, f, pStart, pEnd, p;

1999:     PetscCall(DMGetGlobalSection(dm, &sectionGlobal));
2000:     PetscCall(PetscSectionGetNumFields(section, &nF));
2001:     PetscCall(PetscMalloc3(nF, &fieldSizes, nF, &fieldNc, nF, &fieldIndices));
2002:     PetscCall(PetscSectionGetChart(sectionGlobal, &pStart, &pEnd));
2003:     for (f = 0; f < nF; ++f) {
2004:       fieldSizes[f] = 0;
2005:       PetscCall(PetscSectionGetFieldComponents(section, f, &fieldNc[f]));
2006:     }
2007:     for (p = pStart; p < pEnd; ++p) {
2008:       PetscInt gdof;

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

2015:           PetscCall(PetscSectionGetFieldDof(section, p, f, &fdof));
2016:           PetscCall(PetscSectionGetFieldConstraintDof(section, p, f, &fcdof));
2017:           fpdof = fdof - fcdof;
2018:           if (fpdof && fpdof != fieldNc[f]) {
2019:             /* Layout does not admit a pointwise block size */
2020:             fieldNc[f] = 1;
2021:           }
2022:           fieldSizes[f] += fpdof;
2023:         }
2024:       }
2025:     }
2026:     for (f = 0; f < nF; ++f) {
2027:       PetscCall(PetscMalloc1(fieldSizes[f], &fieldIndices[f]));
2028:       fieldSizes[f] = 0;
2029:     }
2030:     for (p = pStart; p < pEnd; ++p) {
2031:       PetscInt gdof, goff;

2033:       PetscCall(PetscSectionGetDof(sectionGlobal, p, &gdof));
2034:       if (gdof > 0) {
2035:         PetscCall(PetscSectionGetOffset(sectionGlobal, p, &goff));
2036:         for (f = 0; f < nF; ++f) {
2037:           PetscInt fdof, fcdof, fc;

2039:           PetscCall(PetscSectionGetFieldDof(section, p, f, &fdof));
2040:           PetscCall(PetscSectionGetFieldConstraintDof(section, p, f, &fcdof));
2041:           for (fc = 0; fc < fdof - fcdof; ++fc, ++fieldSizes[f]) fieldIndices[f][fieldSizes[f]] = goff++;
2042:         }
2043:       }
2044:     }
2045:     if (numFields) *numFields = nF;
2046:     if (fieldNames) {
2047:       PetscCall(PetscMalloc1(nF, fieldNames));
2048:       for (f = 0; f < nF; ++f) {
2049:         const char *fieldName;

2051:         PetscCall(PetscSectionGetFieldName(section, f, &fieldName));
2052:         PetscCall(PetscStrallocpy(fieldName, &(*fieldNames)[f]));
2053:       }
2054:     }
2055:     if (fields) {
2056:       PetscCall(PetscMalloc1(nF, fields));
2057:       for (f = 0; f < nF; ++f) {
2058:         PetscInt bs, out[2];

2060:         PetscCall(ISCreateGeneral(PetscObjectComm((PetscObject)dm), fieldSizes[f], fieldIndices[f], PETSC_OWN_POINTER, &(*fields)[f]));
2061:         out[0] = -fieldNc[f];
2062:         out[1] = fieldNc[f];
2063:         PetscCallMPI(MPIU_Allreduce(MPI_IN_PLACE, out, 2, MPIU_INT, MPI_MAX, PetscObjectComm((PetscObject)dm)));
2064:         bs = (-out[0] == out[1]) ? out[1] : 1;
2065:         PetscCall(ISSetBlockSize((*fields)[f], bs));
2066:       }
2067:     }
2068:     PetscCall(PetscFree3(fieldSizes, fieldNc, fieldIndices));
2069:   } else PetscTryTypeMethod(dm, createfieldis, numFields, fieldNames, fields);
2070:   PetscFunctionReturn(PETSC_SUCCESS);
2071: }

2073: /*@
2074:   DMCreateFieldDecomposition - Returns a list of `IS` objects defining a decomposition of a problem into subproblems
2075:   corresponding to different fields.

2077:   Not Collective; No Fortran Support

2079:   Input Parameter:
2080: . dm - the `DM` object

2082:   Output Parameters:
2083: + len      - The number of fields (or `NULL` if not requested)
2084: . namelist - The name for each field (or `NULL` if not requested)
2085: . islist   - The global indices for each field (or `NULL` if not requested)
2086: - dmlist   - The `DM`s for each field subproblem (or `NULL`, if not requested; if `NULL` is returned, no `DM`s are defined)

2088:   Level: intermediate

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

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

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

2100:   Fortran Notes:
2101:   Use the declarations
2102: .vb
2103:   character(80), pointer :: namelist(:)
2104:   IS, pointer :: islist(:)
2105:   DM, pointer :: dmlist(:)
2106: .ve

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

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

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

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

2118: .seealso: [](ch_dmbase), `DM`, `DMAddField()`, `DMCreateFieldIS()`, `DMCreateSubDM()`, `DMCreateDomainDecomposition()`, `DMDestroy()`, `DMView()`, `DMCreateInterpolation()`, `DMCreateColoring()`, `DMCreateMatrix()`, `DMCreateMassMatrix()`, `DMRefine()`, `DMCoarsen()`
2119: @*/
2120: PetscErrorCode DMCreateFieldDecomposition(DM dm, PetscInt *len, char ***namelist, IS *islist[], DM *dmlist[])
2121: {
2122:   PetscFunctionBegin;
2124:   if (len) {
2125:     PetscAssertPointer(len, 2);
2126:     *len = 0;
2127:   }
2128:   if (namelist) {
2129:     PetscAssertPointer(namelist, 3);
2130:     *namelist = NULL;
2131:   }
2132:   if (islist) {
2133:     PetscAssertPointer(islist, 4);
2134:     *islist = NULL;
2135:   }
2136:   if (dmlist) {
2137:     PetscAssertPointer(dmlist, 5);
2138:     *dmlist = NULL;
2139:   }
2140:   /*
2141:    Is it a good idea to apply the following check across all impls?
2142:    Perhaps some impls can have a well-defined decomposition before DMSetUp?
2143:    This, however, follows the general principle that accessors are not well-behaved until the object is set up.
2144:    */
2145:   PetscCheck(dm->setupcalled, PetscObjectComm((PetscObject)dm), PETSC_ERR_ARG_WRONGSTATE, "Decomposition defined only after DMSetUp");
2146:   if (!dm->ops->createfielddecomposition) {
2147:     PetscSection section;
2148:     PetscInt     numFields;

2150:     PetscCall(DMGetLocalSection(dm, &section));
2151:     if (section) PetscCall(PetscSectionGetNumFields(section, &numFields));
2152:     if (section && numFields && dm->ops->createsubdm) {
2153:       if (len) *len = numFields;
2154:       if (namelist) PetscCall(PetscMalloc1(numFields, namelist));
2155:       if (islist) PetscCall(PetscMalloc1(numFields, islist));
2156:       if (dmlist) PetscCall(PetscMalloc1(numFields, dmlist));
2157:       for (PetscInt f = 0; f < numFields; ++f) {
2158:         const char *fieldName;

2160:         PetscCall(DMCreateSubDM(dm, 1, &f, islist ? &(*islist)[f] : NULL, dmlist ? &(*dmlist)[f] : NULL));
2161:         if (namelist) {
2162:           PetscCall(PetscSectionGetFieldName(section, f, &fieldName));
2163:           PetscCall(PetscStrallocpy(fieldName, &(*namelist)[f]));
2164:         }
2165:       }
2166:     } else {
2167:       PetscCall(DMCreateFieldIS(dm, len, namelist, islist));
2168:       /* By default there are no DMs associated with subproblems. */
2169:       if (dmlist) *dmlist = NULL;
2170:     }
2171:   } else PetscUseTypeMethod(dm, createfielddecomposition, len, namelist, islist, dmlist);
2172:   PetscFunctionReturn(PETSC_SUCCESS);
2173: }

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

2179:   Not collective

2181:   Input Parameters:
2182: + dm        - The `DM` object
2183: . numFields - The number of fields to select
2184: - fields    - The field numbers of the selected fields

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

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`, `DMCreateFieldIS()`, `DMCreateFieldDecomposition()`, `DMAddField()`, `DMCreateSuperDM()`, `IS`, `VecISCopy()`, `DMPlexSetMigrationSF()`, `DMDestroy()`, `DMView()`, `DMCreateInterpolation()`, `DMCreateColoring()`, `DMCreateMatrix()`, `DMCreateMassMatrix()`
2196: @*/
2197: PetscErrorCode DMCreateSubDM(DM dm, PetscInt numFields, const PetscInt fields[], IS *is, DM *subdm)
2198: {
2199:   PetscFunctionBegin;
2201:   PetscAssertPointer(fields, 3);
2202:   if (is) PetscAssertPointer(is, 4);
2203:   if (subdm) PetscAssertPointer(subdm, 5);
2204:   PetscUseTypeMethod(dm, createsubdm, numFields, fields, is, subdm);
2205:   PetscFunctionReturn(PETSC_SUCCESS);
2206: }

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

2211:   Not collective

2213:   Input Parameters:
2214: + dms - The `DM` objects
2215: - n   - The number of `DM`s

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

2221:   Level: intermediate

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

2226: .seealso: [](ch_dmbase), `DM`, `DMCreateSubDM()`, `DMPlexSetMigrationSF()`, `DMDestroy()`, `DMView()`, `DMCreateInterpolation()`, `DMCreateColoring()`, `DMCreateMatrix()`, `DMCreateMassMatrix()`, `DMCreateFieldIS()`, `DMCreateDomainDecomposition()`
2227: @*/
2228: PetscErrorCode DMCreateSuperDM(DM dms[], PetscInt n, IS *is[], DM *superdm)
2229: {
2230:   PetscFunctionBegin;
2231:   PetscAssertPointer(dms, 1);
2233:   if (is) PetscAssertPointer(is, 3);
2234:   PetscAssertPointer(superdm, 4);
2235:   PetscCheck(n >= 0, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Number of DMs must be nonnegative: %" PetscInt_FMT, n);
2236:   if (n) {
2237:     DM dm = dms[0];
2238:     PetscCheck(dm->ops->createsuperdm, PetscObjectComm((PetscObject)dm), PETSC_ERR_SUP, "No method createsuperdm for DM of type %s", ((PetscObject)dm)->type_name);
2239:     PetscCall((*dm->ops->createsuperdm)(dms, n, is, superdm));
2240:   }
2241:   PetscFunctionReturn(PETSC_SUCCESS);
2242: }

2244: /*@
2245:   DMCreateDomainDecomposition - Returns lists of `IS` objects defining a decomposition of a
2246:   problem into subproblems corresponding to restrictions to pairs of nested subdomains.

2248:   Not Collective

2250:   Input Parameter:
2251: . dm - the `DM` object

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

2260:   Level: intermediate

2262:   Notes:
2263:   Each `IS` contains the global indices of the dofs of the corresponding subdomains with in the
2264:   dofs of the original `DM`. The inner subdomains conceptually define a nonoverlapping
2265:   covering, while outer subdomains can overlap.

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

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

2273:   Developer Notes:
2274:   The `dmlist` is for the inner subdomains or the outer subdomains or all subdomains?

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

2278: .seealso: [](ch_dmbase), `DM`, `DMCreateFieldDecomposition()`, `DMDestroy()`, `DMCreateDomainDecompositionScatters()`, `DMView()`, `DMCreateInterpolation()`,
2279:           `DMSubDomainHookAdd()`, `DMSubDomainHookRemove()`, `DMCreateColoring()`, `DMCreateMatrix()`, `DMCreateMassMatrix()`, `DMRefine()`, `DMCoarsen()`
2280: @*/
2281: PetscErrorCode DMCreateDomainDecomposition(DM dm, PetscInt *n, char **namelist[], IS *innerislist[], IS *outerislist[], DM *dmlist[])
2282: {
2283:   DMSubDomainHookLink link;
2284:   PetscInt            l;

2286:   PetscFunctionBegin;
2288:   if (n) {
2289:     PetscAssertPointer(n, 2);
2290:     *n = 0;
2291:   }
2292:   if (namelist) {
2293:     PetscAssertPointer(namelist, 3);
2294:     *namelist = NULL;
2295:   }
2296:   if (innerislist) {
2297:     PetscAssertPointer(innerislist, 4);
2298:     *innerislist = NULL;
2299:   }
2300:   if (outerislist) {
2301:     PetscAssertPointer(outerislist, 5);
2302:     *outerislist = NULL;
2303:   }
2304:   if (dmlist) {
2305:     PetscAssertPointer(dmlist, 6);
2306:     *dmlist = NULL;
2307:   }
2308:   /*
2309:    Is it a good idea to apply the following check across all impls?
2310:    Perhaps some impls can have a well-defined decomposition before DMSetUp?
2311:    This, however, follows the general principle that accessors are not well-behaved until the object is set up.
2312:    */
2313:   PetscCheck(dm->setupcalled, PetscObjectComm((PetscObject)dm), PETSC_ERR_ARG_WRONGSTATE, "Decomposition defined only after DMSetUp");
2314:   if (dm->ops->createdomaindecomposition) {
2315:     PetscUseTypeMethod(dm, createdomaindecomposition, &l, namelist, innerislist, outerislist, dmlist);
2316:     /* copy subdomain hooks and context over to the subdomain DMs */
2317:     if (dmlist && *dmlist) {
2318:       for (PetscInt i = 0; i < l; i++) {
2319:         for (link = dm->subdomainhook; link; link = link->next) {
2320:           if (link->ddhook) PetscCall((*link->ddhook)(dm, (*dmlist)[i], link->ctx));
2321:         }
2322:         if (dm->ctx) (*dmlist)[i]->ctx = dm->ctx;
2323:       }
2324:     }
2325:     if (n) *n = l;
2326:   }
2327:   PetscFunctionReturn(PETSC_SUCCESS);
2328: }

2330: /*@
2331:   DMCreateDomainDecompositionScatters - Returns scatters to the subdomain vectors from the global vector for subdomains created with
2332:   `DMCreateDomainDecomposition()`

2334:   Not Collective

2336:   Input Parameters:
2337: + dm     - the `DM` object
2338: . n      - the number of subdomains
2339: - subdms - the local subdomains

2341:   Output Parameters:
2342: + iscat - scatter from global vector to nonoverlapping global vector entries on subdomain
2343: . oscat - scatter from global vector to overlapping global vector entries on subdomain
2344: - gscat - scatter from global vector to local vector on subdomain (fills in ghosts)

2346:   Level: developer

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

2354:   Developer Note:
2355:   Can the `subdms` input be anything or are they exactly the `DM` obtained from
2356:   `DMCreateDomainDecomposition()`?

2358: .seealso: [](ch_dmbase), `DM`, `DMCreateDomainDecomposition()`, `DMDestroy()`, `DMView()`, `DMCreateInterpolation()`, `DMCreateColoring()`, `DMCreateMatrix()`, `DMCreateMassMatrix()`, `DMCreateFieldIS()`
2359: @*/
2360: PetscErrorCode DMCreateDomainDecompositionScatters(DM dm, PetscInt n, DM subdms[], VecScatter *iscat[], VecScatter *oscat[], VecScatter *gscat[])
2361: {
2362:   PetscFunctionBegin;
2364:   PetscAssertPointer(subdms, 3);
2365:   PetscUseTypeMethod(dm, createddscatters, n, subdms, iscat, oscat, gscat);
2366:   PetscFunctionReturn(PETSC_SUCCESS);
2367: }

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

2372:   Collective

2374:   Input Parameters:
2375: + dm   - the `DM` object
2376: - comm - the communicator to contain the new `DM` object (or `MPI_COMM_NULL`)

2378:   Output Parameter:
2379: . dmf - the refined `DM`, or `NULL`

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

2384:   Level: developer

2386:   Note:
2387:   If no refinement was done, the return value is `NULL`

2389: .seealso: [](ch_dmbase), `DM`, `DMCoarsen()`, `DMDestroy()`, `DMView()`, `DMCreateGlobalVector()`, `DMCreateInterpolation()`, `DMCreateDomainDecomposition()`,
2390:           `DMRefineHookAdd()`, `DMRefineHookRemove()`
2391: @*/
2392: PetscErrorCode DMRefine(DM dm, MPI_Comm comm, DM *dmf)
2393: {
2394:   DMRefineHookLink link;

2396:   PetscFunctionBegin;
2398:   PetscCall(PetscLogEventBegin(DM_Refine, dm, 0, 0, 0));
2399:   PetscUseTypeMethod(dm, refine, comm, dmf);
2400:   if (*dmf) {
2401:     (*dmf)->ops->creatematrix = dm->ops->creatematrix;

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

2405:     (*dmf)->ctx       = dm->ctx;
2406:     (*dmf)->leveldown = dm->leveldown;
2407:     (*dmf)->levelup   = dm->levelup + 1;

2409:     PetscCall(DMSetMatType(*dmf, dm->mattype));
2410:     for (link = dm->refinehook; link; link = link->next) {
2411:       if (link->refinehook) PetscCall((*link->refinehook)(dm, *dmf, link->ctx));
2412:     }
2413:   }
2414:   PetscCall(PetscLogEventEnd(DM_Refine, dm, 0, 0, 0));
2415:   PetscFunctionReturn(PETSC_SUCCESS);
2416: }

2418: /*@
2419:   DMRefineHookAdd - adds a callback to be run when interpolating a nonlinear problem to a finer grid

2421:   Logically Collective; No Fortran Support

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

2429:   Calling sequence of `refinehook`:
2430: + coarse - coarse level `DM`
2431: . fine   - fine level `DM` to interpolate problem to
2432: - ctx    - optional function context

2434:   Calling sequence of `interphook`:
2435: + coarse - coarse level `DM`
2436: . interp - matrix interpolating a coarse-level solution to the finer grid
2437: . fine   - fine level `DM` to update
2438: - ctx    - optional function context

2440:   Level: advanced

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

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

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

2450: .seealso: [](ch_dmbase), `DM`, `DMCoarsenHookAdd()`, `DMInterpolate()`, `SNESFASGetInterpolation()`, `SNESFASGetInjection()`, `PetscObjectCompose()`, `PetscContainerCreate()`
2451: @*/
2452: PetscErrorCode DMRefineHookAdd(DM coarse, PetscErrorCode (*refinehook)(DM coarse, DM fine, PetscCtx ctx), PetscErrorCode (*interphook)(DM coarse, Mat interp, DM fine, PetscCtx ctx), PetscCtx ctx)
2453: {
2454:   DMRefineHookLink link, *p;

2456:   PetscFunctionBegin;
2458:   for (p = &coarse->refinehook; *p; p = &(*p)->next) { /* Scan to the end of the current list of hooks */
2459:     if ((*p)->refinehook == refinehook && (*p)->interphook == interphook && (*p)->ctx == ctx) PetscFunctionReturn(PETSC_SUCCESS);
2460:   }
2461:   PetscCall(PetscNew(&link));
2462:   link->refinehook = refinehook;
2463:   link->interphook = interphook;
2464:   link->ctx        = ctx;
2465:   link->next       = NULL;
2466:   *p               = link;
2467:   PetscFunctionReturn(PETSC_SUCCESS);
2468: }

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

2474:   Logically Collective; No Fortran Support

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

2482:   Calling sequence of refinehook:
2483: + coarse - the coarse `DM`
2484: . fine   - the fine `DM`
2485: - ctx    - context for the function

2487:   Calling sequence of interphook:
2488: + coarse - the coarse `DM`
2489: . interp - the interpolation `Mat` from coarse to fine
2490: . fine   - the fine `DM`
2491: - ctx    - context for the function

2493:   Level: advanced

2495:   Note:
2496:   This function does nothing if the hook is not in the list.

2498: .seealso: [](ch_dmbase), `DM`, `DMRefineHookAdd()`, `DMCoarsenHookRemove()`, `DMInterpolate()`, `SNESFASGetInterpolation()`, `SNESFASGetInjection()`, `PetscObjectCompose()`, `PetscContainerCreate()`
2499: @*/
2500: PetscErrorCode DMRefineHookRemove(DM coarse, PetscErrorCode (*refinehook)(DM coarse, DM fine, PetscCtx ctx), PetscErrorCode (*interphook)(DM coarse, Mat interp, DM fine, PetscCtx ctx), PetscCtx ctx)
2501: {
2502:   DMRefineHookLink link, *p;

2504:   PetscFunctionBegin;
2506:   for (p = &coarse->refinehook; *p; p = &(*p)->next) { /* Search the list of current hooks */
2507:     if ((*p)->refinehook == refinehook && (*p)->interphook == interphook && (*p)->ctx == ctx) {
2508:       link = *p;
2509:       *p   = link->next;
2510:       PetscCall(PetscFree(link));
2511:       break;
2512:     }
2513:   }
2514:   PetscFunctionReturn(PETSC_SUCCESS);
2515: }

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

2520:   Collective if any hooks are

2522:   Input Parameters:
2523: + coarse - coarser `DM` to use as a base
2524: . interp - interpolation matrix, apply using `MatInterpolate()`
2525: - fine   - finer `DM` to update

2527:   Level: developer

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

2533: .seealso: [](ch_dmbase), `DM`, `DMRefineHookAdd()`, `MatInterpolate()`
2534: @*/
2535: PetscErrorCode DMInterpolate(DM coarse, Mat interp, DM fine)
2536: {
2537:   DMRefineHookLink link;

2539:   PetscFunctionBegin;
2540:   for (link = fine->refinehook; link; link = link->next) {
2541:     if (link->interphook) PetscCall((*link->interphook)(coarse, interp, fine, link->ctx));
2542:   }
2543:   PetscFunctionReturn(PETSC_SUCCESS);
2544: }

2546: /*@
2547:   DMInterpolateSolution - Interpolates a solution from a coarse mesh to a fine mesh.

2549:   Collective

2551:   Input Parameters:
2552: + coarse    - coarse `DM`
2553: . fine      - fine `DM`
2554: . interp    - (optional) the matrix computed by `DMCreateInterpolation()`.  Implementations may not need this, but if it
2555:             is available it can avoid some recomputation.  If it is provided, `MatInterpolate()` will be used if
2556:             the coarse `DM` does not have a specialized implementation.
2557: - coarseSol - solution on the coarse mesh

2559:   Output Parameter:
2560: . fineSol - the interpolation of coarseSol to the fine mesh

2562:   Level: developer

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

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

2573: .seealso: [](ch_dmbase), `DM`, `DMInterpolate()`, `DMCreateInterpolation()`
2574: @*/
2575: PetscErrorCode DMInterpolateSolution(DM coarse, DM fine, Mat interp, Vec coarseSol, Vec fineSol)
2576: {
2577:   PetscErrorCode (*interpsol)(DM, DM, Mat, Vec, Vec) = NULL;

2579:   PetscFunctionBegin;

2585:   PetscCall(PetscObjectQueryFunction((PetscObject)coarse, "DMInterpolateSolution_C", &interpsol));
2586:   if (interpsol) {
2587:     PetscCall((*interpsol)(coarse, fine, interp, coarseSol, fineSol));
2588:   } else if (interp) {
2589:     PetscCall(MatInterpolate(interp, coarseSol, fineSol));
2590:   } else SETERRQ(PetscObjectComm((PetscObject)coarse), PETSC_ERR_SUP, "DM %s does not implement DMInterpolateSolution()", ((PetscObject)coarse)->type_name);
2591:   PetscFunctionReturn(PETSC_SUCCESS);
2592: }

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

2597:   Not Collective

2599:   Input Parameter:
2600: . dm - the `DM` object

2602:   Output Parameter:
2603: . level - number of refinements

2605:   Level: developer

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

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

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

2623:   Not Collective

2625:   Input Parameters:
2626: + dm    - the `DM` object
2627: - level - number of refinements

2629:   Level: advanced

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

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

2636: .seealso: [](ch_dmbase), `DM`, `DMGetRefineLevel()`, `DMCoarsen()`, `DMGetCoarsenLevel()`, `DMDestroy()`, `DMView()`, `DMCreateGlobalVector()`, `DMCreateInterpolation()`
2637: @*/
2638: PetscErrorCode DMSetRefineLevel(DM dm, PetscInt level)
2639: {
2640:   PetscFunctionBegin;
2642:   dm->levelup = level;
2643:   PetscFunctionReturn(PETSC_SUCCESS);
2644: }

2646: /*@
2647:   DMExtrude - Extrude a `DM` object from a surface

2649:   Collective

2651:   Input Parameters:
2652: + dm     - the `DM` object
2653: - layers - the number of extruded cell layers

2655:   Output Parameter:
2656: . dme - the extruded `DM`, or `NULL`

2658:   Level: developer

2660:   Note:
2661:   If no extrusion was done, the return value is `NULL`

2663: .seealso: [](ch_dmbase), `DM`, `DMRefine()`, `DMCoarsen()`, `DMDestroy()`, `DMView()`, `DMCreateGlobalVector()`
2664: @*/
2665: PetscErrorCode DMExtrude(DM dm, PetscInt layers, DM *dme)
2666: {
2667:   PetscFunctionBegin;
2669:   PetscUseTypeMethod(dm, extrude, layers, dme);
2670:   if (*dme) {
2671:     (*dme)->ops->creatematrix = dm->ops->creatematrix;
2672:     PetscCall(PetscObjectCopyFortranFunctionPointers((PetscObject)dm, (PetscObject)*dme));
2673:     (*dme)->ctx = dm->ctx;
2674:     PetscCall(DMSetMatType(*dme, dm->mattype));
2675:   }
2676:   PetscFunctionReturn(PETSC_SUCCESS);
2677: }

2679: PetscErrorCode DMGetBasisTransformDM_Internal(DM dm, DM *tdm)
2680: {
2681:   PetscFunctionBegin;
2683:   PetscAssertPointer(tdm, 2);
2684:   *tdm = dm->transformDM;
2685:   PetscFunctionReturn(PETSC_SUCCESS);
2686: }

2688: PetscErrorCode DMGetBasisTransformVec_Internal(DM dm, Vec *tv)
2689: {
2690:   PetscFunctionBegin;
2692:   PetscAssertPointer(tv, 2);
2693:   *tv = dm->transform;
2694:   PetscFunctionReturn(PETSC_SUCCESS);
2695: }

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

2700:   Input Parameter:
2701: . dm - The `DM`

2703:   Output Parameter:
2704: . flg - `PETSC_TRUE` if a basis transformation should be done

2706:   Level: developer

2708: .seealso: [](ch_dmbase), `DM`, `DMPlexGlobalToLocalBasis()`, `DMPlexLocalToGlobalBasis()`, `DMPlexCreateBasisRotation()`
2709: @*/
2710: PetscErrorCode DMHasBasisTransform(DM dm, PetscBool *flg)
2711: {
2712:   Vec tv;

2714:   PetscFunctionBegin;
2716:   PetscAssertPointer(flg, 2);
2717:   PetscCall(DMGetBasisTransformVec_Internal(dm, &tv));
2718:   *flg = tv ? PETSC_TRUE : PETSC_FALSE;
2719:   PetscFunctionReturn(PETSC_SUCCESS);
2720: }

2722: PetscErrorCode DMConstructBasisTransform_Internal(DM dm)
2723: {
2724:   PetscSection s, ts;
2725:   PetscScalar *ta;
2726:   PetscInt     cdim, pStart, pEnd, p, Nf, f, Nc, dof;

2728:   PetscFunctionBegin;
2729:   PetscCall(DMGetCoordinateDim(dm, &cdim));
2730:   PetscCall(DMGetLocalSection(dm, &s));
2731:   PetscCall(PetscSectionGetChart(s, &pStart, &pEnd));
2732:   PetscCall(PetscSectionGetNumFields(s, &Nf));
2733:   PetscCall(DMClone(dm, &dm->transformDM));
2734:   PetscCall(DMGetLocalSection(dm->transformDM, &ts));
2735:   PetscCall(PetscSectionSetNumFields(ts, Nf));
2736:   PetscCall(PetscSectionSetChart(ts, pStart, pEnd));
2737:   for (f = 0; f < Nf; ++f) {
2738:     PetscCall(PetscSectionGetFieldComponents(s, f, &Nc));
2739:     /* We could start to label fields by their transformation properties */
2740:     if (Nc != cdim) continue;
2741:     for (p = pStart; p < pEnd; ++p) {
2742:       PetscCall(PetscSectionGetFieldDof(s, p, f, &dof));
2743:       if (!dof) continue;
2744:       PetscCall(PetscSectionSetFieldDof(ts, p, f, PetscSqr(cdim)));
2745:       PetscCall(PetscSectionAddDof(ts, p, PetscSqr(cdim)));
2746:     }
2747:   }
2748:   PetscCall(PetscSectionSetUp(ts));
2749:   PetscCall(DMCreateLocalVector(dm->transformDM, &dm->transform));
2750:   PetscCall(VecGetArray(dm->transform, &ta));
2751:   for (p = pStart; p < pEnd; ++p) {
2752:     for (f = 0; f < Nf; ++f) {
2753:       PetscCall(PetscSectionGetFieldDof(ts, p, f, &dof));
2754:       if (dof) {
2755:         PetscReal          x[3] = {0.0, 0.0, 0.0};
2756:         PetscScalar       *tva;
2757:         const PetscScalar *A;

2759:         /* TODO Get quadrature point for this dual basis vector for coordinate */
2760:         PetscCall((*dm->transformGetMatrix)(dm, x, PETSC_TRUE, &A, dm->transformCtx));
2761:         PetscCall(DMPlexPointLocalFieldRef(dm->transformDM, p, f, ta, (void *)&tva));
2762:         PetscCall(PetscArraycpy(tva, A, PetscSqr(cdim)));
2763:       }
2764:     }
2765:   }
2766:   PetscCall(VecRestoreArray(dm->transform, &ta));
2767:   PetscFunctionReturn(PETSC_SUCCESS);
2768: }

2770: /*@
2771:   DMCopyTransform - Copy the basis transform context and callbacks from `dm` to `newdm`

2773:   Not Collective

2775:   Input Parameter:
2776: . dm - the source `DM`

2778:   Output Parameter:
2779: . newdm - the destination `DM`

2781:   Level: developer

2783:   Note:
2784:   If the transform requires setup, `DMConstructBasisTransform_Internal()` is invoked on `newdm`.

2786: .seealso: [](ch_dmbase), `DM`, `DMCopyDS()`, `DMCopyDisc()`
2787: @*/
2788: PetscErrorCode DMCopyTransform(DM dm, DM newdm)
2789: {
2790:   PetscFunctionBegin;
2793:   newdm->transformCtx       = dm->transformCtx;
2794:   newdm->transformSetUp     = dm->transformSetUp;
2795:   newdm->transformDestroy   = NULL;
2796:   newdm->transformGetMatrix = dm->transformGetMatrix;
2797:   if (newdm->transformSetUp) PetscCall(DMConstructBasisTransform_Internal(newdm));
2798:   PetscFunctionReturn(PETSC_SUCCESS);
2799: }

2801: /*@
2802:   DMGlobalToLocalHookAdd - adds a callback to be run when `DMGlobalToLocal()` is called

2804:   Logically Collective

2806:   Input Parameters:
2807: + dm        - the `DM`
2808: . beginhook - function to run at the beginning of `DMGlobalToLocalBegin()`
2809: . endhook   - function to run after `DMGlobalToLocalEnd()` has completed
2810: - ctx       - [optional] context for provide data for the hooks (may be `NULL`)

2812:   Calling sequence of `beginhook`:
2813: + dm   - global `DM`
2814: . g    - global vector
2815: . mode - mode
2816: . l    - local vector
2817: - ctx  - optional function context

2819:   Calling sequence of `endhook`:
2820: + dm   - global `DM`
2821: . g    - global vector
2822: . mode - mode
2823: . l    - local vector
2824: - ctx  - optional function context

2826:   Level: advanced

2828:   Note:
2829:   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.

2831: .seealso: [](ch_dmbase), `DM`, `DMGlobalToLocal()`, `DMRefineHookAdd()`, `SNESFASGetInterpolation()`, `SNESFASGetInjection()`, `PetscObjectCompose()`, `PetscContainerCreate()`
2832: @*/
2833: 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)
2834: {
2835:   DMGlobalToLocalHookLink link, *p;

2837:   PetscFunctionBegin;
2839:   for (p = &dm->gtolhook; *p; p = &(*p)->next) { } /* Scan to the end of the current list of hooks */
2840:   PetscCall(PetscNew(&link));
2841:   link->beginhook = beginhook;
2842:   link->endhook   = endhook;
2843:   link->ctx       = ctx;
2844:   link->next      = NULL;
2845:   *p              = link;
2846:   PetscFunctionReturn(PETSC_SUCCESS);
2847: }

2849: static PetscErrorCode DMGlobalToLocalHook_Constraints(DM dm, Vec g, InsertMode mode, Vec l, PetscCtx ctx)
2850: {
2851:   Mat          cMat;
2852:   Vec          cVec, cBias;
2853:   PetscSection section, cSec;
2854:   PetscInt     pStart, pEnd, p, dof;

2856:   PetscFunctionBegin;
2857:   (void)g;
2858:   (void)ctx;
2860:   PetscCall(DMGetDefaultConstraints(dm, &cSec, &cMat, &cBias));
2861:   if (cMat && (mode == INSERT_VALUES || mode == INSERT_ALL_VALUES || mode == INSERT_BC_VALUES)) {
2862:     PetscInt nRows;

2864:     PetscCall(MatGetSize(cMat, &nRows, NULL));
2865:     if (nRows <= 0) PetscFunctionReturn(PETSC_SUCCESS);
2866:     PetscCall(DMGetLocalSection(dm, &section));
2867:     PetscCall(MatCreateVecs(cMat, NULL, &cVec));
2868:     PetscCall(MatMult(cMat, l, cVec));
2869:     if (cBias) PetscCall(VecAXPY(cVec, 1., cBias));
2870:     PetscCall(PetscSectionGetChart(cSec, &pStart, &pEnd));
2871:     for (p = pStart; p < pEnd; p++) {
2872:       PetscCall(PetscSectionGetDof(cSec, p, &dof));
2873:       if (dof) {
2874:         PetscScalar *vals;
2875:         PetscCall(VecGetValuesSection(cVec, cSec, p, &vals));
2876:         PetscCall(VecSetValuesSection(l, section, p, vals, INSERT_ALL_VALUES));
2877:       }
2878:     }
2879:     PetscCall(VecDestroy(&cVec));
2880:   }
2881:   PetscFunctionReturn(PETSC_SUCCESS);
2882: }

2884: /*@
2885:   DMGlobalToLocal - update local vectors from global vector

2887:   Neighbor-wise Collective

2889:   Input Parameters:
2890: + dm   - the `DM` object
2891: . g    - the global vector
2892: . mode - `INSERT_VALUES` or `ADD_VALUES`
2893: - l    - the local vector

2895:   Level: beginner

2897:   Notes:
2898:   The communication involved in this update can be overlapped with computation by instead using
2899:   `DMGlobalToLocalBegin()` and `DMGlobalToLocalEnd()`.

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

2903: .seealso: [](ch_dmbase), `DM`, `DMGlobalToLocalHookAdd()`, `DMCoarsen()`, `DMDestroy()`, `DMView()`, `DMCreateGlobalVector()`, `DMCreateInterpolation()`,
2904:           `DMLocalToGlobalBegin()`, `DMLocalToGlobal()`, `DMLocalToGlobalEnd()`,
2905:           `DMGlobalToLocalBegin()`, `DMGlobalToLocalEnd()`
2906: @*/
2907: PetscErrorCode DMGlobalToLocal(DM dm, Vec g, InsertMode mode, Vec l)
2908: {
2909:   PetscFunctionBegin;
2910:   PetscCall(DMGlobalToLocalBegin(dm, g, mode, l));
2911:   PetscCall(DMGlobalToLocalEnd(dm, g, mode, l));
2912:   PetscFunctionReturn(PETSC_SUCCESS);
2913: }

2915: /*@
2916:   DMGlobalToLocalBegin - Begins updating local vectors from global vector

2918:   Neighbor-wise Collective

2920:   Input Parameters:
2921: + dm   - the `DM` object
2922: . g    - the global vector
2923: . mode - `INSERT_VALUES` or `ADD_VALUES`
2924: - l    - the local vector

2926:   Level: intermediate

2928:   Notes:
2929:   The operation is completed with `DMGlobalToLocalEnd()`

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

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

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

2937: .seealso: [](ch_dmbase), `DM`, `DMCoarsen()`, `DMDestroy()`, `DMView()`, `DMCreateGlobalVector()`, `DMCreateInterpolation()`, `DMGlobalToLocal()`, `DMGlobalToLocalEnd()`, `DMLocalToGlobalBegin()`, `DMLocalToGlobal()`, `DMLocalToGlobalEnd()`
2938: @*/
2939: PetscErrorCode DMGlobalToLocalBegin(DM dm, Vec g, InsertMode mode, Vec l)
2940: {
2941:   PetscSF                 sf;
2942:   DMGlobalToLocalHookLink link;

2944:   PetscFunctionBegin;
2946:   for (link = dm->gtolhook; link; link = link->next) {
2947:     if (link->beginhook) PetscCall((*link->beginhook)(dm, g, mode, l, link->ctx));
2948:   }
2949:   PetscCall(DMGetSectionSF(dm, &sf));
2950:   if (sf) {
2951:     const PetscScalar *gArray;
2952:     PetscScalar       *lArray;
2953:     PetscMemType       lmtype, gmtype;

2955:     PetscCheck(mode != ADD_VALUES, PetscObjectComm((PetscObject)dm), PETSC_ERR_ARG_OUTOFRANGE, "Invalid insertion mode %d", (int)mode);
2956:     PetscCall(VecGetArrayAndMemType(l, &lArray, &lmtype));
2957:     PetscCall(VecGetArrayReadAndMemType(g, &gArray, &gmtype));
2958:     PetscCall(PetscSFBcastWithMemTypeBegin(sf, MPIU_SCALAR, gmtype, gArray, lmtype, lArray, MPI_REPLACE));
2959:     PetscCall(VecRestoreArrayAndMemType(l, &lArray));
2960:     PetscCall(VecRestoreArrayReadAndMemType(g, &gArray));
2961:   } else {
2962:     PetscUseTypeMethod(dm, globaltolocalbegin, g, mode == INSERT_ALL_VALUES ? INSERT_VALUES : (mode == ADD_ALL_VALUES ? ADD_VALUES : mode), l);
2963:   }
2964:   PetscFunctionReturn(PETSC_SUCCESS);
2965: }

2967: /*@
2968:   DMGlobalToLocalEnd - Ends updating local vectors from global vector

2970:   Neighbor-wise Collective

2972:   Input Parameters:
2973: + dm   - the `DM` object
2974: . g    - the global vector
2975: . mode - `INSERT_VALUES` or `ADD_VALUES`
2976: - l    - the local vector

2978:   Level: intermediate

2980:   Note:
2981:   See `DMGlobalToLocalBegin()` for details.

2983: .seealso: [](ch_dmbase), `DM`, `DMCoarsen()`, `DMDestroy()`, `DMView()`, `DMCreateGlobalVector()`, `DMCreateInterpolation()`, `DMGlobalToLocal()`, `DMLocalToGlobalBegin()`, `DMLocalToGlobal()`, `DMLocalToGlobalEnd()`
2984: @*/
2985: PetscErrorCode DMGlobalToLocalEnd(DM dm, Vec g, InsertMode mode, Vec l)
2986: {
2987:   PetscSF                 sf;
2988:   const PetscScalar      *gArray;
2989:   PetscScalar            *lArray;
2990:   PetscBool               transform;
2991:   DMGlobalToLocalHookLink link;
2992:   PetscMemType            lmtype, gmtype;

2994:   PetscFunctionBegin;
2996:   PetscCall(DMGetSectionSF(dm, &sf));
2997:   PetscCall(DMHasBasisTransform(dm, &transform));
2998:   if (sf) {
2999:     PetscCheck(mode != ADD_VALUES, PetscObjectComm((PetscObject)dm), PETSC_ERR_ARG_OUTOFRANGE, "Invalid insertion mode %d", (int)mode);

3001:     PetscCall(VecGetArrayAndMemType(l, &lArray, &lmtype));
3002:     PetscCall(VecGetArrayReadAndMemType(g, &gArray, &gmtype));
3003:     PetscCall(PetscSFBcastEnd(sf, MPIU_SCALAR, gArray, lArray, MPI_REPLACE));
3004:     PetscCall(VecRestoreArrayAndMemType(l, &lArray));
3005:     PetscCall(VecRestoreArrayReadAndMemType(g, &gArray));
3006:     if (transform) PetscCall(DMPlexGlobalToLocalBasis(dm, l));
3007:   } else {
3008:     PetscUseTypeMethod(dm, globaltolocalend, g, mode == INSERT_ALL_VALUES ? INSERT_VALUES : (mode == ADD_ALL_VALUES ? ADD_VALUES : mode), l);
3009:   }
3010:   PetscCall(DMGlobalToLocalHook_Constraints(dm, g, mode, l, NULL));
3011:   for (link = dm->gtolhook; link; link = link->next) {
3012:     if (link->endhook) PetscCall((*link->endhook)(dm, g, mode, l, link->ctx));
3013:   }
3014:   PetscFunctionReturn(PETSC_SUCCESS);
3015: }

3017: /*@
3018:   DMLocalToGlobalHookAdd - adds a callback to be run when a local to global is called

3020:   Logically Collective

3022:   Input Parameters:
3023: + dm        - the `DM`
3024: . beginhook - function to run at the beginning of `DMLocalToGlobalBegin()`
3025: . endhook   - function to run after `DMLocalToGlobalEnd()` has completed
3026: - ctx       - [optional] context for provide data for the hooks (may be `NULL`)

3028:   Calling sequence of `beginhook`:
3029: + global - global `DM`
3030: . l      - local vector
3031: . mode   - mode
3032: . g      - global vector
3033: - ctx    - optional function context

3035:   Calling sequence of `endhook`:
3036: + global - global `DM`
3037: . l      - local vector
3038: . mode   - mode
3039: . g      - global vector
3040: - ctx    - optional function context

3042:   Level: advanced

3044: .seealso: [](ch_dmbase), `DM`, `DMLocalToGlobal()`, `DMRefineHookAdd()`, `DMGlobalToLocalHookAdd()`, `SNESFASGetInterpolation()`, `SNESFASGetInjection()`, `PetscObjectCompose()`, `PetscContainerCreate()`
3045: @*/
3046: 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)
3047: {
3048:   DMLocalToGlobalHookLink link, *p;

3050:   PetscFunctionBegin;
3052:   for (p = &dm->ltoghook; *p; p = &(*p)->next) { } /* Scan to the end of the current list of hooks */
3053:   PetscCall(PetscNew(&link));
3054:   link->beginhook = beginhook;
3055:   link->endhook   = endhook;
3056:   link->ctx       = ctx;
3057:   link->next      = NULL;
3058:   *p              = link;
3059:   PetscFunctionReturn(PETSC_SUCCESS);
3060: }

3062: static PetscErrorCode DMLocalToGlobalHook_Constraints(DM dm, Vec l, InsertMode mode, Vec g, PetscCtx ctx)
3063: {
3064:   PetscFunctionBegin;
3065:   (void)g;
3066:   (void)ctx;
3068:   if (mode == ADD_VALUES || mode == ADD_ALL_VALUES || mode == ADD_BC_VALUES) {
3069:     Mat          cMat;
3070:     Vec          cVec;
3071:     PetscInt     nRows;
3072:     PetscSection section, cSec;
3073:     PetscInt     pStart, pEnd, p, dof;

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

3078:     PetscCall(MatGetSize(cMat, &nRows, NULL));
3079:     if (nRows <= 0) PetscFunctionReturn(PETSC_SUCCESS);
3080:     PetscCall(DMGetLocalSection(dm, &section));
3081:     PetscCall(MatCreateVecs(cMat, NULL, &cVec));
3082:     PetscCall(PetscSectionGetChart(cSec, &pStart, &pEnd));
3083:     for (p = pStart; p < pEnd; p++) {
3084:       PetscCall(PetscSectionGetDof(cSec, p, &dof));
3085:       if (dof) {
3086:         PetscInt     d;
3087:         PetscScalar *vals;
3088:         PetscCall(VecGetValuesSection(l, section, p, &vals));
3089:         PetscCall(VecSetValuesSection(cVec, cSec, p, vals, mode));
3090:         /* for this to be the true transpose, we have to zero the values that
3091:          * we just extracted */
3092:         for (d = 0; d < dof; d++) vals[d] = 0.;
3093:       }
3094:     }
3095:     PetscCall(MatMultTransposeAdd(cMat, cVec, l, l));
3096:     PetscCall(VecDestroy(&cVec));
3097:   }
3098:   PetscFunctionReturn(PETSC_SUCCESS);
3099: }
3100: /*@
3101:   DMLocalToGlobal - updates global vectors from local vectors

3103:   Neighbor-wise Collective

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

3111:   Level: beginner

3113:   Notes:
3114:   The communication involved in this update can be overlapped with computation by using
3115:   `DMLocalToGlobalBegin()` and `DMLocalToGlobalEnd()`.

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

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

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

3123: .seealso: [](ch_dmbase), `DM`, `DMLocalToGlobalBegin()`, `DMLocalToGlobalEnd()`, `DMCoarsen()`, `DMDestroy()`, `DMView()`, `DMCreateGlobalVector()`, `DMCreateInterpolation()`, `DMGlobalToLocal()`, `DMGlobalToLocalEnd()`, `DMGlobalToLocalBegin()`, `DMLocalToGlobalHookAdd()`, `DMGlobaToLocallHookAdd()`
3124: @*/
3125: PetscErrorCode DMLocalToGlobal(DM dm, Vec l, InsertMode mode, Vec g)
3126: {
3127:   PetscFunctionBegin;
3128:   PetscCall(DMLocalToGlobalBegin(dm, l, mode, g));
3129:   PetscCall(DMLocalToGlobalEnd(dm, l, mode, g));
3130:   PetscFunctionReturn(PETSC_SUCCESS);
3131: }

3133: /*@
3134:   DMLocalToGlobalBegin - begins updating global vectors from local vectors

3136:   Neighbor-wise Collective

3138:   Input Parameters:
3139: + dm   - the `DM` object
3140: . l    - the local vector
3141: . 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.
3142: - g    - the global vector

3144:   Level: intermediate

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

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

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

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

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

3157: .seealso: [](ch_dmbase), `DM`, `DMLocalToGlobal()`, `DMLocalToGlobalEnd()`, `DMCoarsen()`, `DMDestroy()`, `DMView()`, `DMCreateGlobalVector()`, `DMCreateInterpolation()`, `DMGlobalToLocal()`, `DMGlobalToLocalEnd()`, `DMGlobalToLocalBegin()`
3158: @*/
3159: PetscErrorCode DMLocalToGlobalBegin(DM dm, Vec l, InsertMode mode, Vec g)
3160: {
3161:   PetscSF                 sf;
3162:   PetscSection            s, gs;
3163:   DMLocalToGlobalHookLink link;
3164:   Vec                     tmpl;
3165:   const PetscScalar      *lArray;
3166:   PetscScalar            *gArray;
3167:   PetscBool               isInsert, transform, l_inplace = PETSC_FALSE, g_inplace = PETSC_FALSE;
3168:   PetscMemType            lmtype = PETSC_MEMTYPE_HOST, gmtype = PETSC_MEMTYPE_HOST;

3170:   PetscFunctionBegin;
3172:   for (link = dm->ltoghook; link; link = link->next) {
3173:     if (link->beginhook) PetscCall((*link->beginhook)(dm, l, mode, g, link->ctx));
3174:   }
3175:   PetscCall(DMLocalToGlobalHook_Constraints(dm, l, mode, g, NULL));
3176:   PetscCall(DMGetSectionSF(dm, &sf));
3177:   PetscCall(DMGetLocalSection(dm, &s));
3178:   switch (mode) {
3179:   case INSERT_VALUES:
3180:   case INSERT_ALL_VALUES:
3181:   case INSERT_BC_VALUES:
3182:     isInsert = PETSC_TRUE;
3183:     break;
3184:   case ADD_VALUES:
3185:   case ADD_ALL_VALUES:
3186:   case ADD_BC_VALUES:
3187:     isInsert = PETSC_FALSE;
3188:     break;
3189:   default:
3190:     SETERRQ(PetscObjectComm((PetscObject)dm), PETSC_ERR_ARG_OUTOFRANGE, "Invalid insertion mode %d", mode);
3191:   }
3192:   if ((sf && !isInsert) || (s && isInsert)) {
3193:     PetscCall(DMHasBasisTransform(dm, &transform));
3194:     if (transform) {
3195:       PetscCall(DMGetNamedLocalVector(dm, "__petsc_dm_transform_local_copy", &tmpl));
3196:       PetscCall(VecCopy(l, tmpl));
3197:       PetscCall(DMPlexLocalToGlobalBasis(dm, tmpl));
3198:       PetscCall(VecGetArrayRead(tmpl, &lArray));
3199:     } else if (isInsert) {
3200:       PetscCall(VecGetArrayRead(l, &lArray));
3201:     } else {
3202:       PetscCall(VecGetArrayReadAndMemType(l, &lArray, &lmtype));
3203:       l_inplace = PETSC_TRUE;
3204:     }
3205:     if (s && isInsert) {
3206:       PetscCall(VecGetArray(g, &gArray));
3207:     } else {
3208:       PetscCall(VecGetArrayAndMemType(g, &gArray, &gmtype));
3209:       g_inplace = PETSC_TRUE;
3210:     }
3211:     if (sf && !isInsert) {
3212:       PetscCall(PetscSFReduceWithMemTypeBegin(sf, MPIU_SCALAR, lmtype, lArray, gmtype, gArray, MPIU_SUM));
3213:     } else if (s && isInsert) {
3214:       PetscInt gStart, pStart, pEnd, p;

3216:       PetscCall(DMGetGlobalSection(dm, &gs));
3217:       PetscCall(PetscSectionGetChart(s, &pStart, &pEnd));
3218:       PetscCall(VecGetOwnershipRange(g, &gStart, NULL));
3219:       for (p = pStart; p < pEnd; ++p) {
3220:         PetscInt dof, gdof, cdof, gcdof, off, goff, d, e;

3222:         PetscCall(PetscSectionGetDof(s, p, &dof));
3223:         PetscCall(PetscSectionGetDof(gs, p, &gdof));
3224:         PetscCall(PetscSectionGetConstraintDof(s, p, &cdof));
3225:         PetscCall(PetscSectionGetConstraintDof(gs, p, &gcdof));
3226:         PetscCall(PetscSectionGetOffset(s, p, &off));
3227:         PetscCall(PetscSectionGetOffset(gs, p, &goff));
3228:         /* Ignore off-process data and points with no global data */
3229:         if (!gdof || goff < 0) continue;
3230:         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);
3231:         /* If no constraints are enforced in the global vector */
3232:         if (!gcdof) {
3233:           for (d = 0; d < dof; ++d) gArray[goff - gStart + d] = lArray[off + d];
3234:           /* If constraints are enforced in the global vector */
3235:         } else if (cdof == gcdof) {
3236:           const PetscInt *cdofs;
3237:           PetscInt        cind = 0;

3239:           PetscCall(PetscSectionGetConstraintIndices(s, p, &cdofs));
3240:           for (d = 0, e = 0; d < dof; ++d) {
3241:             if (cind < cdof && d == cdofs[cind]) {
3242:               ++cind;
3243:               continue;
3244:             }
3245:             gArray[goff - gStart + e++] = lArray[off + d];
3246:           }
3247:         } 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);
3248:       }
3249:     }
3250:     if (g_inplace) {
3251:       PetscCall(VecRestoreArrayAndMemType(g, &gArray));
3252:     } else {
3253:       PetscCall(VecRestoreArray(g, &gArray));
3254:     }
3255:     if (transform) {
3256:       PetscCall(VecRestoreArrayRead(tmpl, &lArray));
3257:       PetscCall(DMRestoreNamedLocalVector(dm, "__petsc_dm_transform_local_copy", &tmpl));
3258:     } else if (l_inplace) {
3259:       PetscCall(VecRestoreArrayReadAndMemType(l, &lArray));
3260:     } else {
3261:       PetscCall(VecRestoreArrayRead(l, &lArray));
3262:     }
3263:   } else {
3264:     PetscUseTypeMethod(dm, localtoglobalbegin, l, mode == INSERT_ALL_VALUES ? INSERT_VALUES : (mode == ADD_ALL_VALUES ? ADD_VALUES : mode), g);
3265:   }
3266:   PetscFunctionReturn(PETSC_SUCCESS);
3267: }

3269: /*@
3270:   DMLocalToGlobalEnd - updates global vectors from local vectors

3272:   Neighbor-wise Collective

3274:   Input Parameters:
3275: + dm   - the `DM` object
3276: . l    - the local vector
3277: . mode - `INSERT_VALUES` or `ADD_VALUES`
3278: - g    - the global vector

3280:   Level: intermediate

3282:   Note:
3283:   See `DMLocalToGlobalBegin()` for full details

3285: .seealso: [](ch_dmbase), `DM`, `DMLocalToGlobalBegin()`, `DMCoarsen()`, `DMDestroy()`, `DMView()`, `DMCreateGlobalVector()`, `DMCreateInterpolation()`, `DMGlobalToLocalEnd()`
3286: @*/
3287: PetscErrorCode DMLocalToGlobalEnd(DM dm, Vec l, InsertMode mode, Vec g)
3288: {
3289:   PetscSF                 sf;
3290:   PetscSection            s;
3291:   DMLocalToGlobalHookLink link;
3292:   PetscBool               isInsert, transform;

3294:   PetscFunctionBegin;
3296:   PetscCall(DMGetSectionSF(dm, &sf));
3297:   PetscCall(DMGetLocalSection(dm, &s));
3298:   switch (mode) {
3299:   case INSERT_VALUES:
3300:   case INSERT_ALL_VALUES:
3301:     isInsert = PETSC_TRUE;
3302:     break;
3303:   case ADD_VALUES:
3304:   case ADD_ALL_VALUES:
3305:     isInsert = PETSC_FALSE;
3306:     break;
3307:   default:
3308:     SETERRQ(PetscObjectComm((PetscObject)dm), PETSC_ERR_ARG_OUTOFRANGE, "Invalid insertion mode %d", mode);
3309:   }
3310:   if (sf && !isInsert) {
3311:     const PetscScalar *lArray;
3312:     PetscScalar       *gArray;
3313:     Vec                tmpl;

3315:     PetscCall(DMHasBasisTransform(dm, &transform));
3316:     if (transform) {
3317:       PetscCall(DMGetNamedLocalVector(dm, "__petsc_dm_transform_local_copy", &tmpl));
3318:       PetscCall(VecGetArrayRead(tmpl, &lArray));
3319:     } else {
3320:       PetscCall(VecGetArrayReadAndMemType(l, &lArray, NULL));
3321:     }
3322:     PetscCall(VecGetArrayAndMemType(g, &gArray, NULL));
3323:     PetscCall(PetscSFReduceEnd(sf, MPIU_SCALAR, lArray, gArray, MPIU_SUM));
3324:     if (transform) {
3325:       PetscCall(VecRestoreArrayRead(tmpl, &lArray));
3326:       PetscCall(DMRestoreNamedLocalVector(dm, "__petsc_dm_transform_local_copy", &tmpl));
3327:     } else {
3328:       PetscCall(VecRestoreArrayReadAndMemType(l, &lArray));
3329:     }
3330:     PetscCall(VecRestoreArrayAndMemType(g, &gArray));
3331:   } else if (s && isInsert) {
3332:   } else {
3333:     PetscUseTypeMethod(dm, localtoglobalend, l, mode == INSERT_ALL_VALUES ? INSERT_VALUES : (mode == ADD_ALL_VALUES ? ADD_VALUES : mode), g);
3334:   }
3335:   for (link = dm->ltoghook; link; link = link->next) {
3336:     if (link->endhook) PetscCall((*link->endhook)(dm, g, mode, l, link->ctx));
3337:   }
3338:   PetscFunctionReturn(PETSC_SUCCESS);
3339: }

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

3346:   Neighbor-wise Collective

3348:   Input Parameters:
3349: + dm   - the `DM` object
3350: . g    - the original local vector
3351: - mode - one of `INSERT_VALUES` or `ADD_VALUES`

3353:   Output Parameter:
3354: . l - the local vector with correct ghost values

3356:   Level: intermediate

3358:   Note:
3359:   Must be followed by `DMLocalToLocalEnd()`.

3361: .seealso: [](ch_dmbase), `DM`, `DMLocalToLocalEnd()`, `DMCoarsen()`, `DMDestroy()`, `DMView()`, `DMCreateLocalVector()`, `DMCreateGlobalVector()`, `DMCreateInterpolation()`, `DMGlobalToLocalEnd()`, `DMLocalToGlobalBegin()`
3362: @*/
3363: PetscErrorCode DMLocalToLocalBegin(DM dm, Vec g, InsertMode mode, Vec l)
3364: {
3365:   PetscFunctionBegin;
3369:   PetscUseTypeMethod(dm, localtolocalbegin, g, mode == INSERT_ALL_VALUES ? INSERT_VALUES : (mode == ADD_ALL_VALUES ? ADD_VALUES : mode), l);
3370:   PetscFunctionReturn(PETSC_SUCCESS);
3371: }

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

3377:   Neighbor-wise Collective

3379:   Input Parameters:
3380: + dm   - the `DM` object
3381: . g    - the original local vector
3382: - mode - one of `INSERT_VALUES` or `ADD_VALUES`

3384:   Output Parameter:
3385: . l - the local vector with correct ghost values

3387:   Level: intermediate

3389: .seealso: [](ch_dmbase), `DM`, `DMLocalToLocalBegin()`, `DMCoarsen()`, `DMDestroy()`, `DMView()`, `DMCreateLocalVector()`, `DMCreateGlobalVector()`, `DMCreateInterpolation()`, `DMGlobalToLocalEnd()`, `DMLocalToGlobalBegin()`
3390: @*/
3391: PetscErrorCode DMLocalToLocalEnd(DM dm, Vec g, InsertMode mode, Vec l)
3392: {
3393:   PetscFunctionBegin;
3397:   PetscUseTypeMethod(dm, localtolocalend, g, mode == INSERT_ALL_VALUES ? INSERT_VALUES : (mode == ADD_ALL_VALUES ? ADD_VALUES : mode), l);
3398:   PetscFunctionReturn(PETSC_SUCCESS);
3399: }

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

3404:   Collective

3406:   Input Parameters:
3407: + dm   - the `DM` object
3408: - comm - the communicator to contain the new `DM` object (or `MPI_COMM_NULL`)

3410:   Output Parameter:
3411: . dmc - the coarsened `DM`

3413:   Level: developer

3415: .seealso: [](ch_dmbase), `DM`, `DMRefine()`, `DMDestroy()`, `DMView()`, `DMCreateGlobalVector()`, `DMCreateInterpolation()`, `DMCreateDomainDecomposition()`,
3416:           `DMCoarsenHookAdd()`, `DMCoarsenHookRemove()`
3417: @*/
3418: PetscErrorCode DMCoarsen(DM dm, MPI_Comm comm, DM *dmc)
3419: {
3420:   DMCoarsenHookLink link;

3422:   PetscFunctionBegin;
3424:   PetscCall(PetscLogEventBegin(DM_Coarsen, dm, 0, 0, 0));
3425:   PetscUseTypeMethod(dm, coarsen, comm, dmc);
3426:   if (*dmc) {
3427:     (*dmc)->bind_below = dm->bind_below; /* Propagate this from parent DM; otherwise -dm_bind_below will be useless for multigrid cases. */
3428:     PetscCall(DMSetCoarseDM(dm, *dmc));
3429:     (*dmc)->ops->creatematrix = dm->ops->creatematrix;
3430:     PetscCall(PetscObjectCopyFortranFunctionPointers((PetscObject)dm, (PetscObject)*dmc));
3431:     (*dmc)->ctx       = dm->ctx;
3432:     (*dmc)->levelup   = dm->levelup;
3433:     (*dmc)->leveldown = dm->leveldown + 1;
3434:     PetscCall(DMSetMatType(*dmc, dm->mattype));
3435:     for (link = dm->coarsenhook; link; link = link->next) {
3436:       if (link->coarsenhook) PetscCall((*link->coarsenhook)(dm, *dmc, link->ctx));
3437:     }
3438:   }
3439:   PetscCall(PetscLogEventEnd(DM_Coarsen, dm, 0, 0, 0));
3440:   PetscCheck(*dmc, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "NULL coarse mesh produced");
3441:   PetscFunctionReturn(PETSC_SUCCESS);
3442: }

3444: /*@
3445:   DMCoarsenHookAdd - adds a callback to be run when restricting a nonlinear problem to the coarse grid

3447:   Logically Collective; No Fortran Support

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

3455:   Calling sequence of `coarsenhook`:
3456: + fine   - fine level `DM`
3457: . coarse - coarse level `DM` to restrict problem to
3458: - ctx    - optional application function context

3460:   Calling sequence of `restricthook`:
3461: + fine      - fine level `DM`
3462: . mrestrict - matrix restricting a fine-level solution to the coarse grid, usually the transpose of the interpolation
3463: . rscale    - scaling vector for restriction
3464: . inject    - matrix restricting by injection
3465: . coarse    - coarse level DM to update
3466: - ctx       - optional application function context

3468:   Level: advanced

3470:   Notes:
3471:   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`.

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

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

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

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

3486:   PetscFunctionBegin;
3488:   for (p = &fine->coarsenhook; *p; p = &(*p)->next) { /* Scan to the end of the current list of hooks */
3489:     if ((*p)->coarsenhook == coarsenhook && (*p)->restricthook == restricthook && (*p)->ctx == ctx) PetscFunctionReturn(PETSC_SUCCESS);
3490:   }
3491:   PetscCall(PetscNew(&link));
3492:   link->coarsenhook  = coarsenhook;
3493:   link->restricthook = restricthook;
3494:   link->ctx          = ctx;
3495:   link->next         = NULL;
3496:   *p                 = link;
3497:   PetscFunctionReturn(PETSC_SUCCESS);
3498: }

3500: /*@
3501:   DMCoarsenHookRemove - remove a callback set with `DMCoarsenHookAdd()`

3503:   Logically Collective; No Fortran Support

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

3511:   Calling sequence of `coarsenhook`:
3512: + fine   - fine level `DM`
3513: . coarse - coarse level `DM` to restrict problem to
3514: - ctx    - optional application function context

3516:   Calling sequence of `restricthook`:
3517: + fine    - fine level `DM`
3518: . rstrict - matrix restricting a fine-level solution to the coarse grid, usually the transpose of the interpolation
3519: . rscale  - scaling vector for restriction
3520: . inject  - matrix restricting by injection
3521: . coarse  - coarse level DM to update
3522: - ctx     - optional application function context

3524:   Level: advanced

3526:   Notes:
3527:   This function does nothing if the `coarsenhook` is not in the list.

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

3531: .seealso: [](ch_dmbase), `DM`, `DMCoarsenHookAdd()`, `DMRefineHookAdd()`, `SNESFASGetInterpolation()`, `SNESFASGetInjection()`, `PetscObjectCompose()`, `PetscContainerCreate()`
3532: @*/
3533: 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)
3534: {
3535:   DMCoarsenHookLink link, *p;

3537:   PetscFunctionBegin;
3539:   for (p = &fine->coarsenhook; *p; p = &(*p)->next) { /* Search the list of current hooks */
3540:     if ((*p)->coarsenhook == coarsenhook && (*p)->restricthook == restricthook && (*p)->ctx == ctx) {
3541:       link = *p;
3542:       *p   = link->next;
3543:       PetscCall(PetscFree(link));
3544:       break;
3545:     }
3546:   }
3547:   PetscFunctionReturn(PETSC_SUCCESS);
3548: }

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

3553:   Collective if any hooks are

3555:   Input Parameters:
3556: + fine    - finer `DM` from which the data is obtained
3557: . restrct - restriction matrix, apply using `MatRestrict()`, usually the transpose of the interpolation
3558: . rscale  - scaling vector for restriction
3559: . inject  - injection matrix, also use `MatRestrict()`
3560: - coarse  - coarser `DM` to update

3562:   Level: developer

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

3567: .seealso: [](ch_dmbase), `DM`, `DMCoarsenHookAdd()`, `MatRestrict()`, `DMInterpolate()`, `DMRefineHookAdd()`
3568: @*/
3569: PetscErrorCode DMRestrict(DM fine, Mat restrct, Vec rscale, Mat inject, DM coarse)
3570: {
3571:   DMCoarsenHookLink link;

3573:   PetscFunctionBegin;
3574:   for (link = fine->coarsenhook; link; link = link->next) {
3575:     if (link->restricthook) PetscCall((*link->restricthook)(fine, restrct, rscale, inject, coarse, link->ctx));
3576:   }
3577:   PetscFunctionReturn(PETSC_SUCCESS);
3578: }

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

3583:   Logically Collective; No Fortran Support

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

3591:   Calling sequence of `ddhook`:
3592: + global - global `DM`
3593: . block  - subdomain `DM`
3594: - ctx    - optional application function context

3596:   Calling sequence of `restricthook`:
3597: + global - global `DM`
3598: . out    - scatter to the outer (with ghost and overlap points) sub vector
3599: . in     - scatter to sub vector values only owned locally
3600: . block  - subdomain `DM`
3601: - ctx    - optional application function context

3603:   Level: advanced

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

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

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

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

3616: .seealso: [](ch_dmbase), `DM`, `DMSubDomainHookRemove()`, `DMRefineHookAdd()`, `SNESFASGetInterpolation()`, `SNESFASGetInjection()`, `PetscObjectCompose()`, `PetscContainerCreate()`, `DMCreateDomainDecomposition()`
3617: @*/
3618: 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)
3619: {
3620:   DMSubDomainHookLink link, *p;

3622:   PetscFunctionBegin;
3624:   for (p = &global->subdomainhook; *p; p = &(*p)->next) { /* Scan to the end of the current list of hooks */
3625:     if ((*p)->ddhook == ddhook && (*p)->restricthook == restricthook && (*p)->ctx == ctx) PetscFunctionReturn(PETSC_SUCCESS);
3626:   }
3627:   PetscCall(PetscNew(&link));
3628:   link->restricthook = restricthook;
3629:   link->ddhook       = ddhook;
3630:   link->ctx          = ctx;
3631:   link->next         = NULL;
3632:   *p                 = link;
3633:   PetscFunctionReturn(PETSC_SUCCESS);
3634: }

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

3639:   Logically Collective; No Fortran Support

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

3647:   Calling sequence of `ddhook`:
3648: + dm    - global `DM`
3649: . block - subdomain `DM`
3650: - ctx   - optional application function context

3652:   Calling sequence of `restricthook`:
3653: + dm       - global `DM`
3654: . oscatter - scatter to the outer (with ghost and overlap points) sub vector
3655: . gscatter - scatter to sub vector values only owned locally
3656: . block    - subdomain `DM`
3657: - ctx      - optional application function context

3659:   Level: advanced

3661: .seealso: [](ch_dmbase), `DM`, `DMSubDomainHookAdd()`, `SNESFASGetInterpolation()`, `SNESFASGetInjection()`, `PetscObjectCompose()`, `PetscContainerCreate()`,
3662:           `DMCreateDomainDecomposition()`
3663: @*/
3664: 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)
3665: {
3666:   DMSubDomainHookLink link, *p;

3668:   PetscFunctionBegin;
3670:   for (p = &global->subdomainhook; *p; p = &(*p)->next) { /* Search the list of current hooks */
3671:     if ((*p)->ddhook == ddhook && (*p)->restricthook == restricthook && (*p)->ctx == ctx) {
3672:       link = *p;
3673:       *p   = link->next;
3674:       PetscCall(PetscFree(link));
3675:       break;
3676:     }
3677:   }
3678:   PetscFunctionReturn(PETSC_SUCCESS);
3679: }

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

3684:   Collective if any hooks are

3686:   Input Parameters:
3687: + global   - The global `DM` to use as a base
3688: . oscatter - The scatter from domain global vector filling subdomain global vector with overlap
3689: . gscatter - The scatter from domain global vector filling subdomain local vector with ghosts
3690: - subdm    - The subdomain `DM` to update

3692:   Level: developer

3694: .seealso: [](ch_dmbase), `DM`, `DMCoarsenHookAdd()`, `MatRestrict()`, `DMCreateDomainDecomposition()`
3695: @*/
3696: PetscErrorCode DMSubDomainRestrict(DM global, VecScatter oscatter, VecScatter gscatter, DM subdm)
3697: {
3698:   DMSubDomainHookLink link;

3700:   PetscFunctionBegin;
3701:   for (link = global->subdomainhook; link; link = link->next) {
3702:     if (link->restricthook) PetscCall((*link->restricthook)(global, oscatter, gscatter, subdm, link->ctx));
3703:   }
3704:   PetscFunctionReturn(PETSC_SUCCESS);
3705: }

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

3710:   Not Collective

3712:   Input Parameter:
3713: . dm - the `DM` object

3715:   Output Parameter:
3716: . level - number of coarsenings

3718:   Level: developer

3720: .seealso: [](ch_dmbase), `DM`, `DMCoarsen()`, `DMSetCoarsenLevel()`, `DMGetRefineLevel()`, `DMDestroy()`, `DMView()`, `DMCreateGlobalVector()`, `DMCreateInterpolation()`
3721: @*/
3722: PetscErrorCode DMGetCoarsenLevel(DM dm, PetscInt *level)
3723: {
3724:   PetscFunctionBegin;
3726:   PetscAssertPointer(level, 2);
3727:   *level = dm->leveldown;
3728:   PetscFunctionReturn(PETSC_SUCCESS);
3729: }

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

3734:   Collective

3736:   Input Parameters:
3737: + dm    - the `DM` object
3738: - level - number of coarsenings

3740:   Level: developer

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

3745: .seealso: [](ch_dmbase), `DM`, `DMCoarsen()`, `DMGetCoarsenLevel()`, `DMGetRefineLevel()`, `DMDestroy()`, `DMView()`, `DMCreateGlobalVector()`, `DMCreateInterpolation()`
3746: @*/
3747: PetscErrorCode DMSetCoarsenLevel(DM dm, PetscInt level)
3748: {
3749:   PetscFunctionBegin;
3751:   dm->leveldown = level;
3752:   PetscFunctionReturn(PETSC_SUCCESS);
3753: }

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

3758:   Collective

3760:   Input Parameters:
3761: + dm      - the `DM` object
3762: - nlevels - the number of levels of refinement

3764:   Output Parameter:
3765: . dmf - the refined `DM` hierarchy

3767:   Level: developer

3769: .seealso: [](ch_dmbase), `DM`, `DMCoarsen()`, `DMCoarsenHierarchy()`, `DMDestroy()`, `DMView()`, `DMCreateGlobalVector()`, `DMCreateInterpolation()`
3770: @*/
3771: PetscErrorCode DMRefineHierarchy(DM dm, PetscInt nlevels, DM dmf[])
3772: {
3773:   PetscFunctionBegin;
3775:   PetscCheck(nlevels >= 0, PetscObjectComm((PetscObject)dm), PETSC_ERR_ARG_OUTOFRANGE, "nlevels cannot be negative");
3776:   if (nlevels == 0) PetscFunctionReturn(PETSC_SUCCESS);
3777:   PetscAssertPointer(dmf, 3);
3778:   if (dm->ops->refine && !dm->ops->refinehierarchy) {
3779:     PetscCall(DMRefine(dm, PetscObjectComm((PetscObject)dm), &dmf[0]));
3780:     for (PetscInt i = 1; i < nlevels; i++) PetscCall(DMRefine(dmf[i - 1], PetscObjectComm((PetscObject)dm), &dmf[i]));
3781:   } else PetscUseTypeMethod(dm, refinehierarchy, nlevels, dmf);
3782:   PetscFunctionReturn(PETSC_SUCCESS);
3783: }

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

3788:   Collective

3790:   Input Parameters:
3791: + dm      - the `DM` object
3792: - nlevels - the number of levels of coarsening

3794:   Output Parameter:
3795: . dmc - the coarsened `DM` hierarchy

3797:   Level: developer

3799: .seealso: [](ch_dmbase), `DM`, `DMCoarsen()`, `DMRefineHierarchy()`, `DMDestroy()`, `DMView()`, `DMCreateGlobalVector()`, `DMCreateInterpolation()`
3800: @*/
3801: PetscErrorCode DMCoarsenHierarchy(DM dm, PetscInt nlevels, DM dmc[])
3802: {
3803:   PetscFunctionBegin;
3805:   PetscCheck(nlevels >= 0, PetscObjectComm((PetscObject)dm), PETSC_ERR_ARG_OUTOFRANGE, "nlevels cannot be negative");
3806:   if (nlevels == 0) PetscFunctionReturn(PETSC_SUCCESS);
3807:   PetscAssertPointer(dmc, 3);
3808:   if (dm->ops->coarsen && !dm->ops->coarsenhierarchy) {
3809:     PetscCall(DMCoarsen(dm, PetscObjectComm((PetscObject)dm), &dmc[0]));
3810:     for (PetscInt i = 1; i < nlevels; i++) PetscCall(DMCoarsen(dmc[i - 1], PetscObjectComm((PetscObject)dm), &dmc[i]));
3811:   } else PetscUseTypeMethod(dm, coarsenhierarchy, nlevels, dmc);
3812:   PetscFunctionReturn(PETSC_SUCCESS);
3813: }

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

3818:   Logically Collective if the function is collective

3820:   Input Parameters:
3821: + dm      - the `DM` object
3822: - destroy - the destroy function, see `PetscCtxDestroyFn` for the calling sequence

3824:   Level: intermediate

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

3837: /*@
3838:   DMSetApplicationContext - Set an application context into a `DM` object

3840:   Not Collective

3842:   Input Parameters:
3843: + dm  - the `DM` object
3844: - ctx - the application context

3846:   Level: intermediate

3848:   Note:
3849:   An application context is a way to pass problem specific information that is accessible whenever the `DM` is available
3850:   In a multilevel solver, the application context is shared by all the `DM` in the hierarchy; it is thus not advisable
3851:   to store objects that represent discretized quantities inside the context.

3853:   Fortran Notes:
3854:   This only works when the context is a Fortran derived type or a `PetscObject`. Declare `ctx` with
3855: .vb
3856:   type(tUsertype), pointer :: ctx
3857: .ve

3859: .seealso: [](ch_dmbase), `DM`, `DMGetApplicationContext()`, `DMView()`, `DMCreateGlobalVector()`, `DMCreateInterpolation()`, `DMCreateColoring()`, `DMCreateMatrix()`, `DMCreateMassMatrix()`
3860: @*/
3861: PetscErrorCode DMSetApplicationContext(DM dm, PetscCtx ctx)
3862: {
3863:   PetscFunctionBegin;
3865:   dm->ctx = ctx;
3866:   PetscFunctionReturn(PETSC_SUCCESS);
3867: }

3869: /*@
3870:   DMGetApplicationContext - Gets an application context from a `DM` object provided with `DMSetApplicationContext()`

3872:   Not Collective

3874:   Input Parameter:
3875: . dm - the `DM` object

3877:   Output Parameter:
3878: . ctx - a pointer to the application context

3880:   Level: intermediate

3882:   Note:
3883:   An application context is a way to pass problem specific information that is accessible whenever the `DM` is available

3885:   Fortran Notes:
3886:   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
3887:   function that tells the Fortran compiler the derived data type that is returned as the `ctx` argument. For example,
3888: .vb
3889:   Interface DMGetApplicationContext
3890:     Subroutine DMGetApplicationContext(dm,ctx,ierr)
3891:   #include <petsc/finclude/petscdm.h>
3892:       use petscdm
3893:       DM dm
3894:       type(tUsertype), pointer :: ctx
3895:       PetscErrorCode ierr
3896:     End Subroutine
3897:   End Interface DMGetApplicationContext
3898: .ve

3900:   The prototype for `ctx` must be
3901: .vb
3902:   type(tUsertype), pointer :: ctx
3903: .ve

3905: .seealso: [](ch_dmbase), `DM`, `DMView()`, `DMCreateGlobalVector()`, `DMCreateInterpolation()`, `DMCreateColoring()`, `DMCreateMatrix()`, `DMCreateMassMatrix()`
3906: @*/
3907: PetscErrorCode DMGetApplicationContext(DM dm, PetscCtxRt ctx)
3908: {
3909:   PetscFunctionBegin;
3911:   *(void **)ctx = dm->ctx;
3912:   PetscFunctionReturn(PETSC_SUCCESS);
3913: }

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

3918:   Logically Collective

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

3924:   Calling sequence of f:
3925: + dm    - the `DM`
3926: . lower - the vector to hold the lower bounds
3927: - upper - the vector to hold the upper bounds

3929:   Level: intermediate

3931:   Developer Note:
3932:   Should be called `DMSetComputeVIBounds()` or something similar

3934: .seealso: [](ch_dmbase), `DM`, `DMComputeVariableBounds()`, `DMHasVariableBounds()`, `DMView()`, `DMCreateGlobalVector()`, `DMCreateInterpolation()`, `DMCreateColoring()`, `DMCreateMatrix()`, `DMCreateMassMatrix()`, `DMGetApplicationContext()`
3935: @*/
3936: PetscErrorCode DMSetVariableBounds(DM dm, PetscErrorCode (*f)(DM dm, Vec lower, Vec upper))
3937: {
3938:   PetscFunctionBegin;
3940:   dm->ops->computevariablebounds = f;
3941:   PetscFunctionReturn(PETSC_SUCCESS);
3942: }

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

3947:   Not Collective

3949:   Input Parameter:
3950: . dm - the `DM` object to destroy

3952:   Output Parameter:
3953: . flg - `PETSC_TRUE` if the variable bounds function exists

3955:   Level: developer

3957: .seealso: [](ch_dmbase), `DM`, `DMComputeVariableBounds()`, `DMView()`, `DMCreateGlobalVector()`, `DMCreateInterpolation()`, `DMCreateColoring()`, `DMCreateMatrix()`, `DMCreateMassMatrix()`, `DMGetApplicationContext()`
3958: @*/
3959: PetscErrorCode DMHasVariableBounds(DM dm, PetscBool *flg)
3960: {
3961:   PetscFunctionBegin;
3963:   PetscAssertPointer(flg, 2);
3964:   *flg = dm->ops->computevariablebounds ? PETSC_TRUE : PETSC_FALSE;
3965:   PetscFunctionReturn(PETSC_SUCCESS);
3966: }

3968: /*@
3969:   DMComputeVariableBounds - compute variable bounds used by `SNESVI`.

3971:   Logically Collective

3973:   Input Parameter:
3974: . dm - the `DM` object

3976:   Output Parameters:
3977: + xl - lower bound
3978: - xu - upper bound

3980:   Level: advanced

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

3985: .seealso: [](ch_dmbase), `DM`, `DMHasVariableBounds()`, `DMView()`, `DMCreateGlobalVector()`, `DMCreateInterpolation()`, `DMCreateColoring()`, `DMCreateMatrix()`, `DMCreateMassMatrix()`, `DMGetApplicationContext()`
3986: @*/
3987: PetscErrorCode DMComputeVariableBounds(DM dm, Vec xl, Vec xu)
3988: {
3989:   PetscFunctionBegin;
3993:   PetscUseTypeMethod(dm, computevariablebounds, xl, xu);
3994:   PetscFunctionReturn(PETSC_SUCCESS);
3995: }

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

4000:   Not Collective

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

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

4008:   Level: developer

4010: .seealso: [](ch_dmbase), `DM`, `DMCreateColoring()`
4011: @*/
4012: PetscErrorCode DMHasColoring(DM dm, PetscBool *flg)
4013: {
4014:   PetscFunctionBegin;
4016:   PetscAssertPointer(flg, 2);
4017:   *flg = dm->ops->getcoloring ? PETSC_TRUE : PETSC_FALSE;
4018:   PetscFunctionReturn(PETSC_SUCCESS);
4019: }

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

4024:   Not Collective

4026:   Input Parameter:
4027: . dm - the `DM` object

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

4032:   Level: developer

4034: .seealso: [](ch_dmbase), `DM`, `DMCreateRestriction()`, `DMHasCreateInterpolation()`, `DMHasCreateInjection()`
4035: @*/
4036: PetscErrorCode DMHasCreateRestriction(DM dm, PetscBool *flg)
4037: {
4038:   PetscFunctionBegin;
4040:   PetscAssertPointer(flg, 2);
4041:   *flg = dm->ops->createrestriction ? PETSC_TRUE : PETSC_FALSE;
4042:   PetscFunctionReturn(PETSC_SUCCESS);
4043: }

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

4048:   Not Collective

4050:   Input Parameter:
4051: . dm - the `DM` object

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

4056:   Level: developer

4058: .seealso: [](ch_dmbase), `DM`, `DMCreateInjection()`, `DMHasCreateRestriction()`, `DMHasCreateInterpolation()`
4059: @*/
4060: PetscErrorCode DMHasCreateInjection(DM dm, PetscBool *flg)
4061: {
4062:   PetscFunctionBegin;
4064:   PetscAssertPointer(flg, 2);
4065:   if (dm->ops->hascreateinjection) PetscUseTypeMethod(dm, hascreateinjection, flg);
4066:   else *flg = dm->ops->createinjection ? PETSC_TRUE : PETSC_FALSE;
4067:   PetscFunctionReturn(PETSC_SUCCESS);
4068: }

4070: PetscFunctionList DMList              = NULL;
4071: PetscBool         DMRegisterAllCalled = PETSC_FALSE;

4073: /*@
4074:   DMSetType - Builds a `DM`, for a particular `DM` implementation.

4076:   Collective

4078:   Input Parameters:
4079: + dm     - The `DM` object
4080: - method - The name of the `DMType`, for example `DMDA`, `DMPLEX`

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

4085:   Level: intermediate

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

4090: .seealso: [](ch_dmbase), `DM`, `DMType`, `DMDA`, `DMPLEX`, `DMGetType()`, `DMCreate()`, `DMDACreate2d()`
4091: @*/
4092: PetscErrorCode DMSetType(DM dm, DMType method)
4093: {
4094:   PetscErrorCode (*r)(DM);
4095:   PetscBool match;

4097:   PetscFunctionBegin;
4099:   PetscCall(PetscObjectTypeCompare((PetscObject)dm, method, &match));
4100:   if (match) PetscFunctionReturn(PETSC_SUCCESS);

4102:   PetscCall(DMRegisterAll());
4103:   PetscCall(PetscFunctionListFind(DMList, method, &r));
4104:   PetscCheck(r, PetscObjectComm((PetscObject)dm), PETSC_ERR_ARG_UNKNOWN_TYPE, "Unknown DM type: %s", method);

4106:   PetscTryTypeMethod(dm, destroy);
4107:   PetscCall(PetscMemzero(dm->ops, sizeof(*dm->ops)));
4108:   PetscCall(PetscObjectChangeTypeName((PetscObject)dm, method));
4109:   PetscCall((*r)(dm));
4110:   PetscFunctionReturn(PETSC_SUCCESS);
4111: }

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

4116:   Not Collective

4118:   Input Parameter:
4119: . dm - The `DM`

4121:   Output Parameter:
4122: . type - The `DMType` name

4124:   Level: intermediate

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

4129: .seealso: [](ch_dmbase), `DM`, `DMType`, `DMDA`, `DMPLEX`, `DMSetType()`, `DMCreate()`, `PetscObjectTypeCompare()`, `PetscObjectTypeCompareAny()`
4130: @*/
4131: PetscErrorCode DMGetType(DM dm, DMType *type)
4132: {
4133:   PetscFunctionBegin;
4135:   PetscAssertPointer(type, 2);
4136:   PetscCall(DMRegisterAll());
4137:   *type = ((PetscObject)dm)->type_name;
4138:   PetscFunctionReturn(PETSC_SUCCESS);
4139: }

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

4144:   Collective

4146:   Input Parameters:
4147: + dm      - the `DM`
4148: - newtype - new `DM` type (use "same" for the same type)

4150:   Output Parameter:
4151: . M - pointer to new `DM`

4153:   Level: intermediate

4155:   Note:
4156:   Cannot be used to convert a sequential `DM` to a parallel or a parallel to sequential,
4157:   the MPI communicator of the generated `DM` is always the same as the communicator
4158:   of the input `DM`.

4160: .seealso: [](ch_dmbase), `DM`, `DMSetType()`, `DMCreate()`, `DMClone()`
4161: @*/
4162: PetscErrorCode DMConvert(DM dm, DMType newtype, DM *M)
4163: {
4164:   DM        B;
4165:   char      convname[256];
4166:   PetscBool sametype /*, issame */;

4168:   PetscFunctionBegin;
4171:   PetscAssertPointer(M, 3);
4172:   PetscCall(PetscObjectTypeCompare((PetscObject)dm, newtype, &sametype));
4173:   /* PetscCall(PetscStrcmp(newtype, "same", &issame)); */
4174:   if (sametype) {
4175:     *M = dm;
4176:     PetscCall(PetscObjectReference((PetscObject)dm));
4177:     PetscFunctionReturn(PETSC_SUCCESS);
4178:   } else {
4179:     PetscErrorCode (*conv)(DM, DMType, DM *) = NULL;

4181:     /*
4182:        Order of precedence:
4183:        1) See if a specialized converter is known to the current DM.
4184:        2) See if a specialized converter is known to the desired DM class.
4185:        3) See if a good general converter is registered for the desired class
4186:        4) See if a good general converter is known for the current matrix.
4187:        5) Use a really basic converter.
4188:     */

4190:     /* 1) See if a specialized converter is known to the current DM and the desired class */
4191:     PetscCall(PetscStrncpy(convname, "DMConvert_", sizeof(convname)));
4192:     PetscCall(PetscStrlcat(convname, ((PetscObject)dm)->type_name, sizeof(convname)));
4193:     PetscCall(PetscStrlcat(convname, "_", sizeof(convname)));
4194:     PetscCall(PetscStrlcat(convname, newtype, sizeof(convname)));
4195:     PetscCall(PetscStrlcat(convname, "_C", sizeof(convname)));
4196:     PetscCall(PetscObjectQueryFunction((PetscObject)dm, convname, &conv));
4197:     if (conv) goto foundconv;

4199:     /* 2)  See if a specialized converter is known to the desired DM class. */
4200:     PetscCall(DMCreate(PetscObjectComm((PetscObject)dm), &B));
4201:     PetscCall(DMSetType(B, newtype));
4202:     PetscCall(PetscStrncpy(convname, "DMConvert_", sizeof(convname)));
4203:     PetscCall(PetscStrlcat(convname, ((PetscObject)dm)->type_name, sizeof(convname)));
4204:     PetscCall(PetscStrlcat(convname, "_", sizeof(convname)));
4205:     PetscCall(PetscStrlcat(convname, newtype, sizeof(convname)));
4206:     PetscCall(PetscStrlcat(convname, "_C", sizeof(convname)));
4207:     PetscCall(PetscObjectQueryFunction((PetscObject)B, convname, &conv));
4208:     if (conv) {
4209:       PetscCall(DMDestroy(&B));
4210:       goto foundconv;
4211:     }

4213: #if 0
4214:     /* 3) See if a good general converter is registered for the desired class */
4215:     conv = B->ops->convertfrom;
4216:     PetscCall(DMDestroy(&B));
4217:     if (conv) goto foundconv;

4219:     /* 4) See if a good general converter is known for the current matrix */
4220:     if (dm->ops->convert) conv = dm->ops->convert;
4221:     if (conv) goto foundconv;
4222: #endif

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

4227:   foundconv:
4228:     PetscCall(PetscLogEventBegin(DM_Convert, dm, 0, 0, 0));
4229:     PetscCall((*conv)(dm, newtype, M));
4230:     /* Things that are independent of DM type: We should consult DMClone() here */
4231:     {
4232:       const PetscReal *maxCell, *Lstart, *L;

4234:       PetscCall(DMGetPeriodicity(dm, &maxCell, &Lstart, &L));
4235:       PetscCall(DMSetPeriodicity(*M, maxCell, Lstart, L));
4236:       (*M)->prealloc_only = dm->prealloc_only;
4237:       PetscCall(PetscFree((*M)->vectype));
4238:       PetscCall(PetscStrallocpy(dm->vectype, (char **)&(*M)->vectype));
4239:       PetscCall(PetscFree((*M)->mattype));
4240:       PetscCall(PetscStrallocpy(dm->mattype, (char **)&(*M)->mattype));
4241:     }
4242:     PetscCall(PetscLogEventEnd(DM_Convert, dm, 0, 0, 0));
4243:   }
4244:   PetscCall(PetscObjectStateIncrease((PetscObject)*M));
4245:   PetscFunctionReturn(PETSC_SUCCESS);
4246: }

4248: /*@
4249:   DMRegister -  Adds a new `DM` type implementation

4251:   Not Collective, No Fortran Support

4253:   Input Parameters:
4254: + sname    - The name of a new user-defined creation routine
4255: - function - The creation routine itself

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

4260:   Level: advanced

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

4265:   Example Usage:
4266: .vb
4267:     DMRegister("my_da", MyDMCreate);
4268: .ve

4270:   Then, your `DM` type can be chosen with the procedural interface via
4271: .vb
4272:     DMCreate(MPI_Comm, DM *);
4273:     DMSetType(DM,"my_da");
4274: .ve
4275:   or at runtime via the option
4276: .vb
4277:     -da_type my_da
4278: .ve

4280: .seealso: [](ch_dmbase), `DM`, `DMType`, `DMSetType()`, `DMRegisterAll()`
4281: @*/
4282: PetscErrorCode DMRegister(const char sname[], PetscErrorCode (*function)(DM dm))
4283: {
4284:   PetscFunctionBegin;
4285:   PetscCall(DMInitializePackage());
4286:   PetscCall(PetscFunctionListAdd(&DMList, sname, function));
4287:   PetscFunctionReturn(PETSC_SUCCESS);
4288: }

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

4293:   Collective

4295:   Input Parameters:
4296: + newdm  - the newly loaded `DM`, this needs to have been created with `DMCreate()` or
4297:            some related function before a call to `DMLoad()`.
4298: - viewer - binary file viewer, obtained from `PetscViewerBinaryOpen()` or
4299:            `PETSCVIEWERHDF5` file viewer, obtained from `PetscViewerHDF5Open()`

4301:   Level: intermediate

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

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

4310: .seealso: [](ch_dmbase), `DM`, `PetscViewerBinaryOpen()`, `DMView()`, `MatLoad()`, `VecLoad()`
4311: @*/
4312: PetscErrorCode DMLoad(DM newdm, PetscViewer viewer)
4313: {
4314:   PetscBool isbinary, ishdf5;

4316:   PetscFunctionBegin;
4319:   PetscCall(PetscViewerCheckReadable(viewer));
4320:   PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERBINARY, &isbinary));
4321:   PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERHDF5, &ishdf5));
4322:   PetscCall(PetscLogEventBegin(DM_Load, viewer, 0, 0, 0));
4323:   if (isbinary) {
4324:     PetscInt classid;
4325:     char     type[256];

4327:     PetscCall(PetscViewerBinaryRead(viewer, &classid, 1, NULL, PETSC_INT));
4328:     PetscCheck(classid == DM_FILE_CLASSID, PetscObjectComm((PetscObject)newdm), PETSC_ERR_ARG_WRONG, "Not DM next in file, classid found %" PetscInt_FMT, classid);
4329:     PetscCall(PetscViewerBinaryRead(viewer, type, 256, NULL, PETSC_CHAR));
4330:     PetscCall(DMSetType(newdm, type));
4331:     PetscTryTypeMethod(newdm, load, viewer);
4332:   } else if (ishdf5) {
4333:     PetscTryTypeMethod(newdm, load, viewer);
4334:   } else SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Invalid viewer; open viewer with PetscViewerBinaryOpen() or PetscViewerHDF5Open()");
4335:   PetscCall(PetscLogEventEnd(DM_Load, viewer, 0, 0, 0));
4336:   PetscFunctionReturn(PETSC_SUCCESS);
4337: }

4339: /* FEM Support */

4341: /*@
4342:   DMPrintCellIndices - Print an integer array of per-cell indices to `PETSC_COMM_SELF`

4344:   Not Collective

4346:   Input Parameters:
4347: + c    - the cell number
4348: . name - the label to print with the cell (typically the element or field name)
4349: . len  - the length of `x`
4350: - x    - the array of integer indices

4352:   Level: developer

4354: .seealso: [](ch_dmbase), `DM`, `DMPrintCellVector()`, `DMPrintCellVectorReal()`, `DMPrintCellMatrix()`, `DMPrintLocalVec()`
4355: @*/
4356: PetscErrorCode DMPrintCellIndices(PetscInt c, const char name[], PetscInt len, const PetscInt x[])
4357: {
4358:   PetscInt f;

4360:   PetscFunctionBegin;
4361:   PetscCall(PetscPrintf(PETSC_COMM_SELF, "Cell %" PetscInt_FMT " Element %s\n", c, name));
4362:   for (f = 0; f < len; ++f) PetscCall(PetscPrintf(PETSC_COMM_SELF, "  | %" PetscInt_FMT " |\n", x[f]));
4363:   PetscFunctionReturn(PETSC_SUCCESS);
4364: }

4366: /*@
4367:   DMPrintCellVector - Print a scalar array representing a per-cell vector to `PETSC_COMM_SELF`

4369:   Not Collective

4371:   Input Parameters:
4372: + c    - the cell number
4373: . name - the label to print with the cell (typically the element or field name)
4374: . len  - the length of `x`
4375: - x    - the array of `PetscScalar` values

4377:   Level: developer

4379:   Note:
4380:   Only the real part of each entry is printed.

4382: .seealso: [](ch_dmbase), `DM`, `DMPrintCellIndices()`, `DMPrintCellVectorReal()`, `DMPrintCellMatrix()`, `DMPrintLocalVec()`
4383: @*/
4384: PetscErrorCode DMPrintCellVector(PetscInt c, const char name[], PetscInt len, const PetscScalar x[])
4385: {
4386:   PetscInt f;

4388:   PetscFunctionBegin;
4389:   PetscCall(PetscPrintf(PETSC_COMM_SELF, "Cell %" PetscInt_FMT " Element %s\n", c, name));
4390:   for (f = 0; f < len; ++f) PetscCall(PetscPrintf(PETSC_COMM_SELF, "  | %g |\n", (double)PetscRealPart(x[f])));
4391:   PetscFunctionReturn(PETSC_SUCCESS);
4392: }

4394: /*@
4395:   DMPrintCellVectorReal - Print a real array representing a per-cell vector to `PETSC_COMM_SELF`

4397:   Not Collective

4399:   Input Parameters:
4400: + c    - the cell number
4401: . name - the label to print with the cell (typically the element or field name)
4402: . len  - the length of `x`
4403: - x    - the array of `PetscReal` values

4405:   Level: developer

4407: .seealso: [](ch_dmbase), `DM`, `DMPrintCellIndices()`, `DMPrintCellVector()`, `DMPrintCellMatrix()`, `DMPrintLocalVec()`
4408: @*/
4409: PetscErrorCode DMPrintCellVectorReal(PetscInt c, const char name[], PetscInt len, const PetscReal x[])
4410: {
4411:   PetscFunctionBegin;
4412:   PetscCall(PetscPrintf(PETSC_COMM_SELF, "Cell %" PetscInt_FMT " Element %s\n", c, name));
4413:   for (PetscInt f = 0; f < len; ++f) PetscCall(PetscPrintf(PETSC_COMM_SELF, "  | %g |\n", (double)x[f]));
4414:   PetscFunctionReturn(PETSC_SUCCESS);
4415: }

4417: /*@
4418:   DMPrintCellMatrix - Print a scalar array representing a per-cell matrix to `PETSC_COMM_SELF`

4420:   Not Collective

4422:   Input Parameters:
4423: + c    - the cell number
4424: . name - the label to print with the cell (typically the element or field name)
4425: . rows - number of rows in the matrix
4426: . cols - number of columns in the matrix
4427: - A    - the row-major array of `PetscScalar` matrix entries

4429:   Level: developer

4431:   Note:
4432:   Only the real part of each entry is printed.

4434: .seealso: [](ch_dmbase), `DM`, `DMPrintCellIndices()`, `DMPrintCellVector()`, `DMPrintCellVectorReal()`, `DMPrintLocalVec()`
4435: @*/
4436: PetscErrorCode DMPrintCellMatrix(PetscInt c, const char name[], PetscInt rows, PetscInt cols, const PetscScalar A[])
4437: {
4438:   PetscFunctionBegin;
4439:   PetscCall(PetscPrintf(PETSC_COMM_SELF, "Cell %" PetscInt_FMT " Element %s\n", c, name));
4440:   for (PetscInt f = 0; f < rows; ++f) {
4441:     PetscCall(PetscPrintf(PETSC_COMM_SELF, "  |"));
4442:     for (PetscInt g = 0; g < cols; ++g) PetscCall(PetscPrintf(PETSC_COMM_SELF, " % 9.5g", (double)PetscRealPart(A[f * cols + g])));
4443:     PetscCall(PetscPrintf(PETSC_COMM_SELF, " |\n"));
4444:   }
4445:   PetscFunctionReturn(PETSC_SUCCESS);
4446: }

4448: /*@
4449:   DMPrintLocalVec - Print a `Vec` associated with a `DM`, filtering out very small entries

4451:   Collective

4453:   Input Parameters:
4454: + dm   - the `DM` providing the communicator
4455: . name - a label printed before the vector values
4456: . tol  - tolerance below which entries are filtered to zero using `VecFilter()`
4457: - X    - the `Vec` to print

4459:   Level: developer

4461:   Note:
4462:   Runs in parallel by wrapping the local portion of the vector in an MPI vector for viewing.

4464: .seealso: [](ch_dmbase), `DM`, `DMPrintCellIndices()`, `DMPrintCellVector()`, `DMPrintCellVectorReal()`, `DMPrintCellMatrix()`, `VecFilter()`
4465: @*/
4466: PetscErrorCode DMPrintLocalVec(DM dm, const char name[], PetscReal tol, Vec X)
4467: {
4468:   PetscInt           localSize, bs;
4469:   PetscMPIInt        size;
4470:   Vec                x, xglob;
4471:   const PetscScalar *xarray;

4473:   PetscFunctionBegin;
4474:   PetscCallMPI(MPI_Comm_size(PetscObjectComm((PetscObject)dm), &size));
4475:   PetscCall(VecDuplicate(X, &x));
4476:   PetscCall(VecCopy(X, x));
4477:   PetscCall(VecFilter(x, tol));
4478:   PetscCall(PetscPrintf(PetscObjectComm((PetscObject)dm), "%s:\n", name));
4479:   if (size > 1) {
4480:     PetscCall(VecGetLocalSize(x, &localSize));
4481:     PetscCall(VecGetArrayRead(x, &xarray));
4482:     PetscCall(VecGetBlockSize(x, &bs));
4483:     PetscCall(VecCreateMPIWithArray(PetscObjectComm((PetscObject)dm), bs, localSize, PETSC_DETERMINE, xarray, &xglob));
4484:   } else {
4485:     xglob = x;
4486:   }
4487:   PetscCall(VecView(xglob, PETSC_VIEWER_STDOUT_(PetscObjectComm((PetscObject)dm))));
4488:   if (size > 1) {
4489:     PetscCall(VecDestroy(&xglob));
4490:     PetscCall(VecRestoreArrayRead(x, &xarray));
4491:   }
4492:   PetscCall(VecDestroy(&x));
4493:   PetscFunctionReturn(PETSC_SUCCESS);
4494: }

4496: PetscErrorCode DMViewDSFromOptions_Internal(DM dm, const char opt[])
4497: {
4498:   PetscObject       obj = (PetscObject)dm;
4499:   PetscViewer       viewer;
4500:   PetscViewerFormat format;
4501:   PetscBool         flg;

4503:   PetscFunctionBegin;
4504:   PetscCall(PetscOptionsCreateViewer(PetscObjectComm(obj), obj->options, obj->prefix, opt, &viewer, &format, &flg));
4505:   if (flg) {
4506:     PetscCall(PetscViewerPushFormat(viewer, format));
4507:     for (PetscInt d = 0; d < dm->Nds; ++d) PetscCall(PetscDSView(dm->probs[d].ds, viewer));
4508:     PetscCall(PetscViewerFlush(viewer));
4509:     PetscCall(PetscViewerPopFormat(viewer));
4510:     PetscCall(PetscViewerDestroy(&viewer));
4511:   }
4512:   PetscFunctionReturn(PETSC_SUCCESS);
4513: }

4515: PetscErrorCode DMViewSectionFromOptions_Internal(DM dm, const char opt[])
4516: {
4517:   PetscObject       obj = (PetscObject)dm;
4518:   PetscViewer       viewer;
4519:   PetscViewerFormat format;
4520:   PetscBool         flg;

4522:   PetscFunctionBegin;
4523:   PetscCall(PetscOptionsCreateViewer(PetscObjectComm(obj), obj->options, obj->prefix, opt, &viewer, &format, &flg));
4524:   if (flg) {
4525:     PetscCall(PetscViewerPushFormat(viewer, format));
4526:     if (dm->localSection) PetscCall(PetscSectionView(dm->localSection, viewer));
4527:     PetscCall(PetscViewerFlush(viewer));
4528:     PetscCall(PetscViewerPopFormat(viewer));
4529:     PetscCall(PetscViewerDestroy(&viewer));
4530:   }
4531:   PetscFunctionReturn(PETSC_SUCCESS);
4532: }

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

4537:   Input Parameter:
4538: . dm - The `DM`

4540:   Output Parameter:
4541: . section - The `PetscSection`

4543:   Options Database Key:
4544: . -dm_petscsection_view - View the section created by the `DM`

4546:   Level: intermediate

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

4551: .seealso: [](ch_dmbase), `DM`, `DMSetLocalSection()`, `DMGetGlobalSection()`
4552: @*/
4553: PetscErrorCode DMGetLocalSection(DM dm, PetscSection *section)
4554: {
4555:   PetscFunctionBegin;
4557:   PetscAssertPointer(section, 2);
4558:   if (!dm->localSection && dm->ops->createlocalsection) {
4559:     if (dm->setfromoptionscalled) {
4560:       for (PetscInt d = 0; d < dm->Nds; ++d) PetscCall(PetscDSSetFromOptions(dm->probs[d].ds));
4561:       PetscCall(DMViewDSFromOptions_Internal(dm, "-dm_petscds_view"));
4562:     }
4563:     PetscUseTypeMethod(dm, createlocalsection);
4564:     if (dm->localSection) PetscCall(PetscObjectViewFromOptions((PetscObject)dm->localSection, NULL, "-dm_petscsection_view"));
4565:   }
4566:   *section = dm->localSection;
4567:   PetscFunctionReturn(PETSC_SUCCESS);
4568: }

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

4573:   Input Parameters:
4574: + dm      - The `DM`
4575: - section - The `PetscSection`

4577:   Level: intermediate

4579:   Note:
4580:   Any existing Section will be destroyed. The global section, the section `PetscSF`, and any local-to-global mapping previously derived from the sections are
4581:   invalidated and will be rebuilt on their next access. A mapping built by the `DM` implementation itself, such as by `DMDA` in `DMSetUp()`, is kept.

4583: .seealso: [](ch_dmbase), `DM`, `PetscSection`, `DMGetLocalSection()`, `DMSetGlobalSection()`
4584: @*/
4585: PetscErrorCode DMSetLocalSection(DM dm, PetscSection section)
4586: {
4587:   PetscInt numFields = 0;

4589:   PetscFunctionBegin;
4592:   PetscCall(PetscObjectReference((PetscObject)section));
4593:   PetscCall(PetscSectionDestroy(&dm->localSection));
4594:   dm->localSection = section;
4595:   if (section) PetscCall(PetscSectionGetNumFields(dm->localSection, &numFields));
4596:   if (numFields) {
4597:     PetscCall(DMSetNumFields(dm, numFields));
4598:     for (PetscInt f = 0; f < numFields; ++f) {
4599:       PetscObject disc;
4600:       const char *name;

4602:       PetscCall(PetscSectionGetFieldName(dm->localSection, f, &name));
4603:       PetscCall(DMGetField(dm, f, NULL, &disc));
4604:       PetscCall(PetscObjectSetName(disc, name));
4605:     }
4606:   }
4607:   /* The global section, the SectionSF, and a section-derived local-to-global mapping will be rebuilt
4608:      in the next call to DMGetGlobalSection(), DMGetSectionSF(), and DMGetLocalToGlobalMapping().
4609:      A mapping built by the implementation (e.g. DMDA in DMSetUp()) does not depend on the sections and could not be rebuilt, so it is kept. */
4610:   PetscCall(PetscSectionDestroy(&dm->globalSection));
4611:   PetscCall(PetscSFDestroy(&dm->sectionSF));
4612:   PetscCall(PetscSFCreate(PetscObjectComm((PetscObject)dm), &dm->sectionSF));
4613:   if (dm->ltogmapFromSection) PetscCall(ISLocalToGlobalMappingDestroy(&dm->ltogmap));

4615:   /* Clear scratch vectors */
4616:   PetscCall(DMClearGlobalVectors(dm));
4617:   PetscCall(DMClearLocalVectors(dm));
4618:   PetscCall(DMClearNamedGlobalVectors(dm));
4619:   PetscCall(DMClearNamedLocalVectors(dm));
4620:   PetscFunctionReturn(PETSC_SUCCESS);
4621: }

4623: /*@
4624:   DMCreateSectionPermutation - Create a permutation of the `PetscSection` chart and optionally a block structure.

4626:   Input Parameter:
4627: . dm - The `DM`

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

4633:   Level: developer

4635: .seealso: [](ch_dmbase), `DM`, `PetscSection`, `DMGetLocalSection()`, `DMGetGlobalSection()`
4636: @*/
4637: PetscErrorCode DMCreateSectionPermutation(DM dm, IS *perm, PetscBT *blockStarts)
4638: {
4639:   PetscFunctionBegin;
4640:   *perm        = NULL;
4641:   *blockStarts = NULL;
4642:   PetscTryTypeMethod(dm, createsectionpermutation, perm, blockStarts);
4643:   PetscFunctionReturn(PETSC_SUCCESS);
4644: }

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

4649:   not Collective

4651:   Input Parameter:
4652: . dm - The `DM`

4654:   Output Parameters:
4655: + 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.
4656: . 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.
4657: - bias    - Vector containing bias to be added to constrained dofs

4659:   Level: advanced

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

4664: .seealso: [](ch_dmbase), `DM`, `DMSetDefaultConstraints()`
4665: @*/
4666: PetscErrorCode DMGetDefaultConstraints(DM dm, PetscSection *section, Mat *mat, Vec *bias)
4667: {
4668:   PetscFunctionBegin;
4670:   if (!dm->defaultConstraint.section && !dm->defaultConstraint.mat && dm->ops->createdefaultconstraints) PetscUseTypeMethod(dm, createdefaultconstraints);
4671:   if (section) *section = dm->defaultConstraint.section;
4672:   if (mat) *mat = dm->defaultConstraint.mat;
4673:   if (bias) *bias = dm->defaultConstraint.bias;
4674:   PetscFunctionReturn(PETSC_SUCCESS);
4675: }

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

4680:   Collective

4682:   Input Parameters:
4683: + dm      - The `DM`
4684: . 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).
4685: . 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).
4686: - 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).

4688:   Level: advanced

4690:   Notes:
4691:   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()`.

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

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

4697: .seealso: [](ch_dmbase), `DM`, `DMGetDefaultConstraints()`
4698: @*/
4699: PetscErrorCode DMSetDefaultConstraints(DM dm, PetscSection section, Mat mat, Vec bias)
4700: {
4701:   PetscMPIInt result;

4703:   PetscFunctionBegin;
4705:   if (section) {
4707:     PetscCallMPI(MPI_Comm_compare(PETSC_COMM_SELF, PetscObjectComm((PetscObject)section), &result));
4708:     PetscCheck(result == MPI_CONGRUENT || result == MPI_IDENT, PETSC_COMM_SELF, PETSC_ERR_ARG_NOTSAMECOMM, "constraint section must have local communicator");
4709:   }
4710:   if (mat) {
4712:     PetscCallMPI(MPI_Comm_compare(PETSC_COMM_SELF, PetscObjectComm((PetscObject)mat), &result));
4713:     PetscCheck(result == MPI_CONGRUENT || result == MPI_IDENT, PETSC_COMM_SELF, PETSC_ERR_ARG_NOTSAMECOMM, "constraint matrix must have local communicator");
4714:   }
4715:   if (bias) {
4717:     PetscCallMPI(MPI_Comm_compare(PETSC_COMM_SELF, PetscObjectComm((PetscObject)bias), &result));
4718:     PetscCheck(result == MPI_CONGRUENT || result == MPI_IDENT, PETSC_COMM_SELF, PETSC_ERR_ARG_NOTSAMECOMM, "constraint bias must have local communicator");
4719:   }
4720:   PetscCall(PetscObjectReference((PetscObject)section));
4721:   PetscCall(PetscSectionDestroy(&dm->defaultConstraint.section));
4722:   dm->defaultConstraint.section = section;
4723:   PetscCall(PetscObjectReference((PetscObject)mat));
4724:   PetscCall(MatDestroy(&dm->defaultConstraint.mat));
4725:   dm->defaultConstraint.mat = mat;
4726:   PetscCall(PetscObjectReference((PetscObject)bias));
4727:   PetscCall(VecDestroy(&dm->defaultConstraint.bias));
4728:   dm->defaultConstraint.bias = bias;
4729:   PetscFunctionReturn(PETSC_SUCCESS);
4730: }

4732: /*
4733:   DMDefaultSectionCheckConsistency - Check the consistentcy of the global and local sections. Generates and error if they are not consistent.

4735:   Input Parameters:
4736: + dm - The `DM`
4737: . localSection - `PetscSection` describing the local data layout
4738: - globalSection - `PetscSection` describing the global data layout

4740:   Level: intermediate

4742: .seealso: [](ch_dmbase), `DM`, `DMGetSectionSF()`, `DMSetSectionSF()`
4743: */
4744: static PetscErrorCode DMDefaultSectionCheckConsistency_Internal(DM dm, PetscSection localSection, PetscSection globalSection)
4745: {
4746:   MPI_Comm        comm;
4747:   PetscLayout     layout;
4748:   const PetscInt *ranges;
4749:   PetscInt        pStart, pEnd, p, nroots;
4750:   PetscMPIInt     size, rank;
4751:   PetscBool       valid = PETSC_TRUE;

4753:   PetscFunctionBegin;
4754:   PetscCall(PetscObjectGetComm((PetscObject)dm, &comm));
4756:   PetscCallMPI(MPI_Comm_size(comm, &size));
4757:   PetscCallMPI(MPI_Comm_rank(comm, &rank));
4758:   PetscCall(PetscSectionGetChart(globalSection, &pStart, &pEnd));
4759:   PetscCall(PetscSectionGetConstrainedStorageSize(globalSection, &nroots));
4760:   PetscCall(PetscLayoutCreate(comm, &layout));
4761:   PetscCall(PetscLayoutSetBlockSize(layout, 1));
4762:   PetscCall(PetscLayoutSetLocalSize(layout, nroots));
4763:   PetscCall(PetscLayoutSetUp(layout));
4764:   PetscCall(PetscLayoutGetRanges(layout, &ranges));
4765:   for (p = pStart; p < pEnd; ++p) {
4766:     PetscInt dof, cdof, off, gdof, gcdof, goff, gsize, d;

4768:     PetscCall(PetscSectionGetDof(localSection, p, &dof));
4769:     PetscCall(PetscSectionGetOffset(localSection, p, &off));
4770:     PetscCall(PetscSectionGetConstraintDof(localSection, p, &cdof));
4771:     PetscCall(PetscSectionGetDof(globalSection, p, &gdof));
4772:     PetscCall(PetscSectionGetConstraintDof(globalSection, p, &gcdof));
4773:     PetscCall(PetscSectionGetOffset(globalSection, p, &goff));
4774:     if (!gdof) continue; /* Censored point */
4775:     if ((gdof < 0 ? -(gdof + 1) : gdof) != dof) {
4776:       PetscCall(PetscSynchronizedPrintf(comm, "[%d]Global dof %" PetscInt_FMT " for point %" PetscInt_FMT " not equal to local dof %" PetscInt_FMT "\n", rank, gdof, p, dof));
4777:       valid = PETSC_FALSE;
4778:     }
4779:     if (gcdof && (gcdof != cdof)) {
4780:       PetscCall(PetscSynchronizedPrintf(comm, "[%d]Global constraints %" PetscInt_FMT " for point %" PetscInt_FMT " not equal to local constraints %" PetscInt_FMT "\n", rank, gcdof, p, cdof));
4781:       valid = PETSC_FALSE;
4782:     }
4783:     if (gdof < 0) {
4784:       gsize = gdof < 0 ? -(gdof + 1) - gcdof : gdof - gcdof;
4785:       for (d = 0; d < gsize; ++d) {
4786:         PetscInt offset = -(goff + 1) + d, r;

4788:         PetscCall(PetscFindInt(offset, size + 1, ranges, &r));
4789:         if (r < 0) r = -(r + 2);
4790:         if (r < 0 || r >= size) {
4791:           PetscCall(PetscSynchronizedPrintf(comm, "[%d]Point %" PetscInt_FMT " mapped to invalid process %" PetscInt_FMT " (%" PetscInt_FMT ", %" PetscInt_FMT ")\n", rank, p, r, gdof, goff));
4792:           valid = PETSC_FALSE;
4793:           break;
4794:         }
4795:       }
4796:     }
4797:   }
4798:   PetscCall(PetscLayoutDestroy(&layout));
4799:   PetscCall(PetscSynchronizedFlush(comm, NULL));
4800:   PetscCallMPI(MPIU_Allreduce(MPI_IN_PLACE, &valid, 1, MPI_C_BOOL, MPI_LAND, comm));
4801:   if (!valid) {
4802:     PetscCall(DMView(dm, NULL));
4803:     SETERRQ(comm, PETSC_ERR_ARG_WRONG, "Inconsistent local and global sections");
4804:   }
4805:   PetscFunctionReturn(PETSC_SUCCESS);
4806: }

4808: PetscErrorCode DMGetIsoperiodicPointSF_Internal(DM dm, PetscSF *sf)
4809: {
4810:   PetscErrorCode (*f)(DM, PetscSF *);

4812:   PetscFunctionBegin;
4814:   PetscAssertPointer(sf, 2);
4815:   PetscCall(PetscObjectQueryFunction((PetscObject)dm, "DMGetIsoperiodicPointSF_C", &f));
4816:   if (f) PetscCall(f(dm, sf));
4817:   else *sf = dm->sf;
4818:   PetscFunctionReturn(PETSC_SUCCESS);
4819: }

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

4824:   Collective

4826:   Input Parameter:
4827: . dm - The `DM`

4829:   Output Parameter:
4830: . section - The `PetscSection`

4832:   Level: intermediate

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

4837: .seealso: [](ch_dmbase), `DM`, `DMSetLocalSection()`, `DMGetLocalSection()`
4838: @*/
4839: PetscErrorCode DMGetGlobalSection(DM dm, PetscSection *section)
4840: {
4841:   PetscFunctionBegin;
4843:   PetscAssertPointer(section, 2);
4844:   if (!dm->globalSection) {
4845:     PetscSection s;
4846:     PetscSF      sf;

4848:     PetscCall(DMGetLocalSection(dm, &s));
4849:     PetscCheck(s, PetscObjectComm((PetscObject)dm), PETSC_ERR_ARG_WRONGSTATE, "DM must have a default PetscSection in order to create a global PetscSection");
4850:     PetscCheck(dm->sf, PetscObjectComm((PetscObject)dm), PETSC_ERR_ARG_WRONGSTATE, "DM must have a point PetscSF in order to create a global PetscSection");
4851:     PetscCall(DMGetIsoperiodicPointSF_Internal(dm, &sf));
4852:     PetscCall(PetscSectionCreateGlobalSection(s, sf, PETSC_TRUE, PETSC_FALSE, PETSC_FALSE, &dm->globalSection));
4853:     PetscCall(PetscLayoutDestroy(&dm->map));
4854:     PetscCall(PetscSectionGetValueLayout(PetscObjectComm((PetscObject)dm), dm->globalSection, &dm->map));
4855:     PetscCall(PetscSectionViewFromOptions(dm->globalSection, NULL, "-global_section_view"));
4856:   }
4857:   *section = dm->globalSection;
4858:   PetscFunctionReturn(PETSC_SUCCESS);
4859: }

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

4864:   Input Parameters:
4865: + dm      - The `DM`
4866: - section - The PetscSection, or `NULL`

4868:   Level: intermediate

4870:   Note:
4871:   Any existing `PetscSection` will be destroyed. The section `PetscSF` and any local-to-global mapping previously derived from the sections are invalidated
4872:   and will be rebuilt on their next access. A mapping built by the `DM` implementation itself, such as by `DMDA` in `DMSetUp()`, is kept.

4874: .seealso: [](ch_dmbase), `DM`, `DMGetGlobalSection()`, `DMSetLocalSection()`
4875: @*/
4876: PetscErrorCode DMSetGlobalSection(DM dm, PetscSection section)
4877: {
4878:   PetscFunctionBegin;
4881:   PetscCall(PetscObjectReference((PetscObject)section));
4882:   PetscCall(PetscSectionDestroy(&dm->globalSection));
4883:   dm->globalSection = section;
4884:   if (PetscDefined(USE_DEBUG) && section) PetscCall(DMDefaultSectionCheckConsistency_Internal(dm, dm->localSection, section));
4885:   /* Clear global scratch vectors, sectionSF, and a section-derived local-to-global mapping, which encodes the old section's offsets */
4886:   PetscCall(PetscSFDestroy(&dm->sectionSF));
4887:   PetscCall(PetscSFCreate(PetscObjectComm((PetscObject)dm), &dm->sectionSF));
4888:   if (dm->ltogmapFromSection) PetscCall(ISLocalToGlobalMappingDestroy(&dm->ltogmap));
4889:   PetscCall(DMClearGlobalVectors(dm));
4890:   PetscCall(DMClearNamedGlobalVectors(dm));
4891:   PetscFunctionReturn(PETSC_SUCCESS);
4892: }

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

4898:   Input Parameter:
4899: . dm - The `DM`

4901:   Output Parameter:
4902: . sf - The `PetscSF`

4904:   Level: intermediate

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

4909: .seealso: [](ch_dmbase), `DM`, `DMSetSectionSF()`, `DMCreateSectionSF()`
4910: @*/
4911: PetscErrorCode DMGetSectionSF(DM dm, PetscSF *sf)
4912: {
4913:   PetscInt nroots;

4915:   PetscFunctionBegin;
4917:   PetscAssertPointer(sf, 2);
4918:   if (!dm->sectionSF) PetscCall(PetscSFCreate(PetscObjectComm((PetscObject)dm), &dm->sectionSF));
4919:   PetscCall(PetscSFGetGraph(dm->sectionSF, &nroots, NULL, NULL, NULL));
4920:   if (nroots < 0) {
4921:     PetscSection section, gSection;

4923:     PetscCall(DMGetLocalSection(dm, &section));
4924:     if (section) {
4925:       PetscCall(DMGetGlobalSection(dm, &gSection));
4926:       PetscCall(DMCreateSectionSF(dm, section, gSection));
4927:     } else {
4928:       *sf = NULL;
4929:       PetscFunctionReturn(PETSC_SUCCESS);
4930:     }
4931:   }
4932:   *sf = dm->sectionSF;
4933:   PetscFunctionReturn(PETSC_SUCCESS);
4934: }

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

4939:   Input Parameters:
4940: + dm - The `DM`
4941: - sf - The `PetscSF`

4943:   Level: intermediate

4945:   Note:
4946:   Any previous `PetscSF` is destroyed

4948: .seealso: [](ch_dmbase), `DM`, `DMGetSectionSF()`, `DMCreateSectionSF()`
4949: @*/
4950: PetscErrorCode DMSetSectionSF(DM dm, PetscSF sf)
4951: {
4952:   PetscFunctionBegin;
4955:   PetscCall(PetscObjectReference((PetscObject)sf));
4956:   PetscCall(PetscSFDestroy(&dm->sectionSF));
4957:   dm->sectionSF = sf;
4958:   PetscFunctionReturn(PETSC_SUCCESS);
4959: }

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

4965:   Input Parameters:
4966: + dm            - The `DM`
4967: . localSection  - `PetscSection` describing the local data layout
4968: - globalSection - `PetscSection` describing the global data layout

4970:   Level: developer

4972:   Note:
4973:   One usually uses `DMGetSectionSF()` to obtain the `PetscSF`

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

4981: .seealso: [](ch_dmbase), `DM`, `DMGetSectionSF()`, `DMSetSectionSF()`, `DMGetLocalSection()`, `DMGetGlobalSection()`
4982: @*/
4983: PetscErrorCode DMCreateSectionSF(DM dm, PetscSection localSection, PetscSection globalSection)
4984: {
4985:   PetscFunctionBegin;
4987:   PetscCall(PetscSFSetGraphSection(dm->sectionSF, localSection, globalSection));
4988:   PetscFunctionReturn(PETSC_SUCCESS);
4989: }

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

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

4996:   Input Parameter:
4997: . dm - The `DM`

4999:   Output Parameter:
5000: . sf - The `PetscSF`

5002:   Level: intermediate

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

5007: .seealso: [](ch_dmbase), `DM`, `DMSetPointSF()`, `DMGetSectionSF()`, `DMSetSectionSF()`, `DMCreateSectionSF()`
5008: @*/
5009: PetscErrorCode DMGetPointSF(DM dm, PetscSF *sf)
5010: {
5011:   PetscFunctionBegin;
5013:   PetscAssertPointer(sf, 2);
5014:   *sf = dm->sf;
5015:   PetscFunctionReturn(PETSC_SUCCESS);
5016: }

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

5021:   Collective

5023:   Input Parameters:
5024: + dm - The `DM`
5025: - sf - The `PetscSF`

5027:   Level: intermediate

5029: .seealso: [](ch_dmbase), `DM`, `DMGetPointSF()`, `DMGetSectionSF()`, `DMSetSectionSF()`, `DMCreateSectionSF()`
5030: @*/
5031: PetscErrorCode DMSetPointSF(DM dm, PetscSF sf)
5032: {
5033:   PetscFunctionBegin;
5036:   PetscCall(PetscObjectReference((PetscObject)sf));
5037:   PetscCall(PetscSFDestroy(&dm->sf));
5038:   dm->sf = sf;
5039:   PetscFunctionReturn(PETSC_SUCCESS);
5040: }

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

5045:   Input Parameter:
5046: . dm - The `DM`

5048:   Output Parameter:
5049: . sf - The `PetscSF`

5051:   Level: intermediate

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

5056: .seealso: [](ch_dmbase), `DM`, `DMSetNaturalSF()`, `DMSetUseNatural()`, `DMGetUseNatural()`, `DMPlexCreateGlobalToNaturalSF()`, `DMPlexDistribute()`
5057: @*/
5058: PetscErrorCode DMGetNaturalSF(DM dm, PetscSF *sf)
5059: {
5060:   PetscFunctionBegin;
5062:   PetscAssertPointer(sf, 2);
5063:   *sf = dm->sfNatural;
5064:   PetscFunctionReturn(PETSC_SUCCESS);
5065: }

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

5070:   Input Parameters:
5071: + dm - The DM
5072: - sf - The PetscSF

5074:   Level: intermediate

5076: .seealso: [](ch_dmbase), `DM`, `DMGetNaturalSF()`, `DMSetUseNatural()`, `DMGetUseNatural()`, `DMPlexCreateGlobalToNaturalSF()`, `DMPlexDistribute()`
5077: @*/
5078: PetscErrorCode DMSetNaturalSF(DM dm, PetscSF sf)
5079: {
5080:   PetscFunctionBegin;
5083:   PetscCall(PetscObjectReference((PetscObject)sf));
5084:   PetscCall(PetscSFDestroy(&dm->sfNatural));
5085:   dm->sfNatural = sf;
5086:   PetscFunctionReturn(PETSC_SUCCESS);
5087: }

5089: static PetscErrorCode DMSetDefaultAdjacency_Private(DM dm, PetscInt f, PetscObject disc)
5090: {
5091:   PetscClassId id;

5093:   PetscFunctionBegin;
5094:   PetscCall(PetscObjectGetClassId(disc, &id));
5095:   if (id == PETSCFE_CLASSID) PetscCall(DMSetAdjacency(dm, f, PETSC_FALSE, PETSC_TRUE));
5096:   else if (id == PETSCFV_CLASSID) PetscCall(DMSetAdjacency(dm, f, PETSC_TRUE, PETSC_FALSE));
5097:   else PetscCall(DMSetAdjacency(dm, f, PETSC_FALSE, PETSC_TRUE));
5098:   PetscFunctionReturn(PETSC_SUCCESS);
5099: }

5101: static PetscErrorCode DMFieldEnlarge_Static(DM dm, PetscInt NfNew)
5102: {
5103:   RegionField *tmpr;
5104:   PetscInt     Nf = dm->Nf, f;

5106:   PetscFunctionBegin;
5107:   if (Nf >= NfNew) PetscFunctionReturn(PETSC_SUCCESS);
5108:   PetscCall(PetscMalloc1(NfNew, &tmpr));
5109:   for (f = 0; f < Nf; ++f) tmpr[f] = dm->fields[f];
5110:   for (f = Nf; f < NfNew; ++f) {
5111:     tmpr[f].disc        = NULL;
5112:     tmpr[f].label       = NULL;
5113:     tmpr[f].avoidTensor = PETSC_FALSE;
5114:   }
5115:   PetscCall(PetscFree(dm->fields));
5116:   dm->Nf     = NfNew;
5117:   dm->fields = tmpr;
5118:   PetscFunctionReturn(PETSC_SUCCESS);
5119: }

5121: /*@
5122:   DMClearFields - Remove all fields from the `DM`

5124:   Logically Collective

5126:   Input Parameter:
5127: . dm - The `DM`

5129:   Level: intermediate

5131: .seealso: [](ch_dmbase), `DM`, `DMGetNumFields()`, `DMSetNumFields()`, `DMSetField()`
5132: @*/
5133: PetscErrorCode DMClearFields(DM dm)
5134: {
5135:   PetscInt f;

5137:   PetscFunctionBegin;
5139:   if (!dm->fields) PetscFunctionReturn(PETSC_SUCCESS); // DMDA does not use fields field in DM
5140:   for (f = 0; f < dm->Nf; ++f) {
5141:     PetscCall(PetscObjectDestroy(&dm->fields[f].disc));
5142:     PetscCall(DMLabelDestroy(&dm->fields[f].label));
5143:   }
5144:   PetscCall(PetscFree(dm->fields));
5145:   dm->fields = NULL;
5146:   dm->Nf     = 0;
5147:   PetscFunctionReturn(PETSC_SUCCESS);
5148: }

5150: /*@
5151:   DMGetNumFields - Get the number of fields in the `DM`

5153:   Not Collective

5155:   Input Parameter:
5156: . dm - The `DM`

5158:   Output Parameter:
5159: . numFields - The number of fields

5161:   Level: intermediate

5163: .seealso: [](ch_dmbase), `DM`, `DMSetNumFields()`, `DMSetField()`
5164: @*/
5165: PetscErrorCode DMGetNumFields(DM dm, PetscInt *numFields)
5166: {
5167:   PetscFunctionBegin;
5169:   PetscAssertPointer(numFields, 2);
5170:   *numFields = dm->Nf;
5171:   PetscFunctionReturn(PETSC_SUCCESS);
5172: }

5174: /*@
5175:   DMSetNumFields - Set the number of fields in the `DM`

5177:   Logically Collective

5179:   Input Parameters:
5180: + dm        - The `DM`
5181: - numFields - The number of fields

5183:   Level: intermediate

5185: .seealso: [](ch_dmbase), `DM`, `DMGetNumFields()`, `DMSetField()`
5186: @*/
5187: PetscErrorCode DMSetNumFields(DM dm, PetscInt numFields)
5188: {
5189:   PetscInt Nf;

5191:   PetscFunctionBegin;
5193:   PetscCall(DMGetNumFields(dm, &Nf));
5194:   for (PetscInt f = Nf; f < numFields; ++f) {
5195:     PetscContainer obj;

5197:     PetscCall(PetscContainerCreate(PetscObjectComm((PetscObject)dm), &obj));
5198:     PetscCall(DMAddField(dm, NULL, (PetscObject)obj));
5199:     PetscCall(PetscContainerDestroy(&obj));
5200:   }
5201:   PetscFunctionReturn(PETSC_SUCCESS);
5202: }

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

5207:   Not Collective

5209:   Input Parameters:
5210: + dm - The `DM`
5211: - f  - The field number

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

5217:   Level: intermediate

5219: .seealso: [](ch_dmbase), `DM`, `DMAddField()`, `DMSetField()`
5220: @*/
5221: PetscErrorCode DMGetField(DM dm, PetscInt f, DMLabel *label, PetscObject *disc)
5222: {
5223:   PetscFunctionBegin;
5225:   PetscAssertPointer(disc, 4);
5226:   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);
5227:   if (!dm->fields) {
5228:     if (label) *label = NULL;
5229:     if (disc) *disc = NULL;
5230:   } else { // some DM such as DMDA do not have dm->fields
5231:     if (label) *label = dm->fields[f].label;
5232:     if (disc) *disc = dm->fields[f].disc;
5233:   }
5234:   PetscFunctionReturn(PETSC_SUCCESS);
5235: }

5237: /* Does not clear the DS */
5238: PetscErrorCode DMSetField_Internal(DM dm, PetscInt f, DMLabel label, PetscObject disc)
5239: {
5240:   PetscFunctionBegin;
5241:   PetscCall(DMFieldEnlarge_Static(dm, f + 1));
5242:   PetscCall(DMLabelDestroy(&dm->fields[f].label));
5243:   PetscCall(PetscObjectDestroy(&dm->fields[f].disc));
5244:   dm->fields[f].label = label;
5245:   dm->fields[f].disc  = disc;
5246:   PetscCall(PetscObjectReference((PetscObject)label));
5247:   PetscCall(PetscObjectReference(disc));
5248:   PetscFunctionReturn(PETSC_SUCCESS);
5249: }

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

5255:   Logically Collective

5257:   Input Parameters:
5258: + dm    - The `DM`
5259: . f     - The field number
5260: . label - The label indicating the support of the field, or `NULL` for the entire mesh
5261: - disc  - The discretization object

5263:   Level: intermediate

5265: .seealso: [](ch_dmbase), `DM`, `DMAddField()`, `DMGetField()`
5266: @*/
5267: PetscErrorCode DMSetField(DM dm, PetscInt f, DMLabel label, PetscObject disc)
5268: {
5269:   PetscFunctionBegin;
5273:   PetscCheck(f >= 0, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Field number %" PetscInt_FMT " must be non-negative", f);
5274:   PetscCall(DMSetField_Internal(dm, f, label, disc));
5275:   PetscCall(DMSetDefaultAdjacency_Private(dm, f, disc));
5276:   PetscCall(DMClearDS(dm));
5277:   PetscFunctionReturn(PETSC_SUCCESS);
5278: }

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

5284:   Logically Collective

5286:   Input Parameters:
5287: + dm    - The `DM`
5288: . label - The label indicating the support of the field, or `NULL` for the entire mesh
5289: - disc  - The discretization object

5291:   Level: intermediate

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

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

5300:   Fortran Note:
5301:   Use the argument `PetscObjectCast(disc)` as the second argument

5303: .seealso: [](ch_dmbase), `DM`, `DMSetLabel()`, `DMSetField()`, `DMGetField()`, `PetscFE`
5304: @*/
5305: PetscErrorCode DMAddField(DM dm, DMLabel label, PetscObject disc)
5306: {
5307:   PetscInt Nf = dm->Nf;

5309:   PetscFunctionBegin;
5313:   PetscCall(DMFieldEnlarge_Static(dm, Nf + 1));
5314:   dm->fields[Nf].label = label;
5315:   dm->fields[Nf].disc  = disc;
5316:   PetscCall(PetscObjectReference((PetscObject)label));
5317:   PetscCall(PetscObjectReference(disc));
5318:   PetscCall(DMSetDefaultAdjacency_Private(dm, Nf, disc));
5319:   PetscCall(DMClearDS(dm));
5320:   PetscFunctionReturn(PETSC_SUCCESS);
5321: }

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

5326:   Logically Collective

5328:   Input Parameters:
5329: + dm          - The `DM`
5330: . f           - The field index
5331: - avoidTensor - `PETSC_TRUE` to skip defining the field on tensor cells

5333:   Level: intermediate

5335: .seealso: [](ch_dmbase), `DM`, `DMGetFieldAvoidTensor()`, `DMSetField()`, `DMGetField()`
5336: @*/
5337: PetscErrorCode DMSetFieldAvoidTensor(DM dm, PetscInt f, PetscBool avoidTensor)
5338: {
5339:   PetscFunctionBegin;
5340:   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);
5341:   dm->fields[f].avoidTensor = avoidTensor;
5342:   PetscFunctionReturn(PETSC_SUCCESS);
5343: }

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

5348:   Not Collective

5350:   Input Parameters:
5351: + dm - The `DM`
5352: - f  - The field index

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

5357:   Level: intermediate

5359: .seealso: [](ch_dmbase), `DM`, `DMAddField()`, `DMSetField()`, `DMGetField()`, `DMSetFieldAvoidTensor()`
5360: @*/
5361: PetscErrorCode DMGetFieldAvoidTensor(DM dm, PetscInt f, PetscBool *avoidTensor)
5362: {
5363:   PetscFunctionBegin;
5364:   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);
5365:   *avoidTensor = dm->fields[f].avoidTensor;
5366:   PetscFunctionReturn(PETSC_SUCCESS);
5367: }

5369: /*@
5370:   DMCopyFields - Copy the discretizations for the `DM` into another `DM`

5372:   Collective

5374:   Input Parameters:
5375: + dm        - The `DM`
5376: . minDegree - Minimum degree for a discretization, or `PETSC_DETERMINE` for no limit
5377: - maxDegree - Maximum degree for a discretization, or `PETSC_DETERMINE` for no limit

5379:   Output Parameter:
5380: . newdm - The `DM`

5382:   Level: advanced

5384: .seealso: [](ch_dmbase), `DM`, `DMGetField()`, `DMSetField()`, `DMAddField()`, `DMCopyDS()`, `DMGetDS()`, `DMGetCellDS()`
5385: @*/
5386: PetscErrorCode DMCopyFields(DM dm, PetscInt minDegree, PetscInt maxDegree, DM newdm)
5387: {
5388:   PetscInt Nf;

5390:   PetscFunctionBegin;
5391:   if (dm == newdm) PetscFunctionReturn(PETSC_SUCCESS);
5392:   PetscCall(DMGetNumFields(dm, &Nf));
5393:   PetscCall(DMClearFields(newdm));
5394:   for (PetscInt f = 0; f < Nf; ++f) {
5395:     DMLabel      label;
5396:     PetscObject  field;
5397:     PetscClassId id;
5398:     PetscBool    useCone, useClosure;

5400:     PetscCall(DMGetField(dm, f, &label, &field));
5401:     PetscCall(PetscObjectGetClassId(field, &id));
5402:     if (id == PETSCFE_CLASSID) {
5403:       PetscFE newfe;

5405:       PetscCall(PetscFELimitDegree((PetscFE)field, minDegree, maxDegree, &newfe));
5406:       PetscCall(DMSetField(newdm, f, label, (PetscObject)newfe));
5407:       PetscCall(PetscFEDestroy(&newfe));
5408:     } else {
5409:       PetscCall(DMSetField(newdm, f, label, field));
5410:     }
5411:     PetscCall(DMGetAdjacency(dm, f, &useCone, &useClosure));
5412:     PetscCall(DMSetAdjacency(newdm, f, useCone, useClosure));
5413:   }
5414:   // Create nullspace constructor slots
5415:   if (dm->nullspaceConstructors) {
5416:     PetscCall(PetscFree2(newdm->nullspaceConstructors, newdm->nearnullspaceConstructors));
5417:     PetscCall(PetscCalloc2(Nf, &newdm->nullspaceConstructors, Nf, &newdm->nearnullspaceConstructors));
5418:   }
5419:   PetscFunctionReturn(PETSC_SUCCESS);
5420: }

5422: /*@
5423:   DMGetAdjacency - Returns the flags for determining variable influence

5425:   Not Collective

5427:   Input Parameters:
5428: + dm - The `DM` object
5429: - f  - The field number, or `PETSC_DEFAULT` for the default adjacency

5431:   Output Parameters:
5432: + useCone    - Flag for variable influence starting with the cone operation
5433: - useClosure - Flag for variable influence using transitive closure

5435:   Level: developer

5437:   Notes:
5438: .vb
5439:      FEM:   Two points p and q are adjacent if q \in closure(star(p)),   useCone = PETSC_FALSE, useClosure = PETSC_TRUE
5440:      FVM:   Two points p and q are adjacent if q \in support(p+cone(p)), useCone = PETSC_TRUE,  useClosure = PETSC_FALSE
5441:      FVM++: Two points p and q are adjacent if q \in star(closure(p)),   useCone = PETSC_TRUE,  useClosure = PETSC_TRUE
5442: .ve
5443:   Further explanation can be found in the User's Manual Section on the Influence of Variables on One Another.

5445: .seealso: [](ch_dmbase), `DM`, `DMSetAdjacency()`, `DMGetField()`, `DMSetField()`
5446: @*/
5447: PetscErrorCode DMGetAdjacency(DM dm, PetscInt f, PetscBool *useCone, PetscBool *useClosure)
5448: {
5449:   PetscFunctionBegin;
5451:   if (useCone) PetscAssertPointer(useCone, 3);
5452:   if (useClosure) PetscAssertPointer(useClosure, 4);
5453:   if (f < 0) {
5454:     if (useCone) *useCone = dm->adjacency[0];
5455:     if (useClosure) *useClosure = dm->adjacency[1];
5456:   } else {
5457:     PetscInt Nf;

5459:     PetscCall(DMGetNumFields(dm, &Nf));
5460:     PetscCheck(f < Nf, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Field number %" PetscInt_FMT " must be in [0, %" PetscInt_FMT ")", f, Nf);
5461:     if (useCone) *useCone = dm->fields[f].adjacency[0];
5462:     if (useClosure) *useClosure = dm->fields[f].adjacency[1];
5463:   }
5464:   PetscFunctionReturn(PETSC_SUCCESS);
5465: }

5467: /*@
5468:   DMSetAdjacency - Set the flags for determining variable influence

5470:   Not Collective

5472:   Input Parameters:
5473: + dm         - The `DM` object
5474: . f          - The field number
5475: . useCone    - Flag for variable influence starting with the cone operation
5476: - useClosure - Flag for variable influence using transitive closure

5478:   Level: developer

5480:   Notes:
5481: .vb
5482:      FEM:   Two points p and q are adjacent if q \in closure(star(p)),   useCone = PETSC_FALSE, useClosure = PETSC_TRUE
5483:      FVM:   Two points p and q are adjacent if q \in support(p+cone(p)), useCone = PETSC_TRUE,  useClosure = PETSC_FALSE
5484:      FVM++: Two points p and q are adjacent if q \in star(closure(p)),   useCone = PETSC_TRUE,  useClosure = PETSC_TRUE
5485: .ve
5486:   Further explanation can be found in the User's Manual Section on the Influence of Variables on One Another.

5488: .seealso: [](ch_dmbase), `DM`, `DMGetAdjacency()`, `DMGetField()`, `DMSetField()`
5489: @*/
5490: PetscErrorCode DMSetAdjacency(DM dm, PetscInt f, PetscBool useCone, PetscBool useClosure)
5491: {
5492:   PetscFunctionBegin;
5494:   if (f < 0) {
5495:     dm->adjacency[0] = useCone;
5496:     dm->adjacency[1] = useClosure;
5497:   } else {
5498:     PetscInt Nf;

5500:     PetscCall(DMGetNumFields(dm, &Nf));
5501:     PetscCheck(f < Nf, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Field number %" PetscInt_FMT " must be in [0, %" PetscInt_FMT ")", f, Nf);
5502:     dm->fields[f].adjacency[0] = useCone;
5503:     dm->fields[f].adjacency[1] = useClosure;
5504:   }
5505:   PetscFunctionReturn(PETSC_SUCCESS);
5506: }

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

5511:   Not collective

5513:   Input Parameter:
5514: . dm - The `DM` object

5516:   Output Parameters:
5517: + useCone    - Flag for variable influence starting with the cone operation
5518: - useClosure - Flag for variable influence using transitive closure

5520:   Level: developer

5522:   Notes:
5523: .vb
5524:      FEM:   Two points p and q are adjacent if q \in closure(star(p)),   useCone = PETSC_FALSE, useClosure = PETSC_TRUE
5525:      FVM:   Two points p and q are adjacent if q \in support(p+cone(p)), useCone = PETSC_TRUE,  useClosure = PETSC_FALSE
5526:      FVM++: Two points p and q are adjacent if q \in star(closure(p)),   useCone = PETSC_TRUE,  useClosure = PETSC_TRUE
5527: .ve

5529: .seealso: [](ch_dmbase), `DM`, `DMSetBasicAdjacency()`, `DMGetField()`, `DMSetField()`
5530: @*/
5531: PetscErrorCode DMGetBasicAdjacency(DM dm, PetscBool *useCone, PetscBool *useClosure)
5532: {
5533:   PetscInt Nf;

5535:   PetscFunctionBegin;
5537:   if (useCone) PetscAssertPointer(useCone, 2);
5538:   if (useClosure) PetscAssertPointer(useClosure, 3);
5539:   PetscCall(DMGetNumFields(dm, &Nf));
5540:   if (!Nf) {
5541:     PetscCall(DMGetAdjacency(dm, PETSC_DEFAULT, useCone, useClosure));
5542:   } else {
5543:     PetscCall(DMGetAdjacency(dm, 0, useCone, useClosure));
5544:   }
5545:   PetscFunctionReturn(PETSC_SUCCESS);
5546: }

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

5551:   Not Collective

5553:   Input Parameters:
5554: + dm         - The `DM` object
5555: . useCone    - Flag for variable influence starting with the cone operation
5556: - useClosure - Flag for variable influence using transitive closure

5558:   Level: developer

5560:   Notes:
5561: .vb
5562:      FEM:   Two points p and q are adjacent if q \in closure(star(p)),   useCone = PETSC_FALSE, useClosure = PETSC_TRUE
5563:      FVM:   Two points p and q are adjacent if q \in support(p+cone(p)), useCone = PETSC_TRUE,  useClosure = PETSC_FALSE
5564:      FVM++: Two points p and q are adjacent if q \in star(closure(p)),   useCone = PETSC_TRUE,  useClosure = PETSC_TRUE
5565: .ve

5567: .seealso: [](ch_dmbase), `DM`, `DMGetBasicAdjacency()`, `DMGetField()`, `DMSetField()`
5568: @*/
5569: PetscErrorCode DMSetBasicAdjacency(DM dm, PetscBool useCone, PetscBool useClosure)
5570: {
5571:   PetscInt Nf;

5573:   PetscFunctionBegin;
5575:   PetscCall(DMGetNumFields(dm, &Nf));
5576:   if (!Nf) {
5577:     PetscCall(DMSetAdjacency(dm, PETSC_DEFAULT, useCone, useClosure));
5578:   } else {
5579:     PetscCall(DMSetAdjacency(dm, 0, useCone, useClosure));
5580:   }
5581:   PetscFunctionReturn(PETSC_SUCCESS);
5582: }

5584: PetscErrorCode DMCompleteBCLabels_Internal(DM dm)
5585: {
5586:   DM           plex;
5587:   DMLabel     *labels, *glabels;
5588:   const char **names;
5589:   char        *sendNames, *recvNames;
5590:   PetscInt     Nds, s, maxLabels = 0, maxLen = 0, Nl = 0, gNl, l, gl, m;
5591:   size_t       len;
5592:   MPI_Comm     comm;
5593:   PetscMPIInt  rank, size, p, *counts, *displs;

5595:   PetscFunctionBegin;
5596:   PetscCall(PetscObjectGetComm((PetscObject)dm, &comm));
5597:   PetscCallMPI(MPI_Comm_size(comm, &size));
5598:   PetscCallMPI(MPI_Comm_rank(comm, &rank));
5599:   PetscCall(DMGetNumDS(dm, &Nds));
5600:   for (s = 0; s < Nds; ++s) {
5601:     PetscDS  dsBC;
5602:     PetscInt numBd;

5604:     PetscCall(DMGetRegionNumDS(dm, s, NULL, NULL, &dsBC, NULL));
5605:     PetscCall(PetscDSGetNumBoundary(dsBC, &numBd));
5606:     maxLabels += numBd;
5607:   }
5608:   PetscCall(PetscCalloc1(maxLabels, &labels));
5609:   /* Get list of labels to be completed */
5610:   for (s = 0; s < Nds; ++s) {
5611:     PetscDS  dsBC;
5612:     PetscInt numBd;

5614:     PetscCall(DMGetRegionNumDS(dm, s, NULL, NULL, &dsBC, NULL));
5615:     PetscCall(PetscDSGetNumBoundary(dsBC, &numBd));
5616:     for (PetscInt bd = 0; bd < numBd; ++bd) {
5617:       DMLabel      label;
5618:       PetscInt     field;
5619:       PetscObject  obj;
5620:       PetscClassId id;

5622:       PetscCall(PetscDSGetBoundary(dsBC, bd, NULL, NULL, NULL, &label, NULL, NULL, &field, NULL, NULL, NULL, NULL, NULL));
5623:       PetscCall(DMGetField(dm, field, NULL, &obj));
5624:       PetscCall(PetscObjectGetClassId(obj, &id));
5625:       if (id != PETSCFE_CLASSID || !label) continue;
5626:       for (l = 0; l < Nl; ++l)
5627:         if (labels[l] == label) break;
5628:       if (l == Nl) labels[Nl++] = label;
5629:     }
5630:   }
5631:   /* Get label names */
5632:   PetscCall(PetscMalloc1(Nl, &names));
5633:   for (l = 0; l < Nl; ++l) PetscCall(PetscObjectGetName((PetscObject)labels[l], &names[l]));
5634:   for (l = 0; l < Nl; ++l) {
5635:     PetscCall(PetscStrlen(names[l], &len));
5636:     maxLen = PetscMax(maxLen, (PetscInt)len + 2);
5637:   }
5638:   PetscCall(PetscFree(labels));
5639:   PetscCallMPI(MPIU_Allreduce(MPI_IN_PLACE, &maxLen, 1, MPIU_INT, MPI_MAX, comm));
5640:   PetscCall(PetscCalloc1(Nl * maxLen, &sendNames));
5641:   for (l = 0; l < Nl; ++l) PetscCall(PetscStrncpy(&sendNames[maxLen * l], names[l], maxLen));
5642:   PetscCall(PetscFree(names));
5643:   /* Put all names on all processes */
5644:   PetscCall(PetscCalloc2(size, &counts, size + 1, &displs));
5645:   PetscCallMPI(MPI_Allgather(&Nl, 1, MPI_INT, counts, 1, MPI_INT, comm));
5646:   for (p = 0; p < size; ++p) displs[p + 1] = displs[p] + counts[p];
5647:   gNl = displs[size];
5648:   for (p = 0; p < size; ++p) {
5649:     counts[p] *= maxLen;
5650:     displs[p] *= maxLen;
5651:   }
5652:   PetscCall(PetscCalloc2(gNl * maxLen, &recvNames, gNl, &glabels));
5653:   PetscCallMPI(MPI_Allgatherv(sendNames, counts[rank], MPI_CHAR, recvNames, counts, displs, MPI_CHAR, comm));
5654:   PetscCall(PetscFree2(counts, displs));
5655:   PetscCall(PetscFree(sendNames));
5656:   for (l = 0, gl = 0; l < gNl; ++l) {
5657:     PetscCall(DMGetLabel(dm, &recvNames[l * maxLen], &glabels[gl]));
5658:     PetscCheck(glabels[gl], PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Label %s missing on rank %d", &recvNames[l * maxLen], rank);
5659:     for (m = 0; m < gl; ++m)
5660:       if (glabels[m] == glabels[gl]) goto next_label;
5661:     PetscCall(DMConvert(dm, DMPLEX, &plex));
5662:     PetscCall(DMPlexLabelComplete(plex, glabels[gl]));
5663:     PetscCall(DMDestroy(&plex));
5664:     ++gl;
5665:   next_label:
5666:     continue;
5667:   }
5668:   PetscCall(PetscFree2(recvNames, glabels));
5669:   PetscFunctionReturn(PETSC_SUCCESS);
5670: }

5672: static PetscErrorCode DMDSEnlarge_Static(DM dm, PetscInt NdsNew)
5673: {
5674:   DMSpace *tmpd;
5675:   PetscInt Nds = dm->Nds, s;

5677:   PetscFunctionBegin;
5678:   if (Nds >= NdsNew) PetscFunctionReturn(PETSC_SUCCESS);
5679:   PetscCall(PetscMalloc1(NdsNew, &tmpd));
5680:   for (s = 0; s < Nds; ++s) tmpd[s] = dm->probs[s];
5681:   for (s = Nds; s < NdsNew; ++s) {
5682:     tmpd[s].ds     = NULL;
5683:     tmpd[s].label  = NULL;
5684:     tmpd[s].fields = NULL;
5685:   }
5686:   PetscCall(PetscFree(dm->probs));
5687:   dm->Nds   = NdsNew;
5688:   dm->probs = tmpd;
5689:   PetscFunctionReturn(PETSC_SUCCESS);
5690: }

5692: /*@
5693:   DMGetNumDS - Get the number of discrete systems in the `DM`

5695:   Not Collective

5697:   Input Parameter:
5698: . dm - The `DM`

5700:   Output Parameter:
5701: . Nds - The number of `PetscDS` objects

5703:   Level: intermediate

5705: .seealso: [](ch_dmbase), `DM`, `DMGetDS()`, `DMGetCellDS()`
5706: @*/
5707: PetscErrorCode DMGetNumDS(DM dm, PetscInt *Nds)
5708: {
5709:   PetscFunctionBegin;
5711:   PetscAssertPointer(Nds, 2);
5712:   *Nds = dm->Nds;
5713:   PetscFunctionReturn(PETSC_SUCCESS);
5714: }

5716: /*@
5717:   DMClearDS - Remove all discrete systems from the `DM`

5719:   Logically Collective

5721:   Input Parameter:
5722: . dm - The `DM`

5724:   Level: intermediate

5726: .seealso: [](ch_dmbase), `DM`, `DMGetNumDS()`, `DMGetDS()`, `DMSetField()`
5727: @*/
5728: PetscErrorCode DMClearDS(DM dm)
5729: {
5730:   PetscInt s;

5732:   PetscFunctionBegin;
5734:   for (s = 0; s < dm->Nds; ++s) {
5735:     PetscCall(PetscDSDestroy(&dm->probs[s].ds));
5736:     PetscCall(PetscDSDestroy(&dm->probs[s].dsIn));
5737:     PetscCall(DMLabelDestroy(&dm->probs[s].label));
5738:     PetscCall(ISDestroy(&dm->probs[s].fields));
5739:   }
5740:   PetscCall(PetscFree(dm->probs));
5741:   dm->probs = NULL;
5742:   dm->Nds   = 0;
5743:   PetscFunctionReturn(PETSC_SUCCESS);
5744: }

5746: /*@
5747:   DMGetDS - Get the default `PetscDS`

5749:   Not Collective

5751:   Input Parameter:
5752: . dm - The `DM`

5754:   Output Parameter:
5755: . ds - The default `PetscDS`

5757:   Level: intermediate

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

5762: .seealso: [](ch_dmbase), `DM`, `DMGetCellDS()`, `DMGetRegionDS()`
5763: @*/
5764: PetscErrorCode DMGetDS(DM dm, PetscDS *ds)
5765: {
5766:   PetscFunctionBeginHot;
5768:   PetscAssertPointer(ds, 2);
5769:   PetscCheck(dm->Nds > 0, PetscObjectComm((PetscObject)dm), PETSC_ERR_ARG_WRONGSTATE, "Need to call DMCreateDS() before calling DMGetDS()");
5770:   *ds = dm->probs[0].ds;
5771:   PetscFunctionReturn(PETSC_SUCCESS);
5772: }

5774: /*@
5775:   DMGetCellDS - Get the `PetscDS` defined on a given cell

5777:   Not Collective

5779:   Input Parameters:
5780: + dm    - The `DM`
5781: - point - Cell for the `PetscDS`

5783:   Output Parameters:
5784: + ds   - The `PetscDS` defined on the given cell
5785: - dsIn - The `PetscDS` for input on the given cell, or `NULL` if the same ds

5787:   Level: developer

5789: .seealso: [](ch_dmbase), `DM`, `DMGetDS()`, `DMSetRegionDS()`
5790: @*/
5791: PetscErrorCode DMGetCellDS(DM dm, PetscInt point, PetscDS *ds, PetscDS *dsIn)
5792: {
5793:   PetscDS  dsDef = NULL;
5794:   PetscInt s;

5796:   PetscFunctionBeginHot;
5798:   if (ds) PetscAssertPointer(ds, 3);
5799:   if (dsIn) PetscAssertPointer(dsIn, 4);
5800:   PetscCheck(point >= 0, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Mesh point cannot be negative: %" PetscInt_FMT, point);
5801:   if (ds) *ds = NULL;
5802:   if (dsIn) *dsIn = NULL;
5803:   for (s = 0; s < dm->Nds; ++s) {
5804:     PetscInt val;

5806:     if (!dm->probs[s].label) {
5807:       dsDef = dm->probs[s].ds;
5808:     } else {
5809:       PetscCall(DMLabelGetValue(dm->probs[s].label, point, &val));
5810:       if (val >= 0) {
5811:         if (ds) *ds = dm->probs[s].ds;
5812:         if (dsIn) *dsIn = dm->probs[s].dsIn;
5813:         break;
5814:       }
5815:     }
5816:   }
5817:   if (ds && !*ds) *ds = dsDef;
5818:   PetscFunctionReturn(PETSC_SUCCESS);
5819: }

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

5824:   Not Collective

5826:   Input Parameters:
5827: + dm    - The `DM`
5828: - label - The `DMLabel` defining the mesh region, or `NULL` for the entire mesh

5830:   Output Parameters:
5831: + fields - The `IS` containing the `DM` field numbers for the fields in this `PetscDS`, or `NULL`
5832: . ds     - The `PetscDS` defined on the given region, or `NULL`
5833: - dsIn   - The `PetscDS` for input in the given region, or `NULL`

5835:   Level: advanced

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

5842: .seealso: [](ch_dmbase), `DM`, `DMGetRegionNumDS()`, `DMSetRegionDS()`, `DMGetDS()`, `DMGetCellDS()`
5843: @*/
5844: PetscErrorCode DMGetRegionDS(DM dm, DMLabel label, IS *fields, PetscDS *ds, PetscDS *dsIn)
5845: {
5846:   PetscInt Nds = dm->Nds, s;

5848:   PetscFunctionBegin;
5851:   if (fields) {
5852:     PetscAssertPointer(fields, 3);
5853:     *fields = NULL;
5854:   }
5855:   if (ds) {
5856:     PetscAssertPointer(ds, 4);
5857:     *ds = NULL;
5858:   }
5859:   if (dsIn) {
5860:     PetscAssertPointer(dsIn, 5);
5861:     *dsIn = NULL;
5862:   }
5863:   for (s = 0; s < Nds; ++s) {
5864:     if (dm->probs[s].label == label || !dm->probs[s].label) {
5865:       if (fields) *fields = dm->probs[s].fields;
5866:       if (ds) *ds = dm->probs[s].ds;
5867:       if (dsIn) *dsIn = dm->probs[s].dsIn;
5868:       if (dm->probs[s].label) PetscFunctionReturn(PETSC_SUCCESS);
5869:     }
5870:   }
5871:   PetscFunctionReturn(PETSC_SUCCESS);
5872: }

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

5877:   Collective

5879:   Input Parameters:
5880: + dm     - The `DM`
5881: . label  - The `DMLabel` defining the mesh region, or `NULL` for the entire mesh
5882: . fields - The `IS` containing the `DM` field numbers for the fields in this `PetscDS`, or `NULL` for all fields
5883: . ds     - The `PetscDS` defined on the given region
5884: - dsIn   - The `PetscDS` for input on the given cell, or `NULL` if it is the same `PetscDS`

5886:   Level: advanced

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

5892: .seealso: [](ch_dmbase), `DM`, `DMGetRegionDS()`, `DMSetRegionNumDS()`, `DMGetDS()`, `DMGetCellDS()`
5893: @*/
5894: PetscErrorCode DMSetRegionDS(DM dm, DMLabel label, IS fields, PetscDS ds, PetscDS dsIn)
5895: {
5896:   PetscInt Nds = dm->Nds, s;

5898:   PetscFunctionBegin;
5904:   for (s = 0; s < Nds; ++s) {
5905:     if (dm->probs[s].label == label) {
5906:       PetscCall(PetscDSDestroy(&dm->probs[s].ds));
5907:       PetscCall(PetscDSDestroy(&dm->probs[s].dsIn));
5908:       dm->probs[s].ds   = ds;
5909:       dm->probs[s].dsIn = dsIn;
5910:       PetscFunctionReturn(PETSC_SUCCESS);
5911:     }
5912:   }
5913:   PetscCall(DMDSEnlarge_Static(dm, Nds + 1));
5914:   PetscCall(PetscObjectReference((PetscObject)label));
5915:   PetscCall(PetscObjectReference((PetscObject)fields));
5916:   PetscCall(PetscObjectReference((PetscObject)ds));
5917:   PetscCall(PetscObjectReference((PetscObject)dsIn));
5918:   if (!label) {
5919:     /* Put the NULL label at the front, so it is returned as the default */
5920:     for (s = Nds - 1; s >= 0; --s) dm->probs[s + 1] = dm->probs[s];
5921:     Nds = 0;
5922:   }
5923:   dm->probs[Nds].label  = label;
5924:   dm->probs[Nds].fields = fields;
5925:   dm->probs[Nds].ds     = ds;
5926:   dm->probs[Nds].dsIn   = dsIn;
5927:   PetscFunctionReturn(PETSC_SUCCESS);
5928: }

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

5933:   Not Collective

5935:   Input Parameters:
5936: + dm  - The `DM`
5937: - num - The region number, in [0, Nds)

5939:   Output Parameters:
5940: + label  - The region label, or `NULL`
5941: . fields - The `IS` containing the `DM` field numbers for the fields in this `PetscDS`, or `NULL`
5942: . ds     - The `PetscDS` defined on the given region, or `NULL`
5943: - dsIn   - The `PetscDS` for input in the given region, or `NULL`

5945:   Level: advanced

5947: .seealso: [](ch_dmbase), `DM`, `DMGetRegionDS()`, `DMSetRegionDS()`, `DMGetDS()`, `DMGetCellDS()`
5948: @*/
5949: PetscErrorCode DMGetRegionNumDS(DM dm, PetscInt num, DMLabel *label, IS *fields, PetscDS *ds, PetscDS *dsIn)
5950: {
5951:   PetscInt Nds;

5953:   PetscFunctionBegin;
5955:   PetscCall(DMGetNumDS(dm, &Nds));
5956:   PetscCheck((num >= 0) && (num < Nds), PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Region number %" PetscInt_FMT " is not in [0, %" PetscInt_FMT ")", num, Nds);
5957:   if (label) {
5958:     PetscAssertPointer(label, 3);
5959:     *label = dm->probs[num].label;
5960:   }
5961:   if (fields) {
5962:     PetscAssertPointer(fields, 4);
5963:     *fields = dm->probs[num].fields;
5964:   }
5965:   if (ds) {
5966:     PetscAssertPointer(ds, 5);
5967:     *ds = dm->probs[num].ds;
5968:   }
5969:   if (dsIn) {
5970:     PetscAssertPointer(dsIn, 6);
5971:     *dsIn = dm->probs[num].dsIn;
5972:   }
5973:   PetscFunctionReturn(PETSC_SUCCESS);
5974: }

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

5979:   Not Collective

5981:   Input Parameters:
5982: + dm     - The `DM`
5983: . num    - The region number, in [0, Nds)
5984: . label  - The region label, or `NULL`
5985: . fields - The `IS` containing the `DM` field numbers for the fields in this `PetscDS`, or `NULL` to prevent setting
5986: . ds     - The `PetscDS` defined on the given region, or `NULL` to prevent setting
5987: - dsIn   - The `PetscDS` for input on the given cell, or `NULL` if it is the same `PetscDS`

5989:   Level: advanced

5991: .seealso: [](ch_dmbase), `DM`, `DMGetRegionDS()`, `DMSetRegionDS()`, `DMGetDS()`, `DMGetCellDS()`
5992: @*/
5993: PetscErrorCode DMSetRegionNumDS(DM dm, PetscInt num, DMLabel label, IS fields, PetscDS ds, PetscDS dsIn)
5994: {
5995:   PetscInt Nds;

5997:   PetscFunctionBegin;
6000:   PetscCall(DMGetNumDS(dm, &Nds));
6001:   PetscCheck((num >= 0) && (num < Nds), PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Region number %" PetscInt_FMT " is not in [0, %" PetscInt_FMT ")", num, Nds);
6002:   PetscCall(PetscObjectReference((PetscObject)label));
6003:   PetscCall(DMLabelDestroy(&dm->probs[num].label));
6004:   dm->probs[num].label = label;
6005:   if (fields) {
6007:     PetscCall(PetscObjectReference((PetscObject)fields));
6008:     PetscCall(ISDestroy(&dm->probs[num].fields));
6009:     dm->probs[num].fields = fields;
6010:   }
6011:   if (ds) {
6013:     PetscCall(PetscObjectReference((PetscObject)ds));
6014:     PetscCall(PetscDSDestroy(&dm->probs[num].ds));
6015:     dm->probs[num].ds = ds;
6016:   }
6017:   if (dsIn) {
6019:     PetscCall(PetscObjectReference((PetscObject)dsIn));
6020:     PetscCall(PetscDSDestroy(&dm->probs[num].dsIn));
6021:     dm->probs[num].dsIn = dsIn;
6022:   }
6023:   PetscFunctionReturn(PETSC_SUCCESS);
6024: }

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

6029:   Not Collective

6031:   Input Parameters:
6032: + dm - The `DM`
6033: - ds - The `PetscDS` defined on the given region

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

6038:   Level: advanced

6040: .seealso: [](ch_dmbase), `DM`, `DMGetRegionNumDS()`, `DMGetRegionDS()`, `DMSetRegionDS()`, `DMGetDS()`, `DMGetCellDS()`
6041: @*/
6042: PetscErrorCode DMFindRegionNum(DM dm, PetscDS ds, PetscInt *num)
6043: {
6044:   PetscInt Nds, n;

6046:   PetscFunctionBegin;
6049:   PetscAssertPointer(num, 3);
6050:   PetscCall(DMGetNumDS(dm, &Nds));
6051:   for (n = 0; n < Nds; ++n)
6052:     if (ds == dm->probs[n].ds) break;
6053:   if (n >= Nds) *num = -1;
6054:   else *num = n;
6055:   PetscFunctionReturn(PETSC_SUCCESS);
6056: }

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

6061:   Not Collective

6063:   Input Parameters:
6064: + dm     - The `DM`
6065: . Nc     - The number of components for the field
6066: . prefix - The options prefix for the output `PetscFE`, or `NULL`
6067: - qorder - The quadrature order or `PETSC_DETERMINE` to use `PetscSpace` polynomial degree

6069:   Output Parameter:
6070: . fem - The `PetscFE`

6072:   Level: intermediate

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

6077: .seealso: [](ch_dmbase), `DM`, `PetscFECreateByCell()`, `DMAddField()`, `DMCreateDS()`, `DMGetCellDS()`, `DMGetRegionDS()`
6078: @*/
6079: PetscErrorCode DMCreateFEDefault(DM dm, PetscInt Nc, const char prefix[], PetscInt qorder, PetscFE *fem)
6080: {
6081:   DMPolytopeType ct;
6082:   PetscInt       dim, cStart;

6084:   PetscFunctionBegin;
6087:   if (prefix) PetscAssertPointer(prefix, 3);
6089:   PetscAssertPointer(fem, 5);
6090:   PetscCall(DMGetDimension(dm, &dim));
6091:   PetscCall(DMPlexGetHeightStratum(dm, 0, &cStart, NULL));
6092:   PetscCall(DMPlexGetCellType(dm, cStart, &ct));
6093:   PetscCall(PetscFECreateByCell(PETSC_COMM_SELF, dim, Nc, ct, prefix, qorder, fem));
6094:   PetscFunctionReturn(PETSC_SUCCESS);
6095: }

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

6100:   Collective

6102:   Input Parameter:
6103: . dm - The `DM`

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

6108:   Level: intermediate

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

6113: .seealso: [](ch_dmbase), `DM`, `DMSetField`, `DMAddField()`, `DMGetDS()`, `DMGetCellDS()`, `DMGetRegionDS()`, `DMSetRegionDS()`
6114: @*/
6115: PetscErrorCode DMCreateDS(DM dm)
6116: {
6117:   MPI_Comm  comm;
6118:   PetscDS   dsDef;
6119:   DMLabel  *labelSet;
6120:   PetscInt  dE, Nf = dm->Nf, f, s, Nl, l, Ndef, k;
6121:   PetscBool doSetup = PETSC_TRUE, flg;

6123:   PetscFunctionBegin;
6125:   if (!dm->fields) PetscFunctionReturn(PETSC_SUCCESS);
6126:   PetscCall(PetscObjectGetComm((PetscObject)dm, &comm));
6127:   PetscCall(DMGetCoordinateDim(dm, &dE));
6128:   // Create nullspace constructor slots
6129:   PetscCall(PetscFree2(dm->nullspaceConstructors, dm->nearnullspaceConstructors));
6130:   PetscCall(PetscCalloc2(Nf, &dm->nullspaceConstructors, Nf, &dm->nearnullspaceConstructors));
6131:   /* Determine how many regions we have */
6132:   PetscCall(PetscMalloc1(Nf, &labelSet));
6133:   Nl   = 0;
6134:   Ndef = 0;
6135:   for (f = 0; f < Nf; ++f) {
6136:     DMLabel  label = dm->fields[f].label;
6137:     PetscInt l;

6139: #if PetscDefined(HAVE_LIBCEED)
6140:     /* Move CEED context to discretizations */
6141:     {
6142:       PetscClassId id;

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

6148:         PetscCall(DMGetCeed(dm, &ceed));
6149:         PetscCall(PetscFESetCeed((PetscFE)dm->fields[f].disc, ceed));
6150:       }
6151:     }
6152: #endif
6153:     if (!label) {
6154:       ++Ndef;
6155:       continue;
6156:     }
6157:     for (l = 0; l < Nl; ++l)
6158:       if (label == labelSet[l]) break;
6159:     if (l < Nl) continue;
6160:     labelSet[Nl++] = label;
6161:   }
6162:   /* Create default DS if there are no labels to intersect with */
6163:   PetscCall(DMGetRegionDS(dm, NULL, NULL, &dsDef, NULL));
6164:   if (!dsDef && Ndef && !Nl) {
6165:     IS        fields;
6166:     PetscInt *fld, nf;

6168:     for (f = 0, nf = 0; f < Nf; ++f)
6169:       if (!dm->fields[f].label) ++nf;
6170:     PetscCheck(nf, comm, PETSC_ERR_PLIB, "All fields have labels, but we are trying to create a default DS");
6171:     PetscCall(PetscMalloc1(nf, &fld));
6172:     for (f = 0, nf = 0; f < Nf; ++f)
6173:       if (!dm->fields[f].label) fld[nf++] = f;
6174:     PetscCall(ISCreate(PETSC_COMM_SELF, &fields));
6175:     PetscCall(PetscObjectSetOptionsPrefix((PetscObject)fields, "dm_fields_"));
6176:     PetscCall(ISSetType(fields, ISGENERAL));
6177:     PetscCall(ISGeneralSetIndices(fields, nf, fld, PETSC_OWN_POINTER));

6179:     PetscCall(PetscDSCreate(PETSC_COMM_SELF, &dsDef));
6180:     PetscCall(DMSetRegionDS(dm, NULL, fields, dsDef, NULL));
6181:     PetscCall(PetscDSDestroy(&dsDef));
6182:     PetscCall(ISDestroy(&fields));
6183:   }
6184:   PetscCall(DMGetRegionDS(dm, NULL, NULL, &dsDef, NULL));
6185:   if (dsDef) PetscCall(PetscDSSetCoordinateDimension(dsDef, dE));
6186:   /* Intersect labels with default fields */
6187:   if (Ndef && Nl) {
6188:     DM              plex;
6189:     DMLabel         cellLabel;
6190:     IS              fieldIS, allcellIS, defcellIS = NULL;
6191:     PetscInt       *fields;
6192:     const PetscInt *cells;
6193:     PetscInt        depth, nf = 0, n, c;

6195:     PetscCall(DMConvert(dm, DMPLEX, &plex));
6196:     PetscCall(DMPlexGetDepth(plex, &depth));
6197:     PetscCall(DMGetStratumIS(plex, "dim", depth, &allcellIS));
6198:     if (!allcellIS) PetscCall(DMGetStratumIS(plex, "depth", depth, &allcellIS));
6199:     /* TODO This looks like it only works for one label */
6200:     for (l = 0; l < Nl; ++l) {
6201:       DMLabel label = labelSet[l];
6202:       IS      pointIS;

6204:       PetscCall(ISDestroy(&defcellIS));
6205:       PetscCall(DMLabelGetStratumIS(label, 1, &pointIS));
6206:       PetscCall(ISDifference(allcellIS, pointIS, &defcellIS));
6207:       PetscCall(ISDestroy(&pointIS));
6208:     }
6209:     PetscCall(ISDestroy(&allcellIS));

6211:     PetscCall(DMLabelCreate(PETSC_COMM_SELF, "defaultCells", &cellLabel));
6212:     PetscCall(ISGetLocalSize(defcellIS, &n));
6213:     PetscCall(ISGetIndices(defcellIS, &cells));
6214:     for (c = 0; c < n; ++c) PetscCall(DMLabelSetValue(cellLabel, cells[c], 1));
6215:     PetscCall(ISRestoreIndices(defcellIS, &cells));
6216:     PetscCall(ISDestroy(&defcellIS));
6217:     PetscCall(DMPlexLabelComplete(plex, cellLabel));

6219:     PetscCall(PetscMalloc1(Ndef, &fields));
6220:     for (f = 0; f < Nf; ++f)
6221:       if (!dm->fields[f].label) fields[nf++] = f;
6222:     PetscCall(ISCreate(PETSC_COMM_SELF, &fieldIS));
6223:     PetscCall(PetscObjectSetOptionsPrefix((PetscObject)fieldIS, "dm_fields_"));
6224:     PetscCall(ISSetType(fieldIS, ISGENERAL));
6225:     PetscCall(ISGeneralSetIndices(fieldIS, nf, fields, PETSC_OWN_POINTER));

6227:     PetscCall(PetscDSCreate(PETSC_COMM_SELF, &dsDef));
6228:     PetscCall(DMSetRegionDS(dm, cellLabel, fieldIS, dsDef, NULL));
6229:     PetscCall(PetscDSSetCoordinateDimension(dsDef, dE));
6230:     PetscCall(DMLabelDestroy(&cellLabel));
6231:     PetscCall(PetscDSDestroy(&dsDef));
6232:     PetscCall(ISDestroy(&fieldIS));
6233:     PetscCall(DMDestroy(&plex));
6234:   }
6235:   /* Create label DSes
6236:      - WE ONLY SUPPORT IDENTICAL OR DISJOINT LABELS
6237:   */
6238:   /* TODO Should check that labels are disjoint */
6239:   for (l = 0; l < Nl; ++l) {
6240:     DMLabel   label = labelSet[l];
6241:     PetscDS   ds, dsIn = NULL;
6242:     IS        fields;
6243:     PetscInt *fld, nf;

6245:     PetscCall(PetscDSCreate(PETSC_COMM_SELF, &ds));
6246:     for (f = 0, nf = 0; f < Nf; ++f)
6247:       if (label == dm->fields[f].label || !dm->fields[f].label) ++nf;
6248:     PetscCall(PetscMalloc1(nf, &fld));
6249:     for (f = 0, nf = 0; f < Nf; ++f)
6250:       if (label == dm->fields[f].label || !dm->fields[f].label) fld[nf++] = f;
6251:     PetscCall(ISCreate(PETSC_COMM_SELF, &fields));
6252:     PetscCall(PetscObjectSetOptionsPrefix((PetscObject)fields, "dm_fields_"));
6253:     PetscCall(ISSetType(fields, ISGENERAL));
6254:     PetscCall(ISGeneralSetIndices(fields, nf, fld, PETSC_OWN_POINTER));
6255:     PetscCall(PetscDSSetCoordinateDimension(ds, dE));
6256:     {
6257:       DMPolytopeType ct;
6258:       PetscInt       lStart, lEnd;
6259:       PetscBool      isCohesive = PETSC_FALSE;

6261:       PetscCall(DMLabelGetBounds(label, &lStart, &lEnd));
6262:       if (lStart >= 0) {
6263:         PetscCall(DMPlexGetCellType(dm, lStart, &ct));
6264:         switch (ct) {
6265:         case DM_POLYTOPE_POINT_PRISM_TENSOR:
6266:         case DM_POLYTOPE_SEG_PRISM_TENSOR:
6267:         case DM_POLYTOPE_TRI_PRISM_TENSOR:
6268:         case DM_POLYTOPE_QUAD_PRISM_TENSOR:
6269:           isCohesive = PETSC_TRUE;
6270:           break;
6271:         default:
6272:           break;
6273:         }
6274:       }
6275:       PetscCallMPI(MPIU_Allreduce(MPI_IN_PLACE, &isCohesive, 1, MPI_C_BOOL, MPI_LOR, comm));
6276:       if (isCohesive) {
6277:         PetscCall(PetscDSCreate(PETSC_COMM_SELF, &dsIn));
6278:         PetscCall(PetscDSSetCoordinateDimension(dsIn, dE));
6279:       }
6280:       for (f = 0, nf = 0; f < Nf; ++f) {
6281:         if (label == dm->fields[f].label || !dm->fields[f].label) {
6282:           if (label == dm->fields[f].label) {
6283:             PetscCall(PetscDSSetDiscretization(ds, nf, NULL));
6284:             PetscCall(PetscDSSetCohesive(ds, nf, isCohesive));
6285:             if (dsIn) {
6286:               PetscCall(PetscDSSetDiscretization(dsIn, nf, NULL));
6287:               PetscCall(PetscDSSetCohesive(dsIn, nf, isCohesive));
6288:             }
6289:           }
6290:           ++nf;
6291:         }
6292:       }
6293:     }
6294:     PetscCall(DMSetRegionDS(dm, label, fields, ds, dsIn));
6295:     PetscCall(ISDestroy(&fields));
6296:     PetscCall(PetscDSDestroy(&ds));
6297:     PetscCall(PetscDSDestroy(&dsIn));
6298:   }
6299:   PetscCall(PetscFree(labelSet));
6300:   /* Set fields in DSes */
6301:   for (s = 0; s < dm->Nds; ++s) {
6302:     PetscDS         ds     = dm->probs[s].ds;
6303:     PetscDS         dsIn   = dm->probs[s].dsIn;
6304:     IS              fields = dm->probs[s].fields;
6305:     const PetscInt *fld;
6306:     PetscInt        nf, dsnf;
6307:     PetscBool       isCohesive;

6309:     PetscCall(PetscDSGetNumFields(ds, &dsnf));
6310:     PetscCall(PetscDSIsCohesive(ds, &isCohesive));
6311:     PetscCall(ISGetLocalSize(fields, &nf));
6312:     PetscCall(ISGetIndices(fields, &fld));
6313:     for (f = 0; f < nf; ++f) {
6314:       PetscObject  disc = dm->fields[fld[f]].disc;
6315:       PetscBool    isCohesiveField;
6316:       PetscClassId id;

6318:       /* Handle DS with no fields */
6319:       if (dsnf) PetscCall(PetscDSGetCohesive(ds, f, &isCohesiveField));
6320:       /* If this is a cohesive cell, then regular fields need the lower dimensional discretization */
6321:       if (isCohesive) {
6322:         if (!isCohesiveField) {
6323:           PetscObject bdDisc;

6325:           PetscCall(PetscFEGetHeightSubspace((PetscFE)disc, 1, (PetscFE *)&bdDisc));
6326:           PetscCall(PetscDSSetDiscretization(ds, f, bdDisc));
6327:           PetscCall(PetscDSSetDiscretization(dsIn, f, disc));
6328:         } else {
6329:           PetscCall(PetscDSSetDiscretization(ds, f, disc));
6330:           PetscCall(PetscDSSetDiscretization(dsIn, f, disc));
6331:         }
6332:       } else {
6333:         PetscCall(PetscDSSetDiscretization(ds, f, disc));
6334:       }
6335:       /* We allow people to have placeholder fields and construct the Section by hand */
6336:       PetscCall(PetscObjectGetClassId(disc, &id));
6337:       if (id != PETSCFE_CLASSID && id != PETSCFV_CLASSID) doSetup = PETSC_FALSE;
6338:     }
6339:     PetscCall(ISRestoreIndices(fields, &fld));
6340:   }
6341:   /* Allow k-jet tabulation */
6342:   PetscCall(PetscOptionsGetInt(NULL, ((PetscObject)dm)->prefix, "-dm_ds_jet_degree", &k, &flg));
6343:   if (flg) {
6344:     for (s = 0; s < dm->Nds; ++s) {
6345:       PetscDS  ds   = dm->probs[s].ds;
6346:       PetscDS  dsIn = dm->probs[s].dsIn;
6347:       PetscInt Nf;

6349:       PetscCall(PetscDSGetNumFields(ds, &Nf));
6350:       for (PetscInt f = 0; f < Nf; ++f) {
6351:         PetscCall(PetscDSSetJetDegree(ds, f, k));
6352:         if (dsIn) PetscCall(PetscDSSetJetDegree(dsIn, f, k));
6353:       }
6354:     }
6355:   }
6356:   /* Setup DSes */
6357:   if (doSetup) {
6358:     for (s = 0; s < dm->Nds; ++s) {
6359:       if (dm->setfromoptionscalled) {
6360:         PetscCall(PetscDSSetFromOptions(dm->probs[s].ds));
6361:         if (dm->probs[s].dsIn) PetscCall(PetscDSSetFromOptions(dm->probs[s].dsIn));
6362:       }
6363:       PetscCall(PetscDSSetUp(dm->probs[s].ds));
6364:       if (dm->probs[s].dsIn) PetscCall(PetscDSSetUp(dm->probs[s].dsIn));
6365:     }
6366:   }
6367:   PetscFunctionReturn(PETSC_SUCCESS);
6368: }

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

6373:   Input Parameters:
6374: + dm     - The DM
6375: - tensor - Flag for tensor order

6377:   Level: developer

6379: .seealso: `DMPlexSetClosurePermutationTensor()`, `PetscSectionResetClosurePermutation()`
6380: @*/
6381: PetscErrorCode DMUseTensorOrder(DM dm, PetscBool tensor)
6382: {
6383:   PetscInt  Nf;
6384:   PetscBool reorder = PETSC_TRUE, isPlex;

6386:   PetscFunctionBegin;
6387:   PetscCall(PetscObjectTypeCompare((PetscObject)dm, DMPLEX, &isPlex));
6388:   PetscCall(DMGetNumFields(dm, &Nf));
6389:   for (PetscInt f = 0; f < Nf; ++f) {
6390:     PetscObject  obj;
6391:     PetscClassId id;

6393:     PetscCall(DMGetField(dm, f, NULL, &obj));
6394:     PetscCall(PetscObjectGetClassId(obj, &id));
6395:     if (id == PETSCFE_CLASSID) {
6396:       PetscSpace sp;
6397:       PetscBool  tensor;

6399:       PetscCall(PetscFEGetBasisSpace((PetscFE)obj, &sp));
6400:       PetscCall(PetscSpacePolynomialGetTensor(sp, &tensor));
6401:       reorder = reorder && tensor ? PETSC_TRUE : PETSC_FALSE;
6402:     } else reorder = PETSC_FALSE;
6403:   }
6404:   if (tensor) {
6405:     if (reorder && isPlex) PetscCall(DMPlexSetClosurePermutationTensor(dm, PETSC_DETERMINE, NULL));
6406:   } else {
6407:     PetscSection s;

6409:     PetscCall(DMGetLocalSection(dm, &s));
6410:     if (s) PetscCall(PetscSectionResetClosurePermutation(s));
6411:   }
6412:   PetscFunctionReturn(PETSC_SUCCESS);
6413: }

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

6418:   Collective

6420:   Input Parameters:
6421: + dm   - The `DM`
6422: - time - The time

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

6428:   Level: developer

6430:   Note:
6431:   The user must call `PetscDSSetExactSolution()` before using this routine

6433: .seealso: [](ch_dmbase), `DM`, `PetscDSSetExactSolution()`
6434: @*/
6435: PetscErrorCode DMComputeExactSolution(DM dm, PetscReal time, Vec u, Vec u_t)
6436: {
6437:   PetscErrorCode (**exacts)(PetscInt, PetscReal, const PetscReal x[], PetscInt, PetscScalar *u, PetscCtx ctx);
6438:   void   **ectxs;
6439:   Vec      locu, locu_t;
6440:   PetscInt Nf, Nds, s;

6442:   PetscFunctionBegin;
6444:   if (u) {
6446:     PetscCall(DMGetLocalVector(dm, &locu));
6447:     PetscCall(VecSet(locu, 0.));
6448:   }
6449:   if (u_t) {
6451:     PetscCall(DMGetLocalVector(dm, &locu_t));
6452:     PetscCall(VecSet(locu_t, 0.));
6453:   }
6454:   PetscCall(DMGetNumFields(dm, &Nf));
6455:   PetscCall(PetscMalloc2(Nf, &exacts, Nf, &ectxs));
6456:   PetscCall(DMGetNumDS(dm, &Nds));
6457:   for (s = 0; s < Nds; ++s) {
6458:     PetscDS         ds;
6459:     DMLabel         label;
6460:     IS              fieldIS;
6461:     const PetscInt *fields, id = 1;
6462:     PetscInt        dsNf;

6464:     PetscCall(DMGetRegionNumDS(dm, s, &label, &fieldIS, &ds, NULL));
6465:     PetscCall(PetscDSGetNumFields(ds, &dsNf));
6466:     PetscCall(ISGetIndices(fieldIS, &fields));
6467:     PetscCall(PetscArrayzero(exacts, Nf));
6468:     PetscCall(PetscArrayzero(ectxs, Nf));
6469:     if (u) {
6470:       for (PetscInt f = 0; f < dsNf; ++f) PetscCall(PetscDSGetExactSolution(ds, fields[f], &exacts[fields[f]], &ectxs[fields[f]]));
6471:       if (label) PetscCall(DMProjectFunctionLabelLocal(dm, time, label, 1, &id, 0, NULL, exacts, ectxs, INSERT_ALL_VALUES, locu));
6472:       else PetscCall(DMProjectFunctionLocal(dm, time, exacts, ectxs, INSERT_ALL_VALUES, locu));
6473:     }
6474:     if (u_t) {
6475:       PetscCall(PetscArrayzero(exacts, Nf));
6476:       PetscCall(PetscArrayzero(ectxs, Nf));
6477:       for (PetscInt f = 0; f < dsNf; ++f) PetscCall(PetscDSGetExactSolutionTimeDerivative(ds, fields[f], &exacts[fields[f]], &ectxs[fields[f]]));
6478:       if (label) PetscCall(DMProjectFunctionLabelLocal(dm, time, label, 1, &id, 0, NULL, exacts, ectxs, INSERT_ALL_VALUES, locu_t));
6479:       else PetscCall(DMProjectFunctionLocal(dm, time, exacts, ectxs, INSERT_ALL_VALUES, locu_t));
6480:     }
6481:     PetscCall(ISRestoreIndices(fieldIS, &fields));
6482:   }
6483:   if (u) {
6484:     PetscCall(PetscObjectSetName((PetscObject)u, "Exact Solution"));
6485:     PetscCall(PetscObjectSetOptionsPrefix((PetscObject)u, "exact_"));
6486:   }
6487:   if (u_t) {
6488:     PetscCall(PetscObjectSetName((PetscObject)u, "Exact Solution Time Derivative"));
6489:     PetscCall(PetscObjectSetOptionsPrefix((PetscObject)u_t, "exact_t_"));
6490:   }
6491:   PetscCall(PetscFree2(exacts, ectxs));
6492:   if (u) {
6493:     PetscCall(DMLocalToGlobalBegin(dm, locu, INSERT_ALL_VALUES, u));
6494:     PetscCall(DMLocalToGlobalEnd(dm, locu, INSERT_ALL_VALUES, u));
6495:     PetscCall(DMRestoreLocalVector(dm, &locu));
6496:   }
6497:   if (u_t) {
6498:     PetscCall(DMLocalToGlobalBegin(dm, locu_t, INSERT_ALL_VALUES, u_t));
6499:     PetscCall(DMLocalToGlobalEnd(dm, locu_t, INSERT_ALL_VALUES, u_t));
6500:     PetscCall(DMRestoreLocalVector(dm, &locu_t));
6501:   }
6502:   PetscFunctionReturn(PETSC_SUCCESS);
6503: }

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

6509:   PetscFunctionBegin;
6510:   PetscCall(PetscDSCreate(PetscObjectComm((PetscObject)ds), &dsNew));
6511:   PetscCall(PetscDSCopy(ds, minDegree, maxDegree, dm, dsNew));
6512:   if (dsIn) {
6513:     PetscCall(PetscDSCreate(PetscObjectComm((PetscObject)dsIn), &dsInNew));
6514:     PetscCall(PetscDSCopy(dsIn, minDegree, maxDegree, dm, dsInNew));
6515:   }
6516:   PetscCall(DMSetRegionDS(dm, label, fields, dsNew, dsInNew));
6517:   PetscCall(PetscDSDestroy(&dsNew));
6518:   PetscCall(PetscDSDestroy(&dsInNew));
6519:   PetscFunctionReturn(PETSC_SUCCESS);
6520: }

6522: /*@
6523:   DMCopyDS - Copy the discrete systems for the `DM` into another `DM`

6525:   Collective

6527:   Input Parameters:
6528: + dm        - The `DM`
6529: . minDegree - Minimum degree for a discretization, or `PETSC_DETERMINE` for no limit
6530: - maxDegree - Maximum degree for a discretization, or `PETSC_DETERMINE` for no limit

6532:   Output Parameter:
6533: . newdm - The `DM`

6535:   Level: advanced

6537: .seealso: [](ch_dmbase), `DM`, `DMCopyFields()`, `DMAddField()`, `DMGetDS()`, `DMGetCellDS()`, `DMGetRegionDS()`, `DMSetRegionDS()`
6538: @*/
6539: PetscErrorCode DMCopyDS(DM dm, PetscInt minDegree, PetscInt maxDegree, DM newdm)
6540: {
6541:   PetscInt Nds;

6543:   PetscFunctionBegin;
6544:   if (dm == newdm) PetscFunctionReturn(PETSC_SUCCESS);
6545:   PetscCall(DMGetNumDS(dm, &Nds));
6546:   PetscCall(DMClearDS(newdm));
6547:   for (PetscInt s = 0; s < Nds; ++s) {
6548:     DMLabel  label;
6549:     IS       fields;
6550:     PetscDS  ds, dsIn, newds;
6551:     PetscInt Nbd;

6553:     PetscCall(DMGetRegionNumDS(dm, s, &label, &fields, &ds, &dsIn));
6554:     /* TODO: We need to change all keys from labels in the old DM to labels in the new DM */
6555:     PetscCall(DMTransferDS_Internal(newdm, label, fields, minDegree, maxDegree, ds, dsIn));
6556:     /* Complete new labels in the new DS */
6557:     PetscCall(DMGetRegionDS(newdm, label, NULL, &newds, NULL));
6558:     PetscCall(PetscDSGetNumBoundary(newds, &Nbd));
6559:     for (PetscInt bd = 0; bd < Nbd; ++bd) {
6560:       PetscWeakForm wf;
6561:       DMLabel       label;
6562:       PetscInt      field;

6564:       PetscCall(PetscDSGetBoundary(newds, bd, &wf, NULL, NULL, &label, NULL, NULL, &field, NULL, NULL, NULL, NULL, NULL));
6565:       PetscCall(PetscWeakFormReplaceLabel(wf, label));
6566:     }
6567:   }
6568:   PetscCall(DMCompleteBCLabels_Internal(newdm));
6569:   PetscFunctionReturn(PETSC_SUCCESS);
6570: }

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

6575:   Collective

6577:   Input Parameter:
6578: . dm - The `DM`

6580:   Output Parameter:
6581: . newdm - The `DM`

6583:   Level: advanced

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

6588: .seealso: [](ch_dmbase), `DM`, `DMCopyFields()`, `DMCopyDS()`
6589: @*/
6590: PetscErrorCode DMCopyDisc(DM dm, DM newdm)
6591: {
6592:   PetscFunctionBegin;
6593:   PetscCall(DMCopyFields(dm, PETSC_DETERMINE, PETSC_DETERMINE, newdm));
6594:   PetscCall(DMCopyDS(dm, PETSC_DETERMINE, PETSC_DETERMINE, newdm));
6595:   PetscFunctionReturn(PETSC_SUCCESS);
6596: }

6598: /*@
6599:   DMGetDimension - Return the topological dimension of the `DM`

6601:   Not Collective

6603:   Input Parameter:
6604: . dm - The `DM`

6606:   Output Parameter:
6607: . dim - The topological dimension

6609:   Level: beginner

6611: .seealso: [](ch_dmbase), `DM`, `DMSetDimension()`, `DMCreate()`
6612: @*/
6613: PetscErrorCode DMGetDimension(DM dm, PetscInt *dim)
6614: {
6615:   PetscFunctionBegin;
6617:   PetscAssertPointer(dim, 2);
6618:   *dim = dm->dim;
6619:   PetscFunctionReturn(PETSC_SUCCESS);
6620: }

6622: /*@
6623:   DMSetDimension - Set the topological dimension of the `DM`

6625:   Collective

6627:   Input Parameters:
6628: + dm  - The `DM`
6629: - dim - The topological dimension

6631:   Level: beginner

6633: .seealso: [](ch_dmbase), `DM`, `DMGetDimension()`, `DMCreate()`
6634: @*/
6635: PetscErrorCode DMSetDimension(DM dm, PetscInt dim)
6636: {
6637:   PetscDS  ds;
6638:   PetscInt Nds;

6640:   PetscFunctionBegin;
6643:   if (dm->dim != dim) PetscCall(DMSetPeriodicity(dm, NULL, NULL, NULL));
6644:   dm->dim = dim;
6645:   if (dm->dim >= 0) {
6646:     PetscCall(DMGetNumDS(dm, &Nds));
6647:     for (PetscInt n = 0; n < Nds; ++n) {
6648:       PetscCall(DMGetRegionNumDS(dm, n, NULL, NULL, &ds, NULL));
6649:       if (ds->dimEmbed < 0) PetscCall(PetscDSSetCoordinateDimension(ds, dim));
6650:     }
6651:   }
6652:   PetscFunctionReturn(PETSC_SUCCESS);
6653: }

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

6658:   Collective

6660:   Input Parameters:
6661: + dm  - the `DM`
6662: - dim - the dimension

6664:   Output Parameters:
6665: + pStart - The first point of the given dimension
6666: - pEnd   - The first point following points of the given dimension

6668:   Level: intermediate

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

6675: .seealso: [](ch_dmbase), `DM`, `DMPLEX`, `DMPlexGetDepthStratum()`, `DMPlexGetHeightStratum()`
6676: @*/
6677: PetscErrorCode DMGetDimPoints(DM dm, PetscInt dim, PetscInt *pStart, PetscInt *pEnd)
6678: {
6679:   PetscInt d;

6681:   PetscFunctionBegin;
6683:   PetscCall(DMGetDimension(dm, &d));
6684:   PetscCheck((dim >= 0) && (dim <= d), PetscObjectComm((PetscObject)dm), PETSC_ERR_ARG_OUTOFRANGE, "Invalid dimension %" PetscInt_FMT, dim);
6685:   PetscUseTypeMethod(dm, getdimpoints, dim, pStart, pEnd);
6686:   PetscFunctionReturn(PETSC_SUCCESS);
6687: }

6689: /*@
6690:   DMGetOutputDM - Retrieve the `DM` associated with the layout for output

6692:   Collective

6694:   Input Parameter:
6695: . dm - The original `DM`

6697:   Output Parameter:
6698: . odm - The `DM` which provides the layout for output

6700:   Level: intermediate

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

6707: .seealso: [](ch_dmbase), `DM`, `VecView()`, `DMGetGlobalSection()`, `DMCreateGlobalVector()`, `PetscSectionHasConstraints()`, `DMSetGlobalSection()`
6708: @*/
6709: PetscErrorCode DMGetOutputDM(DM dm, DM *odm)
6710: {
6711:   PetscSection section;
6712:   IS           perm;
6713:   PetscBool    hasConstraints, newDM;
6714:   PetscInt     num_face_sfs = 0;

6716:   PetscFunctionBegin;
6718:   PetscAssertPointer(odm, 2);
6719:   PetscCall(DMGetLocalSection(dm, &section));
6720:   PetscCall(PetscSectionHasConstraints(section, &hasConstraints));
6721:   PetscCall(PetscSectionGetPermutation(section, &perm));
6722:   PetscCall(DMPlexGetIsoperiodicFaceSF(dm, &num_face_sfs, NULL));
6723:   newDM = hasConstraints || perm || (num_face_sfs > 0) ? PETSC_TRUE : PETSC_FALSE;
6724:   PetscCallMPI(MPIU_Allreduce(MPI_IN_PLACE, &newDM, 1, MPI_C_BOOL, MPI_LOR, PetscObjectComm((PetscObject)dm)));
6725:   if (!newDM) {
6726:     *odm = dm;
6727:     PetscFunctionReturn(PETSC_SUCCESS);
6728:   }
6729:   if (!dm->dmBC) {
6730:     PetscSection newSection, gsection;
6731:     PetscSF      sf, sfNatural;
6732:     PetscBool    usePerm = dm->ignorePermOutput ? PETSC_FALSE : PETSC_TRUE;

6734:     PetscCall(DMClone(dm, &dm->dmBC));
6735:     PetscCall(DMCopyDisc(dm, dm->dmBC));
6736:     PetscCall(PetscSectionClone(section, &newSection));
6737:     PetscCall(DMSetLocalSection(dm->dmBC, newSection));
6738:     PetscCall(PetscSectionDestroy(&newSection));
6739:     PetscCall(DMGetNaturalSF(dm, &sfNatural));
6740:     PetscCall(DMSetNaturalSF(dm->dmBC, sfNatural));
6741:     PetscCall(DMGetPointSF(dm->dmBC, &sf));
6742:     PetscCall(PetscSectionCreateGlobalSection(section, sf, usePerm, PETSC_TRUE, PETSC_FALSE, &gsection));
6743:     PetscCall(DMSetGlobalSection(dm->dmBC, gsection));
6744:     PetscCall(PetscSectionDestroy(&gsection));
6745:   }
6746:   *odm = dm->dmBC;
6747:   PetscFunctionReturn(PETSC_SUCCESS);
6748: }

6750: /*@
6751:   DMGetOutputSequenceNumber - Retrieve the sequence number/value for output

6753:   Input Parameter:
6754: . dm - The original `DM`

6756:   Output Parameters:
6757: + num - The output sequence number
6758: - val - The output sequence value

6760:   Level: intermediate

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

6766:   Developer Note:
6767:   The `DM` serves as a convenient place to store the current iteration value. The iteration is not
6768:   not directly related to the `DM`.

6770: .seealso: [](ch_dmbase), `DM`, `VecView()`
6771: @*/
6772: PetscErrorCode DMGetOutputSequenceNumber(DM dm, PetscInt *num, PetscReal *val)
6773: {
6774:   PetscFunctionBegin;
6776:   if (num) {
6777:     PetscAssertPointer(num, 2);
6778:     *num = dm->outputSequenceNum;
6779:   }
6780:   if (val) {
6781:     PetscAssertPointer(val, 3);
6782:     *val = dm->outputSequenceVal;
6783:   }
6784:   PetscFunctionReturn(PETSC_SUCCESS);
6785: }

6787: /*@
6788:   DMSetOutputSequenceNumber - Set the sequence number/value for output

6790:   Input Parameters:
6791: + dm  - The original `DM`
6792: . num - The output sequence number
6793: - val - The output sequence value

6795:   Level: intermediate

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

6801: .seealso: [](ch_dmbase), `DM`, `VecView()`
6802: @*/
6803: PetscErrorCode DMSetOutputSequenceNumber(DM dm, PetscInt num, PetscReal val)
6804: {
6805:   PetscFunctionBegin;
6807:   dm->outputSequenceNum = num;
6808:   dm->outputSequenceVal = val;
6809:   PetscFunctionReturn(PETSC_SUCCESS);
6810: }

6812: /*@
6813:   DMOutputSequenceLoad - Retrieve the sequence value from a `PetscViewer`

6815:   Input Parameters:
6816: + dm     - The original `DM`
6817: . viewer - The `PetscViewer` to get it from
6818: . name   - The sequence name
6819: - num    - The output sequence number

6821:   Output Parameter:
6822: . val - The output sequence value

6824:   Level: intermediate

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

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

6833: .seealso: [](ch_dmbase), `DM`, `DMGetOutputSequenceNumber()`, `DMSetOutputSequenceNumber()`, `VecView()`
6834: @*/
6835: PetscErrorCode DMOutputSequenceLoad(DM dm, PetscViewer viewer, const char name[], PetscInt num, PetscReal *val)
6836: {
6837:   PetscBool ishdf5;

6839:   PetscFunctionBegin;
6842:   PetscAssertPointer(name, 3);
6843:   PetscAssertPointer(val, 5);
6844:   PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERHDF5, &ishdf5));
6845:   PetscCheck(ishdf5, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Invalid viewer; open viewer with PetscViewerHDF5Open()");
6846: #if PetscDefined(HAVE_HDF5)
6847:   PetscScalar value;

6849:   PetscCall(DMSequenceLoad_HDF5_Internal(dm, name, num, &value, viewer));
6850:   *val = PetscRealPart(value);
6851: #endif
6852:   PetscFunctionReturn(PETSC_SUCCESS);
6853: }

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

6858:   Input Parameters:
6859: + dm     - The original `DM`
6860: . viewer - The `PetscViewer` to get it from
6861: - name   - The sequence name

6863:   Output Parameter:
6864: . len - The length of the output sequence

6866:   Level: intermediate

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

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

6875: .seealso: [](ch_dmbase), `DM`, `DMGetOutputSequenceNumber()`, `DMSetOutputSequenceNumber()`, `VecView()`
6876: @*/
6877: PetscErrorCode DMGetOutputSequenceLength(DM dm, PetscViewer viewer, const char name[], PetscInt *len)
6878: {
6879:   PetscBool ishdf5;

6881:   PetscFunctionBegin;
6884:   PetscAssertPointer(name, 3);
6885:   PetscAssertPointer(len, 4);
6886:   PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERHDF5, &ishdf5));
6887:   PetscCheck(ishdf5, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Invalid viewer; open viewer with PetscViewerHDF5Open()");
6888: #if PetscDefined(HAVE_HDF5)
6889:   PetscCall(DMSequenceGetLength_HDF5_Internal(dm, name, len, viewer));
6890: #endif
6891:   PetscFunctionReturn(PETSC_SUCCESS);
6892: }

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

6897:   Not Collective

6899:   Input Parameter:
6900: . dm - The `DM`

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

6905:   Level: beginner

6907: .seealso: [](ch_dmbase), `DM`, `DMSetUseNatural()`, `DMCreate()`
6908: @*/
6909: PetscErrorCode DMGetUseNatural(DM dm, PetscBool *useNatural)
6910: {
6911:   PetscFunctionBegin;
6913:   PetscAssertPointer(useNatural, 2);
6914:   *useNatural = dm->useNatural;
6915:   PetscFunctionReturn(PETSC_SUCCESS);
6916: }

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

6921:   Collective

6923:   Input Parameters:
6924: + dm         - The `DM`
6925: - useNatural - `PETSC_TRUE` to build the mapping to a natural order during distribution

6927:   Level: beginner

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

6932: .seealso: [](ch_dmbase), `DM`, `DMGetUseNatural()`, `DMCreate()`, `DMPlexDistribute()`, `DMCreateSubDM()`, `DMCreateSuperDM()`
6933: @*/
6934: PetscErrorCode DMSetUseNatural(DM dm, PetscBool useNatural)
6935: {
6936:   PetscFunctionBegin;
6939:   dm->useNatural = useNatural;
6940:   PetscFunctionReturn(PETSC_SUCCESS);
6941: }

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

6946:   Not Collective

6948:   Input Parameters:
6949: + dm   - The `DM` object
6950: - name - The label name

6952:   Level: intermediate

6954: .seealso: [](ch_dmbase), `DM`, `DMLabelCreate()`, `DMHasLabel()`, `DMGetLabelValue()`, `DMSetLabelValue()`, `DMGetStratumIS()`
6955: @*/
6956: PetscErrorCode DMCreateLabel(DM dm, const char name[])
6957: {
6958:   PetscBool flg;
6959:   DMLabel   label;

6961:   PetscFunctionBegin;
6963:   PetscAssertPointer(name, 2);
6964:   PetscCall(DMHasLabel(dm, name, &flg));
6965:   if (!flg) {
6966:     PetscCall(DMLabelCreate(PETSC_COMM_SELF, name, &label));
6967:     PetscCall(DMAddLabel(dm, label));
6968:     PetscCall(DMLabelDestroy(&label));
6969:   }
6970:   PetscFunctionReturn(PETSC_SUCCESS);
6971: }

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

6976:   Not Collective

6978:   Input Parameters:
6979: + dm   - The `DM` object
6980: . l    - The index for the label
6981: - name - The label name

6983:   Level: intermediate

6985: .seealso: [](ch_dmbase), `DM`, `DMCreateLabel()`, `DMLabelCreate()`, `DMHasLabel()`, `DMGetLabelValue()`, `DMSetLabelValue()`, `DMGetStratumIS()`
6986: @*/
6987: PetscErrorCode DMCreateLabelAtIndex(DM dm, PetscInt l, const char name[])
6988: {
6989:   DMLabelLink orig, prev = NULL;
6990:   DMLabel     label;
6991:   PetscInt    Nl, m;
6992:   PetscBool   flg, match;
6993:   const char *lname;

6995:   PetscFunctionBegin;
6997:   PetscAssertPointer(name, 3);
6998:   PetscCall(DMHasLabel(dm, name, &flg));
6999:   if (!flg) {
7000:     PetscCall(DMLabelCreate(PETSC_COMM_SELF, name, &label));
7001:     PetscCall(DMAddLabel(dm, label));
7002:     PetscCall(DMLabelDestroy(&label));
7003:   }
7004:   PetscCall(DMGetNumLabels(dm, &Nl));
7005:   PetscCheck(l < Nl, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Label index %" PetscInt_FMT " must be in [0, %" PetscInt_FMT ")", l, Nl);
7006:   for (m = 0, orig = dm->labels; m < Nl; ++m, prev = orig, orig = orig->next) {
7007:     PetscCall(PetscObjectGetName((PetscObject)orig->label, &lname));
7008:     PetscCall(PetscStrcmp(name, lname, &match));
7009:     if (match) break;
7010:   }
7011:   if (m == l) PetscFunctionReturn(PETSC_SUCCESS);
7012:   if (!m) dm->labels = orig->next;
7013:   else prev->next = orig->next;
7014:   if (!l) {
7015:     orig->next = dm->labels;
7016:     dm->labels = orig;
7017:   } else {
7018:     for (m = 0, prev = dm->labels; m < l - 1; ++m, prev = prev->next);
7019:     orig->next = prev->next;
7020:     prev->next = orig;
7021:   }
7022:   PetscFunctionReturn(PETSC_SUCCESS);
7023: }

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

7028:   Not Collective

7030:   Input Parameters:
7031: + dm    - The `DM` object
7032: . name  - The label name
7033: - point - The mesh point

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

7038:   Level: beginner

7040: .seealso: [](ch_dmbase), `DM`, `DMLabelGetValue()`, `DMSetLabelValue()`, `DMGetStratumIS()`
7041: @*/
7042: PetscErrorCode DMGetLabelValue(DM dm, const char name[], PetscInt point, PetscInt *value)
7043: {
7044:   DMLabel label;

7046:   PetscFunctionBegin;
7048:   PetscAssertPointer(name, 2);
7049:   PetscCall(DMGetLabel(dm, name, &label));
7050:   PetscCheck(label, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "No label named %s was found", name);
7051:   PetscCall(DMLabelGetValue(label, point, value));
7052:   PetscFunctionReturn(PETSC_SUCCESS);
7053: }

7055: /*@
7056:   DMSetLabelValue - Add a point to a `DMLabel` with given value

7058:   Not Collective

7060:   Input Parameters:
7061: + dm    - The `DM` object
7062: . name  - The label name
7063: . point - The mesh point
7064: - value - The label value for this point

7066:   Output Parameter:

7068:   Level: beginner

7070: .seealso: [](ch_dmbase), `DM`, `DMLabelSetValue()`, `DMGetStratumIS()`, `DMClearLabelValue()`
7071: @*/
7072: PetscErrorCode DMSetLabelValue(DM dm, const char name[], PetscInt point, PetscInt value)
7073: {
7074:   DMLabel label;

7076:   PetscFunctionBegin;
7078:   PetscAssertPointer(name, 2);
7079:   PetscCall(DMGetLabel(dm, name, &label));
7080:   if (!label) {
7081:     PetscCall(DMCreateLabel(dm, name));
7082:     PetscCall(DMGetLabel(dm, name, &label));
7083:   }
7084:   PetscCall(DMLabelSetValue(label, point, value));
7085:   PetscFunctionReturn(PETSC_SUCCESS);
7086: }

7088: /*@
7089:   DMClearLabelValue - Remove a point from a `DMLabel` with given value

7091:   Not Collective

7093:   Input Parameters:
7094: + dm    - The `DM` object
7095: . name  - The label name
7096: . point - The mesh point
7097: - value - The label value for this point

7099:   Level: beginner

7101: .seealso: [](ch_dmbase), `DM`, `DMLabelClearValue()`, `DMSetLabelValue()`, `DMGetStratumIS()`
7102: @*/
7103: PetscErrorCode DMClearLabelValue(DM dm, const char name[], PetscInt point, PetscInt value)
7104: {
7105:   DMLabel label;

7107:   PetscFunctionBegin;
7109:   PetscAssertPointer(name, 2);
7110:   PetscCall(DMGetLabel(dm, name, &label));
7111:   if (!label) PetscFunctionReturn(PETSC_SUCCESS);
7112:   PetscCall(DMLabelClearValue(label, point, value));
7113:   PetscFunctionReturn(PETSC_SUCCESS);
7114: }

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

7119:   Not Collective

7121:   Input Parameters:
7122: + dm   - The `DM` object
7123: - name - The label name

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

7128:   Level: beginner

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

7133: .seealso: [](ch_dmbase), `DM`, `DMLabelGetNumValues()`, `DMSetLabelValue()`, `DMGetLabel()`
7134: @*/
7135: PetscErrorCode DMGetLabelSize(DM dm, const char name[], PetscInt *size)
7136: {
7137:   DMLabel label;

7139:   PetscFunctionBegin;
7141:   PetscAssertPointer(name, 2);
7142:   PetscAssertPointer(size, 3);
7143:   PetscCall(DMGetLabel(dm, name, &label));
7144:   *size = 0;
7145:   if (!label) PetscFunctionReturn(PETSC_SUCCESS);
7146:   PetscCall(DMLabelGetNumValues(label, size));
7147:   PetscFunctionReturn(PETSC_SUCCESS);
7148: }

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

7153:   Not Collective

7155:   Input Parameters:
7156: + dm   - The `DM` object
7157: - name - The label name

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

7162:   Level: beginner

7164: .seealso: [](ch_dmbase), `DM`, `DMLabelGetValueIS()`, `DMGetLabelSize()`
7165: @*/
7166: PetscErrorCode DMGetLabelIdIS(DM dm, const char name[], IS *ids)
7167: {
7168:   DMLabel label;

7170:   PetscFunctionBegin;
7172:   PetscAssertPointer(name, 2);
7173:   PetscAssertPointer(ids, 3);
7174:   PetscCall(DMGetLabel(dm, name, &label));
7175:   *ids = NULL;
7176:   if (label) PetscCall(DMLabelGetValueIS(label, ids));
7177:   else {
7178:     /* returning an empty IS */
7179:     PetscCall(ISCreateGeneral(PETSC_COMM_SELF, 0, NULL, PETSC_USE_POINTER, ids));
7180:   }
7181:   PetscFunctionReturn(PETSC_SUCCESS);
7182: }

7184: /*@
7185:   DMGetStratumSize - Get the number of points in a label stratum

7187:   Not Collective

7189:   Input Parameters:
7190: + dm    - The `DM` object
7191: . name  - The label name of the stratum
7192: - value - The stratum value

7194:   Output Parameter:
7195: . size - The number of points, also called the stratum size

7197:   Level: beginner

7199: .seealso: [](ch_dmbase), `DM`, `DMLabelGetStratumSize()`, `DMGetLabelSize()`, `DMGetLabelIds()`
7200: @*/
7201: PetscErrorCode DMGetStratumSize(DM dm, const char name[], PetscInt value, PetscInt *size)
7202: {
7203:   DMLabel label;

7205:   PetscFunctionBegin;
7207:   PetscAssertPointer(name, 2);
7208:   PetscAssertPointer(size, 4);
7209:   PetscCall(DMGetLabel(dm, name, &label));
7210:   *size = 0;
7211:   if (!label) PetscFunctionReturn(PETSC_SUCCESS);
7212:   PetscCall(DMLabelGetStratumSize(label, value, size));
7213:   PetscFunctionReturn(PETSC_SUCCESS);
7214: }

7216: /*@
7217:   DMGetStratumIS - Get the points in a label stratum

7219:   Not Collective

7221:   Input Parameters:
7222: + dm    - The `DM` object
7223: . name  - The label name
7224: - value - The stratum value

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

7229:   Level: beginner

7231: .seealso: [](ch_dmbase), `DM`, `DMLabelGetStratumIS()`, `DMGetStratumSize()`
7232: @*/
7233: PetscErrorCode DMGetStratumIS(DM dm, const char name[], PetscInt value, IS *points)
7234: {
7235:   DMLabel label;

7237:   PetscFunctionBegin;
7239:   PetscAssertPointer(name, 2);
7240:   PetscAssertPointer(points, 4);
7241:   PetscCall(DMGetLabel(dm, name, &label));
7242:   *points = NULL;
7243:   if (!label) PetscFunctionReturn(PETSC_SUCCESS);
7244:   PetscCall(DMLabelGetStratumIS(label, value, points));
7245:   PetscFunctionReturn(PETSC_SUCCESS);
7246: }

7248: /*@
7249:   DMSetStratumIS - Set the points in a label stratum

7251:   Not Collective

7253:   Input Parameters:
7254: + dm     - The `DM` object
7255: . name   - The label name
7256: . value  - The stratum value
7257: - points - The stratum points

7259:   Level: beginner

7261: .seealso: [](ch_dmbase), `DM`, `DMLabel`, `DMClearLabelStratum()`, `DMLabelClearStratum()`, `DMLabelSetStratumIS()`, `DMGetStratumSize()`
7262: @*/
7263: PetscErrorCode DMSetStratumIS(DM dm, const char name[], PetscInt value, IS points)
7264: {
7265:   DMLabel label;

7267:   PetscFunctionBegin;
7269:   PetscAssertPointer(name, 2);
7271:   PetscCall(DMGetLabel(dm, name, &label));
7272:   if (!label) PetscFunctionReturn(PETSC_SUCCESS);
7273:   PetscCall(DMLabelSetStratumIS(label, value, points));
7274:   PetscFunctionReturn(PETSC_SUCCESS);
7275: }

7277: /*@
7278:   DMClearLabelStratum - Remove all points from a stratum from a `DMLabel`

7280:   Not Collective

7282:   Input Parameters:
7283: + dm    - The `DM` object
7284: . name  - The label name
7285: - value - The label value for this point

7287:   Output Parameter:

7289:   Level: beginner

7291: .seealso: [](ch_dmbase), `DM`, `DMLabel`, `DMLabelClearStratum()`, `DMSetLabelValue()`, `DMGetStratumIS()`, `DMClearLabelValue()`
7292: @*/
7293: PetscErrorCode DMClearLabelStratum(DM dm, const char name[], PetscInt value)
7294: {
7295:   DMLabel label;

7297:   PetscFunctionBegin;
7299:   PetscAssertPointer(name, 2);
7300:   PetscCall(DMGetLabel(dm, name, &label));
7301:   if (!label) PetscFunctionReturn(PETSC_SUCCESS);
7302:   PetscCall(DMLabelClearStratum(label, value));
7303:   PetscFunctionReturn(PETSC_SUCCESS);
7304: }

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

7309:   Not Collective

7311:   Input Parameter:
7312: . dm - The `DM` object

7314:   Output Parameter:
7315: . numLabels - the number of Labels

7317:   Level: intermediate

7319: .seealso: [](ch_dmbase), `DM`, `DMLabel`, `DMGetLabelByNum()`, `DMGetLabelName()`, `DMGetLabelValue()`, `DMSetLabelValue()`, `DMGetStratumIS()`
7320: @*/
7321: PetscErrorCode DMGetNumLabels(DM dm, PetscInt *numLabels)
7322: {
7323:   DMLabelLink next = dm->labels;
7324:   PetscInt    n    = 0;

7326:   PetscFunctionBegin;
7328:   PetscAssertPointer(numLabels, 2);
7329:   while (next) {
7330:     ++n;
7331:     next = next->next;
7332:   }
7333:   *numLabels = n;
7334:   PetscFunctionReturn(PETSC_SUCCESS);
7335: }

7337: /*@
7338:   DMGetLabelName - Return the name of nth label

7340:   Not Collective

7342:   Input Parameters:
7343: + dm - The `DM` object
7344: - n  - the label number

7346:   Output Parameter:
7347: . name - the label name

7349:   Level: intermediate

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

7354: .seealso: [](ch_dmbase), `DM`, `DMLabel`, `DMGetLabelByNum()`, `DMGetLabel()`, `DMGetLabelValue()`, `DMSetLabelValue()`, `DMGetStratumIS()`
7355: @*/
7356: PetscErrorCode DMGetLabelName(DM dm, PetscInt n, const char *name[])
7357: {
7358:   DMLabelLink next = dm->labels;
7359:   PetscInt    l    = 0;

7361:   PetscFunctionBegin;
7363:   PetscAssertPointer(name, 3);
7364:   while (next) {
7365:     if (l == n) {
7366:       PetscCall(PetscObjectGetName((PetscObject)next->label, name));
7367:       PetscFunctionReturn(PETSC_SUCCESS);
7368:     }
7369:     ++l;
7370:     next = next->next;
7371:   }
7372:   SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Label %" PetscInt_FMT " does not exist in this DM", n);
7373: }

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

7378:   Not Collective

7380:   Input Parameters:
7381: + dm   - The `DM` object
7382: - name - The label name

7384:   Output Parameter:
7385: . hasLabel - `PETSC_TRUE` if the label is present

7387:   Level: intermediate

7389: .seealso: [](ch_dmbase), `DM`, `DMLabel`, `DMGetLabel()`, `DMGetLabelByNum()`, `DMCreateLabel()`, `DMGetLabelValue()`, `DMSetLabelValue()`, `DMGetStratumIS()`
7390: @*/
7391: PetscErrorCode DMHasLabel(DM dm, const char name[], PetscBool *hasLabel)
7392: {
7393:   DMLabelLink next = dm->labels;
7394:   const char *lname;

7396:   PetscFunctionBegin;
7398:   PetscAssertPointer(name, 2);
7399:   PetscAssertPointer(hasLabel, 3);
7400:   *hasLabel = PETSC_FALSE;
7401:   while (next) {
7402:     PetscCall(PetscObjectGetName((PetscObject)next->label, &lname));
7403:     PetscCall(PetscStrcmp(name, lname, hasLabel));
7404:     if (*hasLabel) break;
7405:     next = next->next;
7406:   }
7407:   PetscFunctionReturn(PETSC_SUCCESS);
7408: }

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

7414:   Not Collective

7416:   Input Parameters:
7417: + dm   - The `DM` object
7418: - name - The label name

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

7423:   Default labels in a `DMPLEX`:
7424: + "depth"       - Holds the depth (co-dimension) of each mesh point
7425: . "celltype"    - Holds the topological type of each cell
7426: . "ghost"       - If the DM is distributed with overlap, this marks the cells and faces in the overlap
7427: . "Cell Sets"   - Mirrors the cell sets defined by GMsh and ExodusII
7428: . "Face Sets"   - Mirrors the face sets defined by GMsh and ExodusII
7429: - "Vertex Sets" - Mirrors the vertex sets defined by GMsh

7431:   Level: intermediate

7433: .seealso: [](ch_dmbase), `DM`, `DMLabel`, `DMHasLabel()`, `DMGetLabelByNum()`, `DMAddLabel()`, `DMCreateLabel()`, `DMPlexGetDepthLabel()`, `DMPlexGetCellType()`
7434: @*/
7435: PetscErrorCode DMGetLabel(DM dm, const char name[], DMLabel *label)
7436: {
7437:   DMLabelLink next = dm->labels;
7438:   PetscBool   hasLabel;
7439:   const char *lname;

7441:   PetscFunctionBegin;
7443:   PetscAssertPointer(name, 2);
7444:   PetscAssertPointer(label, 3);
7445:   *label = NULL;
7446:   while (next) {
7447:     PetscCall(PetscObjectGetName((PetscObject)next->label, &lname));
7448:     PetscCall(PetscStrcmp(name, lname, &hasLabel));
7449:     if (hasLabel) {
7450:       *label = next->label;
7451:       break;
7452:     }
7453:     next = next->next;
7454:   }
7455:   PetscFunctionReturn(PETSC_SUCCESS);
7456: }

7458: /*@
7459:   DMGetLabelByNum - Return the nth label on a `DM`

7461:   Not Collective

7463:   Input Parameters:
7464: + dm - The `DM` object
7465: - n  - the label number

7467:   Output Parameter:
7468: . label - the label

7470:   Level: intermediate

7472: .seealso: [](ch_dmbase), `DM`, `DMLabel`, `DMAddLabel()`, `DMGetLabelValue()`, `DMSetLabelValue()`, `DMGetStratumIS()`
7473: @*/
7474: PetscErrorCode DMGetLabelByNum(DM dm, PetscInt n, DMLabel *label)
7475: {
7476:   DMLabelLink next = dm->labels;
7477:   PetscInt    l    = 0;

7479:   PetscFunctionBegin;
7481:   PetscAssertPointer(label, 3);
7482:   while (next) {
7483:     if (l == n) {
7484:       *label = next->label;
7485:       PetscFunctionReturn(PETSC_SUCCESS);
7486:     }
7487:     ++l;
7488:     next = next->next;
7489:   }
7490:   SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Label %" PetscInt_FMT " does not exist in this DM", n);
7491: }

7493: /*@
7494:   DMAddLabel - Add the label to this `DM`

7496:   Not Collective

7498:   Input Parameters:
7499: + dm    - The `DM` object
7500: - label - The `DMLabel`

7502:   Level: developer

7504: .seealso: [](ch_dmbase), `DM`, `DMLabel`, `DMCreateLabel()`, `DMHasLabel()`, `DMGetLabelValue()`, `DMSetLabelValue()`, `DMGetStratumIS()`
7505: @*/
7506: PetscErrorCode DMAddLabel(DM dm, DMLabel label)
7507: {
7508:   DMLabelLink l, *p, tmpLabel;
7509:   PetscBool   hasLabel;
7510:   const char *lname;
7511:   PetscBool   flg;

7513:   PetscFunctionBegin;
7515:   PetscCall(PetscObjectGetName((PetscObject)label, &lname));
7516:   PetscCall(DMHasLabel(dm, lname, &hasLabel));
7517:   PetscCheck(!hasLabel, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Label %s already exists in this DM", lname);
7518:   PetscCall(PetscCalloc1(1, &tmpLabel));
7519:   tmpLabel->label  = label;
7520:   tmpLabel->output = PETSC_TRUE;
7521:   for (p = &dm->labels; (l = *p); p = &l->next) { }
7522:   *p = tmpLabel;
7523:   PetscCall(PetscObjectReference((PetscObject)label));
7524:   PetscCall(PetscStrcmp(lname, "depth", &flg));
7525:   if (flg) dm->depthLabel = label;
7526:   PetscCall(PetscStrcmp(lname, "celltype", &flg));
7527:   if (flg) dm->celltypeLabel = label;
7528:   PetscFunctionReturn(PETSC_SUCCESS);
7529: }

7531: // PetscClangLinter pragma ignore: -fdoc-section-header-unknown
7532: /*@
7533:   DMSetLabel - Replaces the label of a given name, or ignores it if the name is not present

7535:   Not Collective

7537:   Input Parameters:
7538: + dm    - The `DM` object
7539: - label - The `DMLabel`, having the same name, to substitute

7541:   Default labels in a `DMPLEX`:
7542: + "depth"       - Holds the depth (co-dimension) of each mesh point
7543: . "celltype"    - Holds the topological type of each cell
7544: . "ghost"       - If the DM is distributed with overlap, this marks the cells and faces in the overlap
7545: . "Cell Sets"   - Mirrors the cell sets defined by GMsh and ExodusII
7546: . "Face Sets"   - Mirrors the face sets defined by GMsh and ExodusII
7547: - "Vertex Sets" - Mirrors the vertex sets defined by GMsh

7549:   Level: intermediate

7551: .seealso: [](ch_dmbase), `DM`, `DMLabel`, `DMCreateLabel()`, `DMHasLabel()`, `DMPlexGetDepthLabel()`, `DMPlexGetCellType()`
7552: @*/
7553: PetscErrorCode DMSetLabel(DM dm, DMLabel label)
7554: {
7555:   DMLabelLink next = dm->labels;
7556:   PetscBool   hasLabel, flg;
7557:   const char *name, *lname;

7559:   PetscFunctionBegin;
7562:   PetscCall(PetscObjectGetName((PetscObject)label, &name));
7563:   while (next) {
7564:     PetscCall(PetscObjectGetName((PetscObject)next->label, &lname));
7565:     PetscCall(PetscStrcmp(name, lname, &hasLabel));
7566:     if (hasLabel) {
7567:       PetscCall(PetscObjectReference((PetscObject)label));
7568:       PetscCall(PetscStrcmp(lname, "depth", &flg));
7569:       if (flg) dm->depthLabel = label;
7570:       PetscCall(PetscStrcmp(lname, "celltype", &flg));
7571:       if (flg) dm->celltypeLabel = label;
7572:       PetscCall(DMLabelDestroy(&next->label));
7573:       next->label = label;
7574:       break;
7575:     }
7576:     next = next->next;
7577:   }
7578:   PetscFunctionReturn(PETSC_SUCCESS);
7579: }

7581: /*@
7582:   DMRemoveLabel - Remove the label given by name from this `DM`

7584:   Not Collective

7586:   Input Parameters:
7587: + dm   - The `DM` object
7588: - name - The label name

7590:   Output Parameter:
7591: . label - The `DMLabel`, or `NULL` if the label is absent. Pass in `NULL` to call `DMLabelDestroy()` on the label, otherwise the
7592:           caller is responsible for calling `DMLabelDestroy()`.

7594:   Level: developer

7596: .seealso: [](ch_dmbase), `DM`, `DMLabel`, `DMCreateLabel()`, `DMHasLabel()`, `DMGetLabel()`, `DMGetLabelValue()`, `DMSetLabelValue()`, `DMLabelDestroy()`, `DMRemoveLabelBySelf()`
7597: @*/
7598: PetscErrorCode DMRemoveLabel(DM dm, const char name[], DMLabel *label)
7599: {
7600:   DMLabelLink link, *pnext;
7601:   PetscBool   hasLabel;
7602:   const char *lname;

7604:   PetscFunctionBegin;
7606:   PetscAssertPointer(name, 2);
7607:   if (label) {
7608:     PetscAssertPointer(label, 3);
7609:     *label = NULL;
7610:   }
7611:   for (pnext = &dm->labels; (link = *pnext); pnext = &link->next) {
7612:     PetscCall(PetscObjectGetName((PetscObject)link->label, &lname));
7613:     PetscCall(PetscStrcmp(name, lname, &hasLabel));
7614:     if (hasLabel) {
7615:       *pnext = link->next; /* Remove from list */
7616:       PetscCall(PetscStrcmp(name, "depth", &hasLabel));
7617:       if (hasLabel) dm->depthLabel = NULL;
7618:       PetscCall(PetscStrcmp(name, "celltype", &hasLabel));
7619:       if (hasLabel) dm->celltypeLabel = NULL;
7620:       if (label) *label = link->label;
7621:       else PetscCall(DMLabelDestroy(&link->label));
7622:       PetscCall(PetscFree(link));
7623:       break;
7624:     }
7625:   }
7626:   PetscFunctionReturn(PETSC_SUCCESS);
7627: }

7629: /*@
7630:   DMRemoveLabelBySelf - Remove the label from this `DM`

7632:   Not Collective

7634:   Input Parameters:
7635: + dm           - The `DM` object
7636: . label        - The `DMLabel` to be removed from the `DM`
7637: - failNotFound - Should it fail if the label is not found in the `DM`?

7639:   Level: developer

7641:   Note:
7642:   Only exactly the same instance is removed if found, name match is ignored.
7643:   If the `DM` has an exclusive reference to the label, the label gets destroyed and
7644:   *label nullified.

7646: .seealso: [](ch_dmbase), `DM`, `DMLabel`, `DMCreateLabel()`, `DMHasLabel()`, `DMGetLabel()`, `DMGetLabelValue()`, `DMSetLabelValue()`, `DMLabelDestroy()`, `DMRemoveLabel()`
7647: @*/
7648: PetscErrorCode DMRemoveLabelBySelf(DM dm, DMLabel *label, PetscBool failNotFound)
7649: {
7650:   DMLabelLink link, *pnext;
7651:   PetscBool   hasLabel = PETSC_FALSE;

7653:   PetscFunctionBegin;
7655:   PetscAssertPointer(label, 2);
7656:   if (!*label && !failNotFound) PetscFunctionReturn(PETSC_SUCCESS);
7659:   for (pnext = &dm->labels; (link = *pnext); pnext = &link->next) {
7660:     if (*label == link->label) {
7661:       hasLabel = PETSC_TRUE;
7662:       *pnext   = link->next; /* Remove from list */
7663:       if (*label == dm->depthLabel) dm->depthLabel = NULL;
7664:       if (*label == dm->celltypeLabel) dm->celltypeLabel = NULL;
7665:       if (((PetscObject)link->label)->refct < 2) *label = NULL; /* nullify if exclusive reference */
7666:       PetscCall(DMLabelDestroy(&link->label));
7667:       PetscCall(PetscFree(link));
7668:       break;
7669:     }
7670:   }
7671:   PetscCheck(hasLabel || !failNotFound, PetscObjectComm((PetscObject)dm), PETSC_ERR_ARG_WRONG, "Given label not found in DM");
7672:   PetscFunctionReturn(PETSC_SUCCESS);
7673: }

7675: /*@
7676:   DMGetLabelOutput - Get the output flag for a given label

7678:   Not Collective

7680:   Input Parameters:
7681: + dm   - The `DM` object
7682: - name - The label name

7684:   Output Parameter:
7685: . output - The flag for output

7687:   Level: developer

7689: .seealso: [](ch_dmbase), `DM`, `DMLabel`, `DMSetLabelOutput()`, `DMCreateLabel()`, `DMHasLabel()`, `DMGetLabelValue()`, `DMSetLabelValue()`, `DMGetStratumIS()`
7690: @*/
7691: PetscErrorCode DMGetLabelOutput(DM dm, const char name[], PetscBool *output)
7692: {
7693:   DMLabelLink next = dm->labels;
7694:   const char *lname;

7696:   PetscFunctionBegin;
7698:   PetscAssertPointer(name, 2);
7699:   PetscAssertPointer(output, 3);
7700:   while (next) {
7701:     PetscBool flg;

7703:     PetscCall(PetscObjectGetName((PetscObject)next->label, &lname));
7704:     PetscCall(PetscStrcmp(name, lname, &flg));
7705:     if (flg) {
7706:       *output = next->output;
7707:       PetscFunctionReturn(PETSC_SUCCESS);
7708:     }
7709:     next = next->next;
7710:   }
7711:   SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "No label named %s was present in this dm", name);
7712: }

7714: /*@
7715:   DMSetLabelOutput - Set if a given label should be saved to a `PetscViewer` in calls to `DMView()`

7717:   Not Collective

7719:   Input Parameters:
7720: + dm     - The `DM` object
7721: . name   - The label name
7722: - output - `PETSC_TRUE` to save the label to the viewer

7724:   Level: developer

7726: .seealso: [](ch_dmbase), `DM`, `DMLabel`, `DMGetOutputFlag()`, `DMGetLabelOutput()`, `DMCreateLabel()`, `DMHasLabel()`, `DMGetLabelValue()`, `DMSetLabelValue()`, `DMGetStratumIS()`
7727: @*/
7728: PetscErrorCode DMSetLabelOutput(DM dm, const char name[], PetscBool output)
7729: {
7730:   DMLabelLink next = dm->labels;
7731:   const char *lname;

7733:   PetscFunctionBegin;
7735:   PetscAssertPointer(name, 2);
7736:   while (next) {
7737:     PetscBool flg;

7739:     PetscCall(PetscObjectGetName((PetscObject)next->label, &lname));
7740:     PetscCall(PetscStrcmp(name, lname, &flg));
7741:     if (flg) {
7742:       next->output = output;
7743:       PetscFunctionReturn(PETSC_SUCCESS);
7744:     }
7745:     next = next->next;
7746:   }
7747:   SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "No label named %s was present in this dm", name);
7748: }

7750: /*@
7751:   DMCopyLabels - Copy labels from one `DM` mesh to another `DM` with a superset of the points

7753:   Collective

7755:   Input Parameters:
7756: + dmA   - The `DM` object with initial labels
7757: . dmB   - The `DM` object to which labels are copied
7758: . mode  - Copy labels by pointers (`PETSC_OWN_POINTER`) or duplicate them (`PETSC_COPY_VALUES`)
7759: . all   - Copy all labels including "depth", "dim", and "celltype" (`PETSC_TRUE`) which are otherwise ignored (`PETSC_FALSE`)
7760: - emode - How to behave when a `DMLabel` in the source and destination `DM`s with the same name is encountered (see `DMCopyLabelsMode`)

7762:   Level: intermediate

7764:   Note:
7765:   This is typically used when interpolating or otherwise adding to a mesh, or testing.

7767: .seealso: [](ch_dmbase), `DM`, `DMLabel`, `DMAddLabel()`, `DMCopyLabelsMode`
7768: @*/
7769: PetscErrorCode DMCopyLabels(DM dmA, DM dmB, PetscCopyMode mode, PetscBool all, DMCopyLabelsMode emode)
7770: {
7771:   DMLabel     label, labelNew, labelOld;
7772:   const char *name;
7773:   PetscBool   flg;
7774:   DMLabelLink link;

7776:   PetscFunctionBegin;
7781:   PetscCheck(mode != PETSC_USE_POINTER, PetscObjectComm((PetscObject)dmA), PETSC_ERR_SUP, "PETSC_USE_POINTER not supported for objects");
7782:   if (dmA == dmB) PetscFunctionReturn(PETSC_SUCCESS);
7783:   for (link = dmA->labels; link; link = link->next) {
7784:     label = link->label;
7785:     PetscCall(PetscObjectGetName((PetscObject)label, &name));
7786:     if (!all) {
7787:       PetscCall(PetscStrcmp(name, "depth", &flg));
7788:       if (flg) continue;
7789:       PetscCall(PetscStrcmp(name, "dim", &flg));
7790:       if (flg) continue;
7791:       PetscCall(PetscStrcmp(name, "celltype", &flg));
7792:       if (flg) continue;
7793:     }
7794:     PetscCall(DMGetLabel(dmB, name, &labelOld));
7795:     if (labelOld) {
7796:       switch (emode) {
7797:       case DM_COPY_LABELS_KEEP:
7798:         continue;
7799:       case DM_COPY_LABELS_REPLACE:
7800:         PetscCall(DMRemoveLabelBySelf(dmB, &labelOld, PETSC_TRUE));
7801:         break;
7802:       case DM_COPY_LABELS_FAIL:
7803:         SETERRQ(PetscObjectComm((PetscObject)dmA), PETSC_ERR_ARG_OUTOFRANGE, "Label %s already exists in destination DM", name);
7804:       default:
7805:         SETERRQ(PetscObjectComm((PetscObject)dmA), PETSC_ERR_ARG_OUTOFRANGE, "Unhandled DMCopyLabelsMode %d", (int)emode);
7806:       }
7807:     }
7808:     if (mode == PETSC_COPY_VALUES) PetscCall(DMLabelDuplicate(label, &labelNew));
7809:     else labelNew = label;
7810:     PetscCall(DMAddLabel(dmB, labelNew));
7811:     if (mode == PETSC_COPY_VALUES) PetscCall(DMLabelDestroy(&labelNew));
7812:   }
7813:   PetscFunctionReturn(PETSC_SUCCESS);
7814: }

7816: /*@
7817:   DMCompareLabels - Compare labels between two `DM` objects

7819:   Collective; No Fortran Support

7821:   Input Parameters:
7822: + dm0 - First `DM` object
7823: - dm1 - Second `DM` object

7825:   Output Parameters:
7826: + equal   - (Optional) Flag whether labels of `dm0` and `dm1` are the same
7827: - message - (Optional) Message describing the difference, or `NULL` if there is no difference

7829:   Level: intermediate

7831:   Notes:
7832:   The output flag equal will be the same on all processes.

7834:   If equal is passed as `NULL` and difference is found, an error is thrown on all processes.

7836:   Make sure to pass equal is `NULL` on all processes or none of them.

7838:   The output message is set independently on each rank.

7840:   message must be freed with `PetscFree()`

7842:   If message is passed as `NULL` and a difference is found, the difference description is printed to `stderr` in synchronized manner.

7844:   Make sure to pass message as `NULL` on all processes or no processes.

7846:   Labels are matched by name. If the number of labels and their names are equal,
7847:   `DMLabelCompare()` is used to compare each pair of labels with the same name.

7849:   Developer Note:
7850:   Cannot automatically generate the Fortran stub because `message` must be freed with `PetscFree()`

7852: .seealso: [](ch_dmbase), `DM`, `DMLabel`, `DMAddLabel()`, `DMCopyLabelsMode`, `DMLabelCompare()`
7853: @*/
7854: PetscErrorCode DMCompareLabels(DM dm0, DM dm1, PetscBool *equal, char *message[]) PeNS
7855: {
7856:   PetscInt    n;
7857:   char        msg[PETSC_MAX_PATH_LEN] = "";
7858:   PetscBool   eq;
7859:   MPI_Comm    comm;
7860:   PetscMPIInt rank;

7862:   PetscFunctionBegin;
7865:   PetscCheckSameComm(dm0, 1, dm1, 2);
7866:   if (equal) PetscAssertPointer(equal, 3);
7867:   if (message) PetscAssertPointer(message, 4);
7868:   PetscCall(PetscObjectGetComm((PetscObject)dm0, &comm));
7869:   PetscCallMPI(MPI_Comm_rank(comm, &rank));
7870:   {
7871:     PetscInt n1;

7873:     PetscCall(DMGetNumLabels(dm0, &n));
7874:     PetscCall(DMGetNumLabels(dm1, &n1));
7875:     eq = (PetscBool)(n == n1);
7876:     if (!eq) PetscCall(PetscSNPrintf(msg, sizeof(msg), "Number of labels in dm0 = %" PetscInt_FMT " != %" PetscInt_FMT " = Number of labels in dm1", n, n1));
7877:     PetscCallMPI(MPIU_Allreduce(MPI_IN_PLACE, &eq, 1, MPI_C_BOOL, MPI_LAND, comm));
7878:     if (!eq) goto finish;
7879:   }
7880:   for (PetscInt i = 0; i < n; i++) {
7881:     DMLabel     l0, l1;
7882:     const char *name;
7883:     char       *msgInner;

7885:     /* Ignore label order */
7886:     PetscCall(DMGetLabelByNum(dm0, i, &l0));
7887:     PetscCall(PetscObjectGetName((PetscObject)l0, &name));
7888:     PetscCall(DMGetLabel(dm1, name, &l1));
7889:     if (!l1) {
7890:       PetscCall(PetscSNPrintf(msg, sizeof(msg), "Label \"%s\" (#%" PetscInt_FMT " in dm0) not found in dm1", name, i));
7891:       eq = PETSC_FALSE;
7892:       break;
7893:     }
7894:     PetscCall(DMLabelCompare(comm, l0, l1, &eq, &msgInner));
7895:     PetscCall(PetscStrncpy(msg, msgInner, sizeof(msg)));
7896:     PetscCall(PetscFree(msgInner));
7897:     if (!eq) break;
7898:   }
7899:   PetscCallMPI(MPIU_Allreduce(MPI_IN_PLACE, &eq, 1, MPI_C_BOOL, MPI_LAND, comm));
7900: finish:
7901:   /* If message output arg not set, print to stderr */
7902:   if (message) {
7903:     *message = NULL;
7904:     if (msg[0]) PetscCall(PetscStrallocpy(msg, message));
7905:   } else {
7906:     if (msg[0]) PetscCall(PetscSynchronizedFPrintf(comm, PETSC_STDERR, "[%d] %s\n", rank, msg));
7907:     PetscCall(PetscSynchronizedFlush(comm, PETSC_STDERR));
7908:   }
7909:   /* If same output arg not ser and labels are not equal, throw error */
7910:   if (equal) *equal = eq;
7911:   else PetscCheck(eq, comm, PETSC_ERR_ARG_INCOMP, "DMLabels are not the same in dm0 and dm1");
7912:   PetscFunctionReturn(PETSC_SUCCESS);
7913: }

7915: PetscErrorCode DMSetLabelValue_Fast(DM dm, DMLabel *label, const char name[], PetscInt point, PetscInt value)
7916: {
7917:   PetscFunctionBegin;
7918:   PetscAssertPointer(label, 2);
7919:   if (!*label) {
7920:     PetscCall(DMCreateLabel(dm, name));
7921:     PetscCall(DMGetLabel(dm, name, label));
7922:   }
7923:   PetscCall(DMLabelSetValue(*label, point, value));
7924:   PetscFunctionReturn(PETSC_SUCCESS);
7925: }

7927: /*
7928:   Many mesh programs, such as Triangle and TetGen, allow only a single label for each mesh point. Therefore, we would
7929:   like to encode all label IDs using a single, universal label. We can do this by assigning an integer to every
7930:   (label, id) pair in the DM.

7932:   However, a mesh point can have multiple labels, so we must separate all these values. We will assign a bit range to
7933:   each label.
7934: */
7935: PetscErrorCode DMUniversalLabelCreate(DM dm, DMUniversalLabel *universal)
7936: {
7937:   DMUniversalLabel ul;
7938:   PetscBool       *active;
7939:   PetscInt         pStart, pEnd, p, Nl, l, m;

7941:   PetscFunctionBegin;
7942:   PetscCall(PetscMalloc1(1, &ul));
7943:   PetscCall(DMLabelCreate(PETSC_COMM_SELF, "universal", &ul->label));
7944:   PetscCall(DMGetNumLabels(dm, &Nl));
7945:   PetscCall(PetscCalloc1(Nl, &active));
7946:   ul->Nl = 0;
7947:   for (l = 0; l < Nl; ++l) {
7948:     PetscBool   isdepth, iscelltype;
7949:     const char *name;

7951:     PetscCall(DMGetLabelName(dm, l, &name));
7952:     PetscCall(PetscStrncmp(name, "depth", 6, &isdepth));
7953:     PetscCall(PetscStrncmp(name, "celltype", 9, &iscelltype));
7954:     active[l] = !(isdepth || iscelltype) ? PETSC_TRUE : PETSC_FALSE;
7955:     if (active[l]) ++ul->Nl;
7956:   }
7957:   PetscCall(PetscCalloc5(ul->Nl, &ul->names, ul->Nl, &ul->indices, ul->Nl + 1, &ul->offsets, ul->Nl + 1, &ul->bits, ul->Nl, &ul->masks));
7958:   ul->Nv = 0;
7959:   for (l = 0, m = 0; l < Nl; ++l) {
7960:     DMLabel     label;
7961:     PetscInt    nv;
7962:     const char *name;

7964:     if (!active[l]) continue;
7965:     PetscCall(DMGetLabelName(dm, l, &name));
7966:     PetscCall(DMGetLabelByNum(dm, l, &label));
7967:     PetscCall(DMLabelGetNumValues(label, &nv));
7968:     PetscCall(PetscStrallocpy(name, &ul->names[m]));
7969:     ul->indices[m] = l;
7970:     ul->Nv += nv;
7971:     ul->offsets[m + 1] = nv;
7972:     ul->bits[m + 1]    = PetscCeilReal(PetscLog2Real(nv + 1));
7973:     ++m;
7974:   }
7975:   for (l = 1; l <= ul->Nl; ++l) {
7976:     ul->offsets[l] = ul->offsets[l - 1] + ul->offsets[l];
7977:     ul->bits[l]    = ul->bits[l - 1] + ul->bits[l];
7978:   }
7979:   for (l = 0; l < ul->Nl; ++l) {
7980:     ul->masks[l] = 0;
7981:     for (PetscInt b = ul->bits[l]; b < ul->bits[l + 1]; ++b) ul->masks[l] |= 1 << b;
7982:   }
7983:   PetscCall(PetscMalloc1(ul->Nv, &ul->values));
7984:   for (l = 0, m = 0; l < Nl; ++l) {
7985:     DMLabel         label;
7986:     IS              valueIS;
7987:     const PetscInt *varr;
7988:     PetscInt        nv;

7990:     if (!active[l]) continue;
7991:     PetscCall(DMGetLabelByNum(dm, l, &label));
7992:     PetscCall(DMLabelGetNumValues(label, &nv));
7993:     PetscCall(DMLabelGetValueIS(label, &valueIS));
7994:     PetscCall(ISGetIndices(valueIS, &varr));
7995:     for (PetscInt v = 0; v < nv; ++v) ul->values[ul->offsets[m] + v] = varr[v];
7996:     PetscCall(ISRestoreIndices(valueIS, &varr));
7997:     PetscCall(ISDestroy(&valueIS));
7998:     PetscCall(PetscSortInt(nv, &ul->values[ul->offsets[m]]));
7999:     ++m;
8000:   }
8001:   PetscCall(DMPlexGetChart(dm, &pStart, &pEnd));
8002:   for (p = pStart; p < pEnd; ++p) {
8003:     PetscInt  uval   = 0;
8004:     PetscBool marked = PETSC_FALSE;

8006:     for (l = 0, m = 0; l < Nl; ++l) {
8007:       DMLabel  label;
8008:       PetscInt val, defval, loc, nv;

8010:       if (!active[l]) continue;
8011:       PetscCall(DMGetLabelByNum(dm, l, &label));
8012:       PetscCall(DMLabelGetValue(label, p, &val));
8013:       PetscCall(DMLabelGetDefaultValue(label, &defval));
8014:       if (val == defval) {
8015:         ++m;
8016:         continue;
8017:       }
8018:       nv     = ul->offsets[m + 1] - ul->offsets[m];
8019:       marked = PETSC_TRUE;
8020:       PetscCall(PetscFindInt(val, nv, &ul->values[ul->offsets[m]], &loc));
8021:       PetscCheck(loc >= 0, PETSC_COMM_SELF, PETSC_ERR_PLIB, "Label value %" PetscInt_FMT " not found in compression array", val);
8022:       uval += (loc + 1) << ul->bits[m];
8023:       ++m;
8024:     }
8025:     if (marked) PetscCall(DMLabelSetValue(ul->label, p, uval));
8026:   }
8027:   PetscCall(PetscFree(active));
8028:   *universal = ul;
8029:   PetscFunctionReturn(PETSC_SUCCESS);
8030: }

8032: PetscErrorCode DMUniversalLabelDestroy(DMUniversalLabel *universal)
8033: {
8034:   PetscInt l;

8036:   PetscFunctionBegin;
8037:   for (l = 0; l < (*universal)->Nl; ++l) PetscCall(PetscFree((*universal)->names[l]));
8038:   PetscCall(DMLabelDestroy(&(*universal)->label));
8039:   PetscCall(PetscFree5((*universal)->names, (*universal)->indices, (*universal)->offsets, (*universal)->bits, (*universal)->masks));
8040:   PetscCall(PetscFree((*universal)->values));
8041:   PetscCall(PetscFree(*universal));
8042:   *universal = NULL;
8043:   PetscFunctionReturn(PETSC_SUCCESS);
8044: }

8046: PetscErrorCode DMUniversalLabelGetLabel(DMUniversalLabel ul, DMLabel *ulabel)
8047: {
8048:   PetscFunctionBegin;
8049:   PetscAssertPointer(ulabel, 2);
8050:   *ulabel = ul->label;
8051:   PetscFunctionReturn(PETSC_SUCCESS);
8052: }

8054: PetscErrorCode DMUniversalLabelCreateLabels(DMUniversalLabel ul, PetscBool preserveOrder, DM dm)
8055: {
8056:   PetscInt Nl = ul->Nl, l;

8058:   PetscFunctionBegin;
8060:   for (l = 0; l < Nl; ++l) {
8061:     if (preserveOrder) PetscCall(DMCreateLabelAtIndex(dm, ul->indices[l], ul->names[l]));
8062:     else PetscCall(DMCreateLabel(dm, ul->names[l]));
8063:   }
8064:   if (preserveOrder) {
8065:     for (l = 0; l < ul->Nl; ++l) {
8066:       const char *name;
8067:       PetscBool   match;

8069:       PetscCall(DMGetLabelName(dm, ul->indices[l], &name));
8070:       PetscCall(PetscStrcmp(name, ul->names[l], &match));
8071:       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]);
8072:     }
8073:   }
8074:   PetscFunctionReturn(PETSC_SUCCESS);
8075: }

8077: PetscErrorCode DMUniversalLabelSetLabelValue(DMUniversalLabel ul, DM dm, PetscBool useIndex, PetscInt p, PetscInt value)
8078: {
8079:   PetscFunctionBegin;
8080:   for (PetscInt l = 0; l < ul->Nl; ++l) {
8081:     DMLabel  label;
8082:     PetscInt lval = (value & ul->masks[l]) >> ul->bits[l];

8084:     if (lval) {
8085:       if (useIndex) PetscCall(DMGetLabelByNum(dm, ul->indices[l], &label));
8086:       else PetscCall(DMGetLabel(dm, ul->names[l], &label));
8087:       PetscCall(DMLabelSetValue(label, p, ul->values[ul->offsets[l] + lval - 1]));
8088:     }
8089:   }
8090:   PetscFunctionReturn(PETSC_SUCCESS);
8091: }

8093: /*@
8094:   DMGetCoarseDM - Get the coarse `DM`from which this `DM` was obtained by refinement

8096:   Not Collective

8098:   Input Parameter:
8099: . dm - The `DM` object

8101:   Output Parameter:
8102: . cdm - The coarse `DM`

8104:   Level: intermediate

8106: .seealso: [](ch_dmbase), `DM`, `DMSetCoarseDM()`, `DMCoarsen()`
8107: @*/
8108: PetscErrorCode DMGetCoarseDM(DM dm, DM *cdm)
8109: {
8110:   PetscFunctionBegin;
8112:   PetscAssertPointer(cdm, 2);
8113:   *cdm = dm->coarseMesh;
8114:   PetscFunctionReturn(PETSC_SUCCESS);
8115: }

8117: /*@
8118:   DMSetCoarseDM - Set the coarse `DM` from which this `DM` was obtained by refinement

8120:   Input Parameters:
8121: + dm  - The `DM` object
8122: - cdm - The coarse `DM`

8124:   Level: intermediate

8126:   Note:
8127:   Normally this is set automatically by `DMRefine()`

8129: .seealso: [](ch_dmbase), `DM`, `DMGetCoarseDM()`, `DMCoarsen()`, `DMSetRefine()`, `DMSetFineDM()`
8130: @*/
8131: PetscErrorCode DMSetCoarseDM(DM dm, DM cdm)
8132: {
8133:   PetscFunctionBegin;
8136:   if (dm == cdm) cdm = NULL;
8137:   PetscCall(PetscObjectReference((PetscObject)cdm));
8138:   PetscCall(DMDestroy(&dm->coarseMesh));
8139:   dm->coarseMesh = cdm;
8140:   PetscFunctionReturn(PETSC_SUCCESS);
8141: }

8143: /*@
8144:   DMGetFineDM - Get the fine mesh from which this `DM` was obtained by coarsening

8146:   Input Parameter:
8147: . dm - The `DM` object

8149:   Output Parameter:
8150: . fdm - The fine `DM`

8152:   Level: intermediate

8154: .seealso: [](ch_dmbase), `DM`, `DMSetFineDM()`, `DMCoarsen()`, `DMRefine()`
8155: @*/
8156: PetscErrorCode DMGetFineDM(DM dm, DM *fdm)
8157: {
8158:   PetscFunctionBegin;
8160:   PetscAssertPointer(fdm, 2);
8161:   *fdm = dm->fineMesh;
8162:   PetscFunctionReturn(PETSC_SUCCESS);
8163: }

8165: /*@
8166:   DMSetFineDM - Set the fine mesh from which this was obtained by coarsening

8168:   Input Parameters:
8169: + dm  - The `DM` object
8170: - fdm - The fine `DM`

8172:   Level: developer

8174:   Note:
8175:   Normally this is set automatically by `DMCoarsen()`

8177: .seealso: [](ch_dmbase), `DM`, `DMGetFineDM()`, `DMCoarsen()`, `DMRefine()`
8178: @*/
8179: PetscErrorCode DMSetFineDM(DM dm, DM fdm)
8180: {
8181:   PetscFunctionBegin;
8184:   if (dm == fdm) fdm = NULL;
8185:   PetscCall(PetscObjectReference((PetscObject)fdm));
8186:   PetscCall(DMDestroy(&dm->fineMesh));
8187:   dm->fineMesh = fdm;
8188:   PetscFunctionReturn(PETSC_SUCCESS);
8189: }

8191: /*@
8192:   DMAddBoundary - Add a boundary condition, for a single field, to a model represented by a `DM`

8194:   Collective

8196:   Input Parameters:
8197: + dm       - The `DM`, with a `PetscDS` that matches the problem being constrained
8198: . type     - The type of condition, e.g. `DM_BC_ESSENTIAL_ANALYTIC`, `DM_BC_ESSENTIAL_FIELD` (Dirichlet), or `DM_BC_NATURAL` (Neumann)
8199: . name     - The BC name
8200: . label    - The label defining constrained points
8201: . Nv       - The number of `DMLabel` values for constrained points
8202: . values   - An array of values for constrained points
8203: . field    - The field to constrain
8204: . Nc       - The number of constrained field components (0 will constrain all components)
8205: . comps    - An array of constrained component numbers
8206: . bcFunc   - A pointwise function giving boundary values
8207: . bcFunc_t - A pointwise function giving the time derivative of the boundary values, or `NULL`
8208: - ctx      - An optional application context for `bcFunc`

8210:   Output Parameter:
8211: . bd - (Optional) Boundary number

8213:   Options Database Keys:
8214: + -bc_NAME values     - Overrides the boundary ids for boundary named NAME
8215: - -bc_NAME_comp comps - Overrides the boundary components for boundary named NAME

8217:   Level: intermediate

8219:   Notes:
8220:   If the `DM` is of type `DMPLEX` and the field is of type `PetscFE`, then this function completes the label using `DMPlexLabelComplete()`.

8222:   Both bcFunc and bcFunc_t will depend on the boundary condition type. If the type if `DM_BC_ESSENTIAL`, then the calling sequence is\:
8223: .vb
8224:  void bcFunc(PetscInt dim, PetscReal time, const PetscReal x[], PetscInt Nc, PetscScalar bcval[])
8225: .ve

8227:   If the type is `DM_BC_ESSENTIAL_FIELD` or other _FIELD value, then the calling sequence is\:

8229: .vb
8230:   void bcFunc(PetscInt dim, PetscInt Nf, PetscInt NfAux,
8231:               const PetscInt uOff[], const PetscInt uOff_x[], const PetscScalar u[], const PetscScalar u_t[], const PetscScalar u_x[],
8232:               const PetscInt aOff[], const PetscInt aOff_x[], const PetscScalar a[], const PetscScalar a_t[], const PetscScalar a_x[],
8233:               PetscReal time, const PetscReal x[], PetscScalar bcval[])
8234: .ve
8235: + dim - the spatial dimension
8236: . Nf - the number of fields
8237: . uOff - the offset into u[] and u_t[] for each field
8238: . uOff_x - the offset into u_x[] for each field
8239: . u - each field evaluated at the current point
8240: . u_t - the time derivative of each field evaluated at the current point
8241: . u_x - the gradient of each field evaluated at the current point
8242: . aOff - the offset into a[] and a_t[] for each auxiliary field
8243: . aOff_x - the offset into a_x[] for each auxiliary field
8244: . a - each auxiliary field evaluated at the current point
8245: . a_t - the time derivative of each auxiliary field evaluated at the current point
8246: . a_x - the gradient of auxiliary each field evaluated at the current point
8247: . t - current time
8248: . x - coordinates of the current point
8249: . numConstants - number of constant parameters
8250: . constants - constant parameters
8251: - bcval - output values at the current point

8253: .seealso: [](ch_dmbase), `DM`, `DSGetBoundary()`, `PetscDSAddBoundary()`
8254: @*/
8255: 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)
8256: {
8257:   PetscDS ds;

8259:   PetscFunctionBegin;
8266:   PetscCheck(!dm->localSection, PetscObjectComm((PetscObject)dm), PETSC_ERR_ARG_WRONGSTATE, "Cannot add boundary to DM after creating local section");
8267:   PetscCall(DMGetDS(dm, &ds));
8268:   /* Complete label */
8269:   if (label) {
8270:     PetscObject  obj;
8271:     PetscClassId id;

8273:     PetscCall(DMGetField(dm, field, NULL, &obj));
8274:     PetscCall(PetscObjectGetClassId(obj, &id));
8275:     if (id == PETSCFE_CLASSID) {
8276:       DM plex;

8278:       PetscCall(DMConvert(dm, DMPLEX, &plex));
8279:       if (plex) PetscCall(DMPlexLabelComplete(plex, label));
8280:       PetscCall(DMDestroy(&plex));
8281:     }
8282:   }
8283:   PetscCall(PetscDSAddBoundary(ds, type, name, label, Nv, values, field, Nc, comps, bcFunc, bcFunc_t, ctx, bd));
8284:   PetscFunctionReturn(PETSC_SUCCESS);
8285: }

8287: /* TODO Remove this since now the structures are the same */
8288: static PetscErrorCode DMPopulateBoundary(DM dm)
8289: {
8290:   PetscDS     ds;
8291:   DMBoundary *lastnext;
8292:   DSBoundary  dsbound;

8294:   PetscFunctionBegin;
8295:   PetscCall(DMGetDS(dm, &ds));
8296:   dsbound = ds->boundary;
8297:   if (dm->boundary) {
8298:     DMBoundary next = dm->boundary;

8300:     /* quick check to see if the PetscDS has changed */
8301:     if (next->dsboundary == dsbound) PetscFunctionReturn(PETSC_SUCCESS);
8302:     /* the PetscDS has changed: tear down and rebuild */
8303:     while (next) {
8304:       DMBoundary b = next;

8306:       next = b->next;
8307:       PetscCall(PetscFree(b));
8308:     }
8309:     dm->boundary = NULL;
8310:   }

8312:   lastnext = &dm->boundary;
8313:   while (dsbound) {
8314:     DMBoundary dmbound;

8316:     PetscCall(PetscNew(&dmbound));
8317:     dmbound->dsboundary = dsbound;
8318:     dmbound->label      = dsbound->label;
8319:     /* push on the back instead of the front so that it is in the same order as in the PetscDS */
8320:     *lastnext = dmbound;
8321:     lastnext  = &dmbound->next;
8322:     dsbound   = dsbound->next;
8323:   }
8324:   PetscFunctionReturn(PETSC_SUCCESS);
8325: }

8327: /*@
8328:   DMIsBoundaryPoint - Determine whether a mesh point lies on a `DM` boundary

8330:   Not Collective

8332:   Input Parameters:
8333: + dm    - the `DM` object
8334: - point - the mesh point number

8336:   Output Parameter:
8337: . isBd - `PETSC_TRUE` if `point` belongs to any boundary label registered on the `DM`

8339:   Level: developer

8341: .seealso: [](ch_dmbase), `DM`, `DMLabel`, `DMAddBoundary()`, `PetscDSGetBoundary()`
8342: @*/
8343: PetscErrorCode DMIsBoundaryPoint(DM dm, PetscInt point, PetscBool *isBd)
8344: {
8345:   DMBoundary b;

8347:   PetscFunctionBegin;
8349:   PetscAssertPointer(isBd, 3);
8350:   *isBd = PETSC_FALSE;
8351:   PetscCall(DMPopulateBoundary(dm));
8352:   b = dm->boundary;
8353:   while (b && !*isBd) {
8354:     DMLabel    label = b->label;
8355:     DSBoundary dsb   = b->dsboundary;

8357:     if (label) {
8358:       for (PetscInt i = 0; i < dsb->Nv && !*isBd; ++i) PetscCall(DMLabelStratumHasPoint(label, dsb->values[i], point, isBd));
8359:     }
8360:     b = b->next;
8361:   }
8362:   PetscFunctionReturn(PETSC_SUCCESS);
8363: }

8365: /*@
8366:   DMHasBound - Determine whether a bound condition was specified

8368:   Logically collective

8370:   Input Parameter:
8371: . dm - The `DM`, with a `PetscDS` that matches the problem being constrained

8373:   Output Parameter:
8374: . hasBound - Flag indicating if a bound condition was specified

8376:   Level: intermediate

8378: .seealso: [](ch_dmbase), `DM`, `DSAddBoundary()`, `PetscDSAddBoundary()`
8379: @*/
8380: PetscErrorCode DMHasBound(DM dm, PetscBool *hasBound)
8381: {
8382:   PetscDS  ds;
8383:   PetscInt Nf, numBd;

8385:   PetscFunctionBegin;
8386:   *hasBound = PETSC_FALSE;
8387:   PetscCall(DMGetDS(dm, &ds));
8388:   PetscCall(PetscDSGetNumFields(ds, &Nf));
8389:   for (PetscInt f = 0; f < Nf; ++f) {
8390:     PetscSimplePointFn *lfunc, *ufunc;

8392:     PetscCall(PetscDSGetLowerBound(ds, f, &lfunc, NULL));
8393:     PetscCall(PetscDSGetUpperBound(ds, f, &ufunc, NULL));
8394:     if (lfunc || ufunc) *hasBound = PETSC_TRUE;
8395:   }

8397:   PetscCall(PetscDSGetNumBoundary(ds, &numBd));
8398:   PetscCall(PetscDSUpdateBoundaryLabels(ds, dm));
8399:   for (PetscInt b = 0; b < numBd; ++b) {
8400:     PetscWeakForm           wf;
8401:     DMBoundaryConditionType type;
8402:     const char             *name;
8403:     DMLabel                 label;
8404:     PetscInt                numids;
8405:     const PetscInt         *ids;
8406:     PetscInt                field, Nc;
8407:     const PetscInt         *comps;
8408:     PetscVoidFn            *bvfunc;
8409:     void                   *ctx;

8411:     PetscCall(PetscDSGetBoundary(ds, b, &wf, &type, &name, &label, &numids, &ids, &field, &Nc, &comps, &bvfunc, NULL, &ctx));
8412:     if (type == DM_BC_LOWER_BOUND || type == DM_BC_UPPER_BOUND) *hasBound = PETSC_TRUE;
8413:   }
8414:   PetscFunctionReturn(PETSC_SUCCESS);
8415: }

8417: /*@
8418:   DMProjectFunction - This projects the given function into the function space provided by a `DM`, putting the coefficients in a global vector.

8420:   Collective

8422:   Input Parameters:
8423: + dm    - The `DM`
8424: . time  - The time
8425: . funcs - The coordinate functions to evaluate, one per field
8426: . ctxs  - Optional array of contexts to pass to each coordinate function.  ctxs itself may be null.
8427: - mode  - The insertion mode for values

8429:   Output Parameter:
8430: . X - vector

8432:   Calling sequence of `funcs`:
8433: + dim  - The spatial dimension
8434: . time - The time at which to sample
8435: . x    - The coordinates
8436: . Nc   - The number of components
8437: . u    - The output field values
8438: - ctx  - optional function context

8440:   Level: developer

8442:   Developer Notes:
8443:   This API is specific to only particular usage of `DM`

8445:   The notes need to provide some information about what has to be provided to the `DM` to be able to perform the computation.

8447: .seealso: [](ch_dmbase), `DM`, `DMProjectFunctionLocal()`, `DMProjectFunctionLabel()`, `DMComputeL2Diff()`
8448: @*/
8449: 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)
8450: {
8451:   Vec localX;

8453:   PetscFunctionBegin;
8455:   PetscCall(PetscLogEventBegin(DM_ProjectFunction, dm, X, 0, 0));
8456:   PetscCall(DMGetLocalVector(dm, &localX));
8457:   PetscCall(VecSet(localX, 0.));
8458:   PetscCall(DMProjectFunctionLocal(dm, time, funcs, ctxs, mode, localX));
8459:   PetscCall(DMLocalToGlobalBegin(dm, localX, mode, X));
8460:   PetscCall(DMLocalToGlobalEnd(dm, localX, mode, X));
8461:   PetscCall(DMRestoreLocalVector(dm, &localX));
8462:   PetscCall(PetscLogEventEnd(DM_ProjectFunction, dm, X, 0, 0));
8463:   PetscFunctionReturn(PETSC_SUCCESS);
8464: }

8466: /*@
8467:   DMProjectFunctionLocal - This projects the given function into the function space provided by a `DM`, putting the coefficients in a local vector.

8469:   Not Collective

8471:   Input Parameters:
8472: + dm    - The `DM`
8473: . time  - The time
8474: . funcs - The coordinate functions to evaluate, one per field
8475: . ctxs  - Optional array of contexts to pass to each coordinate function.  ctxs itself may be null.
8476: - mode  - The insertion mode for values

8478:   Output Parameter:
8479: . localX - vector

8481:   Calling sequence of `funcs`:
8482: + dim  - The spatial dimension
8483: . time - The current timestep
8484: . x    - The coordinates
8485: . Nc   - The number of components
8486: . u    - The output field values
8487: - ctx  - optional function context

8489:   Level: developer

8491:   Developer Notes:
8492:   This API is specific to only particular usage of `DM`

8494:   The notes need to provide some information about what has to be provided to the `DM` to be able to perform the computation.

8496: .seealso: [](ch_dmbase), `DM`, `DMProjectFunction()`, `DMProjectFunctionLabel()`, `DMComputeL2Diff()`
8497: @*/
8498: 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)
8499: {
8500:   PetscFunctionBegin;
8503:   PetscUseTypeMethod(dm, projectfunctionlocal, time, funcs, ctxs, mode, localX);
8504:   PetscFunctionReturn(PETSC_SUCCESS);
8505: }

8507: /*@
8508:   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.

8510:   Collective

8512:   Input Parameters:
8513: + dm     - The `DM`
8514: . time   - The time
8515: . numIds - The number of ids
8516: . ids    - The ids
8517: . Nc     - The number of components
8518: . comps  - The components
8519: . label  - The `DMLabel` selecting the portion of the mesh for projection
8520: . funcs  - The coordinate functions to evaluate, one per field
8521: . ctxs   - Optional array of contexts to pass to each coordinate function.  ctxs may be null.
8522: - mode   - The insertion mode for values

8524:   Output Parameter:
8525: . X - vector

8527:   Calling sequence of `funcs`:
8528: + dim  - The spatial dimension
8529: . time - The current timestep
8530: . x    - The coordinates
8531: . Nc   - The number of components
8532: . u    - The output field values
8533: - ctx  - optional function context

8535:   Level: developer

8537:   Developer Notes:
8538:   This API is specific to only particular usage of `DM`

8540:   The notes need to provide some information about what has to be provided to the `DM` to be able to perform the computation.

8542: .seealso: [](ch_dmbase), `DM`, `DMProjectFunction()`, `DMProjectFunctionLocal()`, `DMProjectFunctionLabelLocal()`, `DMComputeL2Diff()`
8543: @*/
8544: 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)
8545: {
8546:   Vec localX;

8548:   PetscFunctionBegin;
8550:   PetscCall(DMGetLocalVector(dm, &localX));
8551:   PetscCall(VecSet(localX, 0.));
8552:   PetscCall(DMProjectFunctionLabelLocal(dm, time, label, numIds, ids, Nc, comps, funcs, ctxs, mode, localX));
8553:   PetscCall(DMLocalToGlobalBegin(dm, localX, mode, X));
8554:   PetscCall(DMLocalToGlobalEnd(dm, localX, mode, X));
8555:   PetscCall(DMRestoreLocalVector(dm, &localX));
8556:   PetscFunctionReturn(PETSC_SUCCESS);
8557: }

8559: /*@
8560:   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.

8562:   Not Collective

8564:   Input Parameters:
8565: + dm     - The `DM`
8566: . time   - The time
8567: . label  - The `DMLabel` selecting the portion of the mesh for projection
8568: . numIds - The number of ids
8569: . ids    - The ids
8570: . Nc     - The number of components
8571: . comps  - The components
8572: . funcs  - The coordinate functions to evaluate, one per field
8573: . ctxs   - Optional array of contexts to pass to each coordinate function.  ctxs itself may be null.
8574: - mode   - The insertion mode for values

8576:   Output Parameter:
8577: . localX - vector

8579:   Calling sequence of `funcs`:
8580: + dim  - The spatial dimension
8581: . time - The current time
8582: . x    - The coordinates
8583: . Nc   - The number of components
8584: . u    - The output field values
8585: - ctx  - optional function context

8587:   Level: developer

8589:   Developer Notes:
8590:   This API is specific to only particular usage of `DM`

8592:   The notes need to provide some information about what has to be provided to the `DM` to be able to perform the computation.

8594: .seealso: [](ch_dmbase), `DM`, `DMProjectFunction()`, `DMProjectFunctionLocal()`, `DMProjectFunctionLabel()`, `DMComputeL2Diff()`
8595: @*/
8596: 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)
8597: {
8598:   PetscFunctionBegin;
8601:   PetscUseTypeMethod(dm, projectfunctionlabellocal, time, label, numIds, ids, Nc, comps, funcs, ctxs, mode, localX);
8602:   PetscFunctionReturn(PETSC_SUCCESS);
8603: }

8605: /*@
8606:   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.

8608:   Not Collective

8610:   Input Parameters:
8611: + dm     - The `DM`
8612: . time   - The time
8613: . localU - The input field vector; may be `NULL` if projection is defined purely by coordinates
8614: . funcs  - The functions to evaluate, one per field
8615: - mode   - The insertion mode for values

8617:   Output Parameter:
8618: . localX - The output vector

8620:   Calling sequence of `funcs`:
8621: + dim          - The spatial dimension
8622: . Nf           - The number of input fields
8623: . NfAux        - The number of input auxiliary fields
8624: . uOff         - The offset of each field in u[]
8625: . uOff_x       - The offset of each field in u_x[]
8626: . u            - The field values at this point in space
8627: . u_t          - The field time derivative at this point in space (or `NULL`)
8628: . u_x          - The field derivatives at this point in space
8629: . aOff         - The offset of each auxiliary field in u[]
8630: . aOff_x       - The offset of each auxiliary field in u_x[]
8631: . a            - The auxiliary field values at this point in space
8632: . a_t          - The auxiliary field time derivative at this point in space (or `NULL`)
8633: . a_x          - The auxiliary field derivatives at this point in space
8634: . t            - The current time
8635: . x            - The coordinates of this point
8636: . numConstants - The number of constants
8637: . constants    - The value of each constant
8638: - f            - The value of the function at this point in space

8640:   Level: intermediate

8642:   Note:
8643:   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.
8644:   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
8645:   a subdomain. You can also output a different number of fields than the input, with different discretizations. Last the auxiliary `DM`, attached to the
8646:   auxiliary field vector, which is attached to dm, can also be different. It can have a different topology, number of fields, and discretizations.

8648:   Developer Notes:
8649:   This API is specific to only particular usage of `DM`

8651:   The notes need to provide some information about what has to be provided to the `DM` to be able to perform the computation.

8653: .seealso: [](ch_dmbase), `DM`, `DMProjectField()`, `DMProjectFieldLabelLocal()`,
8654: `DMProjectFunction()`, `DMComputeL2Diff()`
8655: @*/
8656: 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)
8657: {
8658:   PetscFunctionBegin;
8662:   PetscUseTypeMethod(dm, projectfieldlocal, time, localU, funcs, mode, localX);
8663:   PetscFunctionReturn(PETSC_SUCCESS);
8664: }

8666: /*@
8667:   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.

8669:   Not Collective

8671:   Input Parameters:
8672: + dm     - The `DM`
8673: . time   - The time
8674: . label  - The `DMLabel` marking the portion of the domain to output
8675: . numIds - The number of label ids to use
8676: . ids    - The label ids to use for marking
8677: . Nc     - The number of components to set in the output, or `PETSC_DETERMINE` for all components
8678: . comps  - The components to set in the output, or `NULL` for all components
8679: . localU - The input field vector
8680: . funcs  - The functions to evaluate, one per field
8681: - mode   - The insertion mode for values

8683:   Output Parameter:
8684: . localX - The output vector

8686:   Calling sequence of `funcs`:
8687: + dim          - The spatial dimension
8688: . Nf           - The number of input fields
8689: . NfAux        - The number of input auxiliary fields
8690: . uOff         - The offset of each field in u[]
8691: . uOff_x       - The offset of each field in u_x[]
8692: . u            - The field values at this point in space
8693: . u_t          - The field time derivative at this point in space (or `NULL`)
8694: . u_x          - The field derivatives at this point in space
8695: . aOff         - The offset of each auxiliary field in u[]
8696: . aOff_x       - The offset of each auxiliary field in u_x[]
8697: . a            - The auxiliary field values at this point in space
8698: . a_t          - The auxiliary field time derivative at this point in space (or `NULL`)
8699: . a_x          - The auxiliary field derivatives at this point in space
8700: . t            - The current time
8701: . x            - The coordinates of this point
8702: . numConstants - The number of constants
8703: . constants    - The value of each constant
8704: - f            - The value of the function at this point in space

8706:   Level: intermediate

8708:   Note:
8709:   There are three different `DM`s that potentially interact in this function. The output `DM`, dm, specifies the layout of the values calculates by funcs.
8710:   The input `DM`, attached to localU, may be different. For example, you can input the solution over the full domain, but output over a piece of the boundary, or
8711:   a subdomain. You can also output a different number of fields than the input, with different discretizations. Last the auxiliary `DM`, attached to the
8712:   auxiliary field vector, which is attached to dm, can also be different. It can have a different topology, number of fields, and discretizations.

8714:   Developer Notes:
8715:   This API is specific to only particular usage of `DM`

8717:   The notes need to provide some information about what has to be provided to the `DM` to be able to perform the computation.

8719: .seealso: [](ch_dmbase), `DM`, `DMProjectField()`, `DMProjectFieldLabel()`, `DMProjectFunction()`, `DMComputeL2Diff()`
8720: @*/
8721: 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)
8722: {
8723:   PetscFunctionBegin;
8727:   PetscUseTypeMethod(dm, projectfieldlabellocal, time, label, numIds, ids, Nc, comps, localU, funcs, mode, localX);
8728:   PetscFunctionReturn(PETSC_SUCCESS);
8729: }

8731: /*@
8732:   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.

8734:   Not Collective

8736:   Input Parameters:
8737: + dm     - The `DM`
8738: . time   - The time
8739: . label  - The `DMLabel` marking the portion of the domain to output
8740: . numIds - The number of label ids to use
8741: . ids    - The label ids to use for marking
8742: . Nc     - The number of components to set in the output, or `PETSC_DETERMINE` for all components
8743: . comps  - The components to set in the output, or `NULL` for all components
8744: . U      - The input field vector
8745: . funcs  - The functions to evaluate, one per field
8746: - mode   - The insertion mode for values

8748:   Output Parameter:
8749: . X - The output vector

8751:   Calling sequence of `funcs`:
8752: + dim          - The spatial dimension
8753: . Nf           - The number of input fields
8754: . NfAux        - The number of input auxiliary fields
8755: . uOff         - The offset of each field in u[]
8756: . uOff_x       - The offset of each field in u_x[]
8757: . u            - The field values at this point in space
8758: . u_t          - The field time derivative at this point in space (or `NULL`)
8759: . u_x          - The field derivatives at this point in space
8760: . aOff         - The offset of each auxiliary field in u[]
8761: . aOff_x       - The offset of each auxiliary field in u_x[]
8762: . a            - The auxiliary field values at this point in space
8763: . a_t          - The auxiliary field time derivative at this point in space (or `NULL`)
8764: . a_x          - The auxiliary field derivatives at this point in space
8765: . t            - The current time
8766: . x            - The coordinates of this point
8767: . numConstants - The number of constants
8768: . constants    - The value of each constant
8769: - f            - The value of the function at this point in space

8771:   Level: intermediate

8773:   Note:
8774:   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.
8775:   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
8776:   a subdomain. You can also output a different number of fields than the input, with different discretizations. Last the auxiliary `DM`, attached to the
8777:   auxiliary field vector, which is attached to dm, can also be different. It can have a different topology, number of fields, and discretizations.

8779:   Developer Notes:
8780:   This API is specific to only particular usage of `DM`

8782:   The notes need to provide some information about what has to be provided to the `DM` to be able to perform the computation.

8784: .seealso: [](ch_dmbase), `DM`, `DMProjectField()`, `DMProjectFieldLabelLocal()`, `DMProjectFunction()`, `DMComputeL2Diff()`
8785: @*/
8786: 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)
8787: {
8788:   DM  dmIn;
8789:   Vec localU, localX;

8791:   PetscFunctionBegin;
8793:   PetscCall(VecGetDM(U, &dmIn));
8794:   PetscCall(DMGetLocalVector(dmIn, &localU));
8795:   PetscCall(DMGetLocalVector(dm, &localX));
8796:   PetscCall(VecSet(localX, 0.));
8797:   PetscCall(DMGlobalToLocalBegin(dmIn, U, mode, localU));
8798:   PetscCall(DMGlobalToLocalEnd(dmIn, U, mode, localU));
8799:   PetscCall(DMProjectFieldLabelLocal(dm, time, label, numIds, ids, Nc, comps, localU, funcs, mode, localX));
8800:   PetscCall(DMLocalToGlobalBegin(dm, localX, mode, X));
8801:   PetscCall(DMLocalToGlobalEnd(dm, localX, mode, X));
8802:   PetscCall(DMRestoreLocalVector(dm, &localX));
8803:   PetscCall(DMRestoreLocalVector(dmIn, &localU));
8804:   PetscFunctionReturn(PETSC_SUCCESS);
8805: }

8807: /*@
8808:   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.

8810:   Not Collective

8812:   Input Parameters:
8813: + dm     - The `DM`
8814: . time   - The time
8815: . label  - The `DMLabel` marking the portion of the domain boundary to output
8816: . numIds - The number of label ids to use
8817: . ids    - The label ids to use for marking
8818: . Nc     - The number of components to set in the output, or `PETSC_DETERMINE` for all components
8819: . comps  - The components to set in the output, or `NULL` for all components
8820: . localU - The input field vector
8821: . funcs  - The functions to evaluate, one per field
8822: - mode   - The insertion mode for values

8824:   Output Parameter:
8825: . localX - The output vector

8827:   Calling sequence of `funcs`:
8828: + dim          - The spatial dimension
8829: . Nf           - The number of input fields
8830: . NfAux        - The number of input auxiliary fields
8831: . uOff         - The offset of each field in u[]
8832: . uOff_x       - The offset of each field in u_x[]
8833: . u            - The field values at this point in space
8834: . u_t          - The field time derivative at this point in space (or `NULL`)
8835: . u_x          - The field derivatives at this point in space
8836: . aOff         - The offset of each auxiliary field in u[]
8837: . aOff_x       - The offset of each auxiliary field in u_x[]
8838: . a            - The auxiliary field values at this point in space
8839: . a_t          - The auxiliary field time derivative at this point in space (or `NULL`)
8840: . a_x          - The auxiliary field derivatives at this point in space
8841: . t            - The current time
8842: . x            - The coordinates of this point
8843: . n            - The face normal
8844: . numConstants - The number of constants
8845: . constants    - The value of each constant
8846: - f            - The value of the function at this point in space

8848:   Level: intermediate

8850:   Note:
8851:   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.
8852:   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
8853:   a subdomain. You can also output a different number of fields than the input, with different discretizations. Last the auxiliary `DM`, attached to the
8854:   auxiliary field vector, which is attached to dm, can also be different. It can have a different topology, number of fields, and discretizations.

8856:   Developer Notes:
8857:   This API is specific to only particular usage of `DM`

8859:   The notes need to provide some information about what has to be provided to the `DM` to be able to perform the computation.

8861: .seealso: [](ch_dmbase), `DM`, `DMProjectField()`, `DMProjectFieldLabelLocal()`, `DMProjectFunction()`, `DMComputeL2Diff()`
8862: @*/
8863: 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)
8864: {
8865:   PetscFunctionBegin;
8869:   PetscUseTypeMethod(dm, projectbdfieldlabellocal, time, label, numIds, ids, Nc, comps, localU, funcs, mode, localX);
8870:   PetscFunctionReturn(PETSC_SUCCESS);
8871: }

8873: /*@
8874:   DMComputeL2Diff - This function computes the L_2 difference between a function u and an FEM interpolant solution u_h.

8876:   Collective

8878:   Input Parameters:
8879: + dm    - The `DM`
8880: . time  - The time
8881: . funcs - The functions to evaluate for each field component
8882: . ctxs  - Optional array of contexts to pass to each function, or `NULL`.
8883: - X     - The coefficient vector u_h, a global vector

8885:   Output Parameter:
8886: . diff - The diff ||u - u_h||_2

8888:   Level: developer

8890:   Developer Notes:
8891:   This API is specific to only particular usage of `DM`

8893:   The notes need to provide some information about what has to be provided to the `DM` to be able to perform the computation.

8895: .seealso: [](ch_dmbase), `DM`, `DMProjectFunction()`, `DMComputeL2FieldDiff()`, `DMComputeL2GradientDiff()`
8896: @*/
8897: PetscErrorCode DMComputeL2Diff(DM dm, PetscReal time, PetscErrorCode (**funcs)(PetscInt, PetscReal, const PetscReal[], PetscInt, PetscScalar *, void *), void **ctxs, Vec X, PetscReal *diff)
8898: {
8899:   PetscFunctionBegin;
8902:   PetscUseTypeMethod(dm, computel2diff, time, funcs, ctxs, X, diff);
8903:   PetscFunctionReturn(PETSC_SUCCESS);
8904: }

8906: /*@
8907:   DMComputeL2GradientDiff - This function computes the L_2 difference between the gradient of a function u and an FEM interpolant solution grad u_h.

8909:   Collective

8911:   Input Parameters:
8912: + dm    - The `DM`
8913: . time  - The time
8914: . funcs - The gradient functions to evaluate for each field component
8915: . ctxs  - Optional array of contexts to pass to each function, or `NULL`.
8916: . X     - The coefficient vector u_h, a global vector
8917: - n     - The vector to project along

8919:   Output Parameter:
8920: . diff - The diff ||(grad u - grad u_h) . n||_2

8922:   Level: developer

8924:   Developer Notes:
8925:   This API is specific to only particular usage of `DM`

8927:   The notes need to provide some information about what has to be provided to the `DM` to be able to perform the computation.

8929: .seealso: [](ch_dmbase), `DM`, `DMProjectFunction()`, `DMComputeL2Diff()`, `DMComputeL2FieldDiff()`
8930: @*/
8931: 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)
8932: {
8933:   PetscFunctionBegin;
8936:   PetscUseTypeMethod(dm, computel2gradientdiff, time, funcs, ctxs, X, n, diff);
8937:   PetscFunctionReturn(PETSC_SUCCESS);
8938: }

8940: /*@
8941:   DMComputeL2FieldDiff - This function computes the L_2 difference between a function u and an FEM interpolant solution u_h, separated into field components.

8943:   Collective

8945:   Input Parameters:
8946: + dm    - The `DM`
8947: . time  - The time
8948: . funcs - The functions to evaluate for each field component
8949: . ctxs  - Optional array of contexts to pass to each function, or `NULL`.
8950: - X     - The coefficient vector u_h, a global vector

8952:   Output Parameter:
8953: . diff - The array of differences, ||u^f - u^f_h||_2

8955:   Level: developer

8957:   Developer Notes:
8958:   This API is specific to only particular usage of `DM`

8960:   The notes need to provide some information about what has to be provided to the `DM` to be able to perform the computation.

8962: .seealso: [](ch_dmbase), `DM`, `DMProjectFunction()`, `DMComputeL2GradientDiff()`
8963: @*/
8964: PetscErrorCode DMComputeL2FieldDiff(DM dm, PetscReal time, PetscErrorCode (**funcs)(PetscInt, PetscReal, const PetscReal[], PetscInt, PetscScalar *, void *), void **ctxs, Vec X, PetscReal diff[])
8965: {
8966:   PetscFunctionBegin;
8969:   PetscUseTypeMethod(dm, computel2fielddiff, time, funcs, ctxs, X, diff);
8970:   PetscFunctionReturn(PETSC_SUCCESS);
8971: }

8973: /*@
8974:   DMGetNeighbors - Gets an array containing the MPI ranks of all the processes neighbors

8976:   Not Collective

8978:   Input Parameter:
8979: . dm - The `DM`

8981:   Output Parameters:
8982: + nranks - the number of neighbours
8983: - ranks  - the neighbors ranks

8985:   Level: beginner

8987:   Note:
8988:   Do not free the array, it is freed when the `DM` is destroyed.

8990: .seealso: [](ch_dmbase), `DM`, `DMDAGetNeighbors()`, `PetscSFGetRootRanks()`
8991: @*/
8992: PetscErrorCode DMGetNeighbors(DM dm, PetscInt *nranks, const PetscMPIInt *ranks[])
8993: {
8994:   PetscFunctionBegin;
8996:   PetscUseTypeMethod(dm, getneighbors, nranks, ranks);
8997:   PetscFunctionReturn(PETSC_SUCCESS);
8998: }

9000: #include <petsc/private/matimpl.h>

9002: /*
9003:     Converts the input vector to a ghosted vector and then calls the standard coloring code.
9004:     This must be a different function because it requires DM which is not defined in the Mat library
9005: */
9006: static PetscErrorCode MatFDColoringApply_AIJDM(Mat J, MatFDColoring coloring, Vec x1, void *sctx)
9007: {
9008:   PetscFunctionBegin;
9009:   if (coloring->ctype == IS_COLORING_LOCAL) {
9010:     Vec x1local;
9011:     DM  dm;
9012:     PetscCall(MatGetDM(J, &dm));
9013:     PetscCheck(dm, PetscObjectComm((PetscObject)J), PETSC_ERR_ARG_INCOMP, "IS_COLORING_LOCAL requires a DM");
9014:     PetscCall(DMGetLocalVector(dm, &x1local));
9015:     PetscCall(DMGlobalToLocalBegin(dm, x1, INSERT_VALUES, x1local));
9016:     PetscCall(DMGlobalToLocalEnd(dm, x1, INSERT_VALUES, x1local));
9017:     x1 = x1local;
9018:   }
9019:   PetscCall(MatFDColoringApply_AIJ(J, coloring, x1, sctx));
9020:   if (coloring->ctype == IS_COLORING_LOCAL) {
9021:     DM dm;
9022:     PetscCall(MatGetDM(J, &dm));
9023:     PetscCall(DMRestoreLocalVector(dm, &x1));
9024:   }
9025:   PetscFunctionReturn(PETSC_SUCCESS);
9026: }

9028: /*@
9029:   MatFDColoringUseDM - allows a `MatFDColoring` object to use the `DM` associated with the matrix to compute a `IS_COLORING_LOCAL` coloring

9031:   Input Parameters:
9032: + coloring   - The matrix to get the `DM` from
9033: - fdcoloring - the `MatFDColoring` object

9035:   Level: advanced

9037:   Developer Note:
9038:   This routine exists because the PETSc `Mat` library does not know about the `DM` objects

9040: .seealso: [](ch_dmbase), `DM`, `MatFDColoring`, `MatFDColoringCreate()`, `ISColoringType`
9041: @*/
9042: PetscErrorCode MatFDColoringUseDM(Mat coloring, MatFDColoring fdcoloring)
9043: {
9044:   PetscFunctionBegin;
9045:   coloring->ops->fdcoloringapply = MatFDColoringApply_AIJDM;
9046:   PetscFunctionReturn(PETSC_SUCCESS);
9047: }

9049: /*@
9050:   DMGetCompatibility - determine if two `DM`s are compatible

9052:   Collective

9054:   Input Parameters:
9055: + dm1 - the first `DM`
9056: - dm2 - the second `DM`

9058:   Output Parameters:
9059: + compatible - whether or not the two `DM`s are compatible
9060: - set        - whether or not the compatible value was actually determined and set

9062:   Level: advanced

9064:   Notes:
9065:   Two `DM`s are deemed compatible if they represent the same parallel decomposition
9066:   of the same topology. This implies that the section (field data) on one
9067:   "makes sense" with respect to the topology and parallel decomposition of the other.
9068:   Loosely speaking, compatible `DM`s represent the same domain and parallel
9069:   decomposition, but hold different data.

9071:   Typically, one would confirm compatibility if intending to simultaneously iterate
9072:   over a pair of vectors obtained from different `DM`s.

9074:   For example, two `DMDA` objects are compatible if they have the same local
9075:   and global sizes and the same stencil width. They can have different numbers
9076:   of degrees of freedom per node. Thus, one could use the node numbering from
9077:   either `DM` in bounds for a loop over vectors derived from either `DM`.

9079:   Consider the operation of summing data living on a 2-dof `DMDA` to data living
9080:   on a 1-dof `DMDA`, which should be compatible, as in the following snippet.
9081: .vb
9082:   ...
9083:   PetscCall(DMGetCompatibility(da1,da2,&compatible,&set));
9084:   if (set && compatible)  {
9085:     PetscCall(DMDAVecGetArrayDOF(da1,vec1,&arr1));
9086:     PetscCall(DMDAVecGetArrayDOF(da2,vec2,&arr2));
9087:     PetscCall(DMDAGetCorners(da1,&x,&y,NULL,&m,&n,NULL));
9088:     for (j=y; j<y+n; ++j) {
9089:       for (i=x; i<x+m, ++i) {
9090:         arr1[j][i][0] = arr2[j][i][0] + arr2[j][i][1];
9091:       }
9092:     }
9093:     PetscCall(DMDAVecRestoreArrayDOF(da1,vec1,&arr1));
9094:     PetscCall(DMDAVecRestoreArrayDOF(da2,vec2,&arr2));
9095:   } else {
9096:     SETERRQ(PetscObjectComm((PetscObject)da1,PETSC_ERR_ARG_INCOMP,"DMDA objects incompatible");
9097:   }
9098:   ...
9099: .ve

9101:   Checking compatibility might be expensive for a given implementation of `DM`,
9102:   or might be impossible to unambiguously confirm or deny. For this reason,
9103:   this function may decline to determine compatibility, and hence users should
9104:   always check the "set" output parameter.

9106:   A `DM` is always compatible with itself.

9108:   In the current implementation, `DM`s which live on "unequal" communicators
9109:   (MPI_UNEQUAL in the terminology of MPI_Comm_compare()) are always deemed
9110:   incompatible.

9112:   This function is labeled "Collective," as information about all subdomains
9113:   is required on each rank. However, in `DM` implementations which store all this
9114:   information locally, this function may be merely "Logically Collective".

9116:   Developer Note:
9117:   Compatibility is assumed to be a symmetric concept; `DM` A is compatible with `DM` B
9118:   iff B is compatible with A. Thus, this function checks the implementations
9119:   of both dm and dmc (if they are of different types), attempting to determine
9120:   compatibility. It is left to `DM` implementers to ensure that symmetry is
9121:   preserved. The simplest way to do this is, when implementing type-specific
9122:   logic for this function, is to check for existing logic in the implementation
9123:   of other `DM` types and let *set = PETSC_FALSE if found.

9125: .seealso: [](ch_dmbase), `DM`, `DMDACreateCompatibleDMDA()`, `DMStagCreateCompatibleDMStag()`
9126: @*/
9127: PetscErrorCode DMGetCompatibility(DM dm1, DM dm2, PetscBool *compatible, PetscBool *set)
9128: {
9129:   PetscMPIInt compareResult;
9130:   DMType      type, type2;
9131:   PetscBool   sameType;

9133:   PetscFunctionBegin;

9137:   /* Declare a DM compatible with itself */
9138:   if (dm1 == dm2) {
9139:     *set        = PETSC_TRUE;
9140:     *compatible = PETSC_TRUE;
9141:     PetscFunctionReturn(PETSC_SUCCESS);
9142:   }

9144:   /* Declare a DM incompatible with a DM that lives on an "unequal"
9145:      communicator. Note that this does not preclude compatibility with
9146:      DMs living on "congruent" or "similar" communicators, but this must be
9147:      determined by the implementation-specific logic */
9148:   PetscCallMPI(MPI_Comm_compare(PetscObjectComm((PetscObject)dm1), PetscObjectComm((PetscObject)dm2), &compareResult));
9149:   if (compareResult == MPI_UNEQUAL) {
9150:     *set        = PETSC_TRUE;
9151:     *compatible = PETSC_FALSE;
9152:     PetscFunctionReturn(PETSC_SUCCESS);
9153:   }

9155:   /* Pass to the implementation-specific routine, if one exists. */
9156:   if (dm1->ops->getcompatibility) {
9157:     PetscUseTypeMethod(dm1, getcompatibility, dm2, compatible, set);
9158:     if (*set) PetscFunctionReturn(PETSC_SUCCESS);
9159:   }

9161:   /* If dm1 and dm2 are of different types, then attempt to check compatibility
9162:      with an implementation of this function from dm2 */
9163:   PetscCall(DMGetType(dm1, &type));
9164:   PetscCall(DMGetType(dm2, &type2));
9165:   PetscCall(PetscStrcmp(type, type2, &sameType));
9166:   if (!sameType && dm2->ops->getcompatibility) {
9167:     PetscUseTypeMethod(dm2, getcompatibility, dm1, compatible, set); /* Note argument order */
9168:   } else {
9169:     *set = PETSC_FALSE;
9170:   }
9171:   PetscFunctionReturn(PETSC_SUCCESS);
9172: }

9174: /*@
9175:   DMMonitorSet - Sets an additional monitor function that is to be used after a solve to monitor discretization performance.

9177:   Logically Collective

9179:   Input Parameters:
9180: + dm             - the `DM`
9181: . f              - the monitor function
9182: . mctx           - [optional] context for private data for the monitor routine (use `NULL` if no context is desired)
9183: - monitordestroy - [optional] routine that frees monitor context (may be `NULL`), see `PetscCtxDestroyFn` for the calling sequence

9185:   Options Database Key:
9186: . -dm_monitor_cancel - cancels all monitors that have been hardwired into a code by calls to `DMMonitorSet()`, but
9187:                        does not cancel those set via the options database.

9189:   Level: intermediate

9191:   Note:
9192:   Several different monitoring routines may be set by calling
9193:   `DMMonitorSet()` multiple times or with `DMMonitorSetFromOptions()`; all will be called in the
9194:   order in which they were set.

9196:   Fortran Note:
9197:   Only a single monitor function can be set for each `DM` object

9199:   Developer Note:
9200:   This API has a generic name but seems specific to a very particular aspect of the use of `DM`

9202: .seealso: [](ch_dmbase), `DM`, `DMMonitorCancel()`, `DMMonitorSetFromOptions()`, `DMMonitor()`, `PetscCtxDestroyFn`
9203: @*/
9204: PetscErrorCode DMMonitorSet(DM dm, PetscErrorCode (*f)(DM, void *), void *mctx, PetscCtxDestroyFn *monitordestroy)
9205: {
9206:   PetscFunctionBegin;
9208:   for (PetscInt m = 0; m < dm->numbermonitors; ++m) {
9209:     PetscBool identical;

9211:     PetscCall(PetscMonitorCompare((PetscErrorCode (*)(void))(PetscVoidFn *)f, mctx, monitordestroy, (PetscErrorCode (*)(void))(PetscVoidFn *)dm->monitor[m], dm->monitorcontext[m], dm->monitordestroy[m], &identical));
9212:     if (identical) PetscFunctionReturn(PETSC_SUCCESS);
9213:   }
9214:   PetscCheck(dm->numbermonitors < MAXDMMONITORS, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Too many monitors set");
9215:   dm->monitor[dm->numbermonitors]          = f;
9216:   dm->monitordestroy[dm->numbermonitors]   = monitordestroy;
9217:   dm->monitorcontext[dm->numbermonitors++] = mctx;
9218:   PetscFunctionReturn(PETSC_SUCCESS);
9219: }

9221: /*@
9222:   DMMonitorCancel - Clears all the monitor functions for a `DM` object.

9224:   Logically Collective

9226:   Input Parameter:
9227: . dm - the DM

9229:   Options Database Key:
9230: . -dm_monitor_cancel - cancels all monitors that have been hardwired
9231:   into a code by calls to `DMonitorSet()`, but does not cancel those
9232:   set via the options database

9234:   Level: intermediate

9236:   Note:
9237:   There is no way to clear one specific monitor from a `DM` object.

9239: .seealso: [](ch_dmbase), `DM`, `DMMonitorSet()`, `DMMonitorSetFromOptions()`, `DMMonitor()`
9240: @*/
9241: PetscErrorCode DMMonitorCancel(DM dm)
9242: {
9243:   PetscFunctionBegin;
9245:   for (PetscInt m = 0; m < dm->numbermonitors; ++m) {
9246:     if (dm->monitordestroy[m]) PetscCall((*dm->monitordestroy[m])(&dm->monitorcontext[m]));
9247:   }
9248:   dm->numbermonitors = 0;
9249:   PetscFunctionReturn(PETSC_SUCCESS);
9250: }

9252: /*@
9253:   DMMonitorSetFromOptions - Sets a monitor function and viewer appropriate for the type indicated by the user

9255:   Collective

9257:   Input Parameters:
9258: + dm           - `DM` object you wish to monitor
9259: . name         - the monitor type one is seeking
9260: . help         - message indicating what monitoring is done
9261: . manual       - manual page for the monitor
9262: . monitor      - the monitor function, this must use a `PetscViewerFormat` as its context
9263: - 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

9265:   Output Parameter:
9266: . flg - Flag set if the monitor was created

9268:   Calling sequence of `monitor`:
9269: + dm  - the `DM` to be monitored
9270: - ctx - monitor context

9272:   Calling sequence of `monitorsetup`:
9273: + dm - the `DM` to be monitored
9274: - vf - the `PetscViewer` and format to be used by the monitor

9276:   Level: developer

9278: .seealso: [](ch_dmbase), `DM`, `PetscOptionsCreateViewer()`, `PetscOptionsGetReal()`, `PetscOptionsHasName()`, `PetscOptionsGetString()`,
9279:           `PetscOptionsGetIntArray()`, `PetscOptionsGetRealArray()`, `PetscOptionsBool()`,
9280:           `PetscOptionsInt()`, `PetscOptionsString()`, `PetscOptionsReal()`,
9281:           `PetscOptionsName()`, `PetscOptionsBegin()`, `PetscOptionsEnd()`, `PetscOptionsHeadBegin()`,
9282:           `PetscOptionsStringArray()`, `PetscOptionsRealArray()`, `PetscOptionsScalar()`,
9283:           `PetscOptionsBoolGroupBegin()`, `PetscOptionsBoolGroup()`, `PetscOptionsBoolGroupEnd()`,
9284:           `PetscOptionsFList()`, `PetscOptionsEList()`, `DMMonitor()`, `DMMonitorSet()`
9285: @*/
9286: 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)
9287: {
9288:   PetscViewer       viewer;
9289:   PetscViewerFormat format;

9291:   PetscFunctionBegin;
9293:   PetscCall(PetscOptionsCreateViewer(PetscObjectComm((PetscObject)dm), ((PetscObject)dm)->options, ((PetscObject)dm)->prefix, name, &viewer, &format, flg));
9294:   if (*flg) {
9295:     PetscViewerAndFormat *vf;

9297:     PetscCall(PetscViewerAndFormatCreate(viewer, format, &vf));
9298:     PetscCall(PetscViewerDestroy(&viewer));
9299:     if (monitorsetup) PetscCall((*monitorsetup)(dm, vf));
9300:     PetscCall(DMMonitorSet(dm, monitor, vf, (PetscCtxDestroyFn *)PetscViewerAndFormatDestroy));
9301:   }
9302:   PetscFunctionReturn(PETSC_SUCCESS);
9303: }

9305: /*@
9306:   DMMonitor - runs the user provided monitor routines, if they exist

9308:   Collective

9310:   Input Parameter:
9311: . dm - The `DM`

9313:   Level: developer

9315:   Developer Note:
9316:   Note should indicate when during the life of the `DM` the monitor is run. It appears to be
9317:   related to the discretization process seems rather specialized since some `DM` have no
9318:   concept of discretization.

9320: .seealso: [](ch_dmbase), `DM`, `DMMonitorSet()`, `DMMonitorSetFromOptions()`
9321: @*/
9322: PetscErrorCode DMMonitor(DM dm)
9323: {
9324:   PetscFunctionBegin;
9325:   if (!dm) PetscFunctionReturn(PETSC_SUCCESS);
9327:   for (PetscInt m = 0; m < dm->numbermonitors; ++m) PetscCall((*dm->monitor[m])(dm, dm->monitorcontext[m]));
9328:   PetscFunctionReturn(PETSC_SUCCESS);
9329: }

9331: /*@
9332:   DMComputeError - Computes the error assuming the user has provided the exact solution functions

9334:   Collective

9336:   Input Parameters:
9337: + dm  - The `DM`
9338: - sol - The solution vector

9340:   Input/Output Parameter:
9341: . errors - An array of length Nf, the number of fields, or `NULL` for no output; on output
9342:            contains the error in each field

9344:   Output Parameter:
9345: . errorVec - A vector to hold the cellwise error (may be `NULL`)

9347:   Level: developer

9349:   Note:
9350:   The exact solutions come from the `PetscDS` object, and the time comes from `DMGetOutputSequenceNumber()`.

9352: .seealso: [](ch_dmbase), `DM`, `DMMonitorSet()`, `DMGetRegionNumDS()`, `PetscDSGetExactSolution()`, `DMGetOutputSequenceNumber()`
9353: @*/
9354: PetscErrorCode DMComputeError(DM dm, Vec sol, PetscReal errors[], Vec *errorVec)
9355: {
9356:   PetscErrorCode (**exactSol)(PetscInt, PetscReal, const PetscReal[], PetscInt, PetscScalar[], void *);
9357:   void    **ctxs;
9358:   PetscReal time;
9359:   PetscInt  Nf, f, Nds, s;

9361:   PetscFunctionBegin;
9362:   PetscCall(DMGetNumFields(dm, &Nf));
9363:   PetscCall(PetscCalloc2(Nf, &exactSol, Nf, &ctxs));
9364:   PetscCall(DMGetNumDS(dm, &Nds));
9365:   for (s = 0; s < Nds; ++s) {
9366:     PetscDS         ds;
9367:     DMLabel         label;
9368:     IS              fieldIS;
9369:     const PetscInt *fields;
9370:     PetscInt        dsNf;

9372:     PetscCall(DMGetRegionNumDS(dm, s, &label, &fieldIS, &ds, NULL));
9373:     PetscCall(PetscDSGetNumFields(ds, &dsNf));
9374:     if (fieldIS) PetscCall(ISGetIndices(fieldIS, &fields));
9375:     for (f = 0; f < dsNf; ++f) {
9376:       const PetscInt field = fields[f];
9377:       PetscCall(PetscDSGetExactSolution(ds, field, &exactSol[field], &ctxs[field]));
9378:     }
9379:     if (fieldIS) PetscCall(ISRestoreIndices(fieldIS, &fields));
9380:   }
9381:   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);
9382:   PetscCall(DMGetOutputSequenceNumber(dm, NULL, &time));
9383:   if (errors) PetscCall(DMComputeL2FieldDiff(dm, time, exactSol, ctxs, sol, errors));
9384:   if (errorVec) {
9385:     DM             edm;
9386:     DMPolytopeType ct;
9387:     PetscBool      simplex;
9388:     PetscInt       dim, cStart, Nf;

9390:     PetscCall(DMClone(dm, &edm));
9391:     PetscCall(DMGetDimension(edm, &dim));
9392:     PetscCall(DMPlexGetHeightStratum(dm, 0, &cStart, NULL));
9393:     PetscCall(DMPlexGetCellType(dm, cStart, &ct));
9394:     simplex = DMPolytopeTypeGetNumVertices(ct) == DMPolytopeTypeGetDim(ct) + 1 ? PETSC_TRUE : PETSC_FALSE;
9395:     PetscCall(DMGetNumFields(dm, &Nf));
9396:     for (f = 0; f < Nf; ++f) {
9397:       PetscFE         fe, efe;
9398:       PetscQuadrature q;
9399:       const char     *name;

9401:       PetscCall(DMGetField(dm, f, NULL, (PetscObject *)&fe));
9402:       PetscCall(PetscFECreateLagrange(PETSC_COMM_SELF, dim, Nf, simplex, 0, PETSC_DETERMINE, &efe));
9403:       PetscCall(PetscObjectGetName((PetscObject)fe, &name));
9404:       PetscCall(PetscObjectSetName((PetscObject)efe, name));
9405:       PetscCall(PetscFEGetQuadrature(fe, &q));
9406:       PetscCall(PetscFESetQuadrature(efe, q));
9407:       PetscCall(DMSetField(edm, f, NULL, (PetscObject)efe));
9408:       PetscCall(PetscFEDestroy(&efe));
9409:     }
9410:     PetscCall(DMCreateDS(edm));

9412:     PetscCall(DMCreateGlobalVector(edm, errorVec));
9413:     PetscCall(PetscObjectSetName((PetscObject)*errorVec, "Error"));
9414:     PetscCall(DMPlexComputeL2DiffVec(dm, time, exactSol, ctxs, sol, *errorVec));
9415:     PetscCall(DMDestroy(&edm));
9416:   }
9417:   PetscCall(PetscFree2(exactSol, ctxs));
9418:   PetscFunctionReturn(PETSC_SUCCESS);
9419: }

9421: /*@
9422:   DMGetNumAuxiliaryVec - Get the number of auxiliary vectors associated with this `DM`

9424:   Not Collective

9426:   Input Parameter:
9427: . dm - The `DM`

9429:   Output Parameter:
9430: . numAux - The number of auxiliary data vectors

9432:   Level: advanced

9434: .seealso: [](ch_dmbase), `DM`, `DMClearAuxiliaryVec()`, `DMSetAuxiliaryVec()`, `DMGetAuxiliaryLabels()`, `DMGetAuxiliaryVec()`
9435: @*/
9436: PetscErrorCode DMGetNumAuxiliaryVec(DM dm, PetscInt *numAux)
9437: {
9438:   PetscFunctionBegin;
9440:   PetscCall(PetscHMapAuxGetSize(dm->auxData, numAux));
9441:   PetscFunctionReturn(PETSC_SUCCESS);
9442: }

9444: /*@
9445:   DMGetAuxiliaryVec - Get the auxiliary vector for region specified by the given label and value, and equation part

9447:   Not Collective

9449:   Input Parameters:
9450: + dm    - The `DM`
9451: . label - The `DMLabel`
9452: . value - The label value indicating the region
9453: - part  - The equation part, or 0 if unused

9455:   Output Parameter:
9456: . aux - The `Vec` holding auxiliary field data

9458:   Level: advanced

9460:   Note:
9461:   If no auxiliary vector is found for this (label, value), (`NULL`, 0, 0) is checked as well.

9463: .seealso: [](ch_dmbase), `DM`, `DMClearAuxiliaryVec()`, `DMSetAuxiliaryVec()`, `DMGetNumAuxiliaryVec()`, `DMGetAuxiliaryLabels()`
9464: @*/
9465: PetscErrorCode DMGetAuxiliaryVec(DM dm, DMLabel label, PetscInt value, PetscInt part, Vec *aux)
9466: {
9467:   PetscHashAuxKey key, wild = {NULL, 0, 0};
9468:   PetscBool       has;

9470:   PetscFunctionBegin;
9473:   key.label = label;
9474:   key.value = value;
9475:   key.part  = part;
9476:   PetscCall(PetscHMapAuxHas(dm->auxData, key, &has));
9477:   if (has) PetscCall(PetscHMapAuxGet(dm->auxData, key, aux));
9478:   else PetscCall(PetscHMapAuxGet(dm->auxData, wild, aux));
9479:   PetscFunctionReturn(PETSC_SUCCESS);
9480: }

9482: /*@
9483:   DMSetAuxiliaryVec - Set an auxiliary vector for region specified by the given label and value, and equation part

9485:   Not Collective because auxiliary vectors are not parallel

9487:   Input Parameters:
9488: + dm    - The `DM`
9489: . label - The `DMLabel`
9490: . value - The label value indicating the region
9491: . part  - The equation part, or 0 if unused
9492: - aux   - The `Vec` holding auxiliary field data

9494:   Level: advanced

9496: .seealso: [](ch_dmbase), `DM`, `DMClearAuxiliaryVec()`, `DMGetAuxiliaryVec()`, `DMGetAuxiliaryLabels()`, `DMCopyAuxiliaryVec()`
9497: @*/
9498: PetscErrorCode DMSetAuxiliaryVec(DM dm, DMLabel label, PetscInt value, PetscInt part, Vec aux)
9499: {
9500:   Vec             old;
9501:   PetscHashAuxKey key;

9503:   PetscFunctionBegin;
9506:   key.label = label;
9507:   key.value = value;
9508:   key.part  = part;
9509:   PetscCall(PetscHMapAuxGet(dm->auxData, key, &old));
9510:   PetscCall(PetscObjectReference((PetscObject)aux));
9511:   if (!aux) PetscCall(PetscHMapAuxDel(dm->auxData, key));
9512:   else PetscCall(PetscHMapAuxSet(dm->auxData, key, aux));
9513:   PetscCall(VecDestroy(&old));
9514:   PetscFunctionReturn(PETSC_SUCCESS);
9515: }

9517: /*@
9518:   DMGetAuxiliaryLabels - Get the labels, values, and parts for all auxiliary vectors in this `DM`

9520:   Not Collective

9522:   Input Parameter:
9523: . dm - The `DM`

9525:   Output Parameters:
9526: + labels - The `DMLabel`s for each `Vec`
9527: . values - The label values for each `Vec`
9528: - parts  - The equation parts for each `Vec`

9530:   Level: advanced

9532:   Note:
9533:   The arrays passed in must be at least as large as `DMGetNumAuxiliaryVec()`.

9535: .seealso: [](ch_dmbase), `DM`, `DMClearAuxiliaryVec()`, `DMGetNumAuxiliaryVec()`, `DMGetAuxiliaryVec()`, `DMSetAuxiliaryVec()`, `DMCopyAuxiliaryVec()`
9536: @*/
9537: PetscErrorCode DMGetAuxiliaryLabels(DM dm, DMLabel labels[], PetscInt values[], PetscInt parts[])
9538: {
9539:   PetscHashAuxKey *keys;
9540:   PetscInt         n, i, off = 0;

9542:   PetscFunctionBegin;
9544:   PetscAssertPointer(labels, 2);
9545:   PetscAssertPointer(values, 3);
9546:   PetscAssertPointer(parts, 4);
9547:   PetscCall(DMGetNumAuxiliaryVec(dm, &n));
9548:   PetscCall(PetscMalloc1(n, &keys));
9549:   PetscCall(PetscHMapAuxGetKeys(dm->auxData, &off, keys));
9550:   for (i = 0; i < n; ++i) {
9551:     labels[i] = keys[i].label;
9552:     values[i] = keys[i].value;
9553:     parts[i]  = keys[i].part;
9554:   }
9555:   PetscCall(PetscFree(keys));
9556:   PetscFunctionReturn(PETSC_SUCCESS);
9557: }

9559: /*@
9560:   DMCopyAuxiliaryVec - Copy the auxiliary vector data on a `DM` to a new `DM`

9562:   Not Collective

9564:   Input Parameter:
9565: . dm - The `DM`

9567:   Output Parameter:
9568: . dmNew - The new `DM`, now with the same auxiliary data

9570:   Level: advanced

9572:   Note:
9573:   This is a shallow copy of the auxiliary vectors

9575: .seealso: [](ch_dmbase), `DM`, `DMClearAuxiliaryVec()`, `DMGetNumAuxiliaryVec()`, `DMGetAuxiliaryVec()`, `DMSetAuxiliaryVec()`
9576: @*/
9577: PetscErrorCode DMCopyAuxiliaryVec(DM dm, DM dmNew)
9578: {
9579:   PetscFunctionBegin;
9582:   if (dm == dmNew) PetscFunctionReturn(PETSC_SUCCESS);
9583:   PetscCall(DMClearAuxiliaryVec(dmNew));

9585:   PetscCall(PetscHMapAuxDestroy(&dmNew->auxData));
9586:   PetscCall(PetscHMapAuxDuplicate(dm->auxData, &dmNew->auxData));
9587:   {
9588:     Vec     *auxData;
9589:     PetscInt n, i, off = 0;

9591:     PetscCall(PetscHMapAuxGetSize(dmNew->auxData, &n));
9592:     PetscCall(PetscMalloc1(n, &auxData));
9593:     PetscCall(PetscHMapAuxGetVals(dmNew->auxData, &off, auxData));
9594:     for (i = 0; i < n; ++i) PetscCall(PetscObjectReference((PetscObject)auxData[i]));
9595:     PetscCall(PetscFree(auxData));
9596:   }
9597:   PetscFunctionReturn(PETSC_SUCCESS);
9598: }

9600: /*@
9601:   DMClearAuxiliaryVec - Destroys the auxiliary vector information and creates a new empty one

9603:   Not Collective

9605:   Input Parameter:
9606: . dm - The `DM`

9608:   Level: advanced

9610: .seealso: [](ch_dmbase), `DM`, `DMCopyAuxiliaryVec()`, `DMGetNumAuxiliaryVec()`, `DMGetAuxiliaryVec()`, `DMSetAuxiliaryVec()`
9611: @*/
9612: PetscErrorCode DMClearAuxiliaryVec(DM dm)
9613: {
9614:   Vec     *auxData;
9615:   PetscInt n, i, off = 0;

9617:   PetscFunctionBegin;
9618:   PetscCall(PetscHMapAuxGetSize(dm->auxData, &n));
9619:   PetscCall(PetscMalloc1(n, &auxData));
9620:   PetscCall(PetscHMapAuxGetVals(dm->auxData, &off, auxData));
9621:   for (i = 0; i < n; ++i) PetscCall(VecDestroy(&auxData[i]));
9622:   PetscCall(PetscFree(auxData));
9623:   PetscCall(PetscHMapAuxDestroy(&dm->auxData));
9624:   PetscCall(PetscHMapAuxCreate(&dm->auxData));
9625:   PetscFunctionReturn(PETSC_SUCCESS);
9626: }

9628: /*@
9629:   DMPolytopeMatchOrientation - Determine an orientation (transformation) that takes the source face arrangement to the target face arrangement

9631:   Not Collective

9633:   Input Parameters:
9634: + ct         - The `DMPolytopeType`
9635: . sourceCone - The source arrangement of faces
9636: - targetCone - The target arrangement of faces

9638:   Output Parameters:
9639: + ornt  - The orientation (transformation) which will take the source arrangement to the target arrangement
9640: - found - Flag indicating that a suitable orientation was found

9642:   Level: advanced

9644:   Note:
9645:   An arrangement is a face order combined with an orientation for each face

9647:   Each orientation (transformation) is labeled with an integer from negative `DMPolytopeTypeGetNumArrangements(ct)`/2 to `DMPolytopeTypeGetNumArrangements(ct)`/2
9648:   that labels each arrangement (face ordering plus orientation for each face).

9650:   See `DMPolytopeMatchVertexOrientation()` to find a new vertex orientation that takes the source vertex arrangement to the target vertex arrangement

9652: .seealso: [](ch_dmbase), `DM`, `DMPolytopeGetOrientation()`, `DMPolytopeMatchVertexOrientation()`, `DMPolytopeGetVertexOrientation()`
9653: @*/
9654: PetscErrorCode DMPolytopeMatchOrientation(DMPolytopeType ct, const PetscInt sourceCone[], const PetscInt targetCone[], PetscInt *ornt, PetscBool *found)
9655: {
9656:   const PetscInt cS = DMPolytopeTypeGetConeSize(ct);
9657:   const PetscInt nO = DMPolytopeTypeGetNumArrangements(ct) / 2;
9658:   PetscInt       o, c;

9660:   PetscFunctionBegin;
9661:   if (!nO) {
9662:     *ornt  = 0;
9663:     *found = PETSC_TRUE;
9664:     PetscFunctionReturn(PETSC_SUCCESS);
9665:   }
9666:   for (o = -nO; o < nO; ++o) {
9667:     const PetscInt *arr = DMPolytopeTypeGetArrangement(ct, o);

9669:     for (c = 0; c < cS; ++c)
9670:       if (sourceCone[arr[c * 2]] != targetCone[c]) break;
9671:     if (c == cS) {
9672:       *ornt = o;
9673:       break;
9674:     }
9675:   }
9676:   *found = o == nO ? PETSC_FALSE : PETSC_TRUE;
9677:   PetscFunctionReturn(PETSC_SUCCESS);
9678: }

9680: /*@
9681:   DMPolytopeGetOrientation - Determine an orientation (transformation) that takes the source face arrangement to the target face arrangement

9683:   Not Collective

9685:   Input Parameters:
9686: + ct         - The `DMPolytopeType`
9687: . sourceCone - The source arrangement of faces
9688: - targetCone - The target arrangement of faces

9690:   Output Parameter:
9691: . ornt - The orientation (transformation) which will take the source arrangement to the target arrangement

9693:   Level: advanced

9695:   Note:
9696:   This function is the same as `DMPolytopeMatchOrientation()` except it will generate an error if no suitable orientation can be found.

9698:   Developer Note:
9699:   It is unclear why this function needs to exist since one can simply call `DMPolytopeMatchOrientation()` and error if none is found

9701: .seealso: [](ch_dmbase), `DM`, `DMPolytopeType`, `DMPolytopeMatchOrientation()`, `DMPolytopeGetVertexOrientation()`, `DMPolytopeMatchVertexOrientation()`
9702: @*/
9703: PetscErrorCode DMPolytopeGetOrientation(DMPolytopeType ct, const PetscInt sourceCone[], const PetscInt targetCone[], PetscInt *ornt)
9704: {
9705:   PetscBool found;

9707:   PetscFunctionBegin;
9708:   PetscCall(DMPolytopeMatchOrientation(ct, sourceCone, targetCone, ornt, &found));
9709:   PetscCheck(found, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Could not find orientation for %s", DMPolytopeTypes[ct]);
9710:   PetscFunctionReturn(PETSC_SUCCESS);
9711: }

9713: /*@
9714:   DMPolytopeMatchVertexOrientation - Determine an orientation (transformation) that takes the source vertex arrangement to the target vertex arrangement

9716:   Not Collective

9718:   Input Parameters:
9719: + ct         - The `DMPolytopeType`
9720: . sourceVert - The source arrangement of vertices
9721: - targetVert - The target arrangement of vertices

9723:   Output Parameters:
9724: + ornt  - The orientation (transformation) which will take the source arrangement to the target arrangement
9725: - found - Flag indicating that a suitable orientation was found

9727:   Level: advanced

9729:   Notes:
9730:   An arrangement is a vertex order

9732:   Each orientation (transformation) is labeled with an integer from negative `DMPolytopeTypeGetNumArrangements(ct)`/2 to `DMPolytopeTypeGetNumArrangements(ct)`/2
9733:   that labels each arrangement (vertex ordering).

9735:   See `DMPolytopeMatchOrientation()` to find a new face orientation that takes the source face arrangement to the target face arrangement

9737: .seealso: [](ch_dmbase), `DM`, `DMPolytopeType`, `DMPolytopeGetOrientation()`, `DMPolytopeMatchOrientation()`, `DMPolytopeTypeGetNumVertices()`, `DMPolytopeTypeGetVertexArrangement()`
9738: @*/
9739: PetscErrorCode DMPolytopeMatchVertexOrientation(DMPolytopeType ct, const PetscInt sourceVert[], const PetscInt targetVert[], PetscInt *ornt, PetscBool *found)
9740: {
9741:   const PetscInt cS = DMPolytopeTypeGetNumVertices(ct);
9742:   const PetscInt nO = DMPolytopeTypeGetNumArrangements(ct) / 2;
9743:   PetscInt       o, c;

9745:   PetscFunctionBegin;
9746:   if (!nO) {
9747:     *ornt  = 0;
9748:     *found = PETSC_TRUE;
9749:     PetscFunctionReturn(PETSC_SUCCESS);
9750:   }
9751:   for (o = -nO; o < nO; ++o) {
9752:     const PetscInt *arr = DMPolytopeTypeGetVertexArrangement(ct, o);

9754:     for (c = 0; c < cS; ++c)
9755:       if (sourceVert[arr[c]] != targetVert[c]) break;
9756:     if (c == cS) {
9757:       *ornt = o;
9758:       break;
9759:     }
9760:   }
9761:   *found = o == nO ? PETSC_FALSE : PETSC_TRUE;
9762:   PetscFunctionReturn(PETSC_SUCCESS);
9763: }

9765: /*@
9766:   DMPolytopeGetVertexOrientation - Determine an orientation (transformation) that takes the source vertex arrangement to the target vertex arrangement

9768:   Not Collective

9770:   Input Parameters:
9771: + ct         - The `DMPolytopeType`
9772: . sourceCone - The source arrangement of vertices
9773: - targetCone - The target arrangement of vertices

9775:   Output Parameter:
9776: . ornt - The orientation (transformation) which will take the source arrangement to the target arrangement

9778:   Level: advanced

9780:   Note:
9781:   This function is the same as `DMPolytopeMatchVertexOrientation()` except it errors if not orientation is possible.

9783:   Developer Note:
9784:   It is unclear why this function needs to exist since one can simply call `DMPolytopeMatchVertexOrientation()` and error if none is found

9786: .seealso: [](ch_dmbase), `DM`, `DMPolytopeType`, `DMPolytopeMatchVertexOrientation()`, `DMPolytopeGetOrientation()`
9787: @*/
9788: PetscErrorCode DMPolytopeGetVertexOrientation(DMPolytopeType ct, const PetscInt sourceCone[], const PetscInt targetCone[], PetscInt *ornt)
9789: {
9790:   PetscBool found;

9792:   PetscFunctionBegin;
9793:   PetscCall(DMPolytopeMatchVertexOrientation(ct, sourceCone, targetCone, ornt, &found));
9794:   PetscCheck(found, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Could not find orientation for %s", DMPolytopeTypes[ct]);
9795:   PetscFunctionReturn(PETSC_SUCCESS);
9796: }

9798: /*@
9799:   DMPolytopeInCellTest - Check whether a point lies inside the reference cell of given type

9801:   Not Collective

9803:   Input Parameters:
9804: + ct    - The `DMPolytopeType`
9805: - point - Coordinates of the point

9807:   Output Parameter:
9808: . inside - Flag indicating whether the point is inside the reference cell of given type

9810:   Level: advanced

9812: .seealso: [](ch_dmbase), `DM`, `DMPolytopeType`, `DMLocatePoints()`
9813: @*/
9814: PetscErrorCode DMPolytopeInCellTest(DMPolytopeType ct, const PetscReal point[], PetscBool *inside)
9815: {
9816:   PetscReal sum = 0.0;

9818:   PetscFunctionBegin;
9819:   *inside = PETSC_TRUE;
9820:   switch (ct) {
9821:   case DM_POLYTOPE_TRIANGLE:
9822:   case DM_POLYTOPE_TETRAHEDRON:
9823:     for (PetscInt d = 0; d < DMPolytopeTypeGetDim(ct); ++d) {
9824:       if (point[d] < -1.0) {
9825:         *inside = PETSC_FALSE;
9826:         break;
9827:       }
9828:       sum += point[d];
9829:     }
9830:     if (sum > PETSC_SMALL) {
9831:       *inside = PETSC_FALSE;
9832:       break;
9833:     }
9834:     break;
9835:   case DM_POLYTOPE_QUADRILATERAL:
9836:   case DM_POLYTOPE_HEXAHEDRON:
9837:     for (PetscInt d = 0; d < DMPolytopeTypeGetDim(ct); ++d)
9838:       if (PetscAbsReal(point[d]) > 1. + PETSC_SMALL) {
9839:         *inside = PETSC_FALSE;
9840:         break;
9841:       }
9842:     break;
9843:   default:
9844:     SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Unsupported polytope type %s", DMPolytopeTypes[ct]);
9845:   }
9846:   PetscFunctionReturn(PETSC_SUCCESS);
9847: }

9849: /*@
9850:   DMReorderSectionSetDefault - Set flag indicating whether the local section should be reordered by default

9852:   Logically collective

9854:   Input Parameters:
9855: + dm      - The DM
9856: - reorder - Flag for reordering

9858:   Level: intermediate

9860: .seealso: `DMReorderSectionGetDefault()`
9861: @*/
9862: PetscErrorCode DMReorderSectionSetDefault(DM dm, DMReorderDefaultFlag reorder)
9863: {
9864:   PetscFunctionBegin;
9866:   PetscTryMethod(dm, "DMReorderSectionSetDefault_C", (DM, DMReorderDefaultFlag), (dm, reorder));
9867:   PetscFunctionReturn(PETSC_SUCCESS);
9868: }

9870: /*@
9871:   DMReorderSectionGetDefault - Get flag indicating whether the local section should be reordered by default

9873:   Not collective

9875:   Input Parameter:
9876: . dm - The DM

9878:   Output Parameter:
9879: . reorder - Flag for reordering

9881:   Level: intermediate

9883: .seealso: `DMReorderSetDefault()`
9884: @*/
9885: PetscErrorCode DMReorderSectionGetDefault(DM dm, DMReorderDefaultFlag *reorder)
9886: {
9887:   PetscFunctionBegin;
9889:   PetscAssertPointer(reorder, 2);
9890:   *reorder = DM_REORDER_DEFAULT_NOTSET;
9891:   PetscTryMethod(dm, "DMReorderSectionGetDefault_C", (DM, DMReorderDefaultFlag *), (dm, reorder));
9892:   PetscFunctionReturn(PETSC_SUCCESS);
9893: }

9895: /*@
9896:   DMReorderSectionSetType - Set the type of local section reordering

9898:   Logically collective

9900:   Input Parameters:
9901: + dm      - The DM
9902: - reorder - The reordering method

9904:   Level: intermediate

9906: .seealso: `DMReorderSectionGetType()`, `DMReorderSectionSetDefault()`
9907: @*/
9908: PetscErrorCode DMReorderSectionSetType(DM dm, MatOrderingType reorder)
9909: {
9910:   PetscFunctionBegin;
9912:   PetscTryMethod(dm, "DMReorderSectionSetType_C", (DM, MatOrderingType), (dm, reorder));
9913:   PetscFunctionReturn(PETSC_SUCCESS);
9914: }

9916: /*@
9917:   DMReorderSectionGetType - Get the reordering type for the local section

9919:   Not collective

9921:   Input Parameter:
9922: . dm - The DM

9924:   Output Parameter:
9925: . reorder - The reordering method

9927:   Level: intermediate

9929: .seealso: `DMReorderSetDefault()`, `DMReorderSectionGetDefault()`
9930: @*/
9931: PetscErrorCode DMReorderSectionGetType(DM dm, MatOrderingType *reorder)
9932: {
9933:   PetscFunctionBegin;
9935:   PetscAssertPointer(reorder, 2);
9936:   *reorder = NULL;
9937:   PetscTryMethod(dm, "DMReorderSectionGetType_C", (DM, MatOrderingType *), (dm, reorder));
9938:   PetscFunctionReturn(PETSC_SUCCESS);
9939: }