Actual source code: dm.c

  1: #include <petsc/private/vecimpl.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 (true|false)        - 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 process 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 processes,
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 processes. 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 (true|false) - 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_transform_type type - chooses the refinement transform, e.g. refine_regular, refine_tobox

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(VecScatterSynchronizeKokkos_Private(sf, g, l, PETSC_TRUE));
2959:     PetscCall(PetscSFBcastWithMemTypeBegin(sf, MPIU_SCALAR, gmtype, gArray, lmtype, lArray, MPI_REPLACE));
2960:     PetscCall(VecRestoreArrayAndMemType(l, &lArray));
2961:     PetscCall(VecRestoreArrayReadAndMemType(g, &gArray));
2962:   } else {
2963:     PetscUseTypeMethod(dm, globaltolocalbegin, g, mode == INSERT_ALL_VALUES ? INSERT_VALUES : (mode == ADD_ALL_VALUES ? ADD_VALUES : mode), l);
2964:   }
2965:   PetscFunctionReturn(PETSC_SUCCESS);
2966: }

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

2971:   Neighbor-wise Collective

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

2979:   Level: intermediate

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

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

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

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

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

3022:   Logically Collective

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

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

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

3044:   Level: advanced

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

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

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

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

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

3105:   Neighbor-wise Collective

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

3113:   Level: beginner

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

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

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

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

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

3135: /*@
3136:   DMLocalToGlobalBegin - begins updating global vectors from local vectors

3138:   Neighbor-wise Collective

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

3146:   Level: intermediate

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

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

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

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

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

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

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

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

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

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

3272: /*@
3273:   DMLocalToGlobalEnd - updates global vectors from local vectors

3275:   Neighbor-wise Collective

3277:   Input Parameters:
3278: + dm   - the `DM` object
3279: . l    - the local vector
3280: . mode - `INSERT_VALUES` or `ADD_VALUES`
3281: - g    - the global vector

3283:   Level: intermediate

3285:   Note:
3286:   See `DMLocalToGlobalBegin()` for full details

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

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

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

3345: /*@
3346:   DMLocalToLocalBegin - Begins the process of mapping values from a local vector (that include
3347:   ghost points that contain irrelevant values) to another local vector where the ghost points
3348:   in the second are set correctly from values on other MPI processes.

3350:   Neighbor-wise Collective

3352:   Input Parameters:
3353: + dm   - the `DM` object
3354: . g    - the original local vector
3355: - mode - one of `INSERT_VALUES` or `ADD_VALUES`

3357:   Output Parameter:
3358: . l - the local vector with correct ghost values

3360:   Level: intermediate

3362:   Note:
3363:   Must be followed by `DMLocalToLocalEnd()`.

3365: .seealso: [](ch_dmbase), `DM`, `DMLocalToLocalEnd()`, `DMCoarsen()`, `DMDestroy()`, `DMView()`, `DMCreateLocalVector()`, `DMCreateGlobalVector()`, `DMCreateInterpolation()`, `DMGlobalToLocalEnd()`, `DMLocalToGlobalBegin()`
3366: @*/
3367: PetscErrorCode DMLocalToLocalBegin(DM dm, Vec g, InsertMode mode, Vec l)
3368: {
3369:   PetscFunctionBegin;
3373:   PetscUseTypeMethod(dm, localtolocalbegin, g, mode == INSERT_ALL_VALUES ? INSERT_VALUES : (mode == ADD_ALL_VALUES ? ADD_VALUES : mode), l);
3374:   PetscFunctionReturn(PETSC_SUCCESS);
3375: }

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

3381:   Neighbor-wise Collective

3383:   Input Parameters:
3384: + dm   - the `DM` object
3385: . g    - the original local vector
3386: - mode - one of `INSERT_VALUES` or `ADD_VALUES`

3388:   Output Parameter:
3389: . l - the local vector with correct ghost values

3391:   Level: intermediate

3393: .seealso: [](ch_dmbase), `DM`, `DMLocalToLocalBegin()`, `DMCoarsen()`, `DMDestroy()`, `DMView()`, `DMCreateLocalVector()`, `DMCreateGlobalVector()`, `DMCreateInterpolation()`, `DMGlobalToLocalEnd()`, `DMLocalToGlobalBegin()`
3394: @*/
3395: PetscErrorCode DMLocalToLocalEnd(DM dm, Vec g, InsertMode mode, Vec l)
3396: {
3397:   PetscFunctionBegin;
3401:   PetscUseTypeMethod(dm, localtolocalend, g, mode == INSERT_ALL_VALUES ? INSERT_VALUES : (mode == ADD_ALL_VALUES ? ADD_VALUES : mode), l);
3402:   PetscFunctionReturn(PETSC_SUCCESS);
3403: }

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

3408:   Collective

3410:   Input Parameters:
3411: + dm   - the `DM` object
3412: - comm - the communicator to contain the new `DM` object (or `MPI_COMM_NULL`)

3414:   Output Parameter:
3415: . dmc - the coarsened `DM`

3417:   Level: developer

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

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

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

3451:   Logically Collective; No Fortran Support

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

3459:   Calling sequence of `coarsenhook`:
3460: + fine   - fine level `DM`
3461: . coarse - coarse level `DM` to restrict problem to
3462: - ctx    - optional application function context

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

3472:   Level: advanced

3474:   Notes:
3475:   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`.

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

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

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

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

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

3504: /*@
3505:   DMCoarsenHookRemove - remove a callback set with `DMCoarsenHookAdd()`

3507:   Logically Collective; No Fortran Support

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

3515:   Calling sequence of `coarsenhook`:
3516: + fine   - fine level `DM`
3517: . coarse - coarse level `DM` to restrict problem to
3518: - ctx    - optional application function context

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

3528:   Level: advanced

3530:   Notes:
3531:   This function does nothing if the `coarsenhook` is not in the list.

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

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

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

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

3557:   Collective if any hooks are

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

3566:   Level: developer

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

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

3577:   PetscFunctionBegin;
3578:   for (link = fine->coarsenhook; link; link = link->next) {
3579:     if (link->restricthook) PetscCall((*link->restricthook)(fine, restrct, rscale, inject, coarse, link->ctx));
3580:   }
3581:   PetscFunctionReturn(PETSC_SUCCESS);
3582: }

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

3587:   Logically Collective; No Fortran Support

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

3595:   Calling sequence of `ddhook`:
3596: + global - global `DM`
3597: . block  - subdomain `DM`
3598: - ctx    - optional application function context

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

3607:   Level: advanced

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

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

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

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

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

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

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

3643:   Logically Collective; No Fortran Support

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

3651:   Calling sequence of `ddhook`:
3652: + dm    - global `DM`
3653: . block - subdomain `DM`
3654: - ctx   - optional application function context

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

3663:   Level: advanced

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

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

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

3688:   Collective if any hooks are

3690:   Input Parameters:
3691: + global   - The global `DM` to use as a base
3692: . oscatter - The scatter from domain global vector filling subdomain global vector with overlap
3693: . gscatter - The scatter from domain global vector filling subdomain local vector with ghosts
3694: - subdm    - The subdomain `DM` to update

3696:   Level: developer

3698: .seealso: [](ch_dmbase), `DM`, `DMCoarsenHookAdd()`, `MatRestrict()`, `DMCreateDomainDecomposition()`
3699: @*/
3700: PetscErrorCode DMSubDomainRestrict(DM global, VecScatter oscatter, VecScatter gscatter, DM subdm)
3701: {
3702:   DMSubDomainHookLink link;

3704:   PetscFunctionBegin;
3705:   for (link = global->subdomainhook; link; link = link->next) {
3706:     if (link->restricthook) PetscCall((*link->restricthook)(global, oscatter, gscatter, subdm, link->ctx));
3707:   }
3708:   PetscFunctionReturn(PETSC_SUCCESS);
3709: }

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

3714:   Not Collective

3716:   Input Parameter:
3717: . dm - the `DM` object

3719:   Output Parameter:
3720: . level - number of coarsenings

3722:   Level: developer

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

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

3738:   Collective

3740:   Input Parameters:
3741: + dm    - the `DM` object
3742: - level - number of coarsenings

3744:   Level: developer

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

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

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

3762:   Collective

3764:   Input Parameters:
3765: + dm      - the `DM` object
3766: - nlevels - the number of levels of refinement

3768:   Output Parameter:
3769: . dmf - the refined `DM` hierarchy

3771:   Level: developer

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

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

3792:   Collective

3794:   Input Parameters:
3795: + dm      - the `DM` object
3796: - nlevels - the number of levels of coarsening

3798:   Output Parameter:
3799: . dmc - the coarsened `DM` hierarchy

3801:   Level: developer

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

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

3822:   Logically Collective if the function is collective

3824:   Input Parameters:
3825: + dm      - the `DM` object
3826: - destroy - the destroy function, see `PetscCtxDestroyFn` for the calling sequence

3828:   Level: intermediate

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

3841: /*@
3842:   DMSetApplicationContext - Set an application context into a `DM` object

3844:   Not Collective

3846:   Input Parameters:
3847: + dm  - the `DM` object
3848: - ctx - the application context

3850:   Level: intermediate

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

3857:   Fortran Notes:
3858:   This only works when the context is a Fortran derived type or a `PetscObject`. Declare `ctx` with
3859: .vb
3860:   type(tUsertype), pointer :: ctx
3861: .ve

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

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

3876:   Not Collective

3878:   Input Parameter:
3879: . dm - the `DM` object

3881:   Output Parameter:
3882: . ctx - a pointer to the application context

3884:   Level: intermediate

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

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

3904:   The prototype for `ctx` must be
3905: .vb
3906:   type(tUsertype), pointer :: ctx
3907: .ve

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

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

3922:   Logically Collective

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

3928:   Calling sequence of f:
3929: + dm    - the `DM`
3930: . lower - the vector to hold the lower bounds
3931: - upper - the vector to hold the upper bounds

3933:   Level: intermediate

3935:   Developer Note:
3936:   Should be called `DMSetComputeVIBounds()` or something similar

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

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

3951:   Not Collective

3953:   Input Parameter:
3954: . dm - the `DM` object to destroy

3956:   Output Parameter:
3957: . flg - `PETSC_TRUE` if the variable bounds function exists

3959:   Level: developer

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

3972: /*@
3973:   DMComputeVariableBounds - compute variable bounds used by `SNESVI`.

3975:   Logically Collective

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

3980:   Output Parameters:
3981: + xl - lower bound
3982: - xu - upper bound

3984:   Level: advanced

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

3989: .seealso: [](ch_dmbase), `DM`, `DMHasVariableBounds()`, `DMView()`, `DMCreateGlobalVector()`, `DMCreateInterpolation()`, `DMCreateColoring()`, `DMCreateMatrix()`, `DMCreateMassMatrix()`, `DMGetApplicationContext()`
3990: @*/
3991: PetscErrorCode DMComputeVariableBounds(DM dm, Vec xl, Vec xu)
3992: {
3993:   PetscFunctionBegin;
3997:   PetscUseTypeMethod(dm, computevariablebounds, xl, xu);
3998:   PetscFunctionReturn(PETSC_SUCCESS);
3999: }

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

4004:   Not Collective

4006:   Input Parameter:
4007: . dm - the DM object

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

4012:   Level: developer

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

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

4028:   Not Collective

4030:   Input Parameter:
4031: . dm - the `DM` object

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

4036:   Level: developer

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

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

4052:   Not Collective

4054:   Input Parameter:
4055: . dm - the `DM` object

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

4060:   Level: developer

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

4074: PetscFunctionList DMList              = NULL;
4075: PetscBool         DMRegisterAllCalled = PETSC_FALSE;

4077: /*@
4078:   DMSetType - Builds a `DM`, for a particular `DM` implementation.

4080:   Collective

4082:   Input Parameters:
4083: + dm     - The `DM` object
4084: - method - The name of the `DMType`, for example `DMDA`, `DMPLEX`

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

4089:   Level: intermediate

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

4094: .seealso: [](ch_dmbase), `DM`, `DMType`, `DMDA`, `DMPLEX`, `DMGetType()`, `DMCreate()`, `DMDACreate2d()`
4095: @*/
4096: PetscErrorCode DMSetType(DM dm, DMType method)
4097: {
4098:   PetscErrorCode (*r)(DM);
4099:   PetscBool match;

4101:   PetscFunctionBegin;
4103:   PetscCall(PetscObjectTypeCompare((PetscObject)dm, method, &match));
4104:   if (match) PetscFunctionReturn(PETSC_SUCCESS);

4106:   PetscCall(DMRegisterAll());
4107:   PetscCall(PetscFunctionListFind(DMList, method, &r));
4108:   PetscCheck(r, PetscObjectComm((PetscObject)dm), PETSC_ERR_ARG_UNKNOWN_TYPE, "Unknown DM type: %s", method);

4110:   PetscTryTypeMethod(dm, destroy);
4111:   PetscCall(PetscMemzero(dm->ops, sizeof(*dm->ops)));
4112:   PetscCall(PetscObjectChangeTypeName((PetscObject)dm, method));
4113:   PetscCall((*r)(dm));
4114:   PetscFunctionReturn(PETSC_SUCCESS);
4115: }

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

4120:   Not Collective

4122:   Input Parameter:
4123: . dm - The `DM`

4125:   Output Parameter:
4126: . type - The `DMType` name

4128:   Level: intermediate

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

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

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

4148:   Collective

4150:   Input Parameters:
4151: + dm      - the `DM`
4152: - newtype - new `DM` type (use "same" for the same type)

4154:   Output Parameter:
4155: . M - pointer to new `DM`

4157:   Level: intermediate

4159:   Note:
4160:   Cannot be used to convert a sequential `DM` to a parallel or a parallel to sequential,
4161:   the MPI communicator of the generated `DM` is always the same as the communicator
4162:   of the input `DM`.

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

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

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

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

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

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

4223:     /* 4) See if a good general converter is known for the current matrix */
4224:     if (dm->ops->convert) conv = dm->ops->convert;
4225:     if (conv) goto foundconv;
4226: #endif

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

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

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

4252: /*@
4253:   DMRegister -  Adds a new `DM` type implementation

4255:   Not Collective, No Fortran Support

4257:   Input Parameters:
4258: + sname    - The name of a new user-defined creation routine
4259: - function - The creation routine itself

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

4264:   Level: advanced

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

4269:   Example Usage:
4270: .vb
4271:     DMRegister("my_da", MyDMCreate);
4272: .ve

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

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

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

4297:   Collective

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

4305:   Level: intermediate

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

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

4314: .seealso: [](ch_dmbase), `DM`, `PetscViewerBinaryOpen()`, `DMView()`, `MatLoad()`, `VecLoad()`
4315: @*/
4316: PetscErrorCode DMLoad(DM newdm, PetscViewer viewer)
4317: {
4318:   PetscBool isbinary, ishdf5;

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

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

4343: /* FEM Support */

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

4348:   Not Collective

4350:   Input Parameters:
4351: + c    - the cell number
4352: . name - the label to print with the cell (typically the element or field name)
4353: . len  - the length of `x`
4354: - x    - the array of integer indices

4356:   Level: developer

4358: .seealso: [](ch_dmbase), `DM`, `DMPrintCellVector()`, `DMPrintCellVectorReal()`, `DMPrintCellMatrix()`, `DMPrintLocalVec()`
4359: @*/
4360: PetscErrorCode DMPrintCellIndices(PetscInt c, const char name[], PetscInt len, const PetscInt x[])
4361: {
4362:   PetscInt f;

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

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

4373:   Not Collective

4375:   Input Parameters:
4376: + c    - the cell number
4377: . name - the label to print with the cell (typically the element or field name)
4378: . len  - the length of `x`
4379: - x    - the array of `PetscScalar` values

4381:   Level: developer

4383:   Note:
4384:   Only the real part of each entry is printed.

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

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

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

4401:   Not Collective

4403:   Input Parameters:
4404: + c    - the cell number
4405: . name - the label to print with the cell (typically the element or field name)
4406: . len  - the length of `x`
4407: - x    - the array of `PetscReal` values

4409:   Level: developer

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

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

4424:   Not Collective

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

4433:   Level: developer

4435:   Note:
4436:   Only the real part of each entry is printed.

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

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

4455:   Collective

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

4463:   Level: developer

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

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

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

4500: PetscErrorCode DMViewDSFromOptions_Internal(DM dm, const char opt[])
4501: {
4502:   PetscObject       obj = (PetscObject)dm;
4503:   PetscViewer       viewer;
4504:   PetscViewerFormat format;
4505:   PetscBool         flg;

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

4519: PetscErrorCode DMViewSectionFromOptions_Internal(DM dm, const char opt[])
4520: {
4521:   PetscObject       obj = (PetscObject)dm;
4522:   PetscViewer       viewer;
4523:   PetscViewerFormat format;
4524:   PetscBool         flg;

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

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

4541:   Input Parameter:
4542: . dm - The `DM`

4544:   Output Parameter:
4545: . section - The `PetscSection`

4547:   Options Database Key:
4548: . -dm_petscsection_view - View the section created by the `DM`

4550:   Level: intermediate

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

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

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

4577:   Input Parameters:
4578: + dm      - The `DM`
4579: - section - The `PetscSection`

4581:   Level: intermediate

4583:   Note:
4584:   Any existing Section will be destroyed. The global section, the section `PetscSF`, and any local-to-global mapping previously derived from the sections are
4585:   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.

4587: .seealso: [](ch_dmbase), `DM`, `PetscSection`, `DMGetLocalSection()`, `DMSetGlobalSection()`
4588: @*/
4589: PetscErrorCode DMSetLocalSection(DM dm, PetscSection section)
4590: {
4591:   PetscInt numFields = 0;

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

4606:       PetscCall(PetscSectionGetFieldName(dm->localSection, f, &name));
4607:       PetscCall(DMGetField(dm, f, NULL, &disc));
4608:       PetscCall(PetscObjectSetName(disc, name));
4609:     }
4610:   }
4611:   /* The global section, the SectionSF, and a section-derived local-to-global mapping will be rebuilt
4612:      in the next call to DMGetGlobalSection(), DMGetSectionSF(), and DMGetLocalToGlobalMapping().
4613:      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. */
4614:   PetscCall(PetscSectionDestroy(&dm->globalSection));
4615:   PetscCall(PetscSFDestroy(&dm->sectionSF));
4616:   PetscCall(PetscSFCreate(PetscObjectComm((PetscObject)dm), &dm->sectionSF));
4617:   if (dm->ltogmapFromSection) PetscCall(ISLocalToGlobalMappingDestroy(&dm->ltogmap));

4619:   /* Clear scratch vectors */
4620:   PetscCall(DMClearGlobalVectors(dm));
4621:   PetscCall(DMClearLocalVectors(dm));
4622:   PetscCall(DMClearNamedGlobalVectors(dm));
4623:   PetscCall(DMClearNamedLocalVectors(dm));
4624:   PetscFunctionReturn(PETSC_SUCCESS);
4625: }

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

4630:   Input Parameter:
4631: . dm - The `DM`

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

4637:   Level: developer

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

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

4653:   not Collective

4655:   Input Parameter:
4656: . dm - The `DM`

4658:   Output Parameters:
4659: + 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.
4660: . 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.
4661: - bias    - Vector containing bias to be added to constrained dofs

4663:   Level: advanced

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

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

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

4684:   Collective

4686:   Input Parameters:
4687: + dm      - The `DM`
4688: . 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).
4689: . 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).
4690: - 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).

4692:   Level: advanced

4694:   Notes:
4695:   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()`.

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

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

4701: .seealso: [](ch_dmbase), `DM`, `DMGetDefaultConstraints()`
4702: @*/
4703: PetscErrorCode DMSetDefaultConstraints(DM dm, PetscSection section, Mat mat, Vec bias)
4704: {
4705:   PetscMPIInt result;

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

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

4739:   Input Parameters:
4740: + dm - The `DM`
4741: . localSection - `PetscSection` describing the local data layout
4742: - globalSection - `PetscSection` describing the global data layout

4744:   Level: intermediate

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

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

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

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

4812: PetscErrorCode DMGetIsoperiodicPointSF_Internal(DM dm, PetscSF *sf)
4813: {
4814:   PetscErrorCode (*f)(DM, PetscSF *);

4816:   PetscFunctionBegin;
4818:   PetscAssertPointer(sf, 2);
4819:   PetscCall(PetscObjectQueryFunction((PetscObject)dm, "DMGetIsoperiodicPointSF_C", &f));
4820:   if (f) PetscCall(f(dm, sf));
4821:   else *sf = dm->sf;
4822:   PetscFunctionReturn(PETSC_SUCCESS);
4823: }

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

4828:   Collective

4830:   Input Parameter:
4831: . dm - The `DM`

4833:   Output Parameter:
4834: . section - The `PetscSection`

4836:   Level: intermediate

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

4841: .seealso: [](ch_dmbase), `DM`, `DMSetLocalSection()`, `DMGetLocalSection()`
4842: @*/
4843: PetscErrorCode DMGetGlobalSection(DM dm, PetscSection *section)
4844: {
4845:   PetscFunctionBegin;
4847:   PetscAssertPointer(section, 2);
4848:   if (!dm->globalSection) {
4849:     PetscSection s;
4850:     PetscSF      sf;

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

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

4868:   Input Parameters:
4869: + dm      - The `DM`
4870: - section - The PetscSection, or `NULL`

4872:   Level: intermediate

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

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

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

4902:   Input Parameter:
4903: . dm - The `DM`

4905:   Output Parameter:
4906: . sf - The `PetscSF`

4908:   Level: intermediate

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

4913: .seealso: [](ch_dmbase), `DM`, `DMSetSectionSF()`, `DMCreateSectionSF()`
4914: @*/
4915: PetscErrorCode DMGetSectionSF(DM dm, PetscSF *sf)
4916: {
4917:   PetscInt nroots;

4919:   PetscFunctionBegin;
4921:   PetscAssertPointer(sf, 2);
4922:   if (!dm->sectionSF) PetscCall(PetscSFCreate(PetscObjectComm((PetscObject)dm), &dm->sectionSF));
4923:   PetscCall(PetscSFGetGraph(dm->sectionSF, &nroots, NULL, NULL, NULL));
4924:   if (nroots < 0) {
4925:     PetscSection section, gSection;

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

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

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

4947:   Level: intermediate

4949:   Note:
4950:   Any previous `PetscSF` is destroyed

4952: .seealso: [](ch_dmbase), `DM`, `DMGetSectionSF()`, `DMCreateSectionSF()`
4953: @*/
4954: PetscErrorCode DMSetSectionSF(DM dm, PetscSF sf)
4955: {
4956:   PetscFunctionBegin;
4959:   PetscCall(PetscObjectReference((PetscObject)sf));
4960:   PetscCall(PetscSFDestroy(&dm->sectionSF));
4961:   dm->sectionSF = sf;
4962:   PetscFunctionReturn(PETSC_SUCCESS);
4963: }

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

4969:   Input Parameters:
4970: + dm            - The `DM`
4971: . localSection  - `PetscSection` describing the local data layout
4972: - globalSection - `PetscSection` describing the global data layout

4974:   Level: developer

4976:   Note:
4977:   One usually uses `DMGetSectionSF()` to obtain the `PetscSF`

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

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

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

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

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

5003:   Output Parameter:
5004: . sf - The `PetscSF`

5006:   Level: intermediate

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

5011: .seealso: [](ch_dmbase), `DM`, `DMSetPointSF()`, `DMGetSectionSF()`, `DMSetSectionSF()`, `DMCreateSectionSF()`
5012: @*/
5013: PetscErrorCode DMGetPointSF(DM dm, PetscSF *sf)
5014: {
5015:   PetscFunctionBegin;
5017:   PetscAssertPointer(sf, 2);
5018:   *sf = dm->sf;
5019:   PetscFunctionReturn(PETSC_SUCCESS);
5020: }

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

5025:   Collective

5027:   Input Parameters:
5028: + dm - The `DM`
5029: - sf - The `PetscSF`

5031:   Level: intermediate

5033: .seealso: [](ch_dmbase), `DM`, `DMGetPointSF()`, `DMGetSectionSF()`, `DMSetSectionSF()`, `DMCreateSectionSF()`
5034: @*/
5035: PetscErrorCode DMSetPointSF(DM dm, PetscSF sf)
5036: {
5037:   PetscFunctionBegin;
5040:   PetscCall(PetscObjectReference((PetscObject)sf));
5041:   PetscCall(PetscSFDestroy(&dm->sf));
5042:   dm->sf = sf;
5043:   PetscFunctionReturn(PETSC_SUCCESS);
5044: }

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

5049:   Input Parameter:
5050: . dm - The `DM`

5052:   Output Parameter:
5053: . sf - The `PetscSF`

5055:   Level: intermediate

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

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

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

5074:   Input Parameters:
5075: + dm - The DM
5076: - sf - The PetscSF

5078:   Level: intermediate

5080: .seealso: [](ch_dmbase), `DM`, `DMGetNaturalSF()`, `DMSetUseNatural()`, `DMGetUseNatural()`, `DMPlexCreateGlobalToNaturalSF()`, `DMPlexDistribute()`
5081: @*/
5082: PetscErrorCode DMSetNaturalSF(DM dm, PetscSF sf)
5083: {
5084:   PetscFunctionBegin;
5087:   PetscCall(PetscObjectReference((PetscObject)sf));
5088:   PetscCall(PetscSFDestroy(&dm->sfNatural));
5089:   dm->sfNatural = sf;
5090:   PetscFunctionReturn(PETSC_SUCCESS);
5091: }

5093: static PetscErrorCode DMSetDefaultAdjacency_Private(DM dm, PetscInt f, PetscObject disc)
5094: {
5095:   PetscClassId id;

5097:   PetscFunctionBegin;
5098:   PetscCall(PetscObjectGetClassId(disc, &id));
5099:   if (id == PETSCFE_CLASSID) PetscCall(DMSetAdjacency(dm, f, PETSC_FALSE, PETSC_TRUE));
5100:   else if (id == PETSCFV_CLASSID) PetscCall(DMSetAdjacency(dm, f, PETSC_TRUE, PETSC_FALSE));
5101:   else PetscCall(DMSetAdjacency(dm, f, PETSC_FALSE, PETSC_TRUE));
5102:   PetscFunctionReturn(PETSC_SUCCESS);
5103: }

5105: static PetscErrorCode DMFieldEnlarge_Static(DM dm, PetscInt NfNew)
5106: {
5107:   RegionField *tmpr;
5108:   PetscInt     Nf = dm->Nf, f;

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

5125: /*@
5126:   DMClearFields - Remove all fields from the `DM`

5128:   Logically Collective

5130:   Input Parameter:
5131: . dm - The `DM`

5133:   Level: intermediate

5135: .seealso: [](ch_dmbase), `DM`, `DMGetNumFields()`, `DMSetNumFields()`, `DMSetField()`
5136: @*/
5137: PetscErrorCode DMClearFields(DM dm)
5138: {
5139:   PetscInt f;

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

5153: /*@
5154:   DMGetNumFields - Get the number of fields in the `DM`

5156:   Not Collective

5158:   Input Parameter:
5159: . dm - The `DM`

5161:   Output Parameter:
5162: . numFields - The number of fields

5164:   Level: intermediate

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

5177: /*@
5178:   DMSetNumFields - Set the number of fields in the `DM`

5180:   Logically Collective

5182:   Input Parameters:
5183: + dm        - The `DM`
5184: - numFields - The number of fields

5186:   Level: intermediate

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

5194:   PetscFunctionBegin;
5196:   PetscCall(DMGetNumFields(dm, &Nf));
5197:   for (PetscInt f = Nf; f < numFields; ++f) {
5198:     PetscContainer obj;

5200:     PetscCall(PetscContainerCreate(PetscObjectComm((PetscObject)dm), &obj));
5201:     PetscCall(DMAddField(dm, NULL, (PetscObject)obj));
5202:     PetscCall(PetscContainerDestroy(&obj));
5203:   }
5204:   PetscFunctionReturn(PETSC_SUCCESS);
5205: }

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

5210:   Not Collective

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

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

5220:   Level: intermediate

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

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

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

5258:   Logically Collective

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

5266:   Level: intermediate

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

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

5287:   Logically Collective

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

5294:   Level: intermediate

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

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

5303:   Fortran Note:
5304:   Use the argument `PetscObjectCast(disc)` as the second argument

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

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

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

5329:   Logically Collective

5331:   Input Parameters:
5332: + dm          - The `DM`
5333: . f           - The field index
5334: - avoidTensor - `PETSC_TRUE` to skip defining the field on tensor cells

5336:   Level: intermediate

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

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

5351:   Not Collective

5353:   Input Parameters:
5354: + dm - The `DM`
5355: - f  - The field index

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

5360:   Level: intermediate

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

5372: /*@
5373:   DMCopyFields - Copy the discretizations for the `DM` into another `DM`

5375:   Collective

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

5382:   Output Parameter:
5383: . newdm - The `DM`

5385:   Level: advanced

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

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

5403:     PetscCall(DMGetField(dm, f, &label, &field));
5404:     PetscCall(PetscObjectGetClassId(field, &id));
5405:     if (id == PETSCFE_CLASSID) {
5406:       PetscFE newfe;

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

5425: /*@
5426:   DMGetAdjacency - Returns the flags for determining variable influence

5428:   Not Collective

5430:   Input Parameters:
5431: + dm - The `DM` object
5432: - f  - The field number, or `PETSC_DEFAULT` for the default adjacency

5434:   Output Parameters:
5435: + useCone    - Flag for variable influence starting with the cone operation
5436: - useClosure - Flag for variable influence using transitive closure

5438:   Level: developer

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

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

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

5470: /*@
5471:   DMSetAdjacency - Set the flags for determining variable influence

5473:   Not Collective

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

5481:   Level: developer

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

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

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

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

5514:   Not collective

5516:   Input Parameter:
5517: . dm - The `DM` object

5519:   Output Parameters:
5520: + useCone    - Flag for variable influence starting with the cone operation
5521: - useClosure - Flag for variable influence using transitive closure

5523:   Level: developer

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

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

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

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

5554:   Not Collective

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

5561:   Level: developer

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

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

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

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

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

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

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

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

5675: static PetscErrorCode DMDSEnlarge_Static(DM dm, PetscInt NdsNew)
5676: {
5677:   DMSpace *tmpd;
5678:   PetscInt Nds = dm->Nds, s;

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

5695: /*@
5696:   DMGetNumDS - Get the number of discrete systems in the `DM`

5698:   Not Collective

5700:   Input Parameter:
5701: . dm - The `DM`

5703:   Output Parameter:
5704: . Nds - The number of `PetscDS` objects

5706:   Level: intermediate

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

5719: /*@
5720:   DMClearDS - Remove all discrete systems from the `DM`

5722:   Logically Collective

5724:   Input Parameter:
5725: . dm - The `DM`

5727:   Level: intermediate

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

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

5748: /*@
5749:   DMGetDS - Get the default `PetscDS`

5751:   Not Collective

5753:   Input Parameter:
5754: . dm - The `DM`

5756:   Output Parameter:
5757: . ds - The default `PetscDS`

5759:   Level: intermediate

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

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

5776: /*@
5777:   DMGetCellDS - Get the `PetscDS` defined on a given cell

5779:   Not Collective

5781:   Input Parameters:
5782: + dm    - The `DM`
5783: - point - Cell for the `PetscDS`

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

5789:   Level: developer

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

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

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

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

5826:   Not Collective

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

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

5837:   Level: advanced

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

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

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

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

5879:   Collective

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

5888:   Level: advanced

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

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

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

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

5935:   Not Collective

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

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

5947:   Level: advanced

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

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

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

5981:   Not Collective

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

5991:   Level: advanced

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

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

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

6031:   Not Collective

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

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

6040:   Level: advanced

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

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

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

6063:   Not Collective

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

6071:   Output Parameter:
6072: . fem - The `PetscFE`

6074:   Level: intermediate

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

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

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

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

6102:   Collective

6104:   Input Parameter:
6105: . dm - The `DM`

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

6110:   Level: intermediate

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

6375:   Input Parameters:
6376: + dm     - The DM
6377: - tensor - Flag for tensor order

6379:   Level: developer

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

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

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

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

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

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

6420:   Collective

6422:   Input Parameters:
6423: + dm   - The `DM`
6424: - time - The time

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

6430:   Level: developer

6432:   Note:
6433:   The user must call `PetscDSSetExactSolution()` before using this routine

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

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

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

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

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

6524: /*@
6525:   DMCopyDS - Copy the discrete systems for the `DM` into another `DM`

6527:   Collective

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

6534:   Output Parameter:
6535: . newdm - The `DM`

6537:   Level: advanced

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

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

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

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

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

6577:   Collective

6579:   Input Parameter:
6580: . dm - The `DM`

6582:   Output Parameter:
6583: . newdm - The `DM`

6585:   Level: advanced

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

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

6600: /*@
6601:   DMGetDimension - Return the topological dimension of the `DM`

6603:   Not Collective

6605:   Input Parameter:
6606: . dm - The `DM`

6608:   Output Parameter:
6609: . dim - The topological dimension

6611:   Level: beginner

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

6624: /*@
6625:   DMSetDimension - Set the topological dimension of the `DM`

6627:   Collective

6629:   Input Parameters:
6630: + dm  - The `DM`
6631: - dim - The topological dimension

6633:   Level: beginner

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

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

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

6660:   Collective

6662:   Input Parameters:
6663: + dm  - the `DM`
6664: - dim - the dimension

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

6670:   Level: intermediate

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

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

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

6691: /*@
6692:   DMGetOutputDM - Retrieve the `DM` associated with the layout for output

6694:   Collective

6696:   Input Parameter:
6697: . dm - The original `DM`

6699:   Output Parameter:
6700: . odm - The `DM` which provides the layout for output

6702:   Level: intermediate

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

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

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

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

6752: /*@
6753:   DMGetOutputSequenceNumber - Retrieve the sequence number/value for output

6755:   Input Parameter:
6756: . dm - The original `DM`

6758:   Output Parameters:
6759: + num - The output sequence number
6760: - val - The output sequence value

6762:   Level: intermediate

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

6768:   Developer Note:
6769:   The `DM` serves as a convenient place to store the current iteration value. The iteration is not
6770:   not directly related to the `DM`.

6772: .seealso: [](ch_dmbase), `DM`, `VecView()`
6773: @*/
6774: PetscErrorCode DMGetOutputSequenceNumber(DM dm, PetscInt *num, PetscReal *val)
6775: {
6776:   PetscFunctionBegin;
6778:   if (num) {
6779:     PetscAssertPointer(num, 2);
6780:     *num = dm->outputSequenceNum;
6781:   }
6782:   if (val) {
6783:     PetscAssertPointer(val, 3);
6784:     *val = dm->outputSequenceVal;
6785:   }
6786:   PetscFunctionReturn(PETSC_SUCCESS);
6787: }

6789: /*@
6790:   DMSetOutputSequenceNumber - Set the sequence number/value for output

6792:   Input Parameters:
6793: + dm  - The original `DM`
6794: . num - The output sequence number
6795: - val - The output sequence value

6797:   Level: intermediate

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

6803: .seealso: [](ch_dmbase), `DM`, `VecView()`
6804: @*/
6805: PetscErrorCode DMSetOutputSequenceNumber(DM dm, PetscInt num, PetscReal val)
6806: {
6807:   PetscFunctionBegin;
6809:   dm->outputSequenceNum = num;
6810:   dm->outputSequenceVal = val;
6811:   PetscFunctionReturn(PETSC_SUCCESS);
6812: }

6814: /*@
6815:   DMOutputSequenceLoad - Retrieve the sequence value from a `PetscViewer`

6817:   Input Parameters:
6818: + dm     - The original `DM`
6819: . viewer - The `PetscViewer` to get it from
6820: . name   - The sequence name
6821: - num    - The output sequence number

6823:   Output Parameter:
6824: . val - The output sequence value

6826:   Level: intermediate

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

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

6835: .seealso: [](ch_dmbase), `DM`, `DMGetOutputSequenceNumber()`, `DMSetOutputSequenceNumber()`, `VecView()`
6836: @*/
6837: PetscErrorCode DMOutputSequenceLoad(DM dm, PetscViewer viewer, const char name[], PetscInt num, PetscReal *val)
6838: {
6839:   PetscBool ishdf5;

6841:   PetscFunctionBegin;
6844:   PetscAssertPointer(name, 3);
6845:   PetscAssertPointer(val, 5);
6846:   PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERHDF5, &ishdf5));
6847:   PetscCheck(ishdf5, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Invalid viewer; open viewer with PetscViewerHDF5Open()");
6848: #if PetscDefined(HAVE_HDF5)
6849:   PetscScalar value;

6851:   PetscCall(DMSequenceLoad_HDF5_Internal(dm, name, num, &value, viewer));
6852:   *val = PetscRealPart(value);
6853: #endif
6854:   PetscFunctionReturn(PETSC_SUCCESS);
6855: }

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

6860:   Input Parameters:
6861: + dm     - The original `DM`
6862: . viewer - The `PetscViewer` to get it from
6863: - name   - The sequence name

6865:   Output Parameter:
6866: . len - The length of the output sequence

6868:   Level: intermediate

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

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

6877: .seealso: [](ch_dmbase), `DM`, `DMGetOutputSequenceNumber()`, `DMSetOutputSequenceNumber()`, `VecView()`
6878: @*/
6879: PetscErrorCode DMGetOutputSequenceLength(DM dm, PetscViewer viewer, const char name[], PetscInt *len)
6880: {
6881:   PetscBool ishdf5;

6883:   PetscFunctionBegin;
6886:   PetscAssertPointer(name, 3);
6887:   PetscAssertPointer(len, 4);
6888:   PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERHDF5, &ishdf5));
6889:   PetscCheck(ishdf5, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Invalid viewer; open viewer with PetscViewerHDF5Open()");
6890: #if PetscDefined(HAVE_HDF5)
6891:   PetscCall(DMSequenceGetLength_HDF5_Internal(dm, name, len, viewer));
6892: #endif
6893:   PetscFunctionReturn(PETSC_SUCCESS);
6894: }

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

6899:   Not Collective

6901:   Input Parameter:
6902: . dm - The `DM`

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

6907:   Level: beginner

6909: .seealso: [](ch_dmbase), `DM`, `DMSetUseNatural()`, `DMCreate()`
6910: @*/
6911: PetscErrorCode DMGetUseNatural(DM dm, PetscBool *useNatural)
6912: {
6913:   PetscFunctionBegin;
6915:   PetscAssertPointer(useNatural, 2);
6916:   *useNatural = dm->useNatural;
6917:   PetscFunctionReturn(PETSC_SUCCESS);
6918: }

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

6923:   Collective

6925:   Input Parameters:
6926: + dm         - The `DM`
6927: - useNatural - `PETSC_TRUE` to build the mapping to a natural order during distribution

6929:   Level: beginner

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

6934: .seealso: [](ch_dmbase), `DM`, `DMGetUseNatural()`, `DMCreate()`, `DMPlexDistribute()`, `DMCreateSubDM()`, `DMCreateSuperDM()`
6935: @*/
6936: PetscErrorCode DMSetUseNatural(DM dm, PetscBool useNatural)
6937: {
6938:   PetscFunctionBegin;
6941:   dm->useNatural = useNatural;
6942:   PetscFunctionReturn(PETSC_SUCCESS);
6943: }

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

6948:   Not Collective

6950:   Input Parameters:
6951: + dm   - The `DM` object
6952: - name - The label name

6954:   Level: intermediate

6956: .seealso: [](ch_dmbase), `DM`, `DMLabelCreate()`, `DMHasLabel()`, `DMGetLabelValue()`, `DMSetLabelValue()`, `DMGetStratumIS()`
6957: @*/
6958: PetscErrorCode DMCreateLabel(DM dm, const char name[])
6959: {
6960:   PetscBool flg;
6961:   DMLabel   label;

6963:   PetscFunctionBegin;
6965:   PetscAssertPointer(name, 2);
6966:   PetscCall(DMHasLabel(dm, name, &flg));
6967:   if (!flg) {
6968:     PetscCall(DMLabelCreate(PETSC_COMM_SELF, name, &label));
6969:     PetscCall(DMAddLabel(dm, label));
6970:     PetscCall(DMLabelDestroy(&label));
6971:   }
6972:   PetscFunctionReturn(PETSC_SUCCESS);
6973: }

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

6978:   Not Collective

6980:   Input Parameters:
6981: + dm   - The `DM` object
6982: . l    - The index for the label
6983: - name - The label name

6985:   Level: intermediate

6987: .seealso: [](ch_dmbase), `DM`, `DMCreateLabel()`, `DMLabelCreate()`, `DMHasLabel()`, `DMGetLabelValue()`, `DMSetLabelValue()`, `DMGetStratumIS()`
6988: @*/
6989: PetscErrorCode DMCreateLabelAtIndex(DM dm, PetscInt l, const char name[])
6990: {
6991:   DMLabelLink orig, prev = NULL;
6992:   DMLabel     label;
6993:   PetscInt    Nl, m;
6994:   PetscBool   flg, match;
6995:   const char *lname;

6997:   PetscFunctionBegin;
6999:   PetscAssertPointer(name, 3);
7000:   PetscCall(DMHasLabel(dm, name, &flg));
7001:   if (!flg) {
7002:     PetscCall(DMLabelCreate(PETSC_COMM_SELF, name, &label));
7003:     PetscCall(DMAddLabel(dm, label));
7004:     PetscCall(DMLabelDestroy(&label));
7005:   }
7006:   PetscCall(DMGetNumLabels(dm, &Nl));
7007:   PetscCheck(l < Nl, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Label index %" PetscInt_FMT " must be in [0, %" PetscInt_FMT ")", l, Nl);
7008:   for (m = 0, orig = dm->labels; m < Nl; ++m, prev = orig, orig = orig->next) {
7009:     PetscCall(PetscObjectGetName((PetscObject)orig->label, &lname));
7010:     PetscCall(PetscStrcmp(name, lname, &match));
7011:     if (match) break;
7012:   }
7013:   if (m == l) PetscFunctionReturn(PETSC_SUCCESS);
7014:   if (!m) dm->labels = orig->next;
7015:   else prev->next = orig->next;
7016:   if (!l) {
7017:     orig->next = dm->labels;
7018:     dm->labels = orig;
7019:   } else {
7020:     for (m = 0, prev = dm->labels; m < l - 1; ++m, prev = prev->next);
7021:     orig->next = prev->next;
7022:     prev->next = orig;
7023:   }
7024:   PetscFunctionReturn(PETSC_SUCCESS);
7025: }

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

7030:   Not Collective

7032:   Input Parameters:
7033: + dm    - The `DM` object
7034: . name  - The label name
7035: - point - The mesh point

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

7040:   Level: beginner

7042: .seealso: [](ch_dmbase), `DM`, `DMLabelGetValue()`, `DMSetLabelValue()`, `DMGetStratumIS()`
7043: @*/
7044: PetscErrorCode DMGetLabelValue(DM dm, const char name[], PetscInt point, PetscInt *value)
7045: {
7046:   DMLabel label;

7048:   PetscFunctionBegin;
7050:   PetscAssertPointer(name, 2);
7051:   PetscCall(DMGetLabel(dm, name, &label));
7052:   PetscCheck(label, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "No label named %s was found", name);
7053:   PetscCall(DMLabelGetValue(label, point, value));
7054:   PetscFunctionReturn(PETSC_SUCCESS);
7055: }

7057: /*@
7058:   DMSetLabelValue - Add a point to a `DMLabel` with given value

7060:   Not Collective

7062:   Input Parameters:
7063: + dm    - The `DM` object
7064: . name  - The label name
7065: . point - The mesh point
7066: - value - The label value for this point

7068:   Output Parameter:

7070:   Level: beginner

7072: .seealso: [](ch_dmbase), `DM`, `DMLabelSetValue()`, `DMGetStratumIS()`, `DMClearLabelValue()`
7073: @*/
7074: PetscErrorCode DMSetLabelValue(DM dm, const char name[], PetscInt point, PetscInt value)
7075: {
7076:   DMLabel label;

7078:   PetscFunctionBegin;
7080:   PetscAssertPointer(name, 2);
7081:   PetscCall(DMGetLabel(dm, name, &label));
7082:   if (!label) {
7083:     PetscCall(DMCreateLabel(dm, name));
7084:     PetscCall(DMGetLabel(dm, name, &label));
7085:   }
7086:   PetscCall(DMLabelSetValue(label, point, value));
7087:   PetscFunctionReturn(PETSC_SUCCESS);
7088: }

7090: /*@
7091:   DMClearLabelValue - Remove a point from a `DMLabel` with given value

7093:   Not Collective

7095:   Input Parameters:
7096: + dm    - The `DM` object
7097: . name  - The label name
7098: . point - The mesh point
7099: - value - The label value for this point

7101:   Level: beginner

7103: .seealso: [](ch_dmbase), `DM`, `DMLabelClearValue()`, `DMSetLabelValue()`, `DMGetStratumIS()`
7104: @*/
7105: PetscErrorCode DMClearLabelValue(DM dm, const char name[], PetscInt point, PetscInt value)
7106: {
7107:   DMLabel label;

7109:   PetscFunctionBegin;
7111:   PetscAssertPointer(name, 2);
7112:   PetscCall(DMGetLabel(dm, name, &label));
7113:   if (!label) PetscFunctionReturn(PETSC_SUCCESS);
7114:   PetscCall(DMLabelClearValue(label, point, value));
7115:   PetscFunctionReturn(PETSC_SUCCESS);
7116: }

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

7121:   Not Collective

7123:   Input Parameters:
7124: + dm   - The `DM` object
7125: - name - The label name

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

7130:   Level: beginner

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

7135: .seealso: [](ch_dmbase), `DM`, `DMLabelGetNumValues()`, `DMSetLabelValue()`, `DMGetLabel()`
7136: @*/
7137: PetscErrorCode DMGetLabelSize(DM dm, const char name[], PetscInt *size)
7138: {
7139:   DMLabel label;

7141:   PetscFunctionBegin;
7143:   PetscAssertPointer(name, 2);
7144:   PetscAssertPointer(size, 3);
7145:   PetscCall(DMGetLabel(dm, name, &label));
7146:   *size = 0;
7147:   if (!label) PetscFunctionReturn(PETSC_SUCCESS);
7148:   PetscCall(DMLabelGetNumValues(label, size));
7149:   PetscFunctionReturn(PETSC_SUCCESS);
7150: }

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

7155:   Not Collective

7157:   Input Parameters:
7158: + dm   - The `DM` object
7159: - name - The label name

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

7164:   Level: beginner

7166: .seealso: [](ch_dmbase), `DM`, `DMLabelGetValueIS()`, `DMGetLabelSize()`
7167: @*/
7168: PetscErrorCode DMGetLabelIdIS(DM dm, const char name[], IS *ids)
7169: {
7170:   DMLabel label;

7172:   PetscFunctionBegin;
7174:   PetscAssertPointer(name, 2);
7175:   PetscAssertPointer(ids, 3);
7176:   PetscCall(DMGetLabel(dm, name, &label));
7177:   *ids = NULL;
7178:   if (label) PetscCall(DMLabelGetValueIS(label, ids));
7179:   else {
7180:     /* returning an empty IS */
7181:     PetscCall(ISCreateGeneral(PETSC_COMM_SELF, 0, NULL, PETSC_USE_POINTER, ids));
7182:   }
7183:   PetscFunctionReturn(PETSC_SUCCESS);
7184: }

7186: /*@
7187:   DMGetStratumSize - Get the number of points in a label stratum

7189:   Not Collective

7191:   Input Parameters:
7192: + dm    - The `DM` object
7193: . name  - The label name of the stratum
7194: - value - The stratum value

7196:   Output Parameter:
7197: . size - The number of points, also called the stratum size

7199:   Level: beginner

7201: .seealso: [](ch_dmbase), `DM`, `DMLabelGetStratumSize()`, `DMGetLabelSize()`, `DMGetLabelIds()`
7202: @*/
7203: PetscErrorCode DMGetStratumSize(DM dm, const char name[], PetscInt value, PetscInt *size)
7204: {
7205:   DMLabel label;

7207:   PetscFunctionBegin;
7209:   PetscAssertPointer(name, 2);
7210:   PetscAssertPointer(size, 4);
7211:   PetscCall(DMGetLabel(dm, name, &label));
7212:   *size = 0;
7213:   if (!label) PetscFunctionReturn(PETSC_SUCCESS);
7214:   PetscCall(DMLabelGetStratumSize(label, value, size));
7215:   PetscFunctionReturn(PETSC_SUCCESS);
7216: }

7218: /*@
7219:   DMGetStratumIS - Get the points in a label stratum

7221:   Not Collective

7223:   Input Parameters:
7224: + dm    - The `DM` object
7225: . name  - The label name
7226: - value - The stratum value

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

7231:   Level: beginner

7233: .seealso: [](ch_dmbase), `DM`, `DMLabelGetStratumIS()`, `DMGetStratumSize()`
7234: @*/
7235: PetscErrorCode DMGetStratumIS(DM dm, const char name[], PetscInt value, IS *points)
7236: {
7237:   DMLabel label;

7239:   PetscFunctionBegin;
7241:   PetscAssertPointer(name, 2);
7242:   PetscAssertPointer(points, 4);
7243:   PetscCall(DMGetLabel(dm, name, &label));
7244:   *points = NULL;
7245:   if (!label) PetscFunctionReturn(PETSC_SUCCESS);
7246:   PetscCall(DMLabelGetStratumIS(label, value, points));
7247:   PetscFunctionReturn(PETSC_SUCCESS);
7248: }

7250: /*@
7251:   DMSetStratumIS - Set the points in a label stratum

7253:   Not Collective

7255:   Input Parameters:
7256: + dm     - The `DM` object
7257: . name   - The label name
7258: . value  - The stratum value
7259: - points - The stratum points

7261:   Level: beginner

7263: .seealso: [](ch_dmbase), `DM`, `DMLabel`, `DMClearLabelStratum()`, `DMLabelClearStratum()`, `DMLabelSetStratumIS()`, `DMGetStratumSize()`
7264: @*/
7265: PetscErrorCode DMSetStratumIS(DM dm, const char name[], PetscInt value, IS points)
7266: {
7267:   DMLabel label;

7269:   PetscFunctionBegin;
7271:   PetscAssertPointer(name, 2);
7273:   PetscCall(DMGetLabel(dm, name, &label));
7274:   if (!label) PetscFunctionReturn(PETSC_SUCCESS);
7275:   PetscCall(DMLabelSetStratumIS(label, value, points));
7276:   PetscFunctionReturn(PETSC_SUCCESS);
7277: }

7279: /*@
7280:   DMClearLabelStratum - Remove all points from a stratum from a `DMLabel`

7282:   Not Collective

7284:   Input Parameters:
7285: + dm    - The `DM` object
7286: . name  - The label name
7287: - value - The label value for this point

7289:   Output Parameter:

7291:   Level: beginner

7293: .seealso: [](ch_dmbase), `DM`, `DMLabel`, `DMLabelClearStratum()`, `DMSetLabelValue()`, `DMGetStratumIS()`, `DMClearLabelValue()`
7294: @*/
7295: PetscErrorCode DMClearLabelStratum(DM dm, const char name[], PetscInt value)
7296: {
7297:   DMLabel label;

7299:   PetscFunctionBegin;
7301:   PetscAssertPointer(name, 2);
7302:   PetscCall(DMGetLabel(dm, name, &label));
7303:   if (!label) PetscFunctionReturn(PETSC_SUCCESS);
7304:   PetscCall(DMLabelClearStratum(label, value));
7305:   PetscFunctionReturn(PETSC_SUCCESS);
7306: }

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

7311:   Not Collective

7313:   Input Parameter:
7314: . dm - The `DM` object

7316:   Output Parameter:
7317: . numLabels - the number of Labels

7319:   Level: intermediate

7321: .seealso: [](ch_dmbase), `DM`, `DMLabel`, `DMGetLabelByNum()`, `DMGetLabelName()`, `DMGetLabelValue()`, `DMSetLabelValue()`, `DMGetStratumIS()`
7322: @*/
7323: PetscErrorCode DMGetNumLabels(DM dm, PetscInt *numLabels)
7324: {
7325:   DMLabelLink next = dm->labels;
7326:   PetscInt    n    = 0;

7328:   PetscFunctionBegin;
7330:   PetscAssertPointer(numLabels, 2);
7331:   while (next) {
7332:     ++n;
7333:     next = next->next;
7334:   }
7335:   *numLabels = n;
7336:   PetscFunctionReturn(PETSC_SUCCESS);
7337: }

7339: /*@
7340:   DMGetLabelName - Return the name of nth label

7342:   Not Collective

7344:   Input Parameters:
7345: + dm - The `DM` object
7346: - n  - the label number

7348:   Output Parameter:
7349: . name - the label name

7351:   Level: intermediate

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

7356: .seealso: [](ch_dmbase), `DM`, `DMLabel`, `DMGetLabelByNum()`, `DMGetLabel()`, `DMGetLabelValue()`, `DMSetLabelValue()`, `DMGetStratumIS()`
7357: @*/
7358: PetscErrorCode DMGetLabelName(DM dm, PetscInt n, const char *name[])
7359: {
7360:   DMLabelLink next = dm->labels;
7361:   PetscInt    l    = 0;

7363:   PetscFunctionBegin;
7365:   PetscAssertPointer(name, 3);
7366:   while (next) {
7367:     if (l == n) {
7368:       PetscCall(PetscObjectGetName((PetscObject)next->label, name));
7369:       PetscFunctionReturn(PETSC_SUCCESS);
7370:     }
7371:     ++l;
7372:     next = next->next;
7373:   }
7374:   SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Label %" PetscInt_FMT " does not exist in this DM", n);
7375: }

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

7380:   Not Collective

7382:   Input Parameters:
7383: + dm   - The `DM` object
7384: - name - The label name

7386:   Output Parameter:
7387: . hasLabel - `PETSC_TRUE` if the label is present

7389:   Level: intermediate

7391: .seealso: [](ch_dmbase), `DM`, `DMLabel`, `DMGetLabel()`, `DMGetLabelByNum()`, `DMCreateLabel()`, `DMGetLabelValue()`, `DMSetLabelValue()`, `DMGetStratumIS()`
7392: @*/
7393: PetscErrorCode DMHasLabel(DM dm, const char name[], PetscBool *hasLabel)
7394: {
7395:   DMLabelLink next = dm->labels;
7396:   const char *lname;

7398:   PetscFunctionBegin;
7400:   PetscAssertPointer(name, 2);
7401:   PetscAssertPointer(hasLabel, 3);
7402:   *hasLabel = PETSC_FALSE;
7403:   while (next) {
7404:     PetscCall(PetscObjectGetName((PetscObject)next->label, &lname));
7405:     PetscCall(PetscStrcmp(name, lname, hasLabel));
7406:     if (*hasLabel) break;
7407:     next = next->next;
7408:   }
7409:   PetscFunctionReturn(PETSC_SUCCESS);
7410: }

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

7416:   Not Collective

7418:   Input Parameters:
7419: + dm   - The `DM` object
7420: - name - The label name

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

7425:   Default labels in a `DMPLEX`:
7426: + "depth"       - Holds the depth (co-dimension) of each mesh point
7427: . "celltype"    - Holds the topological type of each cell
7428: . "ghost"       - If the DM is distributed with overlap, this marks the cells and faces in the overlap
7429: . "Cell Sets"   - Mirrors the cell sets defined by GMsh and ExodusII
7430: . "Face Sets"   - Mirrors the face sets defined by GMsh and ExodusII
7431: - "Vertex Sets" - Mirrors the vertex sets defined by GMsh

7433:   Level: intermediate

7435: .seealso: [](ch_dmbase), `DM`, `DMLabel`, `DMHasLabel()`, `DMGetLabelByNum()`, `DMAddLabel()`, `DMCreateLabel()`, `DMPlexGetDepthLabel()`, `DMPlexGetCellType()`
7436: @*/
7437: PetscErrorCode DMGetLabel(DM dm, const char name[], DMLabel *label)
7438: {
7439:   DMLabelLink next = dm->labels;
7440:   PetscBool   hasLabel;
7441:   const char *lname;

7443:   PetscFunctionBegin;
7445:   PetscAssertPointer(name, 2);
7446:   PetscAssertPointer(label, 3);
7447:   *label = NULL;
7448:   while (next) {
7449:     PetscCall(PetscObjectGetName((PetscObject)next->label, &lname));
7450:     PetscCall(PetscStrcmp(name, lname, &hasLabel));
7451:     if (hasLabel) {
7452:       *label = next->label;
7453:       break;
7454:     }
7455:     next = next->next;
7456:   }
7457:   PetscFunctionReturn(PETSC_SUCCESS);
7458: }

7460: /*@
7461:   DMGetLabelByNum - Return the nth label on a `DM`

7463:   Not Collective

7465:   Input Parameters:
7466: + dm - The `DM` object
7467: - n  - the label number

7469:   Output Parameter:
7470: . label - the label

7472:   Level: intermediate

7474: .seealso: [](ch_dmbase), `DM`, `DMLabel`, `DMAddLabel()`, `DMGetLabelValue()`, `DMSetLabelValue()`, `DMGetStratumIS()`
7475: @*/
7476: PetscErrorCode DMGetLabelByNum(DM dm, PetscInt n, DMLabel *label)
7477: {
7478:   DMLabelLink next = dm->labels;
7479:   PetscInt    l    = 0;

7481:   PetscFunctionBegin;
7483:   PetscAssertPointer(label, 3);
7484:   while (next) {
7485:     if (l == n) {
7486:       *label = next->label;
7487:       PetscFunctionReturn(PETSC_SUCCESS);
7488:     }
7489:     ++l;
7490:     next = next->next;
7491:   }
7492:   SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Label %" PetscInt_FMT " does not exist in this DM", n);
7493: }

7495: /*@
7496:   DMAddLabel - Add the label to this `DM`

7498:   Not Collective

7500:   Input Parameters:
7501: + dm    - The `DM` object
7502: - label - The `DMLabel`

7504:   Level: developer

7506: .seealso: [](ch_dmbase), `DM`, `DMLabel`, `DMCreateLabel()`, `DMHasLabel()`, `DMGetLabelValue()`, `DMSetLabelValue()`, `DMGetStratumIS()`
7507: @*/
7508: PetscErrorCode DMAddLabel(DM dm, DMLabel label)
7509: {
7510:   DMLabelLink l, *p, tmpLabel;
7511:   PetscBool   hasLabel;
7512:   const char *lname;
7513:   PetscBool   flg;

7515:   PetscFunctionBegin;
7517:   PetscCall(PetscObjectGetName((PetscObject)label, &lname));
7518:   PetscCall(DMHasLabel(dm, lname, &hasLabel));
7519:   PetscCheck(!hasLabel, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Label %s already exists in this DM", lname);
7520:   PetscCall(PetscCalloc1(1, &tmpLabel));
7521:   tmpLabel->label  = label;
7522:   tmpLabel->output = PETSC_TRUE;
7523:   for (p = &dm->labels; (l = *p); p = &l->next) { }
7524:   *p = tmpLabel;
7525:   PetscCall(PetscObjectReference((PetscObject)label));
7526:   PetscCall(PetscStrcmp(lname, "depth", &flg));
7527:   if (flg) dm->depthLabel = label;
7528:   PetscCall(PetscStrcmp(lname, "celltype", &flg));
7529:   if (flg) dm->celltypeLabel = label;
7530:   PetscFunctionReturn(PETSC_SUCCESS);
7531: }

7533: // PetscClangLinter pragma ignore: -fdoc-section-header-unknown
7534: /*@
7535:   DMSetLabel - Replaces the label of a given name, or ignores it if the name is not present

7537:   Not Collective

7539:   Input Parameters:
7540: + dm    - The `DM` object
7541: - label - The `DMLabel`, having the same name, to substitute

7543:   Default labels in a `DMPLEX`:
7544: + "depth"       - Holds the depth (co-dimension) of each mesh point
7545: . "celltype"    - Holds the topological type of each cell
7546: . "ghost"       - If the DM is distributed with overlap, this marks the cells and faces in the overlap
7547: . "Cell Sets"   - Mirrors the cell sets defined by GMsh and ExodusII
7548: . "Face Sets"   - Mirrors the face sets defined by GMsh and ExodusII
7549: - "Vertex Sets" - Mirrors the vertex sets defined by GMsh

7551:   Level: intermediate

7553: .seealso: [](ch_dmbase), `DM`, `DMLabel`, `DMCreateLabel()`, `DMHasLabel()`, `DMPlexGetDepthLabel()`, `DMPlexGetCellType()`
7554: @*/
7555: PetscErrorCode DMSetLabel(DM dm, DMLabel label)
7556: {
7557:   DMLabelLink next = dm->labels;
7558:   PetscBool   hasLabel, flg;
7559:   const char *name, *lname;

7561:   PetscFunctionBegin;
7564:   PetscCall(PetscObjectGetName((PetscObject)label, &name));
7565:   while (next) {
7566:     PetscCall(PetscObjectGetName((PetscObject)next->label, &lname));
7567:     PetscCall(PetscStrcmp(name, lname, &hasLabel));
7568:     if (hasLabel) {
7569:       PetscCall(PetscObjectReference((PetscObject)label));
7570:       PetscCall(PetscStrcmp(lname, "depth", &flg));
7571:       if (flg) dm->depthLabel = label;
7572:       PetscCall(PetscStrcmp(lname, "celltype", &flg));
7573:       if (flg) dm->celltypeLabel = label;
7574:       PetscCall(DMLabelDestroy(&next->label));
7575:       next->label = label;
7576:       break;
7577:     }
7578:     next = next->next;
7579:   }
7580:   PetscFunctionReturn(PETSC_SUCCESS);
7581: }

7583: /*@
7584:   DMRemoveLabel - Remove the label given by name from this `DM`

7586:   Not Collective

7588:   Input Parameters:
7589: + dm   - The `DM` object
7590: - name - The label name

7592:   Output Parameter:
7593: . label - The `DMLabel`, or `NULL` if the label is absent. Pass in `NULL` to call `DMLabelDestroy()` on the label, otherwise the
7594:           caller is responsible for calling `DMLabelDestroy()`.

7596:   Level: developer

7598: .seealso: [](ch_dmbase), `DM`, `DMLabel`, `DMCreateLabel()`, `DMHasLabel()`, `DMGetLabel()`, `DMGetLabelValue()`, `DMSetLabelValue()`, `DMLabelDestroy()`, `DMRemoveLabelBySelf()`
7599: @*/
7600: PetscErrorCode DMRemoveLabel(DM dm, const char name[], DMLabel *label)
7601: {
7602:   DMLabelLink link, *pnext;
7603:   PetscBool   hasLabel;
7604:   const char *lname;

7606:   PetscFunctionBegin;
7608:   PetscAssertPointer(name, 2);
7609:   if (label) {
7610:     PetscAssertPointer(label, 3);
7611:     *label = NULL;
7612:   }
7613:   for (pnext = &dm->labels; (link = *pnext); pnext = &link->next) {
7614:     PetscCall(PetscObjectGetName((PetscObject)link->label, &lname));
7615:     PetscCall(PetscStrcmp(name, lname, &hasLabel));
7616:     if (hasLabel) {
7617:       *pnext = link->next; /* Remove from list */
7618:       PetscCall(PetscStrcmp(name, "depth", &hasLabel));
7619:       if (hasLabel) dm->depthLabel = NULL;
7620:       PetscCall(PetscStrcmp(name, "celltype", &hasLabel));
7621:       if (hasLabel) dm->celltypeLabel = NULL;
7622:       if (label) *label = link->label;
7623:       else PetscCall(DMLabelDestroy(&link->label));
7624:       PetscCall(PetscFree(link));
7625:       break;
7626:     }
7627:   }
7628:   PetscFunctionReturn(PETSC_SUCCESS);
7629: }

7631: /*@
7632:   DMRemoveLabelBySelf - Remove the label from this `DM`

7634:   Not Collective

7636:   Input Parameters:
7637: + dm           - The `DM` object
7638: . label        - The `DMLabel` to be removed from the `DM`
7639: - failNotFound - Should it fail if the label is not found in the `DM`?

7641:   Level: developer

7643:   Note:
7644:   Only exactly the same instance is removed if found, name match is ignored.
7645:   If the `DM` has an exclusive reference to the label, the label gets destroyed and
7646:   *label nullified.

7648: .seealso: [](ch_dmbase), `DM`, `DMLabel`, `DMCreateLabel()`, `DMHasLabel()`, `DMGetLabel()`, `DMGetLabelValue()`, `DMSetLabelValue()`, `DMLabelDestroy()`, `DMRemoveLabel()`
7649: @*/
7650: PetscErrorCode DMRemoveLabelBySelf(DM dm, DMLabel *label, PetscBool failNotFound)
7651: {
7652:   DMLabelLink link, *pnext;
7653:   PetscBool   hasLabel = PETSC_FALSE;

7655:   PetscFunctionBegin;
7657:   PetscAssertPointer(label, 2);
7658:   if (!*label && !failNotFound) PetscFunctionReturn(PETSC_SUCCESS);
7661:   for (pnext = &dm->labels; (link = *pnext); pnext = &link->next) {
7662:     if (*label == link->label) {
7663:       hasLabel = PETSC_TRUE;
7664:       *pnext   = link->next; /* Remove from list */
7665:       if (*label == dm->depthLabel) dm->depthLabel = NULL;
7666:       if (*label == dm->celltypeLabel) dm->celltypeLabel = NULL;
7667:       if (((PetscObject)link->label)->refct < 2) *label = NULL; /* nullify if exclusive reference */
7668:       PetscCall(DMLabelDestroy(&link->label));
7669:       PetscCall(PetscFree(link));
7670:       break;
7671:     }
7672:   }
7673:   PetscCheck(hasLabel || !failNotFound, PetscObjectComm((PetscObject)dm), PETSC_ERR_ARG_WRONG, "Given label not found in DM");
7674:   PetscFunctionReturn(PETSC_SUCCESS);
7675: }

7677: /*@
7678:   DMGetLabelOutput - Get the output flag for a given label

7680:   Not Collective

7682:   Input Parameters:
7683: + dm   - The `DM` object
7684: - name - The label name

7686:   Output Parameter:
7687: . output - The flag for output

7689:   Level: developer

7691: .seealso: [](ch_dmbase), `DM`, `DMLabel`, `DMSetLabelOutput()`, `DMCreateLabel()`, `DMHasLabel()`, `DMGetLabelValue()`, `DMSetLabelValue()`, `DMGetStratumIS()`
7692: @*/
7693: PetscErrorCode DMGetLabelOutput(DM dm, const char name[], PetscBool *output)
7694: {
7695:   DMLabelLink next = dm->labels;
7696:   const char *lname;

7698:   PetscFunctionBegin;
7700:   PetscAssertPointer(name, 2);
7701:   PetscAssertPointer(output, 3);
7702:   while (next) {
7703:     PetscBool flg;

7705:     PetscCall(PetscObjectGetName((PetscObject)next->label, &lname));
7706:     PetscCall(PetscStrcmp(name, lname, &flg));
7707:     if (flg) {
7708:       *output = next->output;
7709:       PetscFunctionReturn(PETSC_SUCCESS);
7710:     }
7711:     next = next->next;
7712:   }
7713:   SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "No label named %s was present in this dm", name);
7714: }

7716: /*@
7717:   DMSetLabelOutput - Set if a given label should be saved to a `PetscViewer` in calls to `DMView()`

7719:   Not Collective

7721:   Input Parameters:
7722: + dm     - The `DM` object
7723: . name   - The label name
7724: - output - `PETSC_TRUE` to save the label to the viewer

7726:   Level: developer

7728: .seealso: [](ch_dmbase), `DM`, `DMLabel`, `DMGetOutputFlag()`, `DMGetLabelOutput()`, `DMCreateLabel()`, `DMHasLabel()`, `DMGetLabelValue()`, `DMSetLabelValue()`, `DMGetStratumIS()`
7729: @*/
7730: PetscErrorCode DMSetLabelOutput(DM dm, const char name[], PetscBool output)
7731: {
7732:   DMLabelLink next = dm->labels;
7733:   const char *lname;

7735:   PetscFunctionBegin;
7737:   PetscAssertPointer(name, 2);
7738:   while (next) {
7739:     PetscBool flg;

7741:     PetscCall(PetscObjectGetName((PetscObject)next->label, &lname));
7742:     PetscCall(PetscStrcmp(name, lname, &flg));
7743:     if (flg) {
7744:       next->output = output;
7745:       PetscFunctionReturn(PETSC_SUCCESS);
7746:     }
7747:     next = next->next;
7748:   }
7749:   SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "No label named %s was present in this dm", name);
7750: }

7752: /*@
7753:   DMCopyLabels - Copy labels from one `DM` mesh to another `DM` with a superset of the points

7755:   Collective

7757:   Input Parameters:
7758: + dmA   - The `DM` object with initial labels
7759: . dmB   - The `DM` object to which labels are copied
7760: . mode  - Copy labels by pointers (`PETSC_OWN_POINTER`) or duplicate them (`PETSC_COPY_VALUES`)
7761: . all   - Copy all labels including "depth", "dim", and "celltype" (`PETSC_TRUE`) which are otherwise ignored (`PETSC_FALSE`)
7762: - emode - How to behave when a `DMLabel` in the source and destination `DM`s with the same name is encountered (see `DMCopyLabelsMode`)

7764:   Level: intermediate

7766:   Note:
7767:   This is typically used when interpolating or otherwise adding to a mesh, or testing.

7769: .seealso: [](ch_dmbase), `DM`, `DMLabel`, `DMAddLabel()`, `DMCopyLabelsMode`
7770: @*/
7771: PetscErrorCode DMCopyLabels(DM dmA, DM dmB, PetscCopyMode mode, PetscBool all, DMCopyLabelsMode emode)
7772: {
7773:   DMLabel     label, labelNew, labelOld;
7774:   const char *name;
7775:   PetscBool   flg;
7776:   DMLabelLink link;

7778:   PetscFunctionBegin;
7783:   PetscCheck(mode != PETSC_USE_POINTER, PetscObjectComm((PetscObject)dmA), PETSC_ERR_SUP, "PETSC_USE_POINTER not supported for objects");
7784:   if (dmA == dmB) PetscFunctionReturn(PETSC_SUCCESS);
7785:   for (link = dmA->labels; link; link = link->next) {
7786:     label = link->label;
7787:     PetscCall(PetscObjectGetName((PetscObject)label, &name));
7788:     if (!all) {
7789:       PetscCall(PetscStrcmp(name, "depth", &flg));
7790:       if (flg) continue;
7791:       PetscCall(PetscStrcmp(name, "dim", &flg));
7792:       if (flg) continue;
7793:       PetscCall(PetscStrcmp(name, "celltype", &flg));
7794:       if (flg) continue;
7795:     }
7796:     PetscCall(DMGetLabel(dmB, name, &labelOld));
7797:     if (labelOld) {
7798:       switch (emode) {
7799:       case DM_COPY_LABELS_KEEP:
7800:         continue;
7801:       case DM_COPY_LABELS_REPLACE:
7802:         PetscCall(DMRemoveLabelBySelf(dmB, &labelOld, PETSC_TRUE));
7803:         break;
7804:       case DM_COPY_LABELS_FAIL:
7805:         SETERRQ(PetscObjectComm((PetscObject)dmA), PETSC_ERR_ARG_OUTOFRANGE, "Label %s already exists in destination DM", name);
7806:       default:
7807:         SETERRQ(PetscObjectComm((PetscObject)dmA), PETSC_ERR_ARG_OUTOFRANGE, "Unhandled DMCopyLabelsMode %d", (int)emode);
7808:       }
7809:     }
7810:     if (mode == PETSC_COPY_VALUES) PetscCall(DMLabelDuplicate(label, &labelNew));
7811:     else labelNew = label;
7812:     PetscCall(DMAddLabel(dmB, labelNew));
7813:     if (mode == PETSC_COPY_VALUES) PetscCall(DMLabelDestroy(&labelNew));
7814:   }
7815:   PetscFunctionReturn(PETSC_SUCCESS);
7816: }

7818: /*@
7819:   DMCompareLabels - Compare labels between two `DM` objects

7821:   Collective; No Fortran Support

7823:   Input Parameters:
7824: + dm0 - First `DM` object
7825: - dm1 - Second `DM` object

7827:   Output Parameters:
7828: + equal   - (Optional) Flag whether labels of `dm0` and `dm1` are the same
7829: - message - (Optional) Message describing the difference, or `NULL` if there is no difference

7831:   Level: intermediate

7833:   Notes:
7834:   The output flag equal will be the same on all processes.

7836:   If equal is passed as `NULL` and difference is found, an error is thrown on all processes.

7838:   Make sure to pass equal is `NULL` on all processes or none of them.

7840:   The output message is set independently on each rank.

7842:   message must be freed with `PetscFree()`

7844:   If message is passed as `NULL` and a difference is found, the difference description is printed to `stderr` in synchronized manner.

7846:   Make sure to pass message as `NULL` on all processes or no processes.

7848:   Labels are matched by name. If the number of labels and their names are equal,
7849:   `DMLabelCompare()` is used to compare each pair of labels with the same name.

7851:   Developer Note:
7852:   Cannot automatically generate the Fortran stub because `message` must be freed with `PetscFree()`

7854: .seealso: [](ch_dmbase), `DM`, `DMLabel`, `DMAddLabel()`, `DMCopyLabelsMode`, `DMLabelCompare()`
7855: @*/
7856: PetscErrorCode DMCompareLabels(DM dm0, DM dm1, PetscBool *equal, char *message[]) PeNS
7857: {
7858:   PetscInt    n;
7859:   char        msg[PETSC_MAX_PATH_LEN] = "";
7860:   PetscBool   eq;
7861:   MPI_Comm    comm;
7862:   PetscMPIInt rank;

7864:   PetscFunctionBegin;
7867:   PetscCheckSameComm(dm0, 1, dm1, 2);
7868:   if (equal) PetscAssertPointer(equal, 3);
7869:   if (message) PetscAssertPointer(message, 4);
7870:   PetscCall(PetscObjectGetComm((PetscObject)dm0, &comm));
7871:   PetscCallMPI(MPI_Comm_rank(comm, &rank));
7872:   {
7873:     PetscInt n1;

7875:     PetscCall(DMGetNumLabels(dm0, &n));
7876:     PetscCall(DMGetNumLabels(dm1, &n1));
7877:     eq = (PetscBool)(n == n1);
7878:     if (!eq) PetscCall(PetscSNPrintf(msg, sizeof(msg), "Number of labels in dm0 = %" PetscInt_FMT " != %" PetscInt_FMT " = Number of labels in dm1", n, n1));
7879:     PetscCallMPI(MPIU_Allreduce(MPI_IN_PLACE, &eq, 1, MPI_C_BOOL, MPI_LAND, comm));
7880:     if (!eq) goto finish;
7881:   }
7882:   for (PetscInt i = 0; i < n; i++) {
7883:     DMLabel     l0, l1;
7884:     const char *name;
7885:     char       *msgInner;

7887:     /* Ignore label order */
7888:     PetscCall(DMGetLabelByNum(dm0, i, &l0));
7889:     PetscCall(PetscObjectGetName((PetscObject)l0, &name));
7890:     PetscCall(DMGetLabel(dm1, name, &l1));
7891:     if (!l1) {
7892:       PetscCall(PetscSNPrintf(msg, sizeof(msg), "Label \"%s\" (#%" PetscInt_FMT " in dm0) not found in dm1", name, i));
7893:       eq = PETSC_FALSE;
7894:       break;
7895:     }
7896:     PetscCall(DMLabelCompare(comm, l0, l1, &eq, &msgInner));
7897:     PetscCall(PetscStrncpy(msg, msgInner, sizeof(msg)));
7898:     PetscCall(PetscFree(msgInner));
7899:     if (!eq) break;
7900:   }
7901:   PetscCallMPI(MPIU_Allreduce(MPI_IN_PLACE, &eq, 1, MPI_C_BOOL, MPI_LAND, comm));
7902: finish:
7903:   /* If message output arg not set, print to stderr */
7904:   if (message) {
7905:     *message = NULL;
7906:     if (msg[0]) PetscCall(PetscStrallocpy(msg, message));
7907:   } else {
7908:     if (msg[0]) PetscCall(PetscSynchronizedFPrintf(comm, PETSC_STDERR, "[%d] %s\n", rank, msg));
7909:     PetscCall(PetscSynchronizedFlush(comm, PETSC_STDERR));
7910:   }
7911:   /* If same output arg not ser and labels are not equal, throw error */
7912:   if (equal) *equal = eq;
7913:   else PetscCheck(eq, comm, PETSC_ERR_ARG_INCOMP, "DMLabels are not the same in dm0 and dm1");
7914:   PetscFunctionReturn(PETSC_SUCCESS);
7915: }

7917: PetscErrorCode DMSetLabelValue_Fast(DM dm, DMLabel *label, const char name[], PetscInt point, PetscInt value)
7918: {
7919:   PetscFunctionBegin;
7920:   PetscAssertPointer(label, 2);
7921:   if (!*label) {
7922:     PetscCall(DMCreateLabel(dm, name));
7923:     PetscCall(DMGetLabel(dm, name, label));
7924:   }
7925:   PetscCall(DMLabelSetValue(*label, point, value));
7926:   PetscFunctionReturn(PETSC_SUCCESS);
7927: }

7929: /*
7930:   Many mesh programs, such as Triangle and TetGen, allow only a single label for each mesh point. Therefore, we would
7931:   like to encode all label IDs using a single, universal label. We can do this by assigning an integer to every
7932:   (label, id) pair in the DM.

7934:   However, a mesh point can have multiple labels, so we must separate all these values. We will assign a bit range to
7935:   each label.
7936: */
7937: PetscErrorCode DMUniversalLabelCreate(DM dm, DMUniversalLabel *universal)
7938: {
7939:   DMUniversalLabel ul;
7940:   PetscBool       *active;
7941:   PetscInt         pStart, pEnd, p, Nl, l, m;

7943:   PetscFunctionBegin;
7944:   PetscCall(PetscMalloc1(1, &ul));
7945:   PetscCall(DMLabelCreate(PETSC_COMM_SELF, "universal", &ul->label));
7946:   PetscCall(DMGetNumLabels(dm, &Nl));
7947:   PetscCall(PetscCalloc1(Nl, &active));
7948:   ul->Nl = 0;
7949:   for (l = 0; l < Nl; ++l) {
7950:     PetscBool   isdepth, iscelltype;
7951:     const char *name;

7953:     PetscCall(DMGetLabelName(dm, l, &name));
7954:     PetscCall(PetscStrncmp(name, "depth", 6, &isdepth));
7955:     PetscCall(PetscStrncmp(name, "celltype", 9, &iscelltype));
7956:     active[l] = !(isdepth || iscelltype) ? PETSC_TRUE : PETSC_FALSE;
7957:     if (active[l]) ++ul->Nl;
7958:   }
7959:   PetscCall(PetscCalloc5(ul->Nl, &ul->names, ul->Nl, &ul->indices, ul->Nl + 1, &ul->offsets, ul->Nl + 1, &ul->bits, ul->Nl, &ul->masks));
7960:   ul->Nv = 0;
7961:   for (l = 0, m = 0; l < Nl; ++l) {
7962:     DMLabel     label;
7963:     PetscInt    nv;
7964:     const char *name;

7966:     if (!active[l]) continue;
7967:     PetscCall(DMGetLabelName(dm, l, &name));
7968:     PetscCall(DMGetLabelByNum(dm, l, &label));
7969:     PetscCall(DMLabelGetNumValues(label, &nv));
7970:     PetscCall(PetscStrallocpy(name, &ul->names[m]));
7971:     ul->indices[m] = l;
7972:     ul->Nv += nv;
7973:     ul->offsets[m + 1] = nv;
7974:     ul->bits[m + 1]    = PetscCeilReal(PetscLog2Real(nv + 1));
7975:     ++m;
7976:   }
7977:   for (l = 1; l <= ul->Nl; ++l) {
7978:     ul->offsets[l] = ul->offsets[l - 1] + ul->offsets[l];
7979:     ul->bits[l]    = ul->bits[l - 1] + ul->bits[l];
7980:   }
7981:   for (l = 0; l < ul->Nl; ++l) {
7982:     ul->masks[l] = 0;
7983:     for (PetscInt b = ul->bits[l]; b < ul->bits[l + 1]; ++b) ul->masks[l] |= 1 << b;
7984:   }
7985:   PetscCall(PetscMalloc1(ul->Nv, &ul->values));
7986:   for (l = 0, m = 0; l < Nl; ++l) {
7987:     DMLabel         label;
7988:     IS              valueIS;
7989:     const PetscInt *varr;
7990:     PetscInt        nv;

7992:     if (!active[l]) continue;
7993:     PetscCall(DMGetLabelByNum(dm, l, &label));
7994:     PetscCall(DMLabelGetNumValues(label, &nv));
7995:     PetscCall(DMLabelGetValueIS(label, &valueIS));
7996:     PetscCall(ISGetIndices(valueIS, &varr));
7997:     for (PetscInt v = 0; v < nv; ++v) ul->values[ul->offsets[m] + v] = varr[v];
7998:     PetscCall(ISRestoreIndices(valueIS, &varr));
7999:     PetscCall(ISDestroy(&valueIS));
8000:     PetscCall(PetscSortInt(nv, &ul->values[ul->offsets[m]]));
8001:     ++m;
8002:   }
8003:   PetscCall(DMPlexGetChart(dm, &pStart, &pEnd));
8004:   for (p = pStart; p < pEnd; ++p) {
8005:     PetscInt  uval   = 0;
8006:     PetscBool marked = PETSC_FALSE;

8008:     for (l = 0, m = 0; l < Nl; ++l) {
8009:       DMLabel  label;
8010:       PetscInt val, defval, loc, nv;

8012:       if (!active[l]) continue;
8013:       PetscCall(DMGetLabelByNum(dm, l, &label));
8014:       PetscCall(DMLabelGetValue(label, p, &val));
8015:       PetscCall(DMLabelGetDefaultValue(label, &defval));
8016:       if (val == defval) {
8017:         ++m;
8018:         continue;
8019:       }
8020:       nv     = ul->offsets[m + 1] - ul->offsets[m];
8021:       marked = PETSC_TRUE;
8022:       PetscCall(PetscFindInt(val, nv, &ul->values[ul->offsets[m]], &loc));
8023:       PetscCheck(loc >= 0, PETSC_COMM_SELF, PETSC_ERR_PLIB, "Label value %" PetscInt_FMT " not found in compression array", val);
8024:       uval += (loc + 1) << ul->bits[m];
8025:       ++m;
8026:     }
8027:     if (marked) PetscCall(DMLabelSetValue(ul->label, p, uval));
8028:   }
8029:   PetscCall(PetscFree(active));
8030:   *universal = ul;
8031:   PetscFunctionReturn(PETSC_SUCCESS);
8032: }

8034: PetscErrorCode DMUniversalLabelDestroy(DMUniversalLabel *universal)
8035: {
8036:   PetscInt l;

8038:   PetscFunctionBegin;
8039:   for (l = 0; l < (*universal)->Nl; ++l) PetscCall(PetscFree((*universal)->names[l]));
8040:   PetscCall(DMLabelDestroy(&(*universal)->label));
8041:   PetscCall(PetscFree5((*universal)->names, (*universal)->indices, (*universal)->offsets, (*universal)->bits, (*universal)->masks));
8042:   PetscCall(PetscFree((*universal)->values));
8043:   PetscCall(PetscFree(*universal));
8044:   PetscFunctionReturn(PETSC_SUCCESS);
8045: }

8047: PetscErrorCode DMUniversalLabelGetLabel(DMUniversalLabel ul, DMLabel *ulabel)
8048: {
8049:   PetscFunctionBegin;
8050:   PetscAssertPointer(ulabel, 2);
8051:   *ulabel = ul->label;
8052:   PetscFunctionReturn(PETSC_SUCCESS);
8053: }

8055: PetscErrorCode DMUniversalLabelCreateLabels(DMUniversalLabel ul, PetscBool preserveOrder, DM dm)
8056: {
8057:   PetscInt Nl = ul->Nl, l;

8059:   PetscFunctionBegin;
8061:   for (l = 0; l < Nl; ++l) {
8062:     if (preserveOrder) PetscCall(DMCreateLabelAtIndex(dm, ul->indices[l], ul->names[l]));
8063:     else PetscCall(DMCreateLabel(dm, ul->names[l]));
8064:   }
8065:   if (preserveOrder) {
8066:     for (l = 0; l < ul->Nl; ++l) {
8067:       const char *name;
8068:       PetscBool   match;

8070:       PetscCall(DMGetLabelName(dm, ul->indices[l], &name));
8071:       PetscCall(PetscStrcmp(name, ul->names[l], &match));
8072:       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]);
8073:     }
8074:   }
8075:   PetscFunctionReturn(PETSC_SUCCESS);
8076: }

8078: PetscErrorCode DMUniversalLabelSetLabelValue(DMUniversalLabel ul, DM dm, PetscBool useIndex, PetscInt p, PetscInt value)
8079: {
8080:   PetscFunctionBegin;
8081:   for (PetscInt l = 0; l < ul->Nl; ++l) {
8082:     DMLabel  label;
8083:     PetscInt lval = (value & ul->masks[l]) >> ul->bits[l];

8085:     if (lval) {
8086:       if (useIndex) PetscCall(DMGetLabelByNum(dm, ul->indices[l], &label));
8087:       else PetscCall(DMGetLabel(dm, ul->names[l], &label));
8088:       PetscCall(DMLabelSetValue(label, p, ul->values[ul->offsets[l] + lval - 1]));
8089:     }
8090:   }
8091:   PetscFunctionReturn(PETSC_SUCCESS);
8092: }

8094: /*@
8095:   DMGetCoarseDM - Get the coarse `DM`from which this `DM` was obtained by refinement

8097:   Not Collective

8099:   Input Parameter:
8100: . dm - The `DM` object

8102:   Output Parameter:
8103: . cdm - The coarse `DM`

8105:   Level: intermediate

8107: .seealso: [](ch_dmbase), `DM`, `DMSetCoarseDM()`, `DMCoarsen()`
8108: @*/
8109: PetscErrorCode DMGetCoarseDM(DM dm, DM *cdm)
8110: {
8111:   PetscFunctionBegin;
8113:   PetscAssertPointer(cdm, 2);
8114:   *cdm = dm->coarseMesh;
8115:   PetscFunctionReturn(PETSC_SUCCESS);
8116: }

8118: /*@
8119:   DMSetCoarseDM - Set the coarse `DM` from which this `DM` was obtained by refinement

8121:   Input Parameters:
8122: + dm  - The `DM` object
8123: - cdm - The coarse `DM`

8125:   Level: intermediate

8127:   Note:
8128:   Normally this is set automatically by `DMRefine()`

8130: .seealso: [](ch_dmbase), `DM`, `DMGetCoarseDM()`, `DMCoarsen()`, `DMSetRefine()`, `DMSetFineDM()`
8131: @*/
8132: PetscErrorCode DMSetCoarseDM(DM dm, DM cdm)
8133: {
8134:   PetscFunctionBegin;
8137:   if (dm == cdm) cdm = NULL;
8138:   PetscCall(PetscObjectReference((PetscObject)cdm));
8139:   PetscCall(DMDestroy(&dm->coarseMesh));
8140:   dm->coarseMesh = cdm;
8141:   PetscFunctionReturn(PETSC_SUCCESS);
8142: }

8144: /*@
8145:   DMGetFineDM - Get the fine mesh from which this `DM` was obtained by coarsening

8147:   Input Parameter:
8148: . dm - The `DM` object

8150:   Output Parameter:
8151: . fdm - The fine `DM`

8153:   Level: intermediate

8155: .seealso: [](ch_dmbase), `DM`, `DMSetFineDM()`, `DMCoarsen()`, `DMRefine()`
8156: @*/
8157: PetscErrorCode DMGetFineDM(DM dm, DM *fdm)
8158: {
8159:   PetscFunctionBegin;
8161:   PetscAssertPointer(fdm, 2);
8162:   *fdm = dm->fineMesh;
8163:   PetscFunctionReturn(PETSC_SUCCESS);
8164: }

8166: /*@
8167:   DMSetFineDM - Set the fine mesh from which this was obtained by coarsening

8169:   Input Parameters:
8170: + dm  - The `DM` object
8171: - fdm - The fine `DM`

8173:   Level: developer

8175:   Note:
8176:   Normally this is set automatically by `DMCoarsen()`

8178: .seealso: [](ch_dmbase), `DM`, `DMGetFineDM()`, `DMCoarsen()`, `DMRefine()`
8179: @*/
8180: PetscErrorCode DMSetFineDM(DM dm, DM fdm)
8181: {
8182:   PetscFunctionBegin;
8185:   if (dm == fdm) fdm = NULL;
8186:   PetscCall(PetscObjectReference((PetscObject)fdm));
8187:   PetscCall(DMDestroy(&dm->fineMesh));
8188:   dm->fineMesh = fdm;
8189:   PetscFunctionReturn(PETSC_SUCCESS);
8190: }

8192: /*@
8193:   DMAddBoundary - Add a boundary condition, for a single field, to a model represented by a `DM`

8195:   Collective

8197:   Input Parameters:
8198: + dm       - The `DM`, with a `PetscDS` that matches the problem being constrained
8199: . type     - The type of condition, e.g. `DM_BC_ESSENTIAL_ANALYTIC`, `DM_BC_ESSENTIAL_FIELD` (Dirichlet), or `DM_BC_NATURAL` (Neumann)
8200: . name     - The BC name
8201: . label    - The label defining constrained points
8202: . Nv       - The number of `DMLabel` values for constrained points
8203: . values   - An array of values for constrained points
8204: . field    - The field to constrain
8205: . Nc       - The number of constrained field components (0 will constrain all components)
8206: . comps    - An array of constrained component numbers
8207: . bcFunc   - A pointwise function giving boundary values
8208: . bcFunc_t - A pointwise function giving the time derivative of the boundary values, or `NULL`
8209: - ctx      - An optional application context for `bcFunc`

8211:   Output Parameter:
8212: . bd - (Optional) Boundary number

8214:   Options Database Keys:
8215: + -bc_NAME values     - Overrides the boundary ids for boundary named NAME
8216: - -bc_NAME_comp comps - Overrides the boundary components for boundary named NAME

8218:   Level: intermediate

8220:   Notes:
8221:   If the `DM` is of type `DMPLEX` and the field is of type `PetscFE`, then this function completes the label using `DMPlexLabelComplete()`.

8223:   Both bcFunc and bcFunc_t will depend on the boundary condition type. If the type if `DM_BC_ESSENTIAL`, then the calling sequence is\:
8224: .vb
8225:  void bcFunc(PetscInt dim, PetscReal time, const PetscReal x[], PetscInt Nc, PetscScalar bcval[])
8226: .ve

8228:   If the type is `DM_BC_ESSENTIAL_FIELD` or other _FIELD value, then the calling sequence is\:

8230: .vb
8231:   void bcFunc(PetscInt dim, PetscInt Nf, PetscInt NfAux,
8232:               const PetscInt uOff[], const PetscInt uOff_x[], const PetscScalar u[], const PetscScalar u_t[], const PetscScalar u_x[],
8233:               const PetscInt aOff[], const PetscInt aOff_x[], const PetscScalar a[], const PetscScalar a_t[], const PetscScalar a_x[],
8234:               PetscReal time, const PetscReal x[], PetscScalar bcval[])
8235: .ve
8236: + dim - the spatial dimension
8237: . Nf - the number of fields
8238: . uOff - the offset into u[] and u_t[] for each field
8239: . uOff_x - the offset into u_x[] for each field
8240: . u - each field evaluated at the current point
8241: . u_t - the time derivative of each field evaluated at the current point
8242: . u_x - the gradient of each field evaluated at the current point
8243: . aOff - the offset into a[] and a_t[] for each auxiliary field
8244: . aOff_x - the offset into a_x[] for each auxiliary field
8245: . a - each auxiliary field evaluated at the current point
8246: . a_t - the time derivative of each auxiliary field evaluated at the current point
8247: . a_x - the gradient of auxiliary each field evaluated at the current point
8248: . t - current time
8249: . x - coordinates of the current point
8250: . numConstants - number of constant parameters
8251: . constants - constant parameters
8252: - bcval - output values at the current point

8254: .seealso: [](ch_dmbase), `DM`, `DSGetBoundary()`, `PetscDSAddBoundary()`
8255: @*/
8256: 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)
8257: {
8258:   PetscDS ds;

8260:   PetscFunctionBegin;
8267:   PetscCheck(!dm->localSection, PetscObjectComm((PetscObject)dm), PETSC_ERR_ARG_WRONGSTATE, "Cannot add boundary to DM after creating local section");
8268:   PetscCall(DMGetDS(dm, &ds));
8269:   /* Complete label */
8270:   if (label) {
8271:     PetscObject  obj;
8272:     PetscClassId id;

8274:     PetscCall(DMGetField(dm, field, NULL, &obj));
8275:     PetscCall(PetscObjectGetClassId(obj, &id));
8276:     if (id == PETSCFE_CLASSID) {
8277:       DM plex;

8279:       PetscCall(DMConvert(dm, DMPLEX, &plex));
8280:       if (plex) PetscCall(DMPlexLabelComplete(plex, label));
8281:       PetscCall(DMDestroy(&plex));
8282:     }
8283:   }
8284:   PetscCall(PetscDSAddBoundary(ds, type, name, label, Nv, values, field, Nc, comps, bcFunc, bcFunc_t, ctx, bd));
8285:   PetscFunctionReturn(PETSC_SUCCESS);
8286: }

8288: /* TODO Remove this since now the structures are the same */
8289: static PetscErrorCode DMPopulateBoundary(DM dm)
8290: {
8291:   PetscDS     ds;
8292:   DMBoundary *lastnext;
8293:   DSBoundary  dsbound;

8295:   PetscFunctionBegin;
8296:   PetscCall(DMGetDS(dm, &ds));
8297:   dsbound = ds->boundary;
8298:   if (dm->boundary) {
8299:     DMBoundary next = dm->boundary;

8301:     /* quick check to see if the PetscDS has changed */
8302:     if (next->dsboundary == dsbound) PetscFunctionReturn(PETSC_SUCCESS);
8303:     /* the PetscDS has changed: tear down and rebuild */
8304:     while (next) {
8305:       DMBoundary b = next;

8307:       next = b->next;
8308:       PetscCall(PetscFree(b));
8309:     }
8310:     dm->boundary = NULL;
8311:   }

8313:   lastnext = &dm->boundary;
8314:   while (dsbound) {
8315:     DMBoundary dmbound;

8317:     PetscCall(PetscNew(&dmbound));
8318:     dmbound->dsboundary = dsbound;
8319:     dmbound->label      = dsbound->label;
8320:     /* push on the back instead of the front so that it is in the same order as in the PetscDS */
8321:     *lastnext = dmbound;
8322:     lastnext  = &dmbound->next;
8323:     dsbound   = dsbound->next;
8324:   }
8325:   PetscFunctionReturn(PETSC_SUCCESS);
8326: }

8328: /*@
8329:   DMIsBoundaryPoint - Determine whether a mesh point lies on a `DM` boundary

8331:   Not Collective

8333:   Input Parameters:
8334: + dm    - the `DM` object
8335: - point - the mesh point number

8337:   Output Parameter:
8338: . isBd - `PETSC_TRUE` if `point` belongs to any boundary label registered on the `DM`

8340:   Level: developer

8342: .seealso: [](ch_dmbase), `DM`, `DMLabel`, `DMAddBoundary()`, `PetscDSGetBoundary()`
8343: @*/
8344: PetscErrorCode DMIsBoundaryPoint(DM dm, PetscInt point, PetscBool *isBd)
8345: {
8346:   DMBoundary b;

8348:   PetscFunctionBegin;
8350:   PetscAssertPointer(isBd, 3);
8351:   *isBd = PETSC_FALSE;
8352:   PetscCall(DMPopulateBoundary(dm));
8353:   b = dm->boundary;
8354:   while (b && !*isBd) {
8355:     DMLabel    label = b->label;
8356:     DSBoundary dsb   = b->dsboundary;

8358:     if (label) {
8359:       for (PetscInt i = 0; i < dsb->Nv && !*isBd; ++i) PetscCall(DMLabelStratumHasPoint(label, dsb->values[i], point, isBd));
8360:     }
8361:     b = b->next;
8362:   }
8363:   PetscFunctionReturn(PETSC_SUCCESS);
8364: }

8366: /*@
8367:   DMHasBound - Determine whether a bound condition was specified

8369:   Logically collective

8371:   Input Parameter:
8372: . dm - The `DM`, with a `PetscDS` that matches the problem being constrained

8374:   Output Parameter:
8375: . hasBound - Flag indicating if a bound condition was specified

8377:   Level: intermediate

8379: .seealso: [](ch_dmbase), `DM`, `DSAddBoundary()`, `PetscDSAddBoundary()`
8380: @*/
8381: PetscErrorCode DMHasBound(DM dm, PetscBool *hasBound)
8382: {
8383:   PetscDS  ds;
8384:   PetscInt Nf, numBd;

8386:   PetscFunctionBegin;
8387:   *hasBound = PETSC_FALSE;
8388:   PetscCall(DMGetDS(dm, &ds));
8389:   PetscCall(PetscDSGetNumFields(ds, &Nf));
8390:   for (PetscInt f = 0; f < Nf; ++f) {
8391:     PetscSimplePointFn *lfunc, *ufunc;

8393:     PetscCall(PetscDSGetLowerBound(ds, f, &lfunc, NULL));
8394:     PetscCall(PetscDSGetUpperBound(ds, f, &ufunc, NULL));
8395:     if (lfunc || ufunc) *hasBound = PETSC_TRUE;
8396:   }

8398:   PetscCall(PetscDSGetNumBoundary(ds, &numBd));
8399:   PetscCall(PetscDSUpdateBoundaryLabels(ds, dm));
8400:   for (PetscInt b = 0; b < numBd; ++b) {
8401:     PetscWeakForm           wf;
8402:     DMBoundaryConditionType type;
8403:     const char             *name;
8404:     DMLabel                 label;
8405:     PetscInt                numids;
8406:     const PetscInt         *ids;
8407:     PetscInt                field, Nc;
8408:     const PetscInt         *comps;
8409:     PetscVoidFn            *bvfunc;
8410:     void                   *ctx;

8412:     PetscCall(PetscDSGetBoundary(ds, b, &wf, &type, &name, &label, &numids, &ids, &field, &Nc, &comps, &bvfunc, NULL, &ctx));
8413:     if (type == DM_BC_LOWER_BOUND || type == DM_BC_UPPER_BOUND) *hasBound = PETSC_TRUE;
8414:   }
8415:   PetscFunctionReturn(PETSC_SUCCESS);
8416: }

8418: /*@
8419:   DMProjectFunction - This projects the given function into the function space provided by a `DM`, putting the coefficients in a global vector.

8421:   Collective

8423:   Input Parameters:
8424: + dm    - The `DM`
8425: . time  - The time
8426: . funcs - The coordinate functions to evaluate, one per field
8427: . ctxs  - Optional array of contexts to pass to each coordinate function.  ctxs itself may be null.
8428: - mode  - The insertion mode for values

8430:   Output Parameter:
8431: . X - vector

8433:   Calling sequence of `funcs`:
8434: + dim  - The spatial dimension
8435: . time - The time at which to sample
8436: . x    - The coordinates
8437: . Nc   - The number of components
8438: . u    - The output field values
8439: - ctx  - optional function context

8441:   Level: developer

8443:   Developer Notes:
8444:   This API is specific to only particular usage of `DM`

8446:   The notes need to provide some information about what has to be provided to the `DM` to be able to perform the computation.

8448: .seealso: [](ch_dmbase), `DM`, `DMProjectFunctionLocal()`, `DMProjectFunctionLabel()`, `DMComputeL2Diff()`
8449: @*/
8450: 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)
8451: {
8452:   Vec localX;

8454:   PetscFunctionBegin;
8456:   PetscCall(PetscLogEventBegin(DM_ProjectFunction, dm, X, 0, 0));
8457:   PetscCall(DMGetLocalVector(dm, &localX));
8458:   PetscCall(VecSet(localX, 0.));
8459:   PetscCall(DMProjectFunctionLocal(dm, time, funcs, ctxs, mode, localX));
8460:   PetscCall(DMLocalToGlobalBegin(dm, localX, mode, X));
8461:   PetscCall(DMLocalToGlobalEnd(dm, localX, mode, X));
8462:   PetscCall(DMRestoreLocalVector(dm, &localX));
8463:   PetscCall(PetscLogEventEnd(DM_ProjectFunction, dm, X, 0, 0));
8464:   PetscFunctionReturn(PETSC_SUCCESS);
8465: }

8467: /*@
8468:   DMProjectFunctionLocal - This projects the given function into the function space provided by a `DM`, putting the coefficients in a local vector.

8470:   Not Collective

8472:   Input Parameters:
8473: + dm    - The `DM`
8474: . time  - The time
8475: . funcs - The coordinate functions to evaluate, one per field
8476: . ctxs  - Optional array of contexts to pass to each coordinate function.  ctxs itself may be null.
8477: - mode  - The insertion mode for values

8479:   Output Parameter:
8480: . localX - vector

8482:   Calling sequence of `funcs`:
8483: + dim  - The spatial dimension
8484: . time - The current timestep
8485: . x    - The coordinates
8486: . Nc   - The number of components
8487: . u    - The output field values
8488: - ctx  - optional function context

8490:   Level: developer

8492:   Developer Notes:
8493:   This API is specific to only particular usage of `DM`

8495:   The notes need to provide some information about what has to be provided to the `DM` to be able to perform the computation.

8497: .seealso: [](ch_dmbase), `DM`, `DMProjectFunction()`, `DMProjectFunctionLabel()`, `DMComputeL2Diff()`
8498: @*/
8499: 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)
8500: {
8501:   PetscFunctionBegin;
8504:   PetscUseTypeMethod(dm, projectfunctionlocal, time, funcs, ctxs, mode, localX);
8505:   PetscFunctionReturn(PETSC_SUCCESS);
8506: }

8508: /*@
8509:   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.

8511:   Collective

8513:   Input Parameters:
8514: + dm     - The `DM`
8515: . time   - The time
8516: . numIds - The number of ids
8517: . ids    - The ids
8518: . Nc     - The number of components
8519: . comps  - The components
8520: . label  - The `DMLabel` selecting the portion of the mesh for projection
8521: . funcs  - The coordinate functions to evaluate, one per field
8522: . ctxs   - Optional array of contexts to pass to each coordinate function.  ctxs may be null.
8523: - mode   - The insertion mode for values

8525:   Output Parameter:
8526: . X - vector

8528:   Calling sequence of `funcs`:
8529: + dim  - The spatial dimension
8530: . time - The current timestep
8531: . x    - The coordinates
8532: . Nc   - The number of components
8533: . u    - The output field values
8534: - ctx  - optional function context

8536:   Level: developer

8538:   Developer Notes:
8539:   This API is specific to only particular usage of `DM`

8541:   The notes need to provide some information about what has to be provided to the `DM` to be able to perform the computation.

8543: .seealso: [](ch_dmbase), `DM`, `DMProjectFunction()`, `DMProjectFunctionLocal()`, `DMProjectFunctionLabelLocal()`, `DMComputeL2Diff()`
8544: @*/
8545: 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)
8546: {
8547:   Vec localX;

8549:   PetscFunctionBegin;
8551:   PetscCall(DMGetLocalVector(dm, &localX));
8552:   PetscCall(VecSet(localX, 0.));
8553:   PetscCall(DMProjectFunctionLabelLocal(dm, time, label, numIds, ids, Nc, comps, funcs, ctxs, mode, localX));
8554:   PetscCall(DMLocalToGlobalBegin(dm, localX, mode, X));
8555:   PetscCall(DMLocalToGlobalEnd(dm, localX, mode, X));
8556:   PetscCall(DMRestoreLocalVector(dm, &localX));
8557:   PetscFunctionReturn(PETSC_SUCCESS);
8558: }

8560: /*@
8561:   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.

8563:   Not Collective

8565:   Input Parameters:
8566: + dm     - The `DM`
8567: . time   - The time
8568: . label  - The `DMLabel` selecting the portion of the mesh for projection
8569: . numIds - The number of ids
8570: . ids    - The ids
8571: . Nc     - The number of components
8572: . comps  - The components
8573: . funcs  - The coordinate functions to evaluate, one per field
8574: . ctxs   - Optional array of contexts to pass to each coordinate function.  ctxs itself may be null.
8575: - mode   - The insertion mode for values

8577:   Output Parameter:
8578: . localX - vector

8580:   Calling sequence of `funcs`:
8581: + dim  - The spatial dimension
8582: . time - The current time
8583: . x    - The coordinates
8584: . Nc   - The number of components
8585: . u    - The output field values
8586: - ctx  - optional function context

8588:   Level: developer

8590:   Developer Notes:
8591:   This API is specific to only particular usage of `DM`

8593:   The notes need to provide some information about what has to be provided to the `DM` to be able to perform the computation.

8595: .seealso: [](ch_dmbase), `DM`, `DMProjectFunction()`, `DMProjectFunctionLocal()`, `DMProjectFunctionLabel()`, `DMComputeL2Diff()`
8596: @*/
8597: 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)
8598: {
8599:   PetscFunctionBegin;
8602:   PetscUseTypeMethod(dm, projectfunctionlabellocal, time, label, numIds, ids, Nc, comps, funcs, ctxs, mode, localX);
8603:   PetscFunctionReturn(PETSC_SUCCESS);
8604: }

8606: /*@
8607:   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.

8609:   Not Collective

8611:   Input Parameters:
8612: + dm     - The `DM`
8613: . time   - The time
8614: . localU - The input field vector; may be `NULL` if projection is defined purely by coordinates
8615: . funcs  - The functions to evaluate, one per field
8616: - mode   - The insertion mode for values

8618:   Output Parameter:
8619: . localX - The output vector

8621:   Calling sequence of `funcs`:
8622: + dim          - The spatial dimension
8623: . Nf           - The number of input fields
8624: . NfAux        - The number of input auxiliary fields
8625: . uOff         - The offset of each field in u[]
8626: . uOff_x       - The offset of each field in u_x[]
8627: . u            - The field values at this point in space
8628: . u_t          - The field time derivative at this point in space (or `NULL`)
8629: . u_x          - The field derivatives at this point in space
8630: . aOff         - The offset of each auxiliary field in u[]
8631: . aOff_x       - The offset of each auxiliary field in u_x[]
8632: . a            - The auxiliary field values at this point in space
8633: . a_t          - The auxiliary field time derivative at this point in space (or `NULL`)
8634: . a_x          - The auxiliary field derivatives at this point in space
8635: . t            - The current time
8636: . x            - The coordinates of this point
8637: . numConstants - The number of constants
8638: . constants    - The value of each constant
8639: - f            - The value of the function at this point in space

8641:   Level: intermediate

8643:   Note:
8644:   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.
8645:   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
8646:   a subdomain. You can also output a different number of fields than the input, with different discretizations. Last the auxiliary `DM`, attached to the
8647:   auxiliary field vector, which is attached to dm, can also be different. It can have a different topology, number of fields, and discretizations.

8649:   Developer Notes:
8650:   This API is specific to only particular usage of `DM`

8652:   The notes need to provide some information about what has to be provided to the `DM` to be able to perform the computation.

8654: .seealso: [](ch_dmbase), `DM`, `DMProjectField()`, `DMProjectFieldLabelLocal()`,
8655: `DMProjectFunction()`, `DMComputeL2Diff()`
8656: @*/
8657: 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)
8658: {
8659:   PetscFunctionBegin;
8663:   PetscUseTypeMethod(dm, projectfieldlocal, time, localU, funcs, mode, localX);
8664:   PetscFunctionReturn(PETSC_SUCCESS);
8665: }

8667: /*@
8668:   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.

8670:   Not Collective

8672:   Input Parameters:
8673: + dm     - The `DM`
8674: . time   - The time
8675: . label  - The `DMLabel` marking the portion of the domain to output
8676: . numIds - The number of label ids to use
8677: . ids    - The label ids to use for marking
8678: . Nc     - The number of components to set in the output, or `PETSC_DETERMINE` for all components
8679: . comps  - The components to set in the output, or `NULL` for all components
8680: . localU - The input field vector
8681: . funcs  - The functions to evaluate, one per field
8682: - mode   - The insertion mode for values

8684:   Output Parameter:
8685: . localX - The output vector

8687:   Calling sequence of `funcs`:
8688: + dim          - The spatial dimension
8689: . Nf           - The number of input fields
8690: . NfAux        - The number of input auxiliary fields
8691: . uOff         - The offset of each field in u[]
8692: . uOff_x       - The offset of each field in u_x[]
8693: . u            - The field values at this point in space
8694: . u_t          - The field time derivative at this point in space (or `NULL`)
8695: . u_x          - The field derivatives at this point in space
8696: . aOff         - The offset of each auxiliary field in u[]
8697: . aOff_x       - The offset of each auxiliary field in u_x[]
8698: . a            - The auxiliary field values at this point in space
8699: . a_t          - The auxiliary field time derivative at this point in space (or `NULL`)
8700: . a_x          - The auxiliary field derivatives at this point in space
8701: . t            - The current time
8702: . x            - The coordinates of this point
8703: . numConstants - The number of constants
8704: . constants    - The value of each constant
8705: - f            - The value of the function at this point in space

8707:   Level: intermediate

8709:   Note:
8710:   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.
8711:   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
8712:   a subdomain. You can also output a different number of fields than the input, with different discretizations. Last the auxiliary `DM`, attached to the
8713:   auxiliary field vector, which is attached to dm, can also be different. It can have a different topology, number of fields, and discretizations.

8715:   Developer Notes:
8716:   This API is specific to only particular usage of `DM`

8718:   The notes need to provide some information about what has to be provided to the `DM` to be able to perform the computation.

8720: .seealso: [](ch_dmbase), `DM`, `DMProjectField()`, `DMProjectFieldLabel()`, `DMProjectFunction()`, `DMComputeL2Diff()`
8721: @*/
8722: 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)
8723: {
8724:   PetscFunctionBegin;
8728:   PetscUseTypeMethod(dm, projectfieldlabellocal, time, label, numIds, ids, Nc, comps, localU, funcs, mode, localX);
8729:   PetscFunctionReturn(PETSC_SUCCESS);
8730: }

8732: /*@
8733:   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.

8735:   Not Collective

8737:   Input Parameters:
8738: + dm     - The `DM`
8739: . time   - The time
8740: . label  - The `DMLabel` marking the portion of the domain to output
8741: . numIds - The number of label ids to use
8742: . ids    - The label ids to use for marking
8743: . Nc     - The number of components to set in the output, or `PETSC_DETERMINE` for all components
8744: . comps  - The components to set in the output, or `NULL` for all components
8745: . U      - The input field vector
8746: . funcs  - The functions to evaluate, one per field
8747: - mode   - The insertion mode for values

8749:   Output Parameter:
8750: . X - The output vector

8752:   Calling sequence of `funcs`:
8753: + dim          - The spatial dimension
8754: . Nf           - The number of input fields
8755: . NfAux        - The number of input auxiliary fields
8756: . uOff         - The offset of each field in u[]
8757: . uOff_x       - The offset of each field in u_x[]
8758: . u            - The field values at this point in space
8759: . u_t          - The field time derivative at this point in space (or `NULL`)
8760: . u_x          - The field derivatives at this point in space
8761: . aOff         - The offset of each auxiliary field in u[]
8762: . aOff_x       - The offset of each auxiliary field in u_x[]
8763: . a            - The auxiliary field values at this point in space
8764: . a_t          - The auxiliary field time derivative at this point in space (or `NULL`)
8765: . a_x          - The auxiliary field derivatives at this point in space
8766: . t            - The current time
8767: . x            - The coordinates of this point
8768: . numConstants - The number of constants
8769: . constants    - The value of each constant
8770: - f            - The value of the function at this point in space

8772:   Level: intermediate

8774:   Note:
8775:   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.
8776:   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
8777:   a subdomain. You can also output a different number of fields than the input, with different discretizations. Last the auxiliary `DM`, attached to the
8778:   auxiliary field vector, which is attached to dm, can also be different. It can have a different topology, number of fields, and discretizations.

8780:   Developer Notes:
8781:   This API is specific to only particular usage of `DM`

8783:   The notes need to provide some information about what has to be provided to the `DM` to be able to perform the computation.

8785: .seealso: [](ch_dmbase), `DM`, `DMProjectField()`, `DMProjectFieldLabelLocal()`, `DMProjectFunction()`, `DMComputeL2Diff()`
8786: @*/
8787: 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)
8788: {
8789:   DM  dmIn;
8790:   Vec localU, localX;

8792:   PetscFunctionBegin;
8794:   PetscCall(VecGetDM(U, &dmIn));
8795:   PetscCall(DMGetLocalVector(dmIn, &localU));
8796:   PetscCall(DMGetLocalVector(dm, &localX));
8797:   PetscCall(VecSet(localX, 0.));
8798:   PetscCall(DMGlobalToLocalBegin(dmIn, U, mode, localU));
8799:   PetscCall(DMGlobalToLocalEnd(dmIn, U, mode, localU));
8800:   PetscCall(DMProjectFieldLabelLocal(dm, time, label, numIds, ids, Nc, comps, localU, funcs, mode, localX));
8801:   PetscCall(DMLocalToGlobalBegin(dm, localX, mode, X));
8802:   PetscCall(DMLocalToGlobalEnd(dm, localX, mode, X));
8803:   PetscCall(DMRestoreLocalVector(dm, &localX));
8804:   PetscCall(DMRestoreLocalVector(dmIn, &localU));
8805:   PetscFunctionReturn(PETSC_SUCCESS);
8806: }

8808: /*@
8809:   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.

8811:   Not Collective

8813:   Input Parameters:
8814: + dm     - The `DM`
8815: . time   - The time
8816: . label  - The `DMLabel` marking the portion of the domain boundary to output
8817: . numIds - The number of label ids to use
8818: . ids    - The label ids to use for marking
8819: . Nc     - The number of components to set in the output, or `PETSC_DETERMINE` for all components
8820: . comps  - The components to set in the output, or `NULL` for all components
8821: . localU - The input field vector
8822: . funcs  - The functions to evaluate, one per field
8823: - mode   - The insertion mode for values

8825:   Output Parameter:
8826: . localX - The output vector

8828:   Calling sequence of `funcs`:
8829: + dim          - The spatial dimension
8830: . Nf           - The number of input fields
8831: . NfAux        - The number of input auxiliary fields
8832: . uOff         - The offset of each field in u[]
8833: . uOff_x       - The offset of each field in u_x[]
8834: . u            - The field values at this point in space
8835: . u_t          - The field time derivative at this point in space (or `NULL`)
8836: . u_x          - The field derivatives at this point in space
8837: . aOff         - The offset of each auxiliary field in u[]
8838: . aOff_x       - The offset of each auxiliary field in u_x[]
8839: . a            - The auxiliary field values at this point in space
8840: . a_t          - The auxiliary field time derivative at this point in space (or `NULL`)
8841: . a_x          - The auxiliary field derivatives at this point in space
8842: . t            - The current time
8843: . x            - The coordinates of this point
8844: . n            - The face normal
8845: . numConstants - The number of constants
8846: . constants    - The value of each constant
8847: - f            - The value of the function at this point in space

8849:   Level: intermediate

8851:   Note:
8852:   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.
8853:   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
8854:   a subdomain. You can also output a different number of fields than the input, with different discretizations. Last the auxiliary `DM`, attached to the
8855:   auxiliary field vector, which is attached to dm, can also be different. It can have a different topology, number of fields, and discretizations.

8857:   Developer Notes:
8858:   This API is specific to only particular usage of `DM`

8860:   The notes need to provide some information about what has to be provided to the `DM` to be able to perform the computation.

8862: .seealso: [](ch_dmbase), `DM`, `DMProjectField()`, `DMProjectFieldLabelLocal()`, `DMProjectFunction()`, `DMComputeL2Diff()`
8863: @*/
8864: 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)
8865: {
8866:   PetscFunctionBegin;
8870:   PetscUseTypeMethod(dm, projectbdfieldlabellocal, time, label, numIds, ids, Nc, comps, localU, funcs, mode, localX);
8871:   PetscFunctionReturn(PETSC_SUCCESS);
8872: }

8874: /*@
8875:   DMComputeL2Diff - This function computes the L_2 difference between a function u and an FEM interpolant solution u_h.

8877:   Collective

8879:   Input Parameters:
8880: + dm    - The `DM`
8881: . time  - The time
8882: . funcs - The functions to evaluate for each field component
8883: . ctxs  - Optional array of contexts to pass to each function, or `NULL`.
8884: - X     - The coefficient vector u_h, a global vector

8886:   Output Parameter:
8887: . diff - The diff ||u - u_h||_2

8889:   Level: developer

8891:   Developer Notes:
8892:   This API is specific to only particular usage of `DM`

8894:   The notes need to provide some information about what has to be provided to the `DM` to be able to perform the computation.

8896: .seealso: [](ch_dmbase), `DM`, `DMProjectFunction()`, `DMComputeL2FieldDiff()`, `DMComputeL2GradientDiff()`
8897: @*/
8898: PetscErrorCode DMComputeL2Diff(DM dm, PetscReal time, PetscErrorCode (**funcs)(PetscInt, PetscReal, const PetscReal[], PetscInt, PetscScalar *, void *), void **ctxs, Vec X, PetscReal *diff)
8899: {
8900:   PetscFunctionBegin;
8903:   PetscUseTypeMethod(dm, computel2diff, time, funcs, ctxs, X, diff);
8904:   PetscFunctionReturn(PETSC_SUCCESS);
8905: }

8907: /*@
8908:   DMComputeL2GradientDiff - This function computes the L_2 difference between the gradient of a function u and an FEM interpolant solution grad u_h.

8910:   Collective

8912:   Input Parameters:
8913: + dm    - The `DM`
8914: . time  - The time
8915: . funcs - The gradient functions to evaluate for each field component
8916: . ctxs  - Optional array of contexts to pass to each function, or `NULL`.
8917: . X     - The coefficient vector u_h, a global vector
8918: - n     - The vector to project along

8920:   Output Parameter:
8921: . diff - The diff ||(grad u - grad u_h) . n||_2

8923:   Level: developer

8925:   Developer Notes:
8926:   This API is specific to only particular usage of `DM`

8928:   The notes need to provide some information about what has to be provided to the `DM` to be able to perform the computation.

8930: .seealso: [](ch_dmbase), `DM`, `DMProjectFunction()`, `DMComputeL2Diff()`, `DMComputeL2FieldDiff()`
8931: @*/
8932: 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)
8933: {
8934:   PetscFunctionBegin;
8937:   PetscUseTypeMethod(dm, computel2gradientdiff, time, funcs, ctxs, X, n, diff);
8938:   PetscFunctionReturn(PETSC_SUCCESS);
8939: }

8941: /*@
8942:   DMComputeL2FieldDiff - This function computes the L_2 difference between a function u and an FEM interpolant solution u_h, separated into field components.

8944:   Collective

8946:   Input Parameters:
8947: + dm    - The `DM`
8948: . time  - The time
8949: . funcs - The functions to evaluate for each field component
8950: . ctxs  - Optional array of contexts to pass to each function, or `NULL`.
8951: - X     - The coefficient vector u_h, a global vector

8953:   Output Parameter:
8954: . diff - The array of differences, ||u^f - u^f_h||_2

8956:   Level: developer

8958:   Developer Notes:
8959:   This API is specific to only particular usage of `DM`

8961:   The notes need to provide some information about what has to be provided to the `DM` to be able to perform the computation.

8963: .seealso: [](ch_dmbase), `DM`, `DMProjectFunction()`, `DMComputeL2GradientDiff()`
8964: @*/
8965: PetscErrorCode DMComputeL2FieldDiff(DM dm, PetscReal time, PetscErrorCode (**funcs)(PetscInt, PetscReal, const PetscReal[], PetscInt, PetscScalar *, void *), void **ctxs, Vec X, PetscReal diff[])
8966: {
8967:   PetscFunctionBegin;
8970:   PetscUseTypeMethod(dm, computel2fielddiff, time, funcs, ctxs, X, diff);
8971:   PetscFunctionReturn(PETSC_SUCCESS);
8972: }

8974: /*@
8975:   DMGetNeighbors - Gets an array containing the MPI ranks of all the processes neighbors

8977:   Not Collective

8979:   Input Parameter:
8980: . dm - The `DM`

8982:   Output Parameters:
8983: + nranks - the number of neighbours
8984: - ranks  - the neighbors ranks

8986:   Level: beginner

8988:   Note:
8989:   Do not free the array, it is freed when the `DM` is destroyed.

8991: .seealso: [](ch_dmbase), `DM`, `DMDAGetNeighbors()`, `PetscSFGetRootRanks()`
8992: @*/
8993: PetscErrorCode DMGetNeighbors(DM dm, PetscInt *nranks, const PetscMPIInt *ranks[])
8994: {
8995:   PetscFunctionBegin;
8997:   PetscUseTypeMethod(dm, getneighbors, nranks, ranks);
8998:   PetscFunctionReturn(PETSC_SUCCESS);
8999: }

9001: #include <petsc/private/matimpl.h>

9003: /*
9004:     Converts the input vector to a ghosted vector and then calls the standard coloring code.
9005:     This must be a different function because it requires DM which is not defined in the Mat library
9006: */
9007: static PetscErrorCode MatFDColoringApply_AIJDM(Mat J, MatFDColoring coloring, Vec x1, void *sctx)
9008: {
9009:   PetscFunctionBegin;
9010:   if (coloring->ctype == IS_COLORING_LOCAL) {
9011:     Vec x1local;
9012:     DM  dm;
9013:     PetscCall(MatGetDM(J, &dm));
9014:     PetscCheck(dm, PetscObjectComm((PetscObject)J), PETSC_ERR_ARG_INCOMP, "IS_COLORING_LOCAL requires a DM");
9015:     PetscCall(DMGetLocalVector(dm, &x1local));
9016:     PetscCall(DMGlobalToLocalBegin(dm, x1, INSERT_VALUES, x1local));
9017:     PetscCall(DMGlobalToLocalEnd(dm, x1, INSERT_VALUES, x1local));
9018:     x1 = x1local;
9019:   }
9020:   PetscCall(MatFDColoringApply_AIJ(J, coloring, x1, sctx));
9021:   if (coloring->ctype == IS_COLORING_LOCAL) {
9022:     DM dm;
9023:     PetscCall(MatGetDM(J, &dm));
9024:     PetscCall(DMRestoreLocalVector(dm, &x1));
9025:   }
9026:   PetscFunctionReturn(PETSC_SUCCESS);
9027: }

9029: /*@
9030:   MatFDColoringUseDM - allows a `MatFDColoring` object to use the `DM` associated with the matrix to compute a `IS_COLORING_LOCAL` coloring

9032:   Input Parameters:
9033: + coloring   - The matrix to get the `DM` from
9034: - fdcoloring - the `MatFDColoring` object

9036:   Level: advanced

9038:   Developer Note:
9039:   This routine exists because the PETSc `Mat` library does not know about the `DM` objects

9041: .seealso: [](ch_dmbase), `DM`, `MatFDColoring`, `MatFDColoringCreate()`, `ISColoringType`
9042: @*/
9043: PetscErrorCode MatFDColoringUseDM(Mat coloring, MatFDColoring fdcoloring)
9044: {
9045:   PetscFunctionBegin;
9046:   coloring->ops->fdcoloringapply = MatFDColoringApply_AIJDM;
9047:   PetscFunctionReturn(PETSC_SUCCESS);
9048: }

9050: /*@
9051:   DMGetCompatibility - determine if two `DM`s are compatible

9053:   Collective

9055:   Input Parameters:
9056: + dm1 - the first `DM`
9057: - dm2 - the second `DM`

9059:   Output Parameters:
9060: + compatible - whether or not the two `DM`s are compatible
9061: - set        - whether or not the compatible value was actually determined and set

9063:   Level: advanced

9065:   Notes:
9066:   Two `DM`s are deemed compatible if they represent the same parallel decomposition
9067:   of the same topology. This implies that the section (field data) on one
9068:   "makes sense" with respect to the topology and parallel decomposition of the other.
9069:   Loosely speaking, compatible `DM`s represent the same domain and parallel
9070:   decomposition, but hold different data.

9072:   Typically, one would confirm compatibility if intending to simultaneously iterate
9073:   over a pair of vectors obtained from different `DM`s.

9075:   For example, two `DMDA` objects are compatible if they have the same local
9076:   and global sizes and the same stencil width. They can have different numbers
9077:   of degrees of freedom per node. Thus, one could use the node numbering from
9078:   either `DM` in bounds for a loop over vectors derived from either `DM`.

9080:   Consider the operation of summing data living on a 2-dof `DMDA` to data living
9081:   on a 1-dof `DMDA`, which should be compatible, as in the following snippet.
9082: .vb
9083:   ...
9084:   PetscCall(DMGetCompatibility(da1,da2,&compatible,&set));
9085:   if (set && compatible)  {
9086:     PetscCall(DMDAVecGetArrayDOF(da1,vec1,&arr1));
9087:     PetscCall(DMDAVecGetArrayDOF(da2,vec2,&arr2));
9088:     PetscCall(DMDAGetCorners(da1,&x,&y,NULL,&m,&n,NULL));
9089:     for (j=y; j<y+n; ++j) {
9090:       for (i=x; i<x+m, ++i) {
9091:         arr1[j][i][0] = arr2[j][i][0] + arr2[j][i][1];
9092:       }
9093:     }
9094:     PetscCall(DMDAVecRestoreArrayDOF(da1,vec1,&arr1));
9095:     PetscCall(DMDAVecRestoreArrayDOF(da2,vec2,&arr2));
9096:   } else {
9097:     SETERRQ(PetscObjectComm((PetscObject)da1,PETSC_ERR_ARG_INCOMP,"DMDA objects incompatible");
9098:   }
9099:   ...
9100: .ve

9102:   Checking compatibility might be expensive for a given implementation of `DM`,
9103:   or might be impossible to unambiguously confirm or deny. For this reason,
9104:   this function may decline to determine compatibility, and hence users should
9105:   always check the "set" output parameter.

9107:   A `DM` is always compatible with itself.

9109:   In the current implementation, `DM`s which live on "unequal" communicators
9110:   (MPI_UNEQUAL in the terminology of MPI_Comm_compare()) are always deemed
9111:   incompatible.

9113:   This function is labeled "Collective," as information about all subdomains
9114:   is required on each rank. However, in `DM` implementations which store all this
9115:   information locally, this function may be merely "Logically Collective".

9117:   Developer Note:
9118:   Compatibility is assumed to be a symmetric concept; `DM` A is compatible with `DM` B
9119:   iff B is compatible with A. Thus, this function checks the implementations
9120:   of both dm and dmc (if they are of different types), attempting to determine
9121:   compatibility. It is left to `DM` implementers to ensure that symmetry is
9122:   preserved. The simplest way to do this is, when implementing type-specific
9123:   logic for this function, is to check for existing logic in the implementation
9124:   of other `DM` types and let *set = PETSC_FALSE if found.

9126: .seealso: [](ch_dmbase), `DM`, `DMDACreateCompatibleDMDA()`, `DMStagCreateCompatibleDMStag()`
9127: @*/
9128: PetscErrorCode DMGetCompatibility(DM dm1, DM dm2, PetscBool *compatible, PetscBool *set)
9129: {
9130:   PetscMPIInt compareResult;
9131:   DMType      type, type2;
9132:   PetscBool   sameType;

9134:   PetscFunctionBegin;

9138:   /* Declare a DM compatible with itself */
9139:   if (dm1 == dm2) {
9140:     *set        = PETSC_TRUE;
9141:     *compatible = PETSC_TRUE;
9142:     PetscFunctionReturn(PETSC_SUCCESS);
9143:   }

9145:   /* Declare a DM incompatible with a DM that lives on an "unequal"
9146:      communicator. Note that this does not preclude compatibility with
9147:      DMs living on "congruent" or "similar" communicators, but this must be
9148:      determined by the implementation-specific logic */
9149:   PetscCallMPI(MPI_Comm_compare(PetscObjectComm((PetscObject)dm1), PetscObjectComm((PetscObject)dm2), &compareResult));
9150:   if (compareResult == MPI_UNEQUAL) {
9151:     *set        = PETSC_TRUE;
9152:     *compatible = PETSC_FALSE;
9153:     PetscFunctionReturn(PETSC_SUCCESS);
9154:   }

9156:   /* Pass to the implementation-specific routine, if one exists. */
9157:   if (dm1->ops->getcompatibility) {
9158:     PetscUseTypeMethod(dm1, getcompatibility, dm2, compatible, set);
9159:     if (*set) PetscFunctionReturn(PETSC_SUCCESS);
9160:   }

9162:   /* If dm1 and dm2 are of different types, then attempt to check compatibility
9163:      with an implementation of this function from dm2 */
9164:   PetscCall(DMGetType(dm1, &type));
9165:   PetscCall(DMGetType(dm2, &type2));
9166:   PetscCall(PetscStrcmp(type, type2, &sameType));
9167:   if (!sameType && dm2->ops->getcompatibility) {
9168:     PetscUseTypeMethod(dm2, getcompatibility, dm1, compatible, set); /* Note argument order */
9169:   } else {
9170:     *set = PETSC_FALSE;
9171:   }
9172:   PetscFunctionReturn(PETSC_SUCCESS);
9173: }

9175: /*@
9176:   DMMonitorSet - Sets an additional monitor function that is to be used after a solve to monitor discretization performance.

9178:   Logically Collective

9180:   Input Parameters:
9181: + dm             - the `DM`
9182: . f              - the monitor function
9183: . mctx           - [optional] context for private data for the monitor routine (use `NULL` if no context is desired)
9184: - monitordestroy - [optional] routine that frees monitor context (may be `NULL`), see `PetscCtxDestroyFn` for the calling sequence

9186:   Options Database Key:
9187: . -dm_monitor_cancel - cancels all monitors that have been hardwired into a code by calls to `DMMonitorSet()`, but
9188:                        does not cancel those set via the options database.

9190:   Level: intermediate

9192:   Note:
9193:   Several different monitoring routines may be set by calling
9194:   `DMMonitorSet()` multiple times or with `DMMonitorSetFromOptions()`; all will be called in the
9195:   order in which they were set.

9197:   Fortran Note:
9198:   Only a single monitor function can be set for each `DM` object

9200:   Developer Note:
9201:   This API has a generic name but seems specific to a very particular aspect of the use of `DM`

9203: .seealso: [](ch_dmbase), `DM`, `DMMonitorCancel()`, `DMMonitorSetFromOptions()`, `DMMonitor()`, `PetscCtxDestroyFn`
9204: @*/
9205: PetscErrorCode DMMonitorSet(DM dm, PetscErrorCode (*f)(DM, void *), void *mctx, PetscCtxDestroyFn *monitordestroy)
9206: {
9207:   PetscFunctionBegin;
9209:   for (PetscInt m = 0; m < dm->numbermonitors; ++m) {
9210:     PetscBool identical;

9212:     PetscCall(PetscMonitorCompare((PetscErrorCode (*)(void))(PetscVoidFn *)f, mctx, monitordestroy, (PetscErrorCode (*)(void))(PetscVoidFn *)dm->monitor[m], dm->monitorcontext[m], dm->monitordestroy[m], &identical));
9213:     if (identical) PetscFunctionReturn(PETSC_SUCCESS);
9214:   }
9215:   PetscCheck(dm->numbermonitors < MAXDMMONITORS, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Too many monitors set");
9216:   dm->monitor[dm->numbermonitors]          = f;
9217:   dm->monitordestroy[dm->numbermonitors]   = monitordestroy;
9218:   dm->monitorcontext[dm->numbermonitors++] = mctx;
9219:   PetscFunctionReturn(PETSC_SUCCESS);
9220: }

9222: /*@
9223:   DMMonitorCancel - Clears all the monitor functions for a `DM` object.

9225:   Logically Collective

9227:   Input Parameter:
9228: . dm - the DM

9230:   Options Database Key:
9231: . -dm_monitor_cancel - cancels all monitors that have been hardwired
9232:   into a code by calls to `DMonitorSet()`, but does not cancel those
9233:   set via the options database

9235:   Level: intermediate

9237:   Note:
9238:   There is no way to clear one specific monitor from a `DM` object.

9240: .seealso: [](ch_dmbase), `DM`, `DMMonitorSet()`, `DMMonitorSetFromOptions()`, `DMMonitor()`
9241: @*/
9242: PetscErrorCode DMMonitorCancel(DM dm)
9243: {
9244:   PetscFunctionBegin;
9246:   for (PetscInt m = 0; m < dm->numbermonitors; ++m) {
9247:     if (dm->monitordestroy[m]) PetscCall((*dm->monitordestroy[m])(&dm->monitorcontext[m]));
9248:   }
9249:   dm->numbermonitors = 0;
9250:   PetscFunctionReturn(PETSC_SUCCESS);
9251: }

9253: /*@
9254:   DMMonitorSetFromOptions - Sets a monitor function and viewer appropriate for the type indicated by the user

9256:   Collective

9258:   Input Parameters:
9259: + dm           - `DM` object you wish to monitor
9260: . name         - the monitor type one is seeking
9261: . help         - message indicating what monitoring is done
9262: . manual       - manual page for the monitor
9263: . monitor      - the monitor function, this must use a `PetscViewerFormat` as its context
9264: - 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

9266:   Output Parameter:
9267: . flg - Flag set if the monitor was created

9269:   Calling sequence of `monitor`:
9270: + dm  - the `DM` to be monitored
9271: - ctx - monitor context

9273:   Calling sequence of `monitorsetup`:
9274: + dm - the `DM` to be monitored
9275: - vf - the `PetscViewer` and format to be used by the monitor

9277:   Level: developer

9279: .seealso: [](ch_dmbase), `DM`, `PetscOptionsCreateViewer()`, `PetscOptionsGetReal()`, `PetscOptionsHasName()`, `PetscOptionsGetString()`,
9280:           `PetscOptionsGetIntArray()`, `PetscOptionsGetRealArray()`, `PetscOptionsBool()`,
9281:           `PetscOptionsInt()`, `PetscOptionsString()`, `PetscOptionsReal()`,
9282:           `PetscOptionsName()`, `PetscOptionsBegin()`, `PetscOptionsEnd()`, `PetscOptionsHeadBegin()`,
9283:           `PetscOptionsStringArray()`, `PetscOptionsRealArray()`, `PetscOptionsScalar()`,
9284:           `PetscOptionsBoolGroupBegin()`, `PetscOptionsBoolGroup()`, `PetscOptionsBoolGroupEnd()`,
9285:           `PetscOptionsFList()`, `PetscOptionsEList()`, `DMMonitor()`, `DMMonitorSet()`
9286: @*/
9287: 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)
9288: {
9289:   PetscViewer       viewer;
9290:   PetscViewerFormat format;

9292:   PetscFunctionBegin;
9294:   PetscCall(PetscOptionsCreateViewer(PetscObjectComm((PetscObject)dm), ((PetscObject)dm)->options, ((PetscObject)dm)->prefix, name, &viewer, &format, flg));
9295:   if (*flg) {
9296:     PetscViewerAndFormat *vf;

9298:     PetscCall(PetscViewerAndFormatCreate(viewer, format, &vf));
9299:     PetscCall(PetscViewerDestroy(&viewer));
9300:     if (monitorsetup) PetscCall((*monitorsetup)(dm, vf));
9301:     PetscCall(DMMonitorSet(dm, monitor, vf, (PetscCtxDestroyFn *)PetscViewerAndFormatDestroy));
9302:   }
9303:   PetscFunctionReturn(PETSC_SUCCESS);
9304: }

9306: /*@
9307:   DMMonitor - runs the user provided monitor routines, if they exist

9309:   Collective

9311:   Input Parameter:
9312: . dm - The `DM`

9314:   Level: developer

9316:   Developer Note:
9317:   Note should indicate when during the life of the `DM` the monitor is run. It appears to be
9318:   related to the discretization process seems rather specialized since some `DM` have no
9319:   concept of discretization.

9321: .seealso: [](ch_dmbase), `DM`, `DMMonitorSet()`, `DMMonitorSetFromOptions()`
9322: @*/
9323: PetscErrorCode DMMonitor(DM dm)
9324: {
9325:   PetscFunctionBegin;
9326:   if (!dm) PetscFunctionReturn(PETSC_SUCCESS);
9328:   for (PetscInt m = 0; m < dm->numbermonitors; ++m) PetscCall((*dm->monitor[m])(dm, dm->monitorcontext[m]));
9329:   PetscFunctionReturn(PETSC_SUCCESS);
9330: }

9332: /*@
9333:   DMComputeError - Computes the error assuming the user has provided the exact solution functions

9335:   Collective

9337:   Input Parameters:
9338: + dm  - The `DM`
9339: - sol - The solution vector

9341:   Input/Output Parameter:
9342: . errors - An array of length Nf, the number of fields, or `NULL` for no output; on output
9343:            contains the error in each field

9345:   Output Parameter:
9346: . errorVec - A vector to hold the cellwise error (may be `NULL`)

9348:   Level: developer

9350:   Note:
9351:   The exact solutions come from the `PetscDS` object, and the time comes from `DMGetOutputSequenceNumber()`.

9353: .seealso: [](ch_dmbase), `DM`, `DMMonitorSet()`, `DMGetRegionNumDS()`, `PetscDSGetExactSolution()`, `DMGetOutputSequenceNumber()`
9354: @*/
9355: PetscErrorCode DMComputeError(DM dm, Vec sol, PetscReal errors[], Vec *errorVec)
9356: {
9357:   PetscErrorCode (**exactSol)(PetscInt, PetscReal, const PetscReal[], PetscInt, PetscScalar[], void *);
9358:   void    **ctxs;
9359:   PetscReal time;
9360:   PetscInt  Nf, f, Nds, s;

9362:   PetscFunctionBegin;
9363:   PetscCall(DMGetNumFields(dm, &Nf));
9364:   PetscCall(PetscCalloc2(Nf, &exactSol, Nf, &ctxs));
9365:   PetscCall(DMGetNumDS(dm, &Nds));
9366:   for (s = 0; s < Nds; ++s) {
9367:     PetscDS         ds;
9368:     DMLabel         label;
9369:     IS              fieldIS;
9370:     const PetscInt *fields;
9371:     PetscInt        dsNf;

9373:     PetscCall(DMGetRegionNumDS(dm, s, &label, &fieldIS, &ds, NULL));
9374:     PetscCall(PetscDSGetNumFields(ds, &dsNf));
9375:     if (fieldIS) PetscCall(ISGetIndices(fieldIS, &fields));
9376:     for (f = 0; f < dsNf; ++f) {
9377:       const PetscInt field = fields[f];
9378:       PetscCall(PetscDSGetExactSolution(ds, field, &exactSol[field], &ctxs[field]));
9379:     }
9380:     if (fieldIS) PetscCall(ISRestoreIndices(fieldIS, &fields));
9381:   }
9382:   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);
9383:   PetscCall(DMGetOutputSequenceNumber(dm, NULL, &time));
9384:   if (errors) PetscCall(DMComputeL2FieldDiff(dm, time, exactSol, ctxs, sol, errors));
9385:   if (errorVec) {
9386:     DM             edm;
9387:     DMPolytopeType ct;
9388:     PetscBool      simplex;
9389:     PetscInt       dim, cStart, Nf;

9391:     PetscCall(DMClone(dm, &edm));
9392:     PetscCall(DMGetDimension(edm, &dim));
9393:     PetscCall(DMPlexGetHeightStratum(dm, 0, &cStart, NULL));
9394:     PetscCall(DMPlexGetCellType(dm, cStart, &ct));
9395:     simplex = DMPolytopeTypeGetNumVertices(ct) == DMPolytopeTypeGetDim(ct) + 1 ? PETSC_TRUE : PETSC_FALSE;
9396:     PetscCall(DMGetNumFields(dm, &Nf));
9397:     for (f = 0; f < Nf; ++f) {
9398:       PetscFE         fe, efe;
9399:       PetscQuadrature q;
9400:       const char     *name;

9402:       PetscCall(DMGetField(dm, f, NULL, (PetscObject *)&fe));
9403:       PetscCall(PetscFECreateLagrange(PETSC_COMM_SELF, dim, Nf, simplex, 0, PETSC_DETERMINE, &efe));
9404:       PetscCall(PetscObjectGetName((PetscObject)fe, &name));
9405:       PetscCall(PetscObjectSetName((PetscObject)efe, name));
9406:       PetscCall(PetscFEGetQuadrature(fe, &q));
9407:       PetscCall(PetscFESetQuadrature(efe, q));
9408:       PetscCall(DMSetField(edm, f, NULL, (PetscObject)efe));
9409:       PetscCall(PetscFEDestroy(&efe));
9410:     }
9411:     PetscCall(DMCreateDS(edm));

9413:     PetscCall(DMCreateGlobalVector(edm, errorVec));
9414:     PetscCall(PetscObjectSetName((PetscObject)*errorVec, "Error"));
9415:     PetscCall(DMPlexComputeL2DiffVec(dm, time, exactSol, ctxs, sol, *errorVec));
9416:     PetscCall(DMDestroy(&edm));
9417:   }
9418:   PetscCall(PetscFree2(exactSol, ctxs));
9419:   PetscFunctionReturn(PETSC_SUCCESS);
9420: }

9422: /*@
9423:   DMGetNumAuxiliaryVec - Get the number of auxiliary vectors associated with this `DM`

9425:   Not Collective

9427:   Input Parameter:
9428: . dm - The `DM`

9430:   Output Parameter:
9431: . numAux - The number of auxiliary data vectors

9433:   Level: advanced

9435: .seealso: [](ch_dmbase), `DM`, `DMClearAuxiliaryVec()`, `DMSetAuxiliaryVec()`, `DMGetAuxiliaryLabels()`, `DMGetAuxiliaryVec()`
9436: @*/
9437: PetscErrorCode DMGetNumAuxiliaryVec(DM dm, PetscInt *numAux)
9438: {
9439:   PetscFunctionBegin;
9441:   PetscCall(PetscHMapAuxGetSize(dm->auxData, numAux));
9442:   PetscFunctionReturn(PETSC_SUCCESS);
9443: }

9445: /*@
9446:   DMGetAuxiliaryVec - Get the auxiliary vector for region specified by the given label and value, and equation part

9448:   Not Collective

9450:   Input Parameters:
9451: + dm    - The `DM`
9452: . label - The `DMLabel`
9453: . value - The label value indicating the region
9454: - part  - The equation part, or 0 if unused

9456:   Output Parameter:
9457: . aux - The `Vec` holding auxiliary field data

9459:   Level: advanced

9461:   Note:
9462:   If no auxiliary vector is found for this (label, value), (`NULL`, 0, 0) is checked as well.

9464: .seealso: [](ch_dmbase), `DM`, `DMClearAuxiliaryVec()`, `DMSetAuxiliaryVec()`, `DMGetNumAuxiliaryVec()`, `DMGetAuxiliaryLabels()`
9465: @*/
9466: PetscErrorCode DMGetAuxiliaryVec(DM dm, DMLabel label, PetscInt value, PetscInt part, Vec *aux)
9467: {
9468:   PetscHashAuxKey key, wild = {NULL, 0, 0};
9469:   PetscBool       has;

9471:   PetscFunctionBegin;
9474:   key.label = label;
9475:   key.value = value;
9476:   key.part  = part;
9477:   PetscCall(PetscHMapAuxHas(dm->auxData, key, &has));
9478:   if (has) PetscCall(PetscHMapAuxGet(dm->auxData, key, aux));
9479:   else PetscCall(PetscHMapAuxGet(dm->auxData, wild, aux));
9480:   PetscFunctionReturn(PETSC_SUCCESS);
9481: }

9483: /*@
9484:   DMSetAuxiliaryVec - Set an auxiliary vector for region specified by the given label and value, and equation part

9486:   Not Collective because auxiliary vectors are not parallel

9488:   Input Parameters:
9489: + dm    - The `DM`
9490: . label - The `DMLabel`
9491: . value - The label value indicating the region
9492: . part  - The equation part, or 0 if unused
9493: - aux   - The `Vec` holding auxiliary field data

9495:   Level: advanced

9497: .seealso: [](ch_dmbase), `DM`, `DMClearAuxiliaryVec()`, `DMGetAuxiliaryVec()`, `DMGetAuxiliaryLabels()`, `DMCopyAuxiliaryVec()`
9498: @*/
9499: PetscErrorCode DMSetAuxiliaryVec(DM dm, DMLabel label, PetscInt value, PetscInt part, Vec aux)
9500: {
9501:   Vec             old;
9502:   PetscHashAuxKey key;

9504:   PetscFunctionBegin;
9507:   key.label = label;
9508:   key.value = value;
9509:   key.part  = part;
9510:   PetscCall(PetscHMapAuxGet(dm->auxData, key, &old));
9511:   PetscCall(PetscObjectReference((PetscObject)aux));
9512:   if (!aux) PetscCall(PetscHMapAuxDel(dm->auxData, key));
9513:   else PetscCall(PetscHMapAuxSet(dm->auxData, key, aux));
9514:   PetscCall(VecDestroy(&old));
9515:   PetscFunctionReturn(PETSC_SUCCESS);
9516: }

9518: /*@
9519:   DMGetAuxiliaryLabels - Get the labels, values, and parts for all auxiliary vectors in this `DM`

9521:   Not Collective

9523:   Input Parameter:
9524: . dm - The `DM`

9526:   Output Parameters:
9527: + labels - The `DMLabel`s for each `Vec`
9528: . values - The label values for each `Vec`
9529: - parts  - The equation parts for each `Vec`

9531:   Level: advanced

9533:   Note:
9534:   The arrays passed in must be at least as large as `DMGetNumAuxiliaryVec()`.

9536: .seealso: [](ch_dmbase), `DM`, `DMClearAuxiliaryVec()`, `DMGetNumAuxiliaryVec()`, `DMGetAuxiliaryVec()`, `DMSetAuxiliaryVec()`, `DMCopyAuxiliaryVec()`
9537: @*/
9538: PetscErrorCode DMGetAuxiliaryLabels(DM dm, DMLabel labels[], PetscInt values[], PetscInt parts[])
9539: {
9540:   PetscHashAuxKey *keys;
9541:   PetscInt         n, i, off = 0;

9543:   PetscFunctionBegin;
9545:   PetscAssertPointer(labels, 2);
9546:   PetscAssertPointer(values, 3);
9547:   PetscAssertPointer(parts, 4);
9548:   PetscCall(DMGetNumAuxiliaryVec(dm, &n));
9549:   PetscCall(PetscMalloc1(n, &keys));
9550:   PetscCall(PetscHMapAuxGetKeys(dm->auxData, &off, keys));
9551:   for (i = 0; i < n; ++i) {
9552:     labels[i] = keys[i].label;
9553:     values[i] = keys[i].value;
9554:     parts[i]  = keys[i].part;
9555:   }
9556:   PetscCall(PetscFree(keys));
9557:   PetscFunctionReturn(PETSC_SUCCESS);
9558: }

9560: /*@
9561:   DMCopyAuxiliaryVec - Copy the auxiliary vector data on a `DM` to a new `DM`

9563:   Not Collective

9565:   Input Parameter:
9566: . dm - The `DM`

9568:   Output Parameter:
9569: . dmNew - The new `DM`, now with the same auxiliary data

9571:   Level: advanced

9573:   Note:
9574:   This is a shallow copy of the auxiliary vectors

9576: .seealso: [](ch_dmbase), `DM`, `DMClearAuxiliaryVec()`, `DMGetNumAuxiliaryVec()`, `DMGetAuxiliaryVec()`, `DMSetAuxiliaryVec()`
9577: @*/
9578: PetscErrorCode DMCopyAuxiliaryVec(DM dm, DM dmNew)
9579: {
9580:   PetscFunctionBegin;
9583:   if (dm == dmNew) PetscFunctionReturn(PETSC_SUCCESS);
9584:   PetscCall(DMClearAuxiliaryVec(dmNew));

9586:   PetscCall(PetscHMapAuxDestroy(&dmNew->auxData));
9587:   PetscCall(PetscHMapAuxDuplicate(dm->auxData, &dmNew->auxData));
9588:   {
9589:     Vec     *auxData;
9590:     PetscInt n, i, off = 0;

9592:     PetscCall(PetscHMapAuxGetSize(dmNew->auxData, &n));
9593:     PetscCall(PetscMalloc1(n, &auxData));
9594:     PetscCall(PetscHMapAuxGetVals(dmNew->auxData, &off, auxData));
9595:     for (i = 0; i < n; ++i) PetscCall(PetscObjectReference((PetscObject)auxData[i]));
9596:     PetscCall(PetscFree(auxData));
9597:   }
9598:   PetscFunctionReturn(PETSC_SUCCESS);
9599: }

9601: /*@
9602:   DMClearAuxiliaryVec - Destroys the auxiliary vector information and creates a new empty one

9604:   Not Collective

9606:   Input Parameter:
9607: . dm - The `DM`

9609:   Level: advanced

9611: .seealso: [](ch_dmbase), `DM`, `DMCopyAuxiliaryVec()`, `DMGetNumAuxiliaryVec()`, `DMGetAuxiliaryVec()`, `DMSetAuxiliaryVec()`
9612: @*/
9613: PetscErrorCode DMClearAuxiliaryVec(DM dm)
9614: {
9615:   Vec     *auxData;
9616:   PetscInt n, i, off = 0;

9618:   PetscFunctionBegin;
9619:   PetscCall(PetscHMapAuxGetSize(dm->auxData, &n));
9620:   PetscCall(PetscMalloc1(n, &auxData));
9621:   PetscCall(PetscHMapAuxGetVals(dm->auxData, &off, auxData));
9622:   for (i = 0; i < n; ++i) PetscCall(VecDestroy(&auxData[i]));
9623:   PetscCall(PetscFree(auxData));
9624:   PetscCall(PetscHMapAuxDestroy(&dm->auxData));
9625:   PetscCall(PetscHMapAuxCreate(&dm->auxData));
9626:   PetscFunctionReturn(PETSC_SUCCESS);
9627: }

9629: /*@
9630:   DMPolytopeMatchOrientation - Determine an orientation (transformation) that takes the source face arrangement to the target face arrangement

9632:   Not Collective

9634:   Input Parameters:
9635: + ct         - The `DMPolytopeType`
9636: . sourceCone - The source arrangement of faces
9637: - targetCone - The target arrangement of faces

9639:   Output Parameters:
9640: + ornt  - The orientation (transformation) which will take the source arrangement to the target arrangement
9641: - found - Flag indicating that a suitable orientation was found

9643:   Level: advanced

9645:   Note:
9646:   An arrangement is a face order combined with an orientation for each face

9648:   Each orientation (transformation) is labeled with an integer from negative `DMPolytopeTypeGetNumArrangements(ct)`/2 to `DMPolytopeTypeGetNumArrangements(ct)`/2
9649:   that labels each arrangement (face ordering plus orientation for each face).

9651:   See `DMPolytopeMatchVertexOrientation()` to find a new vertex orientation that takes the source vertex arrangement to the target vertex arrangement

9653: .seealso: [](ch_dmbase), `DM`, `DMPolytopeGetOrientation()`, `DMPolytopeMatchVertexOrientation()`, `DMPolytopeGetVertexOrientation()`
9654: @*/
9655: PetscErrorCode DMPolytopeMatchOrientation(DMPolytopeType ct, const PetscInt sourceCone[], const PetscInt targetCone[], PetscInt *ornt, PetscBool *found)
9656: {
9657:   const PetscInt cS = DMPolytopeTypeGetConeSize(ct);
9658:   const PetscInt nO = DMPolytopeTypeGetNumArrangements(ct) / 2;
9659:   PetscInt       o, c;

9661:   PetscFunctionBegin;
9662:   if (!nO) {
9663:     *ornt  = 0;
9664:     *found = PETSC_TRUE;
9665:     PetscFunctionReturn(PETSC_SUCCESS);
9666:   }
9667:   for (o = -nO; o < nO; ++o) {
9668:     const PetscInt *arr = DMPolytopeTypeGetArrangement(ct, o);

9670:     for (c = 0; c < cS; ++c)
9671:       if (sourceCone[arr[c * 2]] != targetCone[c]) break;
9672:     if (c == cS) {
9673:       *ornt = o;
9674:       break;
9675:     }
9676:   }
9677:   *found = o == nO ? PETSC_FALSE : PETSC_TRUE;
9678:   PetscFunctionReturn(PETSC_SUCCESS);
9679: }

9681: /*@
9682:   DMPolytopeGetOrientation - Determine an orientation (transformation) that takes the source face arrangement to the target face arrangement

9684:   Not Collective

9686:   Input Parameters:
9687: + ct         - The `DMPolytopeType`
9688: . sourceCone - The source arrangement of faces
9689: - targetCone - The target arrangement of faces

9691:   Output Parameter:
9692: . ornt - The orientation (transformation) which will take the source arrangement to the target arrangement

9694:   Level: advanced

9696:   Note:
9697:   This function is the same as `DMPolytopeMatchOrientation()` except it will generate an error if no suitable orientation can be found.

9699:   Developer Note:
9700:   It is unclear why this function needs to exist since one can simply call `DMPolytopeMatchOrientation()` and error if none is found

9702: .seealso: [](ch_dmbase), `DM`, `DMPolytopeType`, `DMPolytopeMatchOrientation()`, `DMPolytopeGetVertexOrientation()`, `DMPolytopeMatchVertexOrientation()`
9703: @*/
9704: PetscErrorCode DMPolytopeGetOrientation(DMPolytopeType ct, const PetscInt sourceCone[], const PetscInt targetCone[], PetscInt *ornt)
9705: {
9706:   PetscBool found;

9708:   PetscFunctionBegin;
9709:   PetscCall(DMPolytopeMatchOrientation(ct, sourceCone, targetCone, ornt, &found));
9710:   PetscCheck(found, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Could not find orientation for %s", DMPolytopeTypes[ct]);
9711:   PetscFunctionReturn(PETSC_SUCCESS);
9712: }

9714: /*@
9715:   DMPolytopeMatchVertexOrientation - Determine an orientation (transformation) that takes the source vertex arrangement to the target vertex arrangement

9717:   Not Collective

9719:   Input Parameters:
9720: + ct         - The `DMPolytopeType`
9721: . sourceVert - The source arrangement of vertices
9722: - targetVert - The target arrangement of vertices

9724:   Output Parameters:
9725: + ornt  - The orientation (transformation) which will take the source arrangement to the target arrangement
9726: - found - Flag indicating that a suitable orientation was found

9728:   Level: advanced

9730:   Notes:
9731:   An arrangement is a vertex order

9733:   Each orientation (transformation) is labeled with an integer from negative `DMPolytopeTypeGetNumArrangements(ct)`/2 to `DMPolytopeTypeGetNumArrangements(ct)`/2
9734:   that labels each arrangement (vertex ordering).

9736:   See `DMPolytopeMatchOrientation()` to find a new face orientation that takes the source face arrangement to the target face arrangement

9738: .seealso: [](ch_dmbase), `DM`, `DMPolytopeType`, `DMPolytopeGetOrientation()`, `DMPolytopeMatchOrientation()`, `DMPolytopeTypeGetNumVertices()`, `DMPolytopeTypeGetVertexArrangement()`
9739: @*/
9740: PetscErrorCode DMPolytopeMatchVertexOrientation(DMPolytopeType ct, const PetscInt sourceVert[], const PetscInt targetVert[], PetscInt *ornt, PetscBool *found)
9741: {
9742:   const PetscInt cS = DMPolytopeTypeGetNumVertices(ct);
9743:   const PetscInt nO = DMPolytopeTypeGetNumArrangements(ct) / 2;
9744:   PetscInt       o, c;

9746:   PetscFunctionBegin;
9747:   if (!nO) {
9748:     *ornt  = 0;
9749:     *found = PETSC_TRUE;
9750:     PetscFunctionReturn(PETSC_SUCCESS);
9751:   }
9752:   for (o = -nO; o < nO; ++o) {
9753:     const PetscInt *arr = DMPolytopeTypeGetVertexArrangement(ct, o);

9755:     for (c = 0; c < cS; ++c)
9756:       if (sourceVert[arr[c]] != targetVert[c]) break;
9757:     if (c == cS) {
9758:       *ornt = o;
9759:       break;
9760:     }
9761:   }
9762:   *found = o == nO ? PETSC_FALSE : PETSC_TRUE;
9763:   PetscFunctionReturn(PETSC_SUCCESS);
9764: }

9766: /*@
9767:   DMPolytopeGetVertexOrientation - Determine an orientation (transformation) that takes the source vertex arrangement to the target vertex arrangement

9769:   Not Collective

9771:   Input Parameters:
9772: + ct         - The `DMPolytopeType`
9773: . sourceCone - The source arrangement of vertices
9774: - targetCone - The target arrangement of vertices

9776:   Output Parameter:
9777: . ornt - The orientation (transformation) which will take the source arrangement to the target arrangement

9779:   Level: advanced

9781:   Note:
9782:   This function is the same as `DMPolytopeMatchVertexOrientation()` except it errors if not orientation is possible.

9784:   Developer Note:
9785:   It is unclear why this function needs to exist since one can simply call `DMPolytopeMatchVertexOrientation()` and error if none is found

9787: .seealso: [](ch_dmbase), `DM`, `DMPolytopeType`, `DMPolytopeMatchVertexOrientation()`, `DMPolytopeGetOrientation()`
9788: @*/
9789: PetscErrorCode DMPolytopeGetVertexOrientation(DMPolytopeType ct, const PetscInt sourceCone[], const PetscInt targetCone[], PetscInt *ornt)
9790: {
9791:   PetscBool found;

9793:   PetscFunctionBegin;
9794:   PetscCall(DMPolytopeMatchVertexOrientation(ct, sourceCone, targetCone, ornt, &found));
9795:   PetscCheck(found, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Could not find orientation for %s", DMPolytopeTypes[ct]);
9796:   PetscFunctionReturn(PETSC_SUCCESS);
9797: }

9799: /*@
9800:   DMPolytopeInCellTest - Check whether a point lies inside the reference cell of given type

9802:   Not Collective

9804:   Input Parameters:
9805: + ct    - The `DMPolytopeType`
9806: - point - Coordinates of the point

9808:   Output Parameter:
9809: . inside - Flag indicating whether the point is inside the reference cell of given type

9811:   Level: advanced

9813: .seealso: [](ch_dmbase), `DM`, `DMPolytopeType`, `DMLocatePoints()`
9814: @*/
9815: PetscErrorCode DMPolytopeInCellTest(DMPolytopeType ct, const PetscReal point[], PetscBool *inside)
9816: {
9817:   PetscReal sum = 0.0;

9819:   PetscFunctionBegin;
9820:   *inside = PETSC_TRUE;
9821:   switch (ct) {
9822:   case DM_POLYTOPE_TRIANGLE:
9823:   case DM_POLYTOPE_TETRAHEDRON:
9824:     for (PetscInt d = 0; d < DMPolytopeTypeGetDim(ct); ++d) {
9825:       if (point[d] < -1.0) {
9826:         *inside = PETSC_FALSE;
9827:         break;
9828:       }
9829:       sum += point[d];
9830:     }
9831:     if (sum > PETSC_SMALL) {
9832:       *inside = PETSC_FALSE;
9833:       break;
9834:     }
9835:     break;
9836:   case DM_POLYTOPE_QUADRILATERAL:
9837:   case DM_POLYTOPE_HEXAHEDRON:
9838:     for (PetscInt d = 0; d < DMPolytopeTypeGetDim(ct); ++d)
9839:       if (PetscAbsReal(point[d]) > 1. + PETSC_SMALL) {
9840:         *inside = PETSC_FALSE;
9841:         break;
9842:       }
9843:     break;
9844:   default:
9845:     SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Unsupported polytope type %s", DMPolytopeTypes[ct]);
9846:   }
9847:   PetscFunctionReturn(PETSC_SUCCESS);
9848: }

9850: /*@
9851:   DMReorderSectionSetDefault - Set flag indicating whether the local section should be reordered by default

9853:   Logically collective

9855:   Input Parameters:
9856: + dm      - The DM
9857: - reorder - Flag for reordering

9859:   Level: intermediate

9861: .seealso: `DMReorderSectionGetDefault()`
9862: @*/
9863: PetscErrorCode DMReorderSectionSetDefault(DM dm, DMReorderDefaultFlag reorder)
9864: {
9865:   PetscFunctionBegin;
9867:   PetscTryMethod(dm, "DMReorderSectionSetDefault_C", (DM, DMReorderDefaultFlag), (dm, reorder));
9868:   PetscFunctionReturn(PETSC_SUCCESS);
9869: }

9871: /*@
9872:   DMReorderSectionGetDefault - Get flag indicating whether the local section should be reordered by default

9874:   Not collective

9876:   Input Parameter:
9877: . dm - The DM

9879:   Output Parameter:
9880: . reorder - Flag for reordering

9882:   Level: intermediate

9884: .seealso: `DMReorderSetDefault()`
9885: @*/
9886: PetscErrorCode DMReorderSectionGetDefault(DM dm, DMReorderDefaultFlag *reorder)
9887: {
9888:   PetscFunctionBegin;
9890:   PetscAssertPointer(reorder, 2);
9891:   *reorder = DM_REORDER_DEFAULT_NOTSET;
9892:   PetscTryMethod(dm, "DMReorderSectionGetDefault_C", (DM, DMReorderDefaultFlag *), (dm, reorder));
9893:   PetscFunctionReturn(PETSC_SUCCESS);
9894: }

9896: /*@
9897:   DMReorderSectionSetType - Set the type of local section reordering

9899:   Logically collective

9901:   Input Parameters:
9902: + dm      - The DM
9903: - reorder - The reordering method

9905:   Level: intermediate

9907: .seealso: `DMReorderSectionGetType()`, `DMReorderSectionSetDefault()`
9908: @*/
9909: PetscErrorCode DMReorderSectionSetType(DM dm, MatOrderingType reorder)
9910: {
9911:   PetscFunctionBegin;
9913:   PetscTryMethod(dm, "DMReorderSectionSetType_C", (DM, MatOrderingType), (dm, reorder));
9914:   PetscFunctionReturn(PETSC_SUCCESS);
9915: }

9917: /*@
9918:   DMReorderSectionGetType - Get the reordering type for the local section

9920:   Not collective

9922:   Input Parameter:
9923: . dm - The DM

9925:   Output Parameter:
9926: . reorder - The reordering method

9928:   Level: intermediate

9930: .seealso: `DMReorderSetDefault()`, `DMReorderSectionGetDefault()`
9931: @*/
9932: PetscErrorCode DMReorderSectionGetType(DM dm, MatOrderingType *reorder)
9933: {
9934:   PetscFunctionBegin;
9936:   PetscAssertPointer(reorder, 2);
9937:   *reorder = NULL;
9938:   PetscTryMethod(dm, "DMReorderSectionGetType_C", (DM, MatOrderingType *), (dm, reorder));
9939:   PetscFunctionReturn(PETSC_SUCCESS);
9940: }