Actual source code: dm.c

  1: #include <petscvec.h>
  2: #include <petsc/private/dmimpl.h>
  3: #include <petsc/private/dmlabelimpl.h>
  4: #include <petsc/private/petscdsimpl.h>
  5: #include <petscdmplex.h>
  6: #include <petscdmceed.h>
  7: #include <petscdmfield.h>
  8: #include <petscsf.h>
  9: #include <petscds.h>

 11: #ifdef PETSC_HAVE_LIBCEED
 12: #include <petscfeceed.h>
 13: #endif

 15: PetscClassId DM_CLASSID;
 16: PetscClassId DMLABEL_CLASSID;
 17: PetscLogEvent DM_Convert, DM_GlobalToLocal, DM_LocalToGlobal, DM_LocalToLocal, DM_LocatePoints, DM_Coarsen, DM_Refine, DM_CreateInterpolation, DM_CreateRestriction, DM_CreateInjection, DM_CreateMatrix, DM_CreateMassMatrix, DM_Load, DM_View, DM_AdaptInterpolator, DM_ProjectFunction;

 19: const char *const DMBoundaryTypes[]          = {"NONE", "GHOSTED", "MIRROR", "PERIODIC", "TWIST", "DMBoundaryType", "DM_BOUNDARY_", NULL};
 20: const char *const DMBoundaryConditionTypes[] = {"INVALID", "ESSENTIAL", "NATURAL", "INVALID", "LOWER_BOUND", "ESSENTIAL_FIELD", "NATURAL_FIELD", "INVALID", "UPPER_BOUND", "ESSENTIAL_BD_FIELD", "NATURAL_RIEMANN", "DMBoundaryConditionType",
 21:                                                 "DM_BC_",  NULL};
 22: const char *const DMBlockingTypes[]          = {"TOPOLOGICAL_POINT", "FIELD_NODE", "DMBlockingType", "DM_BLOCKING_", NULL};
 23: const char *const DMPolytopeTypes[] =
 24:   {"vertex",  "segment",      "tensor_segment", "triangle", "quadrilateral",  "tensor_quad",  "tetrahedron", "hexahedron", "triangular_prism", "tensor_triangular_prism", "tensor_quadrilateral_prism", "pyramid", "FV_ghost_cell", "interior_ghost_cell",
 25:    "unknown", "unknown_cell", "unknown_face",   "invalid",  "DMPolytopeType", "DM_POLYTOPE_", NULL};
 26: const char *const DMCopyLabelsModes[] = {"replace", "keep", "fail", "DMCopyLabelsMode", "DM_COPY_LABELS_", NULL};

 28: /*@
 29:   DMCreate - Creates an empty `DM` object. `DM`s are the abstract objects in PETSc that mediate between meshes and discretizations and the
 30:   algebraic solvers, time integrators, and optimization algorithms in PETSc.

 32:   Collective

 34:   Input Parameter:
 35: . comm - The communicator for the `DM` object

 37:   Output Parameter:
 38: . dm - The `DM` object

 40:   Level: beginner

 42:   Notes:
 43:   See `DMType` for a brief summary of available `DM`.

 45:   The type must then be set with `DMSetType()`. If you never call `DMSetType()` it will generate an
 46:   error when you try to use the `dm`.

 48:   `DM` is an orphan initialism or orphan acronym, the letters have no meaning and never did.

 50: .seealso: [](ch_dmbase), `DM`, `DMSetType()`, `DMType`, `DMDACreate()`, `DMDA`, `DMSLICED`, `DMCOMPOSITE`, `DMPLEX`, `DMMOAB`, `DMNETWORK`
 51: @*/
 52: PetscErrorCode DMCreate(MPI_Comm comm, DM *dm)
 53: {
 54:   DM      v;
 55:   PetscDS ds;

 57:   PetscFunctionBegin;
 58:   PetscAssertPointer(dm, 2);

 60:   PetscCall(DMInitializePackage());
 61:   PetscCall(PetscHeaderCreate(v, DM_CLASSID, "DM", "Distribution Manager", "DM", comm, DMDestroy, DMView));
 62:   ((PetscObject)v)->non_cyclic_references = &DMCountNonCyclicReferences;
 63:   v->setupcalled                          = PETSC_FALSE;
 64:   v->setfromoptionscalled                 = PETSC_FALSE;
 65:   v->ltogmap                              = NULL;
 66:   v->bind_below                           = 0;
 67:   v->bs                                   = 1;
 68:   v->coloringtype                         = IS_COLORING_GLOBAL;
 69:   PetscCall(PetscSFCreate(comm, &v->sf));
 70:   PetscCall(PetscSFCreate(comm, &v->sectionSF));
 71:   v->labels                    = NULL;
 72:   v->adjacency[0]              = PETSC_FALSE;
 73:   v->adjacency[1]              = PETSC_TRUE;
 74:   v->depthLabel                = NULL;
 75:   v->celltypeLabel             = NULL;
 76:   v->localSection              = NULL;
 77:   v->globalSection             = NULL;
 78:   v->defaultConstraint.section = NULL;
 79:   v->defaultConstraint.mat     = NULL;
 80:   v->defaultConstraint.bias    = NULL;
 81:   v->coordinates[0].dim        = PETSC_DEFAULT;
 82:   v->coordinates[1].dim        = PETSC_DEFAULT;
 83:   v->sparseLocalize            = PETSC_TRUE;
 84:   v->dim                       = PETSC_DETERMINE;
 85:   PetscCall(PetscDSCreate(PETSC_COMM_SELF, &ds));
 86:   PetscCall(DMSetRegionDS(v, NULL, NULL, ds, NULL));
 87:   PetscCall(PetscDSDestroy(&ds));
 88:   PetscCall(PetscHMapAuxCreate(&v->auxData));
 89:   v->dmBC              = NULL;
 90:   v->coarseMesh        = NULL;
 91:   v->outputSequenceNum = -1;
 92:   v->outputSequenceVal = 0.0;
 93:   PetscCall(DMSetVecType(v, VECSTANDARD));
 94:   PetscCall(DMSetMatType(v, MATAIJ));

 96:   *dm = v;
 97:   PetscFunctionReturn(PETSC_SUCCESS);
 98: }

100: /*@
101:   DMClone - Creates a `DM` object with the same topology as the original.

103:   Collective

105:   Input Parameter:
106: . dm - The original `DM` object

108:   Output Parameter:
109: . newdm - The new `DM` object

111:   Level: beginner

113:   Notes:
114:   For some `DM` implementations this is a shallow clone, the result of which may share (reference counted) information with its parent. For example,
115:   `DMClone()` applied to a `DMPLEX` object will result in a new `DMPLEX` that shares the topology with the original `DMPLEX`. It does not
116:   share the `PetscSection` of the original `DM`.

118:   The clone is considered set up if the original has been set up.

120:   Use `DMConvert()` for a general way to create new `DM` from a given `DM`

122: .seealso: [](ch_dmbase), `DM`, `DMDestroy()`, `DMCreate()`, `DMSetType()`, `DMSetLocalSection()`, `DMSetGlobalSection()`, `DMPLEX`, `DMConvert()`
123: @*/
124: PetscErrorCode DMClone(DM dm, DM *newdm)
125: {
126:   PetscSF              sf;
127:   Vec                  coords;
128:   void                *ctx;
129:   MatOrderingType      otype;
130:   DMReorderDefaultFlag flg;
131:   PetscInt             dim, cdim, i;
132:   PetscBool            sparse;

134:   PetscFunctionBegin;
136:   PetscAssertPointer(newdm, 2);
137:   PetscCall(DMCreate(PetscObjectComm((PetscObject)dm), newdm));
138:   PetscCall(DMCopyLabels(dm, *newdm, PETSC_COPY_VALUES, PETSC_TRUE, DM_COPY_LABELS_FAIL));
139:   (*newdm)->leveldown     = dm->leveldown;
140:   (*newdm)->levelup       = dm->levelup;
141:   (*newdm)->prealloc_only = dm->prealloc_only;
142:   (*newdm)->prealloc_skip = dm->prealloc_skip;
143:   PetscCall(PetscFree((*newdm)->vectype));
144:   PetscCall(PetscStrallocpy(dm->vectype, (char **)&(*newdm)->vectype));
145:   PetscCall(PetscFree((*newdm)->mattype));
146:   PetscCall(PetscStrallocpy(dm->mattype, (char **)&(*newdm)->mattype));
147:   PetscCall(DMGetDimension(dm, &dim));
148:   PetscCall(DMSetDimension(*newdm, dim));
149:   PetscTryTypeMethod(dm, clone, newdm);
150:   (*newdm)->setupcalled = dm->setupcalled;
151:   PetscCall(DMGetPointSF(dm, &sf));
152:   PetscCall(DMSetPointSF(*newdm, sf));
153:   PetscCall(DMGetApplicationContext(dm, &ctx));
154:   PetscCall(DMSetApplicationContext(*newdm, ctx));
155:   PetscCall(DMReorderSectionGetDefault(dm, &flg));
156:   PetscCall(DMReorderSectionSetDefault(*newdm, flg));
157:   PetscCall(DMReorderSectionGetType(dm, &otype));
158:   PetscCall(DMReorderSectionSetType(*newdm, otype));
159:   for (i = 0; i < 2; ++i) {
160:     if (dm->coordinates[i].dm) {
161:       DM           ncdm;
162:       PetscSection cs;
163:       PetscInt     pEnd = -1, pEndMax = -1;

165:       PetscCall(DMGetLocalSection(dm->coordinates[i].dm, &cs));
166:       if (cs) PetscCall(PetscSectionGetChart(cs, NULL, &pEnd));
167:       PetscCallMPI(MPIU_Allreduce(&pEnd, &pEndMax, 1, MPIU_INT, MPI_MAX, PetscObjectComm((PetscObject)dm)));
168:       if (pEndMax >= 0) {
169:         PetscCall(DMClone(dm->coordinates[i].dm, &ncdm));
170:         PetscCall(DMCopyDisc(dm->coordinates[i].dm, ncdm));
171:         PetscCall(DMSetLocalSection(ncdm, cs));
172:         if (dm->coordinates[i].dm->periodic.setup) {
173:           ncdm->periodic.setup = dm->coordinates[i].dm->periodic.setup;
174:           PetscCall(ncdm->periodic.setup(ncdm));
175:         }
176:         if (i) PetscCall(DMSetCellCoordinateDM(*newdm, ncdm));
177:         else PetscCall(DMSetCoordinateDM(*newdm, ncdm));
178:         PetscCall(DMDestroy(&ncdm));
179:       }
180:     }
181:   }
182:   PetscCall(DMGetCoordinateDim(dm, &cdim));
183:   PetscCall(DMSetCoordinateDim(*newdm, cdim));
184:   PetscCall(DMGetCoordinatesLocal(dm, &coords));
185:   if (coords) {
186:     PetscCall(DMSetCoordinatesLocal(*newdm, coords));
187:   } else {
188:     PetscCall(DMGetCoordinates(dm, &coords));
189:     if (coords) PetscCall(DMSetCoordinates(*newdm, coords));
190:   }
191:   PetscCall(DMGetSparseLocalize(dm, &sparse));
192:   PetscCall(DMSetSparseLocalize(*newdm, sparse));
193:   PetscCall(DMGetCellCoordinatesLocal(dm, &coords));
194:   if (coords) {
195:     PetscCall(DMSetCellCoordinatesLocal(*newdm, coords));
196:   } else {
197:     PetscCall(DMGetCellCoordinates(dm, &coords));
198:     if (coords) PetscCall(DMSetCellCoordinates(*newdm, coords));
199:   }
200:   {
201:     const PetscReal *maxCell, *Lstart, *L;

203:     PetscCall(DMGetPeriodicity(dm, &maxCell, &Lstart, &L));
204:     PetscCall(DMSetPeriodicity(*newdm, maxCell, Lstart, L));
205:   }
206:   {
207:     PetscBool useCone, useClosure;

209:     PetscCall(DMGetAdjacency(dm, PETSC_DEFAULT, &useCone, &useClosure));
210:     PetscCall(DMSetAdjacency(*newdm, PETSC_DEFAULT, useCone, useClosure));
211:   }
212:   PetscFunctionReturn(PETSC_SUCCESS);
213: }

215: /*@
216:   DMSetVecType - Sets the type of vector to be created with `DMCreateLocalVector()` and `DMCreateGlobalVector()`

218:   Logically Collective

220:   Input Parameters:
221: + dm    - initial distributed array
222: - ctype - the vector type, for example `VECSTANDARD`, `VECCUDA`, or `VECVIENNACL`

224:   Options Database Key:
225: . -dm_vec_type ctype - the type of vector to create

227:   Level: intermediate

229: .seealso: [](ch_dmbase), `DM`, `DMCreate()`, `DMDestroy()`, `DMDAInterpolationType`, `VecType`, `DMGetVecType()`, `DMSetMatType()`, `DMGetMatType()`,
230:           `VECSTANDARD`, `VECCUDA`, `VECVIENNACL`, `DMCreateLocalVector()`, `DMCreateGlobalVector()`
231: @*/
232: PetscErrorCode DMSetVecType(DM dm, VecType ctype)
233: {
234:   char *tmp;

236:   PetscFunctionBegin;
238:   PetscAssertPointer(ctype, 2);
239:   tmp = (char *)dm->vectype;
240:   PetscCall(PetscStrallocpy(ctype, (char **)&dm->vectype));
241:   PetscCall(PetscFree(tmp));
242:   PetscFunctionReturn(PETSC_SUCCESS);
243: }

245: /*@
246:   DMGetVecType - Gets the type of vector created with `DMCreateLocalVector()` and `DMCreateGlobalVector()`

248:   Logically Collective

250:   Input Parameter:
251: . da - initial distributed array

253:   Output Parameter:
254: . ctype - the vector type

256:   Level: intermediate

258: .seealso: [](ch_dmbase), `DM`, `DMCreate()`, `DMDestroy()`, `DMDAInterpolationType`, `VecType`, `DMSetMatType()`, `DMGetMatType()`, `DMSetVecType()`
259: @*/
260: PetscErrorCode DMGetVecType(DM da, VecType *ctype)
261: {
262:   PetscFunctionBegin;
264:   *ctype = da->vectype;
265:   PetscFunctionReturn(PETSC_SUCCESS);
266: }

268: /*@
269:   VecGetDM - Gets the `DM` defining the data layout of the vector

271:   Not Collective

273:   Input Parameter:
274: . v - The `Vec`

276:   Output Parameter:
277: . dm - The `DM`

279:   Level: intermediate

281:   Note:
282:   A `Vec` may not have a `DM` associated with it.

284: .seealso: [](ch_dmbase), `DM`, `VecSetDM()`, `DMGetLocalVector()`, `DMGetGlobalVector()`, `DMSetVecType()`
285: @*/
286: PetscErrorCode VecGetDM(Vec v, DM *dm)
287: {
288:   PetscFunctionBegin;
290:   PetscAssertPointer(dm, 2);
291:   PetscCall(PetscObjectQuery((PetscObject)v, "__PETSc_dm", (PetscObject *)dm));
292:   PetscFunctionReturn(PETSC_SUCCESS);
293: }

295: /*@
296:   VecSetDM - Sets the `DM` defining the data layout of the vector.

298:   Not Collective

300:   Input Parameters:
301: + v  - The `Vec`
302: - dm - The `DM`

304:   Level: developer

306:   Notes:
307:   This is rarely used, generally one uses `DMGetLocalVector()` or  `DMGetGlobalVector()` to create a vector associated with a given `DM`

309:   This is NOT the same as `DMCreateGlobalVector()` since it does not change the view methods or perform other customization, but merely sets the `DM` member.

311: .seealso: [](ch_dmbase), `DM`, `VecGetDM()`, `DMGetLocalVector()`, `DMGetGlobalVector()`, `DMSetVecType()`
312: @*/
313: PetscErrorCode VecSetDM(Vec v, DM dm)
314: {
315:   PetscFunctionBegin;
318:   PetscCall(PetscObjectCompose((PetscObject)v, "__PETSc_dm", (PetscObject)dm));
319:   PetscFunctionReturn(PETSC_SUCCESS);
320: }

322: /*@
323:   DMSetISColoringType - Sets the type of coloring, `IS_COLORING_GLOBAL` or `IS_COLORING_LOCAL` that is created by the `DM`

325:   Logically Collective

327:   Input Parameters:
328: + dm    - the `DM` context
329: - ctype - the matrix type

331:   Options Database Key:
332: . -dm_is_coloring_type (global|local) - see `ISColoringType`

334:   Level: intermediate

336: .seealso: [](ch_dmbase), `DM`, `DMDACreate1d()`, `DMDACreate2d()`, `DMDACreate3d()`, `DMCreateMatrix()`, `DMCreateMassMatrix()`, `DMSetMatrixPreallocateOnly()`, `MatType`, `DMGetMatType()`,
337:           `DMGetISColoringType()`, `ISColoringType`, `IS_COLORING_GLOBAL`, `IS_COLORING_LOCAL`
338: @*/
339: PetscErrorCode DMSetISColoringType(DM dm, ISColoringType ctype)
340: {
341:   PetscFunctionBegin;
343:   dm->coloringtype = ctype;
344:   PetscFunctionReturn(PETSC_SUCCESS);
345: }

347: /*@
348:   DMGetISColoringType - Gets the type of coloring, `IS_COLORING_GLOBAL` or `IS_COLORING_LOCAL` that is created by the `DM`

350:   Logically Collective

352:   Input Parameter:
353: . dm - the `DM` context

355:   Output Parameter:
356: . ctype - the matrix type

358:   Level: intermediate

360: .seealso: [](ch_dmbase), `DM`, `DMDACreate1d()`, `DMDACreate2d()`, `DMDACreate3d()`, `DMCreateMatrix()`, `DMCreateMassMatrix()`, `DMSetMatrixPreallocateOnly()`, `MatType`, `DMGetMatType()`,
361:           `ISColoringType`, `IS_COLORING_GLOBAL`, `IS_COLORING_LOCAL`
362: @*/
363: PetscErrorCode DMGetISColoringType(DM dm, ISColoringType *ctype)
364: {
365:   PetscFunctionBegin;
367:   *ctype = dm->coloringtype;
368:   PetscFunctionReturn(PETSC_SUCCESS);
369: }

371: /*@
372:   DMSetMatType - Sets the type of matrix created with `DMCreateMatrix()`

374:   Logically Collective

376:   Input Parameters:
377: + dm    - the `DM` context
378: - ctype - the matrix type, for example `MATMPIAIJ`

380:   Options Database Key:
381: . -dm_mat_type ctype - the type of the matrix to create, see `MatType`

383:   Level: intermediate

385: .seealso: [](ch_dmbase), `DM`, `MatType`, `DMDACreate1d()`, `DMDACreate2d()`, `DMDACreate3d()`, `DMCreateMatrix()`, `DMCreateMassMatrix()`, `DMSetMatrixPreallocateOnly()`, `DMGetMatType()`, `DMCreateGlobalVector()`, `DMCreateLocalVector()`
386: @*/
387: PetscErrorCode DMSetMatType(DM dm, MatType ctype)
388: {
389:   char *tmp;

391:   PetscFunctionBegin;
393:   PetscAssertPointer(ctype, 2);
394:   tmp = (char *)dm->mattype;
395:   PetscCall(PetscStrallocpy(ctype, (char **)&dm->mattype));
396:   PetscCall(PetscFree(tmp));
397:   PetscFunctionReturn(PETSC_SUCCESS);
398: }

400: /*@
401:   DMGetMatType - Gets the type of matrix that would be created with `DMCreateMatrix()`

403:   Logically Collective

405:   Input Parameter:
406: . dm - the `DM` context

408:   Output Parameter:
409: . ctype - the matrix type

411:   Level: intermediate

413: .seealso: [](ch_dmbase), `DM`, `DMDACreate1d()`, `DMDACreate2d()`, `DMDACreate3d()`, `DMCreateMatrix()`, `DMCreateMassMatrix()`, `DMSetMatrixPreallocateOnly()`, `MatType`, `DMSetMatType()`
414: @*/
415: PetscErrorCode DMGetMatType(DM dm, MatType *ctype)
416: {
417:   PetscFunctionBegin;
419:   *ctype = dm->mattype;
420:   PetscFunctionReturn(PETSC_SUCCESS);
421: }

423: /*@
424:   MatGetDM - Gets the `DM` defining the data layout of the matrix

426:   Not Collective

428:   Input Parameter:
429: . A - The `Mat`

431:   Output Parameter:
432: . dm - The `DM`

434:   Level: intermediate

436:   Note:
437:   A matrix may not have a `DM` associated with it

439:   Developer Note:
440:   Since the `Mat` class doesn't know about the `DM` class the `DM` object is associated with the `Mat` through a `PetscObjectCompose()` operation

442: .seealso: [](ch_dmbase), `DM`, `MatSetDM()`, `DMCreateMatrix()`, `DMSetMatType()`
443: @*/
444: PetscErrorCode MatGetDM(Mat A, DM *dm)
445: {
446:   PetscFunctionBegin;
448:   PetscAssertPointer(dm, 2);
449:   PetscCall(PetscObjectQuery((PetscObject)A, "__PETSc_dm", (PetscObject *)dm));
450:   PetscFunctionReturn(PETSC_SUCCESS);
451: }

453: /*@
454:   MatSetDM - Sets the `DM` defining the data layout of the matrix

456:   Not Collective

458:   Input Parameters:
459: + A  - The `Mat`
460: - dm - The `DM`

462:   Level: developer

464:   Note:
465:   This is rarely used in practice, rather `DMCreateMatrix()` is used to create a matrix associated with a particular `DM`

467:   Developer Note:
468:   Since the `Mat` class doesn't know about the `DM` class the `DM` object is associated with
469:   the `Mat` through a `PetscObjectCompose()` operation

471: .seealso: [](ch_dmbase), `DM`, `MatGetDM()`, `DMCreateMatrix()`, `DMSetMatType()`
472: @*/
473: PetscErrorCode MatSetDM(Mat A, DM dm)
474: {
475:   PetscFunctionBegin;
478:   PetscCall(PetscObjectCompose((PetscObject)A, "__PETSc_dm", (PetscObject)dm));
479:   PetscFunctionReturn(PETSC_SUCCESS);
480: }

482: /*@
483:   DMSetOptionsPrefix - Sets the prefix prepended to all option names when searching through the options database

485:   Logically Collective

487:   Input Parameters:
488: + dm     - the `DM` context
489: - prefix - the prefix to prepend

491:   Level: advanced

493:   Note:
494:   A hyphen (-) must NOT be given at the beginning of the prefix name.
495:   The first character of all runtime options is AUTOMATICALLY the hyphen.

497: .seealso: [](ch_dmbase), `DM`, `PetscObjectSetOptionsPrefix()`, `DMSetFromOptions()`
498: @*/
499: PetscErrorCode DMSetOptionsPrefix(DM dm, const char prefix[])
500: {
501:   PetscFunctionBegin;
503:   PetscCall(PetscObjectSetOptionsPrefix((PetscObject)dm, prefix));
504:   if (dm->sf) PetscCall(PetscObjectSetOptionsPrefix((PetscObject)dm->sf, prefix));
505:   if (dm->sectionSF) PetscCall(PetscObjectSetOptionsPrefix((PetscObject)dm->sectionSF, prefix));
506:   PetscFunctionReturn(PETSC_SUCCESS);
507: }

509: /*@
510:   DMAppendOptionsPrefix - Appends an additional string to an already existing prefix used for searching for
511:   `DM` options in the options database.

513:   Logically Collective

515:   Input Parameters:
516: + dm     - the `DM` context
517: - prefix - the string to append to the current prefix

519:   Level: advanced

521:   Note:
522:   If the `DM` does not currently have an options prefix then this value is used alone as the prefix as if `DMSetOptionsPrefix()` had been called.
523:   A hyphen (-) must NOT be given at the beginning of the prefix name.
524:   The first character of all runtime options is AUTOMATICALLY the hyphen.

526: .seealso: [](ch_dmbase), `DM`, `DMSetOptionsPrefix()`, `DMGetOptionsPrefix()`, `PetscObjectAppendOptionsPrefix()`, `DMSetFromOptions()`
527: @*/
528: PetscErrorCode DMAppendOptionsPrefix(DM dm, const char prefix[])
529: {
530:   PetscFunctionBegin;
532:   PetscCall(PetscObjectAppendOptionsPrefix((PetscObject)dm, prefix));
533:   PetscFunctionReturn(PETSC_SUCCESS);
534: }

536: /*@
537:   DMGetOptionsPrefix - Gets the prefix used for searching for all
538:   DM options in the options database.

540:   Not Collective

542:   Input Parameter:
543: . dm - the `DM` context

545:   Output Parameter:
546: . prefix - pointer to the prefix string used is returned

548:   Level: advanced

550: .seealso: [](ch_dmbase), `DM`, `DMSetOptionsPrefix()`, `DMAppendOptionsPrefix()`, `DMSetFromOptions()`
551: @*/
552: PetscErrorCode DMGetOptionsPrefix(DM dm, const char *prefix[])
553: {
554:   PetscFunctionBegin;
556:   PetscCall(PetscObjectGetOptionsPrefix((PetscObject)dm, prefix));
557:   PetscFunctionReturn(PETSC_SUCCESS);
558: }

560: static PetscErrorCode DMCountNonCyclicReferences_Internal(DM dm, PetscBool recurseCoarse, PetscBool recurseFine, PetscInt *ncrefct)
561: {
562:   PetscInt refct = ((PetscObject)dm)->refct;

564:   PetscFunctionBegin;
565:   *ncrefct = 0;
566:   if (dm->coarseMesh && dm->coarseMesh->fineMesh == dm) {
567:     refct--;
568:     if (recurseCoarse) {
569:       PetscInt coarseCount;

571:       PetscCall(DMCountNonCyclicReferences_Internal(dm->coarseMesh, PETSC_TRUE, PETSC_FALSE, &coarseCount));
572:       refct += coarseCount;
573:     }
574:   }
575:   if (dm->fineMesh && dm->fineMesh->coarseMesh == dm) {
576:     refct--;
577:     if (recurseFine) {
578:       PetscInt fineCount;

580:       PetscCall(DMCountNonCyclicReferences_Internal(dm->fineMesh, PETSC_FALSE, PETSC_TRUE, &fineCount));
581:       refct += fineCount;
582:     }
583:   }
584:   *ncrefct = refct;
585:   PetscFunctionReturn(PETSC_SUCCESS);
586: }

588: /* Generic wrapper for DMCountNonCyclicReferences_Internal() */
589: PetscErrorCode DMCountNonCyclicReferences(PetscObject dm, PetscInt *ncrefct)
590: {
591:   PetscFunctionBegin;
592:   PetscCall(DMCountNonCyclicReferences_Internal((DM)dm, PETSC_TRUE, PETSC_TRUE, ncrefct));
593:   PetscFunctionReturn(PETSC_SUCCESS);
594: }

596: PetscErrorCode DMDestroyLabelLinkList_Internal(DM dm)
597: {
598:   DMLabelLink next = dm->labels;

600:   PetscFunctionBegin;
601:   /* destroy the labels */
602:   while (next) {
603:     DMLabelLink tmp = next->next;

605:     if (next->label == dm->depthLabel) dm->depthLabel = NULL;
606:     if (next->label == dm->celltypeLabel) dm->celltypeLabel = NULL;
607:     PetscCall(DMLabelDestroy(&next->label));
608:     PetscCall(PetscFree(next));
609:     next = tmp;
610:   }
611:   dm->labels = NULL;
612:   PetscFunctionReturn(PETSC_SUCCESS);
613: }

615: PetscErrorCode DMDestroyCoordinates_Internal(DMCoordinates *c)
616: {
617:   PetscFunctionBegin;
618:   c->dim = PETSC_DEFAULT;
619:   PetscCall(DMDestroy(&c->dm));
620:   PetscCall(VecDestroy(&c->x));
621:   PetscCall(VecDestroy(&c->xl));
622:   PetscCall(DMFieldDestroy(&c->field));
623:   PetscFunctionReturn(PETSC_SUCCESS);
624: }

626: /*@
627:   DMDestroy - Destroys a `DM`.

629:   Collective

631:   Input Parameter:
632: . dm - the `DM` object to destroy

634:   Level: developer

636: .seealso: [](ch_dmbase), `DM`, `DMCreate()`, `DMType`, `DMSetType()`, `DMView()`, `DMCreateGlobalVector()`, `DMCreateInterpolation()`, `DMCreateColoring()`, `DMCreateMatrix()`
637: @*/
638: PetscErrorCode DMDestroy(DM *dm)
639: {
640:   PetscInt cnt;

642:   PetscFunctionBegin;
643:   if (!*dm) PetscFunctionReturn(PETSC_SUCCESS);

646:   /* count all non-cyclic references in the doubly-linked list of coarse<->fine meshes */
647:   PetscCall(DMCountNonCyclicReferences_Internal(*dm, PETSC_TRUE, PETSC_TRUE, &cnt));
648:   --((PetscObject)*dm)->refct;
649:   if (--cnt > 0) {
650:     *dm = NULL;
651:     PetscFunctionReturn(PETSC_SUCCESS);
652:   }
653:   if (((PetscObject)*dm)->refct < 0) PetscFunctionReturn(PETSC_SUCCESS);
654:   ((PetscObject)*dm)->refct = 0;

656:   PetscCall(DMClearGlobalVectors(*dm));
657:   PetscCall(DMClearLocalVectors(*dm));
658:   PetscCall(DMClearNamedGlobalVectors(*dm));
659:   PetscCall(DMClearNamedLocalVectors(*dm));

661:   /* Destroy the list of hooks */
662:   {
663:     DMCoarsenHookLink link, next;
664:     for (link = (*dm)->coarsenhook; link; link = next) {
665:       next = link->next;
666:       PetscCall(PetscFree(link));
667:     }
668:     (*dm)->coarsenhook = NULL;
669:   }
670:   {
671:     DMRefineHookLink link, next;
672:     for (link = (*dm)->refinehook; link; link = next) {
673:       next = link->next;
674:       PetscCall(PetscFree(link));
675:     }
676:     (*dm)->refinehook = NULL;
677:   }
678:   {
679:     DMSubDomainHookLink link, next;
680:     for (link = (*dm)->subdomainhook; link; link = next) {
681:       next = link->next;
682:       PetscCall(PetscFree(link));
683:     }
684:     (*dm)->subdomainhook = NULL;
685:   }
686:   {
687:     DMGlobalToLocalHookLink link, next;
688:     for (link = (*dm)->gtolhook; link; link = next) {
689:       next = link->next;
690:       PetscCall(PetscFree(link));
691:     }
692:     (*dm)->gtolhook = NULL;
693:   }
694:   {
695:     DMLocalToGlobalHookLink link, next;
696:     for (link = (*dm)->ltoghook; link; link = next) {
697:       next = link->next;
698:       PetscCall(PetscFree(link));
699:     }
700:     (*dm)->ltoghook = NULL;
701:   }
702:   /* Destroy the work arrays */
703:   {
704:     DMWorkLink link, next;
705:     PetscCheck(!(*dm)->workout, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Work array still checked out %p %p", (void *)(*dm)->workout, (*dm)->workout->mem);
706:     for (link = (*dm)->workin; link; link = next) {
707:       next = link->next;
708:       PetscCall(PetscFree(link->mem));
709:       PetscCall(PetscFree(link));
710:     }
711:     (*dm)->workin = NULL;
712:   }
713:   /* destroy the labels */
714:   PetscCall(DMDestroyLabelLinkList_Internal(*dm));
715:   /* destroy the fields */
716:   PetscCall(DMClearFields(*dm));
717:   /* destroy the boundaries */
718:   {
719:     DMBoundary next = (*dm)->boundary;
720:     while (next) {
721:       DMBoundary b = next;

723:       next = b->next;
724:       PetscCall(PetscFree(b));
725:     }
726:   }

728:   PetscCall(PetscObjectDestroy(&(*dm)->dmksp));
729:   PetscCall(PetscObjectDestroy(&(*dm)->dmsnes));
730:   PetscCall(PetscObjectDestroy(&(*dm)->dmts));

732:   if ((*dm)->ctx && (*dm)->ctxdestroy) PetscCall((*(*dm)->ctxdestroy)(&(*dm)->ctx));
733:   PetscCall(MatFDColoringDestroy(&(*dm)->fd));
734:   PetscCall(ISLocalToGlobalMappingDestroy(&(*dm)->ltogmap));
735:   PetscCall(PetscFree((*dm)->vectype));
736:   PetscCall(PetscFree((*dm)->mattype));

738:   PetscCall(PetscSectionDestroy(&(*dm)->localSection));
739:   PetscCall(PetscSectionDestroy(&(*dm)->globalSection));
740:   PetscCall(PetscFree((*dm)->reorderSectionType));
741:   PetscCall(PetscLayoutDestroy(&(*dm)->map));
742:   PetscCall(PetscSectionDestroy(&(*dm)->defaultConstraint.section));
743:   PetscCall(MatDestroy(&(*dm)->defaultConstraint.mat));
744:   PetscCall(PetscSFDestroy(&(*dm)->sf));
745:   PetscCall(PetscSFDestroy(&(*dm)->sectionSF));
746:   PetscCall(PetscSFDestroy(&(*dm)->sfNatural));
747:   PetscCall(PetscObjectDereference((PetscObject)(*dm)->sfMigration));
748:   PetscCall(DMClearAuxiliaryVec(*dm));
749:   PetscCall(PetscHMapAuxDestroy(&(*dm)->auxData));
750:   if ((*dm)->coarseMesh && (*dm)->coarseMesh->fineMesh == *dm) PetscCall(DMSetFineDM((*dm)->coarseMesh, NULL));

752:   PetscCall(DMDestroy(&(*dm)->coarseMesh));
753:   if ((*dm)->fineMesh && (*dm)->fineMesh->coarseMesh == *dm) PetscCall(DMSetCoarseDM((*dm)->fineMesh, NULL));
754:   PetscCall(DMDestroy(&(*dm)->fineMesh));
755:   PetscCall(PetscFree((*dm)->Lstart));
756:   PetscCall(PetscFree((*dm)->L));
757:   PetscCall(PetscFree((*dm)->maxCell));
758:   PetscCall(PetscFree2((*dm)->nullspaceConstructors, (*dm)->nearnullspaceConstructors));
759:   PetscCall(DMDestroyCoordinates_Internal(&(*dm)->coordinates[0]));
760:   PetscCall(DMDestroyCoordinates_Internal(&(*dm)->coordinates[1]));
761:   if ((*dm)->transformDestroy) PetscCall((*(*dm)->transformDestroy)(*dm, (*dm)->transformCtx));
762:   PetscCall(DMDestroy(&(*dm)->transformDM));
763:   PetscCall(VecDestroy(&(*dm)->transform));
764:   for (PetscInt i = 0; i < (*dm)->periodic.num_affines; i++) {
765:     PetscCall(VecScatterDestroy(&(*dm)->periodic.affine_to_local[i]));
766:     PetscCall(VecDestroy(&(*dm)->periodic.affine[i]));
767:   }
768:   if ((*dm)->periodic.num_affines > 0) PetscCall(PetscFree2((*dm)->periodic.affine_to_local, (*dm)->periodic.affine));

770:   PetscCall(DMClearDS(*dm));
771:   PetscCall(DMDestroy(&(*dm)->dmBC));
772:   /* if memory was published with SAWs then destroy it */
773:   PetscCall(PetscObjectSAWsViewOff((PetscObject)*dm));

775:   PetscTryTypeMethod(*dm, destroy);
776:   PetscCall(DMMonitorCancel(*dm));
777:   PetscCall(DMCeedDestroy(&(*dm)->dmceed));
778: #ifdef PETSC_HAVE_LIBCEED
779:   PetscCallCEED(CeedElemRestrictionDestroy(&(*dm)->ceedERestrict));
780:   PetscCallCEED(CeedDestroy(&(*dm)->ceed));
781: #endif
782:   /* We do not destroy (*dm)->data here so that we can reference count backend objects */
783:   PetscCall(PetscHeaderDestroy(dm));
784:   PetscFunctionReturn(PETSC_SUCCESS);
785: }

787: /*@
788:   DMSetUp - sets up the data structures inside a `DM` object

790:   Collective

792:   Input Parameter:
793: . dm - the `DM` object to setup

795:   Level: intermediate

797:   Note:
798:   This is usually called after various parameter setting operations and `DMSetFromOptions()` are called on the `DM`

800: .seealso: [](ch_dmbase), `DM`, `DMCreate()`, `DMSetType()`, `DMView()`, `DMCreateGlobalVector()`, `DMCreateInterpolation()`, `DMCreateColoring()`, `DMCreateMatrix()`
801: @*/
802: PetscErrorCode DMSetUp(DM dm)
803: {
804:   PetscFunctionBegin;
806:   if (dm->setupcalled) PetscFunctionReturn(PETSC_SUCCESS);
807:   PetscTryTypeMethod(dm, setup);
808:   dm->setupcalled = PETSC_TRUE;
809:   PetscFunctionReturn(PETSC_SUCCESS);
810: }

812: /*@
813:   DMSetFromOptions - sets parameters in a `DM` from the options database

815:   Collective

817:   Input Parameter:
818: . dm - the `DM` object to set options for

820:   Options Database Keys:
821: + -dm_preallocate_only (true|false)                  - Only preallocate the matrix for `DMCreateMatrix()` and `DMCreateMassMatrix()`, but do not fill it with zeros
822: . -dm_vec_type type                                  - type of vector to create inside `DM`
823: . -dm_mat_type type                                  - type of matrix to create inside `DM`
824: . -dm_is_coloring_type (global|local)                - see `ISColoringType`
825: . -dm_bind_below n                                   - bind (force execution on CPU) for `Vec` and `Mat` objects with local size (number of vector entries or matrix rows) below n; currently only supported for `DMDA`
826: . -dm_plex_option_phases ph0_, ph1_, ...             - List of prefixes for option processing phases
827: . -dm_plex_filename str                              - File containing a mesh
828: . -dm_plex_boundary_filename str                     - File containing a mesh boundary
829: . -dm_plex_name str                                  - Name of the mesh in the file
830: . -dm_plex_shape shape                               - The domain shape, such as `BOX`, `SPHERE`, etc.
831: . -dm_plex_cell ct                                   - Cell shape
832: . -dm_plex_reference_cell_domain (true|false)        - Use a reference cell domain
833: . -dm_plex_dim dim                                   - Set the topological dimension
834: . -dm_plex_simplex (true|false)                      - `PETSC_TRUE` for simplex elements, `PETSC_FALSE` for tensor elements
835: . -dm_plex_interpolate (true|false)                  - `PETSC_TRUE` turns on topological interpolation (creating edges and faces)
836: . -dm_plex_orient (true|false)                       - `PETSC_TRUE` turns on topological orientation (flipping edges and faces)
837: . -dm_plex_scale sc                                  - Scale factor for mesh coordinates
838: . -dm_coord_remap (true|false)                       - Map coordinates using a function
839: . -dm_plex_coordinate_dim dim                        - Change the coordinate dimension of a mesh (usually given with cdm_ prefix)
840: . -dm_coord_map mapname                              - Select a builtin coordinate map
841: . -dm_coord_map_params p0,p1,p2,...                  - Set coordinate mapping parameters
842: . -dm_plex_box_faces m,n,p                           - Number of faces along each dimension
843: . -dm_plex_box_lower x,y,z                           - Specify lower-left-bottom coordinates for the box
844: . -dm_plex_box_upper x,y,z                           - Specify upper-right-top coordinates for the box
845: . -dm_plex_box_bd bx,by,bz                           - Specify the `DMBoundaryType` for each direction
846: . -dm_plex_sphere_radius r                           - The sphere radius
847: . -dm_plex_ball_radius r                             - Radius of the ball
848: . -dm_plex_cylinder_bd bz                            - Boundary type in the z direction
849: . -dm_plex_cylinder_num_wedges n                     - Number of wedges around the cylinder
850: . -dm_plex_reorder order                             - Reorder the mesh using the specified algorithm
851: . -dm_refine_pre n                                   - The number of refinements before distribution
852: . -dm_refine_uniform_pre (true|false)                - Flag for uniform refinement before distribution
853: . -dm_refine_volume_limit_pre v                      - The maximum cell volume after refinement before distribution
854: . -dm_refine n                                       - The number of refinements after distribution
855: . -dm_extrude l                                      - Activate extrusion and specify the number of layers to extrude
856: . -dm_plex_save_transform (true|false)               - Save the `DMPlexTransform` that produced this mesh
857: . -dm_plex_transform_extrude_thickness t             - The total thickness of extruded layers
858: . -dm_plex_transform_extrude_use_tensor (true|false) - Use tensor cells when extruding
859: . -dm_plex_transform_extrude_symmetric (true|false)  - Extrude layers symmetrically about the surface
860: . -dm_plex_transform_extrude_normal n0,...,nd        - Specify the extrusion direction
861: . -dm_plex_transform_extrude_thicknesses t0,...,tl   - Specify thickness of each layer
862: . -dm_plex_create_fv_ghost_cells                     - Flag to create finite volume ghost cells on the boundary
863: . -dm_plex_fv_ghost_cells_label name                 - Label name for ghost cells boundary
864: . -dm_distribute (true|false)                        - Flag to redistribute a mesh among processes
865: . -dm_distribute_overlap n                           - The size of the overlap halo
866: . -dm_plex_adj_cone (true|false)                     - Set adjacency direction
867: . -dm_plex_adj_closure (true|false)                  - Set adjacency size
868: . -dm_plex_use_ceed (true|false)                     - Use LibCEED as the FEM backend
869: . -dm_plex_check_symmetry (true|false)               - Check that the adjacency information in the mesh is symmetric - `DMPlexCheckSymmetry()`
870: . -dm_plex_check_skeleton (true|false)               - Check that each cell has the correct number of vertices (only for homogeneous simplex or tensor meshes) - `DMPlexCheckSkeleton()`
871: . -dm_plex_check_faces (true|false)                  - Check that the faces of each cell give a vertex order this is consistent with what we expect from the cell type - `DMPlexCheckFaces()`
872: . -dm_plex_check_geometry (true|false)               - Check that cells have positive volume - `DMPlexCheckGeometry()`
873: . -dm_plex_check_pointsf (true|false)                - Check some necessary conditions for `PointSF` - `DMPlexCheckPointSF()`
874: . -dm_plex_check_interface_cones (true|false)        - Check points on inter-partition interfaces have conforming order of cone points - `DMPlexCheckInterfaceCones()`
875: - -dm_plex_check_all (true|false)                    - Perform all the checks above

877:   Level: intermediate

879:   Note:
880:   For some `DMType` such as `DMDA` this cannot be called after `DMSetUp()` has been called.

882: .seealso: [](ch_dmbase), `DM`, `DMView()`, `DMCreateGlobalVector()`, `DMCreateInterpolation()`, `DMCreateColoring()`, `DMCreateMatrix()`,
883:          `DMPlexCheckSymmetry()`, `DMPlexCheckSkeleton()`, `DMPlexCheckFaces()`, `DMPlexCheckGeometry()`, `DMPlexCheckPointSF()`, `DMPlexCheckInterfaceCones()`,
884:          `DMSetOptionsPrefix()`, `DMType`, `DMPLEX`, `DMDA`, `DMSetUp()`
885: @*/
886: PetscErrorCode DMSetFromOptions(DM dm)
887: {
888:   char      typeName[256];
889:   PetscBool flg;

891:   PetscFunctionBegin;
893:   dm->setfromoptionscalled = PETSC_TRUE;
894:   if (dm->sf) PetscCall(PetscSFSetFromOptions(dm->sf));
895:   if (dm->sectionSF) PetscCall(PetscSFSetFromOptions(dm->sectionSF));
896:   if (dm->coordinates[0].dm) PetscCall(DMSetFromOptions(dm->coordinates[0].dm));
897:   PetscObjectOptionsBegin((PetscObject)dm);
898:   PetscCall(PetscOptionsBool("-dm_preallocate_only", "only preallocate matrix, but do not set column indices", "DMSetMatrixPreallocateOnly", dm->prealloc_only, &dm->prealloc_only, NULL));
899:   PetscCall(PetscOptionsFList("-dm_vec_type", "Vector type used for created vectors", "DMSetVecType", VecList, dm->vectype, typeName, 256, &flg));
900:   if (flg) PetscCall(DMSetVecType(dm, typeName));
901:   PetscCall(PetscOptionsFList("-dm_mat_type", "Matrix type used for created matrices", "DMSetMatType", MatList, dm->mattype ? dm->mattype : typeName, typeName, sizeof(typeName), &flg));
902:   if (flg) PetscCall(DMSetMatType(dm, typeName));
903:   PetscCall(PetscOptionsEnum("-dm_blocking_type", "Topological point or field node blocking", "DMSetBlockingType", DMBlockingTypes, (PetscEnum)dm->blocking_type, (PetscEnum *)&dm->blocking_type, NULL));
904:   PetscCall(PetscOptionsEnum("-dm_is_coloring_type", "Global or local coloring of Jacobian", "DMSetISColoringType", ISColoringTypes, (PetscEnum)dm->coloringtype, (PetscEnum *)&dm->coloringtype, NULL));
905:   PetscCall(PetscOptionsInt("-dm_bind_below", "Set the size threshold (in entries) below which the Vec is bound to the CPU", "VecBindToCPU", dm->bind_below, &dm->bind_below, &flg));
906:   PetscCall(PetscOptionsBool("-dm_ignore_perm_output", "Ignore the local section permutation on output", "DMGetOutputDM", dm->ignorePermOutput, &dm->ignorePermOutput, NULL));
907:   PetscTryTypeMethod(dm, setfromoptions, PetscOptionsObject);
908:   /* process any options handlers added with PetscObjectAddOptionsHandler() */
909:   PetscCall(PetscObjectProcessOptionsHandlers((PetscObject)dm, PetscOptionsObject));
910:   PetscOptionsEnd();
911:   PetscFunctionReturn(PETSC_SUCCESS);
912: }

914: /*@
915:   DMViewFromOptions - View a `DM` in a particular way based on a request in the options database

917:   Collective

919:   Input Parameters:
920: + dm   - the `DM` object
921: . obj  - optional object that provides the prefix for the options database (if `NULL` then the prefix in `obj` is used)
922: - name - option string that is used to activate viewing

924:   Options Database Key:
925: . -name [viewertype][:...] - option name and values. See `PetscObjectViewFromOptions()` for the possible arguments

927:   Level: intermediate

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

939: /*@
940:   DMView - Views a `DM`. Depending on the `PetscViewer` and its `PetscViewerFormat` it may print some ASCII information about the `DM` to the screen or a file or
941:   save the `DM` in a binary file to be loaded later or create a visualization of the `DM`

943:   Collective

945:   Input Parameters:
946: + dm - the `DM` object to view
947: - v  - the viewer

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

956:   Level: beginner

958:   Notes:

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

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

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

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

971:   `DMPLEX` only represents geometry while most post-processing software expect that a mesh also provides information on the discretization space. This function assumes that the file represents Lagrange finite elements of order 1 or 2.
972:   The order of the mesh shall be set using `PetscViewerExodusIISetOrder()`

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

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

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

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

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

1017: /*@
1018:   DMCreateGlobalVector - Creates a global vector from a `DM` object. A global vector is a parallel vector that has no duplicate values shared between MPI ranks,
1019:   that is it has no ghost locations.

1021:   Collective

1023:   Input Parameter:
1024: . dm - the `DM` object

1026:   Output Parameter:
1027: . vec - the global vector

1029:   Level: beginner

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

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

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

1052:   Not Collective

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

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

1060:   Level: beginner

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

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

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

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

1086:   Collective

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

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

1094:   Level: advanced

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

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

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

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

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

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

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

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

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

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

1173:   Not Collective

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

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

1181:   Level: intermediate

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

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

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

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

1205:   Collective

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

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

1215:   Level: developer

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

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

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

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

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

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

1250:   Level: advanced

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

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

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

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

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

1295:   Collective

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

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

1304:   Level: developer

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

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

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

1327:   Collective

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

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

1336:   Level: developer

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

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

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

1364: /*@
1365:   DMCreateMassMatrix - Gets the mass matrix between two `DM` objects, M_ij = \int \phi_i \psi_j where the \phi are Galerkin basis functions for a
1366:   a Galerkin finite element model on the `DM`

1368:   Collective

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

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

1377:   Level: developer

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

1382:   if `dmc` is `dmf` or `NULL`, then x^t M x is an approximation to the L2 norm of the vector x which is obtained by `DMCreateGlobalVector()`

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

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

1402:   Collective

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

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

1411:   Level: developer

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

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

1428: /*@
1429:   DMCreateGradientMatrix - Gets the gradient matrix between two `DM` objects, M_(ic)j = \int \partial_c \phi_i \psi_j where the \phi are Galerkin basis functions for a Galerkin finite element model on the `DM`

1431:   Collective

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

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

1440:   Level: developer

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

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

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

1462:   Collective

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

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

1471:   Level: developer

1473:   Notes:
1474:   Coloring of matrices can also be computed directly from the sparse matrix nonzero structure via the `MatColoring` object or from the mesh from which the
1475:   matrix comes from (what this function provides). In general using the mesh produces a more optimal coloring (fewer colors).

1477:   This produces a coloring with the distance of 2, see `MatSetColoringDistance()` which can be used for efficiently computing Jacobians with `MatFDColoringCreate()`
1478:   For `DMDA` in three dimensions with periodic boundary conditions the number of grid points in each dimension must be divisible by 2*stencil_width + 1,
1479:   otherwise an error will be generated.

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

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

1495:   Collective

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

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

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

1506:   Level: beginner

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

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

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

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

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

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

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

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

1568:   Logically Collective

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

1574:   Level: developer

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

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

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

1594:   Logically Collective

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

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

1603:   Level: developer

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

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

1619:   Logically Collective

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

1625:   Level: developer

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

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

1640:   Logically Collective

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

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

1649:   Level: advanced

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

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

1664:   Not Collective

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

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

1672:   Level: advanced

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

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

1688:   Not Collective

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

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

1698:   Level: developer

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

1703:   The array may contain nonzero values

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

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

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

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

1751:   Not Collective

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

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

1761:   Level: developer

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

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

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

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

1793:   Logically Collective; No Fortran Support

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

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

1806:   Level: intermediate

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

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

1823:   Not Collective; No Fortran Support

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

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

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

1838:   Level: intermediate

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

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

1856:   Logically Collective; No Fortran Support

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

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

1869:   Level: intermediate

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

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

1887:   Not Collective; No Fortran Support

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

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

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

1902:   Level: intermediate

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

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

1921:   Not Collective; No Fortran Support

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

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

1931:   Level: intermediate

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

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

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

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

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

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

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

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

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

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

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

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

2046:   Not Collective; No Fortran Support

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

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

2057:   Level: intermediate

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

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

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

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

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

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

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

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

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

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

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

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

2148:   Not collective

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

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

2159:   Level: intermediate

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

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

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

2180:   Not collective

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

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

2190:   Level: intermediate

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

2195: .seealso: [](ch_dmbase), `DM`, `DMCreateSubDM()`, `DMPlexSetMigrationSF()`, `DMDestroy()`, `DMView()`, `DMCreateInterpolation()`, `DMCreateColoring()`, `DMCreateMatrix()`, `DMCreateMassMatrix()`, `DMCreateFieldIS()`, `DMCreateDomainDecomposition()`
2196: @*/
2197: PetscErrorCode DMCreateSuperDM(DM dms[], PetscInt n, IS *is[], DM *superdm)
2198: {
2199:   PetscInt i;

2201:   PetscFunctionBegin;
2202:   PetscAssertPointer(dms, 1);
2204:   if (is) PetscAssertPointer(is, 3);
2205:   PetscAssertPointer(superdm, 4);
2206:   PetscCheck(n >= 0, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Number of DMs must be nonnegative: %" PetscInt_FMT, n);
2207:   if (n) {
2208:     DM dm = dms[0];
2209:     PetscCheck(dm->ops->createsuperdm, PetscObjectComm((PetscObject)dm), PETSC_ERR_SUP, "No method createsuperdm for DM of type %s", ((PetscObject)dm)->type_name);
2210:     PetscCall((*dm->ops->createsuperdm)(dms, n, is, superdm));
2211:   }
2212:   PetscFunctionReturn(PETSC_SUCCESS);
2213: }

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

2219:   Not Collective

2221:   Input Parameter:
2222: . dm - the `DM` object

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

2231:   Level: intermediate

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

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

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

2244:   Developer Notes:
2245:   The `dmlist` is for the inner subdomains or the outer subdomains or all subdomains?

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

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

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

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

2305:   Not Collective

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

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

2317:   Level: developer

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

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

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

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

2343:   Collective

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

2349:   Output Parameter:
2350: . dmf - the refined `DM`, or `NULL`

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

2355:   Level: developer

2357:   Note:
2358:   If no refinement was done, the return value is `NULL`

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

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

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

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

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

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

2392:   Logically Collective; No Fortran Support

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

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

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

2411:   Level: advanced

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

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

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

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

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

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

2445:   Logically Collective; No Fortran Support

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

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

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

2464:   Level: advanced

2466:   Note:
2467:   This function does nothing if the hook is not in the list.

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

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

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

2491:   Collective if any hooks are

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

2498:   Level: developer

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

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

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

2517: /*@
2518:   DMInterpolateSolution - Interpolates a solution from a coarse mesh to a fine mesh.

2520:   Collective

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

2530:   Output Parameter:
2531: . fineSol - the interpolation of coarseSol to the fine mesh

2533:   Level: developer

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

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

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

2550:   PetscFunctionBegin;

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

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

2568:   Not Collective

2570:   Input Parameter:
2571: . dm - the `DM` object

2573:   Output Parameter:
2574: . level - number of refinements

2576:   Level: developer

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

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

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

2594:   Not Collective

2596:   Input Parameters:
2597: + dm    - the `DM` object
2598: - level - number of refinements

2600:   Level: advanced

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

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

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

2617: /*@
2618:   DMExtrude - Extrude a `DM` object from a surface

2620:   Collective

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

2626:   Output Parameter:
2627: . dme - the extruded `DM`, or `NULL`

2629:   Level: developer

2631:   Note:
2632:   If no extrusion was done, the return value is `NULL`

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

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

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

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

2671:   Input Parameter:
2672: . dm - The `DM`

2674:   Output Parameter:
2675: . flg - `PETSC_TRUE` if a basis transformation should be done

2677:   Level: developer

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

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

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

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

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

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

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

2757:   Logically Collective

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

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

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

2779:   Level: advanced

2781:   Note:
2782:   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.

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

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

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

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

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

2837: /*@
2838:   DMGlobalToLocal - update local vectors from global vector

2840:   Neighbor-wise Collective

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

2848:   Level: beginner

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

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

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

2868: /*@
2869:   DMGlobalToLocalBegin - Begins updating local vectors from global vector

2871:   Neighbor-wise Collective

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

2879:   Level: intermediate

2881:   Notes:
2882:   The operation is completed with `DMGlobalToLocalEnd()`

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

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

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

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

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

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

2920: /*@
2921:   DMGlobalToLocalEnd - Ends updating local vectors from global vector

2923:   Neighbor-wise Collective

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

2931:   Level: intermediate

2933:   Note:
2934:   See `DMGlobalToLocalBegin()` for details.

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

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

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

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

2973:   Logically Collective

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

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

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

2995:   Level: advanced

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

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

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

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

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

3056:   Neighbor-wise Collective

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

3064:   Level: beginner

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

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

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

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

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

3086: /*@
3087:   DMLocalToGlobalBegin - begins updating global vectors from local vectors

3089:   Neighbor-wise Collective

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

3097:   Level: intermediate

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

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

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

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

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

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

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

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

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

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

3222: /*@
3223:   DMLocalToGlobalEnd - updates global vectors from local vectors

3225:   Neighbor-wise Collective

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

3233:   Level: intermediate

3235:   Note:
3236:   See `DMLocalToGlobalBegin()` for full details

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

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

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

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

3299:   Neighbor-wise Collective

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

3306:   Output Parameter:
3307: . l - the local vector with correct ghost values

3309:   Level: intermediate

3311:   Note:
3312:   Must be followed by `DMLocalToLocalEnd()`.

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

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

3330:   Neighbor-wise Collective

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

3337:   Output Parameter:
3338: . l - the local vector with correct ghost values

3340:   Level: intermediate

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

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

3357:   Collective

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

3363:   Output Parameter:
3364: . dmc - the coarsened `DM`

3366:   Level: developer

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

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

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

3400:   Logically Collective; No Fortran Support

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

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

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

3421:   Level: advanced

3423:   Notes:
3424:   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`.

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

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

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

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

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

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

3456:   Logically Collective; No Fortran Support

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

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

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

3477:   Level: advanced

3479:   Notes:
3480:   This function does nothing if the `coarsenhook` is not in the list.

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

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

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

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

3506:   Collective if any hooks are

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

3515:   Level: developer

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

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

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

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

3536:   Logically Collective; No Fortran Support

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

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

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

3556:   Level: advanced

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

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

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

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

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

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

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

3592:   Logically Collective; No Fortran Support

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

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

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

3612:   Level: advanced

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

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

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

3637:   Collective if any hooks are

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

3645:   Level: developer

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

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

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

3663:   Not Collective

3665:   Input Parameter:
3666: . dm - the `DM` object

3668:   Output Parameter:
3669: . level - number of coarsenings

3671:   Level: developer

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

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

3687:   Collective

3689:   Input Parameters:
3690: + dm    - the `DM` object
3691: - level - number of coarsenings

3693:   Level: developer

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

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

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

3711:   Collective

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

3717:   Output Parameter:
3718: . dmf - the refined `DM` hierarchy

3720:   Level: developer

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

3734:     PetscCall(DMRefine(dm, PetscObjectComm((PetscObject)dm), &dmf[0]));
3735:     for (i = 1; i < nlevels; i++) PetscCall(DMRefine(dmf[i - 1], PetscObjectComm((PetscObject)dm), &dmf[i]));
3736:   } else PetscUseTypeMethod(dm, refinehierarchy, nlevels, dmf);
3737:   PetscFunctionReturn(PETSC_SUCCESS);
3738: }

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

3743:   Collective

3745:   Input Parameters:
3746: + dm      - the `DM` object
3747: - nlevels - the number of levels of coarsening

3749:   Output Parameter:
3750: . dmc - the coarsened `DM` hierarchy

3752:   Level: developer

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

3766:     PetscCall(DMCoarsen(dm, PetscObjectComm((PetscObject)dm), &dmc[0]));
3767:     for (i = 1; i < nlevels; i++) PetscCall(DMCoarsen(dmc[i - 1], PetscObjectComm((PetscObject)dm), &dmc[i]));
3768:   } else PetscUseTypeMethod(dm, coarsenhierarchy, nlevels, dmc);
3769:   PetscFunctionReturn(PETSC_SUCCESS);
3770: }

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

3775:   Logically Collective if the function is collective

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

3781:   Level: intermediate

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

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

3797:   Not Collective

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

3803:   Level: intermediate

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

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

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

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

3829:   Not Collective

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

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

3837:   Level: intermediate

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

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

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

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

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

3875:   Logically Collective

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

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

3886:   Level: intermediate

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

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

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

3905:   Not Collective

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

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

3913:   Level: developer

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

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

3929:   Logically Collective

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

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

3938:   Level: advanced

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

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

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

3958:   Not Collective

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

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

3966:   Level: developer

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

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

3982:   Not Collective

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

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

3990:   Level: developer

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

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

4006:   Not Collective

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

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

4014:   Level: developer

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

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

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

4034:   Collective

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

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

4043:   Level: intermediate

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

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

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

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

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

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

4074:   Not Collective

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

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

4082:   Level: intermediate

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

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

4099:   Collective

4101:   Input Parameters:
4102: + dm      - the `DM`
4103: - newtype - new `DM` type (use "same" for the same type)

4105:   Output Parameter:
4106: . M - pointer to new `DM`

4108:   Level: intermediate

4110:   Note:
4111:   Cannot be used to convert a sequential `DM` to a parallel or a parallel to sequential,
4112:   the MPI communicator of the generated `DM` is always the same as the communicator
4113:   of the input `DM`.

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

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

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

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

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

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

4174:     /* 4) See if a good general converter is known for the current matrix */
4175:     if (dm->ops->convert) conv = dm->ops->convert;
4176:     if (conv) goto foundconv;
4177: #endif

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

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

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

4203: /*@C
4204:   DMRegister -  Adds a new `DM` type implementation

4206:   Not Collective, No Fortran Support

4208:   Input Parameters:
4209: + sname    - The name of a new user-defined creation routine
4210: - function - The creation routine itself

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

4215:   Level: advanced

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

4220:   Example Usage:
4221: .vb
4222:     DMRegister("my_da", MyDMCreate);
4223: .ve

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

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

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

4248:   Collective

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

4256:   Level: intermediate

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

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

4265: .seealso: [](ch_dmbase), `DM`, `PetscViewerBinaryOpen()`, `DMView()`, `MatLoad()`, `VecLoad()`
4266: @*/
4267: PetscErrorCode DMLoad(DM newdm, PetscViewer viewer)
4268: {
4269:   PetscBool isbinary, ishdf5;

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

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

4294: /* FEM Support */

4296: PetscErrorCode DMPrintCellIndices(PetscInt c, const char name[], PetscInt len, const PetscInt x[])
4297: {
4298:   PetscInt f;

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

4306: PetscErrorCode DMPrintCellVector(PetscInt c, const char name[], PetscInt len, const PetscScalar x[])
4307: {
4308:   PetscInt f;

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

4316: PetscErrorCode DMPrintCellVectorReal(PetscInt c, const char name[], PetscInt len, const PetscReal x[])
4317: {
4318:   PetscInt f;

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

4326: PetscErrorCode DMPrintCellMatrix(PetscInt c, const char name[], PetscInt rows, PetscInt cols, const PetscScalar A[])
4327: {
4328:   PetscInt f, g;

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

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

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

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

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

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

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

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

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

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

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

4420:   Level: intermediate

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

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

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

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

4451:   Level: intermediate

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

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

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

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

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

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

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

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

4505:   Level: developer

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

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

4521:   not Collective

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

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

4531:   Level: advanced

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

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

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

4552:   Collective

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

4560:   Level: advanced

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

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

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

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

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

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

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

4613:   Level: intermediate

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

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

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

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

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

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

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

4698:   Collective

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

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

4706:   Level: intermediate

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

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

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

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

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

4742:   Level: intermediate

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

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

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

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

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

4778:   Level: intermediate

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

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

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

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

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

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

4817:   Level: intermediate

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

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

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

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

4844:   Level: developer

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

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

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

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

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

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

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

4876:   Level: intermediate

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

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

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

4895:   Collective

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

4901:   Level: intermediate

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

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

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

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

4925:   Level: intermediate

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

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

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

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

4948:   Level: intermediate

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

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

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

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

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

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

4998:   Logically Collective

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

5003:   Level: intermediate

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

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

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

5027:   Not Collective

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

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

5035:   Level: intermediate

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

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

5051:   Logically Collective

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

5057:   Level: intermediate

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

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

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

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

5081:   Not Collective

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

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

5091:   Level: intermediate

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

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

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

5129:   Logically Collective

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

5137:   Level: intermediate

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

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

5158:   Logically Collective

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

5165:   Level: intermediate

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

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

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

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

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

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

5200:   Logically Collective

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

5207:   Level: intermediate

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

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

5222:   Not Collective

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

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

5231:   Level: intermediate

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

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

5246:   Collective

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

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

5256:   Level: advanced

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

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

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

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

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

5299:   Not Collective

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

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

5309:   Level: developer

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

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

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

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

5344:   Not Collective

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

5352:   Level: developer

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

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

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

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

5385:   Not collective

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

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

5394:   Level: developer

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

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

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

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

5425:   Not Collective

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

5432:   Level: developer

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

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

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

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

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

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

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

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

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

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

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

5569:   Not Collective

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

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

5577:   Level: intermediate

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

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

5593:   Logically Collective

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

5598:   Level: intermediate

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

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

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

5623:   Not Collective

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

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

5631:   Level: intermediate

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

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

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

5651:   Not Collective

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

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

5661:   Level: developer

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

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

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

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

5698:   Not Collective

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

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

5709:   Level: advanced

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

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

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

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

5751:   Collective

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

5760:   Level: advanced

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

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

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

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

5807:   Not Collective

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

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

5819:   Level: advanced

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

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

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

5853:   Not Collective

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

5863:   Level: advanced

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

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

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

5903:   Not Collective

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

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

5912:   Level: advanced

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

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

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

5935:   Not Collective

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

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

5946:   Level: intermediate

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

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

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

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

5974:   Collective

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

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

5982:   Level: intermediate

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

6251:   Level: developer

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

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

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

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

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

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

6292:   Collective

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

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

6302:   Level: developer

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

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

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

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

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

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

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

6399:   Collective

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

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

6409:   Level: advanced

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

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

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

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

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

6449:   Collective

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

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

6457:   Level: advanced

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

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

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

6475:   Not Collective

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

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

6483:   Level: beginner

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

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

6499:   Collective

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

6505:   Level: beginner

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

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

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

6532:   Collective

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

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

6542:   Level: intermediate

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

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

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

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

6566:   Collective

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

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

6574:   Level: intermediate

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

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

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

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

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

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

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

6634:   Level: intermediate

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

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

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

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

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

6669:   Level: intermediate

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

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

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

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

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

6698:   Level: intermediate

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

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

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

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

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

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

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

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

6740:   Level: intermediate

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

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

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

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

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

6771:   Not Collective

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

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

6779:   Level: beginner

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

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

6795:   Collective

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

6801:   Level: beginner

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

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

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

6820:   Not Collective

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

6826:   Level: intermediate

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

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

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

6850:   Not Collective

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

6857:   Level: intermediate

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

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

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

6902:   Not Collective

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

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

6912:   Level: beginner

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

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

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

6932:   Not Collective

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

6940:   Output Parameter:

6942:   Level: beginner

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

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

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

6965:   Not Collective

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

6973:   Level: beginner

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

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

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

6993:   Not Collective

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

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

7002:   Level: beginner

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

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

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

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

7027:   Not Collective

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

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

7036:   Level: beginner

7038: .seealso: [](ch_dmbase), `DM`, `DMLabelGetValueIS()`, `DMGetLabelSize()`
7039: @*/
7040: PetscErrorCode DMGetLabelIdIS(DM dm, const char name[], IS *ids)
7041: {
7042:   DMLabel label;

7044:   PetscFunctionBegin;
7046:   PetscAssertPointer(name, 2);
7047:   PetscAssertPointer(ids, 3);
7048:   PetscCall(DMGetLabel(dm, name, &label));
7049:   *ids = NULL;
7050:   if (label) PetscCall(DMLabelGetValueIS(label, ids));
7051:   else {
7052:     /* returning an empty IS */
7053:     PetscCall(ISCreateGeneral(PETSC_COMM_SELF, 0, NULL, PETSC_USE_POINTER, ids));
7054:   }
7055:   PetscFunctionReturn(PETSC_SUCCESS);
7056: }

7058: /*@
7059:   DMGetStratumSize - Get the number of points in a label stratum

7061:   Not Collective

7063:   Input Parameters:
7064: + dm    - The `DM` object
7065: . name  - The label name of the stratum
7066: - value - The stratum value

7068:   Output Parameter:
7069: . size - The number of points, also called the stratum size

7071:   Level: beginner

7073: .seealso: [](ch_dmbase), `DM`, `DMLabelGetStratumSize()`, `DMGetLabelSize()`, `DMGetLabelIds()`
7074: @*/
7075: PetscErrorCode DMGetStratumSize(DM dm, const char name[], PetscInt value, PetscInt *size)
7076: {
7077:   DMLabel label;

7079:   PetscFunctionBegin;
7081:   PetscAssertPointer(name, 2);
7082:   PetscAssertPointer(size, 4);
7083:   PetscCall(DMGetLabel(dm, name, &label));
7084:   *size = 0;
7085:   if (!label) PetscFunctionReturn(PETSC_SUCCESS);
7086:   PetscCall(DMLabelGetStratumSize(label, value, size));
7087:   PetscFunctionReturn(PETSC_SUCCESS);
7088: }

7090: /*@
7091:   DMGetStratumIS - Get the points in a label stratum

7093:   Not Collective

7095:   Input Parameters:
7096: + dm    - The `DM` object
7097: . name  - The label name
7098: - value - The stratum value

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

7103:   Level: beginner

7105: .seealso: [](ch_dmbase), `DM`, `DMLabelGetStratumIS()`, `DMGetStratumSize()`
7106: @*/
7107: PetscErrorCode DMGetStratumIS(DM dm, const char name[], PetscInt value, IS *points)
7108: {
7109:   DMLabel label;

7111:   PetscFunctionBegin;
7113:   PetscAssertPointer(name, 2);
7114:   PetscAssertPointer(points, 4);
7115:   PetscCall(DMGetLabel(dm, name, &label));
7116:   *points = NULL;
7117:   if (!label) PetscFunctionReturn(PETSC_SUCCESS);
7118:   PetscCall(DMLabelGetStratumIS(label, value, points));
7119:   PetscFunctionReturn(PETSC_SUCCESS);
7120: }

7122: /*@
7123:   DMSetStratumIS - Set the points in a label stratum

7125:   Not Collective

7127:   Input Parameters:
7128: + dm     - The `DM` object
7129: . name   - The label name
7130: . value  - The stratum value
7131: - points - The stratum points

7133:   Level: beginner

7135: .seealso: [](ch_dmbase), `DM`, `DMLabel`, `DMClearLabelStratum()`, `DMLabelClearStratum()`, `DMLabelSetStratumIS()`, `DMGetStratumSize()`
7136: @*/
7137: PetscErrorCode DMSetStratumIS(DM dm, const char name[], PetscInt value, IS points)
7138: {
7139:   DMLabel label;

7141:   PetscFunctionBegin;
7143:   PetscAssertPointer(name, 2);
7145:   PetscCall(DMGetLabel(dm, name, &label));
7146:   if (!label) PetscFunctionReturn(PETSC_SUCCESS);
7147:   PetscCall(DMLabelSetStratumIS(label, value, points));
7148:   PetscFunctionReturn(PETSC_SUCCESS);
7149: }

7151: /*@
7152:   DMClearLabelStratum - Remove all points from a stratum from a `DMLabel`

7154:   Not Collective

7156:   Input Parameters:
7157: + dm    - The `DM` object
7158: . name  - The label name
7159: - value - The label value for this point

7161:   Output Parameter:

7163:   Level: beginner

7165: .seealso: [](ch_dmbase), `DM`, `DMLabel`, `DMLabelClearStratum()`, `DMSetLabelValue()`, `DMGetStratumIS()`, `DMClearLabelValue()`
7166: @*/
7167: PetscErrorCode DMClearLabelStratum(DM dm, const char name[], PetscInt value)
7168: {
7169:   DMLabel label;

7171:   PetscFunctionBegin;
7173:   PetscAssertPointer(name, 2);
7174:   PetscCall(DMGetLabel(dm, name, &label));
7175:   if (!label) PetscFunctionReturn(PETSC_SUCCESS);
7176:   PetscCall(DMLabelClearStratum(label, value));
7177:   PetscFunctionReturn(PETSC_SUCCESS);
7178: }

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

7183:   Not Collective

7185:   Input Parameter:
7186: . dm - The `DM` object

7188:   Output Parameter:
7189: . numLabels - the number of Labels

7191:   Level: intermediate

7193: .seealso: [](ch_dmbase), `DM`, `DMLabel`, `DMGetLabelByNum()`, `DMGetLabelName()`, `DMGetLabelValue()`, `DMSetLabelValue()`, `DMGetStratumIS()`
7194: @*/
7195: PetscErrorCode DMGetNumLabels(DM dm, PetscInt *numLabels)
7196: {
7197:   DMLabelLink next = dm->labels;
7198:   PetscInt    n    = 0;

7200:   PetscFunctionBegin;
7202:   PetscAssertPointer(numLabels, 2);
7203:   while (next) {
7204:     ++n;
7205:     next = next->next;
7206:   }
7207:   *numLabels = n;
7208:   PetscFunctionReturn(PETSC_SUCCESS);
7209: }

7211: /*@
7212:   DMGetLabelName - Return the name of nth label

7214:   Not Collective

7216:   Input Parameters:
7217: + dm - The `DM` object
7218: - n  - the label number

7220:   Output Parameter:
7221: . name - the label name

7223:   Level: intermediate

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

7228: .seealso: [](ch_dmbase), `DM`, `DMLabel`, `DMGetLabelByNum()`, `DMGetLabel()`, `DMGetLabelValue()`, `DMSetLabelValue()`, `DMGetStratumIS()`
7229: @*/
7230: PetscErrorCode DMGetLabelName(DM dm, PetscInt n, const char *name[])
7231: {
7232:   DMLabelLink next = dm->labels;
7233:   PetscInt    l    = 0;

7235:   PetscFunctionBegin;
7237:   PetscAssertPointer(name, 3);
7238:   while (next) {
7239:     if (l == n) {
7240:       PetscCall(PetscObjectGetName((PetscObject)next->label, name));
7241:       PetscFunctionReturn(PETSC_SUCCESS);
7242:     }
7243:     ++l;
7244:     next = next->next;
7245:   }
7246:   SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Label %" PetscInt_FMT " does not exist in this DM", n);
7247: }

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

7252:   Not Collective

7254:   Input Parameters:
7255: + dm   - The `DM` object
7256: - name - The label name

7258:   Output Parameter:
7259: . hasLabel - `PETSC_TRUE` if the label is present

7261:   Level: intermediate

7263: .seealso: [](ch_dmbase), `DM`, `DMLabel`, `DMGetLabel()`, `DMGetLabelByNum()`, `DMCreateLabel()`, `DMGetLabelValue()`, `DMSetLabelValue()`, `DMGetStratumIS()`
7264: @*/
7265: PetscErrorCode DMHasLabel(DM dm, const char name[], PetscBool *hasLabel)
7266: {
7267:   DMLabelLink next = dm->labels;
7268:   const char *lname;

7270:   PetscFunctionBegin;
7272:   PetscAssertPointer(name, 2);
7273:   PetscAssertPointer(hasLabel, 3);
7274:   *hasLabel = PETSC_FALSE;
7275:   while (next) {
7276:     PetscCall(PetscObjectGetName((PetscObject)next->label, &lname));
7277:     PetscCall(PetscStrcmp(name, lname, hasLabel));
7278:     if (*hasLabel) break;
7279:     next = next->next;
7280:   }
7281:   PetscFunctionReturn(PETSC_SUCCESS);
7282: }

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

7288:   Not Collective

7290:   Input Parameters:
7291: + dm   - The `DM` object
7292: - name - The label name

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

7297:   Default labels in a `DMPLEX`:
7298: + "depth"       - Holds the depth (co-dimension) of each mesh point
7299: . "celltype"    - Holds the topological type of each cell
7300: . "ghost"       - If the DM is distributed with overlap, this marks the cells and faces in the overlap
7301: . "Cell Sets"   - Mirrors the cell sets defined by GMsh and ExodusII
7302: . "Face Sets"   - Mirrors the face sets defined by GMsh and ExodusII
7303: - "Vertex Sets" - Mirrors the vertex sets defined by GMsh

7305:   Level: intermediate

7307: .seealso: [](ch_dmbase), `DM`, `DMLabel`, `DMHasLabel()`, `DMGetLabelByNum()`, `DMAddLabel()`, `DMCreateLabel()`, `DMPlexGetDepthLabel()`, `DMPlexGetCellType()`
7308: @*/
7309: PetscErrorCode DMGetLabel(DM dm, const char name[], DMLabel *label)
7310: {
7311:   DMLabelLink next = dm->labels;
7312:   PetscBool   hasLabel;
7313:   const char *lname;

7315:   PetscFunctionBegin;
7317:   PetscAssertPointer(name, 2);
7318:   PetscAssertPointer(label, 3);
7319:   *label = NULL;
7320:   while (next) {
7321:     PetscCall(PetscObjectGetName((PetscObject)next->label, &lname));
7322:     PetscCall(PetscStrcmp(name, lname, &hasLabel));
7323:     if (hasLabel) {
7324:       *label = next->label;
7325:       break;
7326:     }
7327:     next = next->next;
7328:   }
7329:   PetscFunctionReturn(PETSC_SUCCESS);
7330: }

7332: /*@
7333:   DMGetLabelByNum - Return the nth label on a `DM`

7335:   Not Collective

7337:   Input Parameters:
7338: + dm - The `DM` object
7339: - n  - the label number

7341:   Output Parameter:
7342: . label - the label

7344:   Level: intermediate

7346: .seealso: [](ch_dmbase), `DM`, `DMLabel`, `DMAddLabel()`, `DMGetLabelValue()`, `DMSetLabelValue()`, `DMGetStratumIS()`
7347: @*/
7348: PetscErrorCode DMGetLabelByNum(DM dm, PetscInt n, DMLabel *label)
7349: {
7350:   DMLabelLink next = dm->labels;
7351:   PetscInt    l    = 0;

7353:   PetscFunctionBegin;
7355:   PetscAssertPointer(label, 3);
7356:   while (next) {
7357:     if (l == n) {
7358:       *label = next->label;
7359:       PetscFunctionReturn(PETSC_SUCCESS);
7360:     }
7361:     ++l;
7362:     next = next->next;
7363:   }
7364:   SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Label %" PetscInt_FMT " does not exist in this DM", n);
7365: }

7367: /*@
7368:   DMAddLabel - Add the label to this `DM`

7370:   Not Collective

7372:   Input Parameters:
7373: + dm    - The `DM` object
7374: - label - The `DMLabel`

7376:   Level: developer

7378: .seealso: [](ch_dmbase), `DM`, `DMLabel`, `DMCreateLabel()`, `DMHasLabel()`, `DMGetLabelValue()`, `DMSetLabelValue()`, `DMGetStratumIS()`
7379: @*/
7380: PetscErrorCode DMAddLabel(DM dm, DMLabel label)
7381: {
7382:   DMLabelLink l, *p, tmpLabel;
7383:   PetscBool   hasLabel;
7384:   const char *lname;
7385:   PetscBool   flg;

7387:   PetscFunctionBegin;
7389:   PetscCall(PetscObjectGetName((PetscObject)label, &lname));
7390:   PetscCall(DMHasLabel(dm, lname, &hasLabel));
7391:   PetscCheck(!hasLabel, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Label %s already exists in this DM", lname);
7392:   PetscCall(PetscCalloc1(1, &tmpLabel));
7393:   tmpLabel->label  = label;
7394:   tmpLabel->output = PETSC_TRUE;
7395:   for (p = &dm->labels; (l = *p); p = &l->next) { }
7396:   *p = tmpLabel;
7397:   PetscCall(PetscObjectReference((PetscObject)label));
7398:   PetscCall(PetscStrcmp(lname, "depth", &flg));
7399:   if (flg) dm->depthLabel = label;
7400:   PetscCall(PetscStrcmp(lname, "celltype", &flg));
7401:   if (flg) dm->celltypeLabel = label;
7402:   PetscFunctionReturn(PETSC_SUCCESS);
7403: }

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

7409:   Not Collective

7411:   Input Parameters:
7412: + dm    - The `DM` object
7413: - label - The `DMLabel`, having the same name, to substitute

7415:   Default labels in a `DMPLEX`:
7416: + "depth"       - Holds the depth (co-dimension) of each mesh point
7417: . "celltype"    - Holds the topological type of each cell
7418: . "ghost"       - If the DM is distributed with overlap, this marks the cells and faces in the overlap
7419: . "Cell Sets"   - Mirrors the cell sets defined by GMsh and ExodusII
7420: . "Face Sets"   - Mirrors the face sets defined by GMsh and ExodusII
7421: - "Vertex Sets" - Mirrors the vertex sets defined by GMsh

7423:   Level: intermediate

7425: .seealso: [](ch_dmbase), `DM`, `DMLabel`, `DMCreateLabel()`, `DMHasLabel()`, `DMPlexGetDepthLabel()`, `DMPlexGetCellType()`
7426: @*/
7427: PetscErrorCode DMSetLabel(DM dm, DMLabel label)
7428: {
7429:   DMLabelLink next = dm->labels;
7430:   PetscBool   hasLabel, flg;
7431:   const char *name, *lname;

7433:   PetscFunctionBegin;
7436:   PetscCall(PetscObjectGetName((PetscObject)label, &name));
7437:   while (next) {
7438:     PetscCall(PetscObjectGetName((PetscObject)next->label, &lname));
7439:     PetscCall(PetscStrcmp(name, lname, &hasLabel));
7440:     if (hasLabel) {
7441:       PetscCall(PetscObjectReference((PetscObject)label));
7442:       PetscCall(PetscStrcmp(lname, "depth", &flg));
7443:       if (flg) dm->depthLabel = label;
7444:       PetscCall(PetscStrcmp(lname, "celltype", &flg));
7445:       if (flg) dm->celltypeLabel = label;
7446:       PetscCall(DMLabelDestroy(&next->label));
7447:       next->label = label;
7448:       break;
7449:     }
7450:     next = next->next;
7451:   }
7452:   PetscFunctionReturn(PETSC_SUCCESS);
7453: }

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

7458:   Not Collective

7460:   Input Parameters:
7461: + dm   - The `DM` object
7462: - name - The label name

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

7468:   Level: developer

7470: .seealso: [](ch_dmbase), `DM`, `DMLabel`, `DMCreateLabel()`, `DMHasLabel()`, `DMGetLabel()`, `DMGetLabelValue()`, `DMSetLabelValue()`, `DMLabelDestroy()`, `DMRemoveLabelBySelf()`
7471: @*/
7472: PetscErrorCode DMRemoveLabel(DM dm, const char name[], DMLabel *label)
7473: {
7474:   DMLabelLink link, *pnext;
7475:   PetscBool   hasLabel;
7476:   const char *lname;

7478:   PetscFunctionBegin;
7480:   PetscAssertPointer(name, 2);
7481:   if (label) {
7482:     PetscAssertPointer(label, 3);
7483:     *label = NULL;
7484:   }
7485:   for (pnext = &dm->labels; (link = *pnext); pnext = &link->next) {
7486:     PetscCall(PetscObjectGetName((PetscObject)link->label, &lname));
7487:     PetscCall(PetscStrcmp(name, lname, &hasLabel));
7488:     if (hasLabel) {
7489:       *pnext = link->next; /* Remove from list */
7490:       PetscCall(PetscStrcmp(name, "depth", &hasLabel));
7491:       if (hasLabel) dm->depthLabel = NULL;
7492:       PetscCall(PetscStrcmp(name, "celltype", &hasLabel));
7493:       if (hasLabel) dm->celltypeLabel = NULL;
7494:       if (label) *label = link->label;
7495:       else PetscCall(DMLabelDestroy(&link->label));
7496:       PetscCall(PetscFree(link));
7497:       break;
7498:     }
7499:   }
7500:   PetscFunctionReturn(PETSC_SUCCESS);
7501: }

7503: /*@
7504:   DMRemoveLabelBySelf - Remove the label from this `DM`

7506:   Not Collective

7508:   Input Parameters:
7509: + dm           - The `DM` object
7510: . label        - The `DMLabel` to be removed from the `DM`
7511: - failNotFound - Should it fail if the label is not found in the `DM`?

7513:   Level: developer

7515:   Note:
7516:   Only exactly the same instance is removed if found, name match is ignored.
7517:   If the `DM` has an exclusive reference to the label, the label gets destroyed and
7518:   *label nullified.

7520: .seealso: [](ch_dmbase), `DM`, `DMLabel`, `DMCreateLabel()`, `DMHasLabel()`, `DMGetLabel()`, `DMGetLabelValue()`, `DMSetLabelValue()`, `DMLabelDestroy()`, `DMRemoveLabel()`
7521: @*/
7522: PetscErrorCode DMRemoveLabelBySelf(DM dm, DMLabel *label, PetscBool failNotFound)
7523: {
7524:   DMLabelLink link, *pnext;
7525:   PetscBool   hasLabel = PETSC_FALSE;

7527:   PetscFunctionBegin;
7529:   PetscAssertPointer(label, 2);
7530:   if (!*label && !failNotFound) PetscFunctionReturn(PETSC_SUCCESS);
7533:   for (pnext = &dm->labels; (link = *pnext); pnext = &link->next) {
7534:     if (*label == link->label) {
7535:       hasLabel = PETSC_TRUE;
7536:       *pnext   = link->next; /* Remove from list */
7537:       if (*label == dm->depthLabel) dm->depthLabel = NULL;
7538:       if (*label == dm->celltypeLabel) dm->celltypeLabel = NULL;
7539:       if (((PetscObject)link->label)->refct < 2) *label = NULL; /* nullify if exclusive reference */
7540:       PetscCall(DMLabelDestroy(&link->label));
7541:       PetscCall(PetscFree(link));
7542:       break;
7543:     }
7544:   }
7545:   PetscCheck(hasLabel || !failNotFound, PetscObjectComm((PetscObject)dm), PETSC_ERR_ARG_WRONG, "Given label not found in DM");
7546:   PetscFunctionReturn(PETSC_SUCCESS);
7547: }

7549: /*@
7550:   DMGetLabelOutput - Get the output flag for a given label

7552:   Not Collective

7554:   Input Parameters:
7555: + dm   - The `DM` object
7556: - name - The label name

7558:   Output Parameter:
7559: . output - The flag for output

7561:   Level: developer

7563: .seealso: [](ch_dmbase), `DM`, `DMLabel`, `DMSetLabelOutput()`, `DMCreateLabel()`, `DMHasLabel()`, `DMGetLabelValue()`, `DMSetLabelValue()`, `DMGetStratumIS()`
7564: @*/
7565: PetscErrorCode DMGetLabelOutput(DM dm, const char name[], PetscBool *output)
7566: {
7567:   DMLabelLink next = dm->labels;
7568:   const char *lname;

7570:   PetscFunctionBegin;
7572:   PetscAssertPointer(name, 2);
7573:   PetscAssertPointer(output, 3);
7574:   while (next) {
7575:     PetscBool flg;

7577:     PetscCall(PetscObjectGetName((PetscObject)next->label, &lname));
7578:     PetscCall(PetscStrcmp(name, lname, &flg));
7579:     if (flg) {
7580:       *output = next->output;
7581:       PetscFunctionReturn(PETSC_SUCCESS);
7582:     }
7583:     next = next->next;
7584:   }
7585:   SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "No label named %s was present in this dm", name);
7586: }

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

7591:   Not Collective

7593:   Input Parameters:
7594: + dm     - The `DM` object
7595: . name   - The label name
7596: - output - `PETSC_TRUE` to save the label to the viewer

7598:   Level: developer

7600: .seealso: [](ch_dmbase), `DM`, `DMLabel`, `DMGetOutputFlag()`, `DMGetLabelOutput()`, `DMCreateLabel()`, `DMHasLabel()`, `DMGetLabelValue()`, `DMSetLabelValue()`, `DMGetStratumIS()`
7601: @*/
7602: PetscErrorCode DMSetLabelOutput(DM dm, const char name[], PetscBool output)
7603: {
7604:   DMLabelLink next = dm->labels;
7605:   const char *lname;

7607:   PetscFunctionBegin;
7609:   PetscAssertPointer(name, 2);
7610:   while (next) {
7611:     PetscBool flg;

7613:     PetscCall(PetscObjectGetName((PetscObject)next->label, &lname));
7614:     PetscCall(PetscStrcmp(name, lname, &flg));
7615:     if (flg) {
7616:       next->output = output;
7617:       PetscFunctionReturn(PETSC_SUCCESS);
7618:     }
7619:     next = next->next;
7620:   }
7621:   SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "No label named %s was present in this dm", name);
7622: }

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

7627:   Collective

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

7636:   Level: intermediate

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

7641: .seealso: [](ch_dmbase), `DM`, `DMLabel`, `DMAddLabel()`, `DMCopyLabelsMode`
7642: @*/
7643: PetscErrorCode DMCopyLabels(DM dmA, DM dmB, PetscCopyMode mode, PetscBool all, DMCopyLabelsMode emode)
7644: {
7645:   DMLabel     label, labelNew, labelOld;
7646:   const char *name;
7647:   PetscBool   flg;
7648:   DMLabelLink link;

7650:   PetscFunctionBegin;
7655:   PetscCheck(mode != PETSC_USE_POINTER, PetscObjectComm((PetscObject)dmA), PETSC_ERR_SUP, "PETSC_USE_POINTER not supported for objects");
7656:   if (dmA == dmB) PetscFunctionReturn(PETSC_SUCCESS);
7657:   for (link = dmA->labels; link; link = link->next) {
7658:     label = link->label;
7659:     PetscCall(PetscObjectGetName((PetscObject)label, &name));
7660:     if (!all) {
7661:       PetscCall(PetscStrcmp(name, "depth", &flg));
7662:       if (flg) continue;
7663:       PetscCall(PetscStrcmp(name, "dim", &flg));
7664:       if (flg) continue;
7665:       PetscCall(PetscStrcmp(name, "celltype", &flg));
7666:       if (flg) continue;
7667:     }
7668:     PetscCall(DMGetLabel(dmB, name, &labelOld));
7669:     if (labelOld) {
7670:       switch (emode) {
7671:       case DM_COPY_LABELS_KEEP:
7672:         continue;
7673:       case DM_COPY_LABELS_REPLACE:
7674:         PetscCall(DMRemoveLabelBySelf(dmB, &labelOld, PETSC_TRUE));
7675:         break;
7676:       case DM_COPY_LABELS_FAIL:
7677:         SETERRQ(PetscObjectComm((PetscObject)dmA), PETSC_ERR_ARG_OUTOFRANGE, "Label %s already exists in destination DM", name);
7678:       default:
7679:         SETERRQ(PetscObjectComm((PetscObject)dmA), PETSC_ERR_ARG_OUTOFRANGE, "Unhandled DMCopyLabelsMode %d", (int)emode);
7680:       }
7681:     }
7682:     if (mode == PETSC_COPY_VALUES) PetscCall(DMLabelDuplicate(label, &labelNew));
7683:     else labelNew = label;
7684:     PetscCall(DMAddLabel(dmB, labelNew));
7685:     if (mode == PETSC_COPY_VALUES) PetscCall(DMLabelDestroy(&labelNew));
7686:   }
7687:   PetscFunctionReturn(PETSC_SUCCESS);
7688: }

7690: /*@C
7691:   DMCompareLabels - Compare labels between two `DM` objects

7693:   Collective; No Fortran Support

7695:   Input Parameters:
7696: + dm0 - First `DM` object
7697: - dm1 - Second `DM` object

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

7703:   Level: intermediate

7705:   Notes:
7706:   The output flag equal will be the same on all processes.

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

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

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

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

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

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

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

7723:   Developer Note:
7724:   Cannot automatically generate the Fortran stub because `message` must be freed with `PetscFree()`

7726: .seealso: [](ch_dmbase), `DM`, `DMLabel`, `DMAddLabel()`, `DMCopyLabelsMode`, `DMLabelCompare()`
7727: @*/
7728: PetscErrorCode DMCompareLabels(DM dm0, DM dm1, PetscBool *equal, char *message[]) PeNS
7729: {
7730:   PetscInt    n, i;
7731:   char        msg[PETSC_MAX_PATH_LEN] = "";
7732:   PetscBool   eq;
7733:   MPI_Comm    comm;
7734:   PetscMPIInt rank;

7736:   PetscFunctionBegin;
7739:   PetscCheckSameComm(dm0, 1, dm1, 2);
7740:   if (equal) PetscAssertPointer(equal, 3);
7741:   if (message) PetscAssertPointer(message, 4);
7742:   PetscCall(PetscObjectGetComm((PetscObject)dm0, &comm));
7743:   PetscCallMPI(MPI_Comm_rank(comm, &rank));
7744:   {
7745:     PetscInt n1;

7747:     PetscCall(DMGetNumLabels(dm0, &n));
7748:     PetscCall(DMGetNumLabels(dm1, &n1));
7749:     eq = (PetscBool)(n == n1);
7750:     if (!eq) PetscCall(PetscSNPrintf(msg, sizeof(msg), "Number of labels in dm0 = %" PetscInt_FMT " != %" PetscInt_FMT " = Number of labels in dm1", n, n1));
7751:     PetscCallMPI(MPIU_Allreduce(MPI_IN_PLACE, &eq, 1, MPI_C_BOOL, MPI_LAND, comm));
7752:     if (!eq) goto finish;
7753:   }
7754:   for (i = 0; i < n; i++) {
7755:     DMLabel     l0, l1;
7756:     const char *name;
7757:     char       *msgInner;

7759:     /* Ignore label order */
7760:     PetscCall(DMGetLabelByNum(dm0, i, &l0));
7761:     PetscCall(PetscObjectGetName((PetscObject)l0, &name));
7762:     PetscCall(DMGetLabel(dm1, name, &l1));
7763:     if (!l1) {
7764:       PetscCall(PetscSNPrintf(msg, sizeof(msg), "Label \"%s\" (#%" PetscInt_FMT " in dm0) not found in dm1", name, i));
7765:       eq = PETSC_FALSE;
7766:       break;
7767:     }
7768:     PetscCall(DMLabelCompare(comm, l0, l1, &eq, &msgInner));
7769:     PetscCall(PetscStrncpy(msg, msgInner, sizeof(msg)));
7770:     PetscCall(PetscFree(msgInner));
7771:     if (!eq) break;
7772:   }
7773:   PetscCallMPI(MPIU_Allreduce(MPI_IN_PLACE, &eq, 1, MPI_C_BOOL, MPI_LAND, comm));
7774: finish:
7775:   /* If message output arg not set, print to stderr */
7776:   if (message) {
7777:     *message = NULL;
7778:     if (msg[0]) PetscCall(PetscStrallocpy(msg, message));
7779:   } else {
7780:     if (msg[0]) PetscCall(PetscSynchronizedFPrintf(comm, PETSC_STDERR, "[%d] %s\n", rank, msg));
7781:     PetscCall(PetscSynchronizedFlush(comm, PETSC_STDERR));
7782:   }
7783:   /* If same output arg not ser and labels are not equal, throw error */
7784:   if (equal) *equal = eq;
7785:   else PetscCheck(eq, comm, PETSC_ERR_ARG_INCOMP, "DMLabels are not the same in dm0 and dm1");
7786:   PetscFunctionReturn(PETSC_SUCCESS);
7787: }

7789: PetscErrorCode DMSetLabelValue_Fast(DM dm, DMLabel *label, const char name[], PetscInt point, PetscInt value)
7790: {
7791:   PetscFunctionBegin;
7792:   PetscAssertPointer(label, 2);
7793:   if (!*label) {
7794:     PetscCall(DMCreateLabel(dm, name));
7795:     PetscCall(DMGetLabel(dm, name, label));
7796:   }
7797:   PetscCall(DMLabelSetValue(*label, point, value));
7798:   PetscFunctionReturn(PETSC_SUCCESS);
7799: }

7801: /*
7802:   Many mesh programs, such as Triangle and TetGen, allow only a single label for each mesh point. Therefore, we would
7803:   like to encode all label IDs using a single, universal label. We can do this by assigning an integer to every
7804:   (label, id) pair in the DM.

7806:   However, a mesh point can have multiple labels, so we must separate all these values. We will assign a bit range to
7807:   each label.
7808: */
7809: PetscErrorCode DMUniversalLabelCreate(DM dm, DMUniversalLabel *universal)
7810: {
7811:   DMUniversalLabel ul;
7812:   PetscBool       *active;
7813:   PetscInt         pStart, pEnd, p, Nl, l, m;

7815:   PetscFunctionBegin;
7816:   PetscCall(PetscMalloc1(1, &ul));
7817:   PetscCall(DMLabelCreate(PETSC_COMM_SELF, "universal", &ul->label));
7818:   PetscCall(DMGetNumLabels(dm, &Nl));
7819:   PetscCall(PetscCalloc1(Nl, &active));
7820:   ul->Nl = 0;
7821:   for (l = 0; l < Nl; ++l) {
7822:     PetscBool   isdepth, iscelltype;
7823:     const char *name;

7825:     PetscCall(DMGetLabelName(dm, l, &name));
7826:     PetscCall(PetscStrncmp(name, "depth", 6, &isdepth));
7827:     PetscCall(PetscStrncmp(name, "celltype", 9, &iscelltype));
7828:     active[l] = !(isdepth || iscelltype) ? PETSC_TRUE : PETSC_FALSE;
7829:     if (active[l]) ++ul->Nl;
7830:   }
7831:   PetscCall(PetscCalloc5(ul->Nl, &ul->names, ul->Nl, &ul->indices, ul->Nl + 1, &ul->offsets, ul->Nl + 1, &ul->bits, ul->Nl, &ul->masks));
7832:   ul->Nv = 0;
7833:   for (l = 0, m = 0; l < Nl; ++l) {
7834:     DMLabel     label;
7835:     PetscInt    nv;
7836:     const char *name;

7838:     if (!active[l]) continue;
7839:     PetscCall(DMGetLabelName(dm, l, &name));
7840:     PetscCall(DMGetLabelByNum(dm, l, &label));
7841:     PetscCall(DMLabelGetNumValues(label, &nv));
7842:     PetscCall(PetscStrallocpy(name, &ul->names[m]));
7843:     ul->indices[m] = l;
7844:     ul->Nv += nv;
7845:     ul->offsets[m + 1] = nv;
7846:     ul->bits[m + 1]    = PetscCeilReal(PetscLog2Real(nv + 1));
7847:     ++m;
7848:   }
7849:   for (l = 1; l <= ul->Nl; ++l) {
7850:     ul->offsets[l] = ul->offsets[l - 1] + ul->offsets[l];
7851:     ul->bits[l]    = ul->bits[l - 1] + ul->bits[l];
7852:   }
7853:   for (l = 0; l < ul->Nl; ++l) {
7854:     PetscInt b;

7856:     ul->masks[l] = 0;
7857:     for (b = ul->bits[l]; b < ul->bits[l + 1]; ++b) ul->masks[l] |= 1 << b;
7858:   }
7859:   PetscCall(PetscMalloc1(ul->Nv, &ul->values));
7860:   for (l = 0, m = 0; l < Nl; ++l) {
7861:     DMLabel         label;
7862:     IS              valueIS;
7863:     const PetscInt *varr;
7864:     PetscInt        nv, v;

7866:     if (!active[l]) continue;
7867:     PetscCall(DMGetLabelByNum(dm, l, &label));
7868:     PetscCall(DMLabelGetNumValues(label, &nv));
7869:     PetscCall(DMLabelGetValueIS(label, &valueIS));
7870:     PetscCall(ISGetIndices(valueIS, &varr));
7871:     for (v = 0; v < nv; ++v) ul->values[ul->offsets[m] + v] = varr[v];
7872:     PetscCall(ISRestoreIndices(valueIS, &varr));
7873:     PetscCall(ISDestroy(&valueIS));
7874:     PetscCall(PetscSortInt(nv, &ul->values[ul->offsets[m]]));
7875:     ++m;
7876:   }
7877:   PetscCall(DMPlexGetChart(dm, &pStart, &pEnd));
7878:   for (p = pStart; p < pEnd; ++p) {
7879:     PetscInt  uval   = 0;
7880:     PetscBool marked = PETSC_FALSE;

7882:     for (l = 0, m = 0; l < Nl; ++l) {
7883:       DMLabel  label;
7884:       PetscInt val, defval, loc, nv;

7886:       if (!active[l]) continue;
7887:       PetscCall(DMGetLabelByNum(dm, l, &label));
7888:       PetscCall(DMLabelGetValue(label, p, &val));
7889:       PetscCall(DMLabelGetDefaultValue(label, &defval));
7890:       if (val == defval) {
7891:         ++m;
7892:         continue;
7893:       }
7894:       nv     = ul->offsets[m + 1] - ul->offsets[m];
7895:       marked = PETSC_TRUE;
7896:       PetscCall(PetscFindInt(val, nv, &ul->values[ul->offsets[m]], &loc));
7897:       PetscCheck(loc >= 0, PETSC_COMM_SELF, PETSC_ERR_PLIB, "Label value %" PetscInt_FMT " not found in compression array", val);
7898:       uval += (loc + 1) << ul->bits[m];
7899:       ++m;
7900:     }
7901:     if (marked) PetscCall(DMLabelSetValue(ul->label, p, uval));
7902:   }
7903:   PetscCall(PetscFree(active));
7904:   *universal = ul;
7905:   PetscFunctionReturn(PETSC_SUCCESS);
7906: }

7908: PetscErrorCode DMUniversalLabelDestroy(DMUniversalLabel *universal)
7909: {
7910:   PetscInt l;

7912:   PetscFunctionBegin;
7913:   for (l = 0; l < (*universal)->Nl; ++l) PetscCall(PetscFree((*universal)->names[l]));
7914:   PetscCall(DMLabelDestroy(&(*universal)->label));
7915:   PetscCall(PetscFree5((*universal)->names, (*universal)->indices, (*universal)->offsets, (*universal)->bits, (*universal)->masks));
7916:   PetscCall(PetscFree((*universal)->values));
7917:   PetscCall(PetscFree(*universal));
7918:   *universal = NULL;
7919:   PetscFunctionReturn(PETSC_SUCCESS);
7920: }

7922: PetscErrorCode DMUniversalLabelGetLabel(DMUniversalLabel ul, DMLabel *ulabel)
7923: {
7924:   PetscFunctionBegin;
7925:   PetscAssertPointer(ulabel, 2);
7926:   *ulabel = ul->label;
7927:   PetscFunctionReturn(PETSC_SUCCESS);
7928: }

7930: PetscErrorCode DMUniversalLabelCreateLabels(DMUniversalLabel ul, PetscBool preserveOrder, DM dm)
7931: {
7932:   PetscInt Nl = ul->Nl, l;

7934:   PetscFunctionBegin;
7936:   for (l = 0; l < Nl; ++l) {
7937:     if (preserveOrder) PetscCall(DMCreateLabelAtIndex(dm, ul->indices[l], ul->names[l]));
7938:     else PetscCall(DMCreateLabel(dm, ul->names[l]));
7939:   }
7940:   if (preserveOrder) {
7941:     for (l = 0; l < ul->Nl; ++l) {
7942:       const char *name;
7943:       PetscBool   match;

7945:       PetscCall(DMGetLabelName(dm, ul->indices[l], &name));
7946:       PetscCall(PetscStrcmp(name, ul->names[l], &match));
7947:       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]);
7948:     }
7949:   }
7950:   PetscFunctionReturn(PETSC_SUCCESS);
7951: }

7953: PetscErrorCode DMUniversalLabelSetLabelValue(DMUniversalLabel ul, DM dm, PetscBool useIndex, PetscInt p, PetscInt value)
7954: {
7955:   PetscInt l;

7957:   PetscFunctionBegin;
7958:   for (l = 0; l < ul->Nl; ++l) {
7959:     DMLabel  label;
7960:     PetscInt lval = (value & ul->masks[l]) >> ul->bits[l];

7962:     if (lval) {
7963:       if (useIndex) PetscCall(DMGetLabelByNum(dm, ul->indices[l], &label));
7964:       else PetscCall(DMGetLabel(dm, ul->names[l], &label));
7965:       PetscCall(DMLabelSetValue(label, p, ul->values[ul->offsets[l] + lval - 1]));
7966:     }
7967:   }
7968:   PetscFunctionReturn(PETSC_SUCCESS);
7969: }

7971: /*@
7972:   DMGetCoarseDM - Get the coarse `DM`from which this `DM` was obtained by refinement

7974:   Not Collective

7976:   Input Parameter:
7977: . dm - The `DM` object

7979:   Output Parameter:
7980: . cdm - The coarse `DM`

7982:   Level: intermediate

7984: .seealso: [](ch_dmbase), `DM`, `DMSetCoarseDM()`, `DMCoarsen()`
7985: @*/
7986: PetscErrorCode DMGetCoarseDM(DM dm, DM *cdm)
7987: {
7988:   PetscFunctionBegin;
7990:   PetscAssertPointer(cdm, 2);
7991:   *cdm = dm->coarseMesh;
7992:   PetscFunctionReturn(PETSC_SUCCESS);
7993: }

7995: /*@
7996:   DMSetCoarseDM - Set the coarse `DM` from which this `DM` was obtained by refinement

7998:   Input Parameters:
7999: + dm  - The `DM` object
8000: - cdm - The coarse `DM`

8002:   Level: intermediate

8004:   Note:
8005:   Normally this is set automatically by `DMRefine()`

8007: .seealso: [](ch_dmbase), `DM`, `DMGetCoarseDM()`, `DMCoarsen()`, `DMSetRefine()`, `DMSetFineDM()`
8008: @*/
8009: PetscErrorCode DMSetCoarseDM(DM dm, DM cdm)
8010: {
8011:   PetscFunctionBegin;
8014:   if (dm == cdm) cdm = NULL;
8015:   PetscCall(PetscObjectReference((PetscObject)cdm));
8016:   PetscCall(DMDestroy(&dm->coarseMesh));
8017:   dm->coarseMesh = cdm;
8018:   PetscFunctionReturn(PETSC_SUCCESS);
8019: }

8021: /*@
8022:   DMGetFineDM - Get the fine mesh from which this `DM` was obtained by coarsening

8024:   Input Parameter:
8025: . dm - The `DM` object

8027:   Output Parameter:
8028: . fdm - The fine `DM`

8030:   Level: intermediate

8032: .seealso: [](ch_dmbase), `DM`, `DMSetFineDM()`, `DMCoarsen()`, `DMRefine()`
8033: @*/
8034: PetscErrorCode DMGetFineDM(DM dm, DM *fdm)
8035: {
8036:   PetscFunctionBegin;
8038:   PetscAssertPointer(fdm, 2);
8039:   *fdm = dm->fineMesh;
8040:   PetscFunctionReturn(PETSC_SUCCESS);
8041: }

8043: /*@
8044:   DMSetFineDM - Set the fine mesh from which this was obtained by coarsening

8046:   Input Parameters:
8047: + dm  - The `DM` object
8048: - fdm - The fine `DM`

8050:   Level: developer

8052:   Note:
8053:   Normally this is set automatically by `DMCoarsen()`

8055: .seealso: [](ch_dmbase), `DM`, `DMGetFineDM()`, `DMCoarsen()`, `DMRefine()`
8056: @*/
8057: PetscErrorCode DMSetFineDM(DM dm, DM fdm)
8058: {
8059:   PetscFunctionBegin;
8062:   if (dm == fdm) fdm = NULL;
8063:   PetscCall(PetscObjectReference((PetscObject)fdm));
8064:   PetscCall(DMDestroy(&dm->fineMesh));
8065:   dm->fineMesh = fdm;
8066:   PetscFunctionReturn(PETSC_SUCCESS);
8067: }

8069: /*@C
8070:   DMAddBoundary - Add a boundary condition, for a single field, to a model represented by a `DM`

8072:   Collective

8074:   Input Parameters:
8075: + dm       - The `DM`, with a `PetscDS` that matches the problem being constrained
8076: . type     - The type of condition, e.g. `DM_BC_ESSENTIAL_ANALYTIC`, `DM_BC_ESSENTIAL_FIELD` (Dirichlet), or `DM_BC_NATURAL` (Neumann)
8077: . name     - The BC name
8078: . label    - The label defining constrained points
8079: . Nv       - The number of `DMLabel` values for constrained points
8080: . values   - An array of values for constrained points
8081: . field    - The field to constrain
8082: . Nc       - The number of constrained field components (0 will constrain all components)
8083: . comps    - An array of constrained component numbers
8084: . bcFunc   - A pointwise function giving boundary values
8085: . bcFunc_t - A pointwise function giving the time derivative of the boundary values, or `NULL`
8086: - ctx      - An optional user context for bcFunc

8088:   Output Parameter:
8089: . bd - (Optional) Boundary number

8091:   Options Database Keys:
8092: + -bc_NAME values     - Overrides the boundary ids for boundary named NAME
8093: - -bc_NAME_comp comps - Overrides the boundary components for boundary named NAME

8095:   Level: intermediate

8097:   Notes:
8098:   If the `DM` is of type `DMPLEX` and the field is of type `PetscFE`, then this function completes the label using `DMPlexLabelComplete()`.

8100:   Both bcFunc and bcFunc_t will depend on the boundary condition type. If the type if `DM_BC_ESSENTIAL`, then the calling sequence is\:
8101: .vb
8102:  void bcFunc(PetscInt dim, PetscReal time, const PetscReal x[], PetscInt Nc, PetscScalar bcval[])
8103: .ve

8105:   If the type is `DM_BC_ESSENTIAL_FIELD` or other _FIELD value, then the calling sequence is\:

8107: .vb
8108:   void bcFunc(PetscInt dim, PetscInt Nf, PetscInt NfAux,
8109:               const PetscInt uOff[], const PetscInt uOff_x[], const PetscScalar u[], const PetscScalar u_t[], const PetscScalar u_x[],
8110:               const PetscInt aOff[], const PetscInt aOff_x[], const PetscScalar a[], const PetscScalar a_t[], const PetscScalar a_x[],
8111:               PetscReal time, const PetscReal x[], PetscScalar bcval[])
8112: .ve
8113: + dim - the spatial dimension
8114: . Nf - the number of fields
8115: . uOff - the offset into u[] and u_t[] for each field
8116: . uOff_x - the offset into u_x[] for each field
8117: . u - each field evaluated at the current point
8118: . u_t - the time derivative of each field evaluated at the current point
8119: . u_x - the gradient of each field evaluated at the current point
8120: . aOff - the offset into a[] and a_t[] for each auxiliary field
8121: . aOff_x - the offset into a_x[] for each auxiliary field
8122: . a - each auxiliary field evaluated at the current point
8123: . a_t - the time derivative of each auxiliary field evaluated at the current point
8124: . a_x - the gradient of auxiliary each field evaluated at the current point
8125: . t - current time
8126: . x - coordinates of the current point
8127: . numConstants - number of constant parameters
8128: . constants - constant parameters
8129: - bcval - output values at the current point

8131: .seealso: [](ch_dmbase), `DM`, `DSGetBoundary()`, `PetscDSAddBoundary()`
8132: @*/
8133: 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)
8134: {
8135:   PetscDS ds;

8137:   PetscFunctionBegin;
8144:   PetscCheck(!dm->localSection, PetscObjectComm((PetscObject)dm), PETSC_ERR_ARG_WRONGSTATE, "Cannot add boundary to DM after creating local section");
8145:   PetscCall(DMGetDS(dm, &ds));
8146:   /* Complete label */
8147:   if (label) {
8148:     PetscObject  obj;
8149:     PetscClassId id;

8151:     PetscCall(DMGetField(dm, field, NULL, &obj));
8152:     PetscCall(PetscObjectGetClassId(obj, &id));
8153:     if (id == PETSCFE_CLASSID) {
8154:       DM plex;

8156:       PetscCall(DMConvert(dm, DMPLEX, &plex));
8157:       if (plex) PetscCall(DMPlexLabelComplete(plex, label));
8158:       PetscCall(DMDestroy(&plex));
8159:     }
8160:   }
8161:   PetscCall(PetscDSAddBoundary(ds, type, name, label, Nv, values, field, Nc, comps, bcFunc, bcFunc_t, ctx, bd));
8162:   PetscFunctionReturn(PETSC_SUCCESS);
8163: }

8165: /* TODO Remove this since now the structures are the same */
8166: static PetscErrorCode DMPopulateBoundary(DM dm)
8167: {
8168:   PetscDS     ds;
8169:   DMBoundary *lastnext;
8170:   DSBoundary  dsbound;

8172:   PetscFunctionBegin;
8173:   PetscCall(DMGetDS(dm, &ds));
8174:   dsbound = ds->boundary;
8175:   if (dm->boundary) {
8176:     DMBoundary next = dm->boundary;

8178:     /* quick check to see if the PetscDS has changed */
8179:     if (next->dsboundary == dsbound) PetscFunctionReturn(PETSC_SUCCESS);
8180:     /* the PetscDS has changed: tear down and rebuild */
8181:     while (next) {
8182:       DMBoundary b = next;

8184:       next = b->next;
8185:       PetscCall(PetscFree(b));
8186:     }
8187:     dm->boundary = NULL;
8188:   }

8190:   lastnext = &dm->boundary;
8191:   while (dsbound) {
8192:     DMBoundary dmbound;

8194:     PetscCall(PetscNew(&dmbound));
8195:     dmbound->dsboundary = dsbound;
8196:     dmbound->label      = dsbound->label;
8197:     /* push on the back instead of the front so that it is in the same order as in the PetscDS */
8198:     *lastnext = dmbound;
8199:     lastnext  = &dmbound->next;
8200:     dsbound   = dsbound->next;
8201:   }
8202:   PetscFunctionReturn(PETSC_SUCCESS);
8203: }

8205: /* TODO: missing manual page */
8206: PetscErrorCode DMIsBoundaryPoint(DM dm, PetscInt point, PetscBool *isBd)
8207: {
8208:   DMBoundary b;

8210:   PetscFunctionBegin;
8212:   PetscAssertPointer(isBd, 3);
8213:   *isBd = PETSC_FALSE;
8214:   PetscCall(DMPopulateBoundary(dm));
8215:   b = dm->boundary;
8216:   while (b && !*isBd) {
8217:     DMLabel    label = b->label;
8218:     DSBoundary dsb   = b->dsboundary;
8219:     PetscInt   i;

8221:     if (label) {
8222:       for (i = 0; i < dsb->Nv && !*isBd; ++i) PetscCall(DMLabelStratumHasPoint(label, dsb->values[i], point, isBd));
8223:     }
8224:     b = b->next;
8225:   }
8226:   PetscFunctionReturn(PETSC_SUCCESS);
8227: }

8229: /*@
8230:   DMHasBound - Determine whether a bound condition was specified

8232:   Logically collective

8234:   Input Parameter:
8235: . dm - The `DM`, with a `PetscDS` that matches the problem being constrained

8237:   Output Parameter:
8238: . hasBound - Flag indicating if a bound condition was specified

8240:   Level: intermediate

8242: .seealso: [](ch_dmbase), `DM`, `DSAddBoundary()`, `PetscDSAddBoundary()`
8243: @*/
8244: PetscErrorCode DMHasBound(DM dm, PetscBool *hasBound)
8245: {
8246:   PetscDS  ds;
8247:   PetscInt Nf, numBd;

8249:   PetscFunctionBegin;
8250:   *hasBound = PETSC_FALSE;
8251:   PetscCall(DMGetDS(dm, &ds));
8252:   PetscCall(PetscDSGetNumFields(ds, &Nf));
8253:   for (PetscInt f = 0; f < Nf; ++f) {
8254:     PetscSimplePointFn *lfunc, *ufunc;

8256:     PetscCall(PetscDSGetLowerBound(ds, f, &lfunc, NULL));
8257:     PetscCall(PetscDSGetUpperBound(ds, f, &ufunc, NULL));
8258:     if (lfunc || ufunc) *hasBound = PETSC_TRUE;
8259:   }

8261:   PetscCall(PetscDSGetNumBoundary(ds, &numBd));
8262:   PetscCall(PetscDSUpdateBoundaryLabels(ds, dm));
8263:   for (PetscInt b = 0; b < numBd; ++b) {
8264:     PetscWeakForm           wf;
8265:     DMBoundaryConditionType type;
8266:     const char             *name;
8267:     DMLabel                 label;
8268:     PetscInt                numids;
8269:     const PetscInt         *ids;
8270:     PetscInt                field, Nc;
8271:     const PetscInt         *comps;
8272:     PetscVoidFn            *bvfunc;
8273:     void                   *ctx;

8275:     PetscCall(PetscDSGetBoundary(ds, b, &wf, &type, &name, &label, &numids, &ids, &field, &Nc, &comps, &bvfunc, NULL, &ctx));
8276:     if (type == DM_BC_LOWER_BOUND || type == DM_BC_UPPER_BOUND) *hasBound = PETSC_TRUE;
8277:   }
8278:   PetscFunctionReturn(PETSC_SUCCESS);
8279: }

8281: /*@C
8282:   DMProjectFunction - This projects the given function into the function space provided by a `DM`, putting the coefficients in a global vector.

8284:   Collective

8286:   Input Parameters:
8287: + dm    - The `DM`
8288: . time  - The time
8289: . funcs - The coordinate functions to evaluate, one per field
8290: . ctxs  - Optional array of contexts to pass to each coordinate function.  ctxs itself may be null.
8291: - mode  - The insertion mode for values

8293:   Output Parameter:
8294: . X - vector

8296:   Calling sequence of `funcs`:
8297: + dim  - The spatial dimension
8298: . time - The time at which to sample
8299: . x    - The coordinates
8300: . Nc   - The number of components
8301: . u    - The output field values
8302: - ctx  - optional function context

8304:   Level: developer

8306:   Developer Notes:
8307:   This API is specific to only particular usage of `DM`

8309:   The notes need to provide some information about what has to be provided to the `DM` to be able to perform the computation.

8311: .seealso: [](ch_dmbase), `DM`, `DMProjectFunctionLocal()`, `DMProjectFunctionLabel()`, `DMComputeL2Diff()`
8312: @*/
8313: 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)
8314: {
8315:   Vec localX;

8317:   PetscFunctionBegin;
8319:   PetscCall(PetscLogEventBegin(DM_ProjectFunction, dm, X, 0, 0));
8320:   PetscCall(DMGetLocalVector(dm, &localX));
8321:   PetscCall(VecSet(localX, 0.));
8322:   PetscCall(DMProjectFunctionLocal(dm, time, funcs, ctxs, mode, localX));
8323:   PetscCall(DMLocalToGlobalBegin(dm, localX, mode, X));
8324:   PetscCall(DMLocalToGlobalEnd(dm, localX, mode, X));
8325:   PetscCall(DMRestoreLocalVector(dm, &localX));
8326:   PetscCall(PetscLogEventEnd(DM_ProjectFunction, dm, X, 0, 0));
8327:   PetscFunctionReturn(PETSC_SUCCESS);
8328: }

8330: /*@C
8331:   DMProjectFunctionLocal - This projects the given function into the function space provided by a `DM`, putting the coefficients in a local vector.

8333:   Not Collective

8335:   Input Parameters:
8336: + dm    - The `DM`
8337: . time  - The time
8338: . funcs - The coordinate functions to evaluate, one per field
8339: . ctxs  - Optional array of contexts to pass to each coordinate function.  ctxs itself may be null.
8340: - mode  - The insertion mode for values

8342:   Output Parameter:
8343: . localX - vector

8345:   Calling sequence of `funcs`:
8346: + dim  - The spatial dimension
8347: . time - The current timestep
8348: . x    - The coordinates
8349: . Nc   - The number of components
8350: . u    - The output field values
8351: - ctx  - optional function context

8353:   Level: developer

8355:   Developer Notes:
8356:   This API is specific to only particular usage of `DM`

8358:   The notes need to provide some information about what has to be provided to the `DM` to be able to perform the computation.

8360: .seealso: [](ch_dmbase), `DM`, `DMProjectFunction()`, `DMProjectFunctionLabel()`, `DMComputeL2Diff()`
8361: @*/
8362: 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)
8363: {
8364:   PetscFunctionBegin;
8367:   PetscUseTypeMethod(dm, projectfunctionlocal, time, funcs, ctxs, mode, localX);
8368:   PetscFunctionReturn(PETSC_SUCCESS);
8369: }

8371: /*@C
8372:   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.

8374:   Collective

8376:   Input Parameters:
8377: + dm     - The `DM`
8378: . time   - The time
8379: . numIds - The number of ids
8380: . ids    - The ids
8381: . Nc     - The number of components
8382: . comps  - The components
8383: . label  - The `DMLabel` selecting the portion of the mesh for projection
8384: . funcs  - The coordinate functions to evaluate, one per field
8385: . ctxs   - Optional array of contexts to pass to each coordinate function.  ctxs may be null.
8386: - mode   - The insertion mode for values

8388:   Output Parameter:
8389: . X - vector

8391:   Calling sequence of `funcs`:
8392: + dim  - The spatial dimension
8393: . time - The current timestep
8394: . x    - The coordinates
8395: . Nc   - The number of components
8396: . u    - The output field values
8397: - ctx  - optional function context

8399:   Level: developer

8401:   Developer Notes:
8402:   This API is specific to only particular usage of `DM`

8404:   The notes need to provide some information about what has to be provided to the `DM` to be able to perform the computation.

8406: .seealso: [](ch_dmbase), `DM`, `DMProjectFunction()`, `DMProjectFunctionLocal()`, `DMProjectFunctionLabelLocal()`, `DMComputeL2Diff()`
8407: @*/
8408: 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)
8409: {
8410:   Vec localX;

8412:   PetscFunctionBegin;
8414:   PetscCall(DMGetLocalVector(dm, &localX));
8415:   PetscCall(VecSet(localX, 0.));
8416:   PetscCall(DMProjectFunctionLabelLocal(dm, time, label, numIds, ids, Nc, comps, funcs, ctxs, mode, localX));
8417:   PetscCall(DMLocalToGlobalBegin(dm, localX, mode, X));
8418:   PetscCall(DMLocalToGlobalEnd(dm, localX, mode, X));
8419:   PetscCall(DMRestoreLocalVector(dm, &localX));
8420:   PetscFunctionReturn(PETSC_SUCCESS);
8421: }

8423: /*@C
8424:   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.

8426:   Not Collective

8428:   Input Parameters:
8429: + dm     - The `DM`
8430: . time   - The time
8431: . label  - The `DMLabel` selecting the portion of the mesh for projection
8432: . numIds - The number of ids
8433: . ids    - The ids
8434: . Nc     - The number of components
8435: . comps  - The components
8436: . funcs  - The coordinate functions to evaluate, one per field
8437: . ctxs   - Optional array of contexts to pass to each coordinate function.  ctxs itself may be null.
8438: - mode   - The insertion mode for values

8440:   Output Parameter:
8441: . localX - vector

8443:   Calling sequence of `funcs`:
8444: + dim  - The spatial dimension
8445: . time - The current time
8446: . x    - The coordinates
8447: . Nc   - The number of components
8448: . u    - The output field values
8449: - ctx  - optional function context

8451:   Level: developer

8453:   Developer Notes:
8454:   This API is specific to only particular usage of `DM`

8456:   The notes need to provide some information about what has to be provided to the `DM` to be able to perform the computation.

8458: .seealso: [](ch_dmbase), `DM`, `DMProjectFunction()`, `DMProjectFunctionLocal()`, `DMProjectFunctionLabel()`, `DMComputeL2Diff()`
8459: @*/
8460: 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)
8461: {
8462:   PetscFunctionBegin;
8465:   PetscUseTypeMethod(dm, projectfunctionlabellocal, time, label, numIds, ids, Nc, comps, funcs, ctxs, mode, localX);
8466:   PetscFunctionReturn(PETSC_SUCCESS);
8467: }

8469: /*@C
8470:   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.

8472:   Not Collective

8474:   Input Parameters:
8475: + dm     - The `DM`
8476: . time   - The time
8477: . localU - The input field vector; may be `NULL` if projection is defined purely by coordinates
8478: . funcs  - The functions to evaluate, one per field
8479: - mode   - The insertion mode for values

8481:   Output Parameter:
8482: . localX - The output vector

8484:   Calling sequence of `funcs`:
8485: + dim          - The spatial dimension
8486: . Nf           - The number of input fields
8487: . NfAux        - The number of input auxiliary fields
8488: . uOff         - The offset of each field in u[]
8489: . uOff_x       - The offset of each field in u_x[]
8490: . u            - The field values at this point in space
8491: . u_t          - The field time derivative at this point in space (or `NULL`)
8492: . u_x          - The field derivatives at this point in space
8493: . aOff         - The offset of each auxiliary field in u[]
8494: . aOff_x       - The offset of each auxiliary field in u_x[]
8495: . a            - The auxiliary field values at this point in space
8496: . a_t          - The auxiliary field time derivative at this point in space (or `NULL`)
8497: . a_x          - The auxiliary field derivatives at this point in space
8498: . t            - The current time
8499: . x            - The coordinates of this point
8500: . numConstants - The number of constants
8501: . constants    - The value of each constant
8502: - f            - The value of the function at this point in space

8504:   Level: intermediate

8506:   Note:
8507:   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.
8508:   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
8509:   a subdomain. You can also output a different number of fields than the input, with different discretizations. Last the auxiliary `DM`, attached to the
8510:   auxiliary field vector, which is attached to dm, can also be different. It can have a different topology, number of fields, and discretizations.

8512:   Developer Notes:
8513:   This API is specific to only particular usage of `DM`

8515:   The notes need to provide some information about what has to be provided to the `DM` to be able to perform the computation.

8517: .seealso: [](ch_dmbase), `DM`, `DMProjectField()`, `DMProjectFieldLabelLocal()`,
8518: `DMProjectFunction()`, `DMComputeL2Diff()`
8519: @*/
8520: 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)
8521: {
8522:   PetscFunctionBegin;
8526:   PetscUseTypeMethod(dm, projectfieldlocal, time, localU, funcs, mode, localX);
8527:   PetscFunctionReturn(PETSC_SUCCESS);
8528: }

8530: /*@C
8531:   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.

8533:   Not Collective

8535:   Input Parameters:
8536: + dm     - The `DM`
8537: . time   - The time
8538: . label  - The `DMLabel` marking the portion of the domain to output
8539: . numIds - The number of label ids to use
8540: . ids    - The label ids to use for marking
8541: . Nc     - The number of components to set in the output, or `PETSC_DETERMINE` for all components
8542: . comps  - The components to set in the output, or `NULL` for all components
8543: . localU - The input field vector
8544: . funcs  - The functions to evaluate, one per field
8545: - mode   - The insertion mode for values

8547:   Output Parameter:
8548: . localX - The output vector

8550:   Calling sequence of `funcs`:
8551: + dim          - The spatial dimension
8552: . Nf           - The number of input fields
8553: . NfAux        - The number of input auxiliary fields
8554: . uOff         - The offset of each field in u[]
8555: . uOff_x       - The offset of each field in u_x[]
8556: . u            - The field values at this point in space
8557: . u_t          - The field time derivative at this point in space (or `NULL`)
8558: . u_x          - The field derivatives at this point in space
8559: . aOff         - The offset of each auxiliary field in u[]
8560: . aOff_x       - The offset of each auxiliary field in u_x[]
8561: . a            - The auxiliary field values at this point in space
8562: . a_t          - The auxiliary field time derivative at this point in space (or `NULL`)
8563: . a_x          - The auxiliary field derivatives at this point in space
8564: . t            - The current time
8565: . x            - The coordinates of this point
8566: . numConstants - The number of constants
8567: . constants    - The value of each constant
8568: - f            - The value of the function at this point in space

8570:   Level: intermediate

8572:   Note:
8573:   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.
8574:   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
8575:   a subdomain. You can also output a different number of fields than the input, with different discretizations. Last the auxiliary `DM`, attached to the
8576:   auxiliary field vector, which is attached to dm, can also be different. It can have a different topology, number of fields, and discretizations.

8578:   Developer Notes:
8579:   This API is specific to only particular usage of `DM`

8581:   The notes need to provide some information about what has to be provided to the `DM` to be able to perform the computation.

8583: .seealso: [](ch_dmbase), `DM`, `DMProjectField()`, `DMProjectFieldLabel()`, `DMProjectFunction()`, `DMComputeL2Diff()`
8584: @*/
8585: 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)
8586: {
8587:   PetscFunctionBegin;
8591:   PetscUseTypeMethod(dm, projectfieldlabellocal, time, label, numIds, ids, Nc, comps, localU, funcs, mode, localX);
8592:   PetscFunctionReturn(PETSC_SUCCESS);
8593: }

8595: /*@C
8596:   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.

8598:   Not Collective

8600:   Input Parameters:
8601: + dm     - The `DM`
8602: . time   - The time
8603: . label  - The `DMLabel` marking the portion of the domain to output
8604: . numIds - The number of label ids to use
8605: . ids    - The label ids to use for marking
8606: . Nc     - The number of components to set in the output, or `PETSC_DETERMINE` for all components
8607: . comps  - The components to set in the output, or `NULL` for all components
8608: . U      - The input field vector
8609: . funcs  - The functions to evaluate, one per field
8610: - mode   - The insertion mode for values

8612:   Output Parameter:
8613: . X - The output vector

8615:   Calling sequence of `funcs`:
8616: + dim          - The spatial dimension
8617: . Nf           - The number of input fields
8618: . NfAux        - The number of input auxiliary fields
8619: . uOff         - The offset of each field in u[]
8620: . uOff_x       - The offset of each field in u_x[]
8621: . u            - The field values at this point in space
8622: . u_t          - The field time derivative at this point in space (or `NULL`)
8623: . u_x          - The field derivatives at this point in space
8624: . aOff         - The offset of each auxiliary field in u[]
8625: . aOff_x       - The offset of each auxiliary field in u_x[]
8626: . a            - The auxiliary field values at this point in space
8627: . a_t          - The auxiliary field time derivative at this point in space (or `NULL`)
8628: . a_x          - The auxiliary field derivatives at this point in space
8629: . t            - The current time
8630: . x            - The coordinates of this point
8631: . numConstants - The number of constants
8632: . constants    - The value of each constant
8633: - f            - The value of the function at this point in space

8635:   Level: intermediate

8637:   Note:
8638:   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.
8639:   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
8640:   a subdomain. You can also output a different number of fields than the input, with different discretizations. Last the auxiliary `DM`, attached to the
8641:   auxiliary field vector, which is attached to dm, can also be different. It can have a different topology, number of fields, and discretizations.

8643:   Developer Notes:
8644:   This API is specific to only particular usage of `DM`

8646:   The notes need to provide some information about what has to be provided to the `DM` to be able to perform the computation.

8648: .seealso: [](ch_dmbase), `DM`, `DMProjectField()`, `DMProjectFieldLabelLocal()`, `DMProjectFunction()`, `DMComputeL2Diff()`
8649: @*/
8650: 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)
8651: {
8652:   DM  dmIn;
8653:   Vec localU, localX;

8655:   PetscFunctionBegin;
8657:   PetscCall(VecGetDM(U, &dmIn));
8658:   PetscCall(DMGetLocalVector(dmIn, &localU));
8659:   PetscCall(DMGetLocalVector(dm, &localX));
8660:   PetscCall(VecSet(localX, 0.));
8661:   PetscCall(DMGlobalToLocalBegin(dmIn, U, mode, localU));
8662:   PetscCall(DMGlobalToLocalEnd(dmIn, U, mode, localU));
8663:   PetscCall(DMProjectFieldLabelLocal(dm, time, label, numIds, ids, Nc, comps, localU, funcs, mode, localX));
8664:   PetscCall(DMLocalToGlobalBegin(dm, localX, mode, X));
8665:   PetscCall(DMLocalToGlobalEnd(dm, localX, mode, X));
8666:   PetscCall(DMRestoreLocalVector(dm, &localX));
8667:   PetscCall(DMRestoreLocalVector(dmIn, &localU));
8668:   PetscFunctionReturn(PETSC_SUCCESS);
8669: }

8671: /*@C
8672:   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.

8674:   Not Collective

8676:   Input Parameters:
8677: + dm     - The `DM`
8678: . time   - The time
8679: . label  - The `DMLabel` marking the portion of the domain boundary to output
8680: . numIds - The number of label ids to use
8681: . ids    - The label ids to use for marking
8682: . Nc     - The number of components to set in the output, or `PETSC_DETERMINE` for all components
8683: . comps  - The components to set in the output, or `NULL` for all components
8684: . localU - The input field vector
8685: . funcs  - The functions to evaluate, one per field
8686: - mode   - The insertion mode for values

8688:   Output Parameter:
8689: . localX - The output vector

8691:   Calling sequence of `funcs`:
8692: + dim          - The spatial dimension
8693: . Nf           - The number of input fields
8694: . NfAux        - The number of input auxiliary fields
8695: . uOff         - The offset of each field in u[]
8696: . uOff_x       - The offset of each field in u_x[]
8697: . u            - The field values at this point in space
8698: . u_t          - The field time derivative at this point in space (or `NULL`)
8699: . u_x          - The field derivatives at this point in space
8700: . aOff         - The offset of each auxiliary field in u[]
8701: . aOff_x       - The offset of each auxiliary field in u_x[]
8702: . a            - The auxiliary field values at this point in space
8703: . a_t          - The auxiliary field time derivative at this point in space (or `NULL`)
8704: . a_x          - The auxiliary field derivatives at this point in space
8705: . t            - The current time
8706: . x            - The coordinates of this point
8707: . n            - The face normal
8708: . numConstants - The number of constants
8709: . constants    - The value of each constant
8710: - f            - The value of the function at this point in space

8712:   Level: intermediate

8714:   Note:
8715:   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.
8716:   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
8717:   a subdomain. You can also output a different number of fields than the input, with different discretizations. Last the auxiliary `DM`, attached to the
8718:   auxiliary field vector, which is attached to dm, can also be different. It can have a different topology, number of fields, and discretizations.

8720:   Developer Notes:
8721:   This API is specific to only particular usage of `DM`

8723:   The notes need to provide some information about what has to be provided to the `DM` to be able to perform the computation.

8725: .seealso: [](ch_dmbase), `DM`, `DMProjectField()`, `DMProjectFieldLabelLocal()`, `DMProjectFunction()`, `DMComputeL2Diff()`
8726: @*/
8727: 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)
8728: {
8729:   PetscFunctionBegin;
8733:   PetscUseTypeMethod(dm, projectbdfieldlabellocal, time, label, numIds, ids, Nc, comps, localU, funcs, mode, localX);
8734:   PetscFunctionReturn(PETSC_SUCCESS);
8735: }

8737: /*@C
8738:   DMComputeL2Diff - This function computes the L_2 difference between a function u and an FEM interpolant solution u_h.

8740:   Collective

8742:   Input Parameters:
8743: + dm    - The `DM`
8744: . time  - The time
8745: . funcs - The functions to evaluate for each field component
8746: . ctxs  - Optional array of contexts to pass to each function, or `NULL`.
8747: - X     - The coefficient vector u_h, a global vector

8749:   Output Parameter:
8750: . diff - The diff ||u - u_h||_2

8752:   Level: developer

8754:   Developer Notes:
8755:   This API is specific to only particular usage of `DM`

8757:   The notes need to provide some information about what has to be provided to the `DM` to be able to perform the computation.

8759: .seealso: [](ch_dmbase), `DM`, `DMProjectFunction()`, `DMComputeL2FieldDiff()`, `DMComputeL2GradientDiff()`
8760: @*/
8761: PetscErrorCode DMComputeL2Diff(DM dm, PetscReal time, PetscErrorCode (**funcs)(PetscInt, PetscReal, const PetscReal[], PetscInt, PetscScalar *, void *), void **ctxs, Vec X, PetscReal *diff)
8762: {
8763:   PetscFunctionBegin;
8766:   PetscUseTypeMethod(dm, computel2diff, time, funcs, ctxs, X, diff);
8767:   PetscFunctionReturn(PETSC_SUCCESS);
8768: }

8770: /*@C
8771:   DMComputeL2GradientDiff - This function computes the L_2 difference between the gradient of a function u and an FEM interpolant solution grad u_h.

8773:   Collective

8775:   Input Parameters:
8776: + dm    - The `DM`
8777: . time  - The time
8778: . funcs - The gradient functions to evaluate for each field component
8779: . ctxs  - Optional array of contexts to pass to each function, or `NULL`.
8780: . X     - The coefficient vector u_h, a global vector
8781: - n     - The vector to project along

8783:   Output Parameter:
8784: . diff - The diff ||(grad u - grad u_h) . n||_2

8786:   Level: developer

8788:   Developer Notes:
8789:   This API is specific to only particular usage of `DM`

8791:   The notes need to provide some information about what has to be provided to the `DM` to be able to perform the computation.

8793: .seealso: [](ch_dmbase), `DM`, `DMProjectFunction()`, `DMComputeL2Diff()`, `DMComputeL2FieldDiff()`
8794: @*/
8795: 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)
8796: {
8797:   PetscFunctionBegin;
8800:   PetscUseTypeMethod(dm, computel2gradientdiff, time, funcs, ctxs, X, n, diff);
8801:   PetscFunctionReturn(PETSC_SUCCESS);
8802: }

8804: /*@C
8805:   DMComputeL2FieldDiff - This function computes the L_2 difference between a function u and an FEM interpolant solution u_h, separated into field components.

8807:   Collective

8809:   Input Parameters:
8810: + dm    - The `DM`
8811: . time  - The time
8812: . funcs - The functions to evaluate for each field component
8813: . ctxs  - Optional array of contexts to pass to each function, or `NULL`.
8814: - X     - The coefficient vector u_h, a global vector

8816:   Output Parameter:
8817: . diff - The array of differences, ||u^f - u^f_h||_2

8819:   Level: developer

8821:   Developer Notes:
8822:   This API is specific to only particular usage of `DM`

8824:   The notes need to provide some information about what has to be provided to the `DM` to be able to perform the computation.

8826: .seealso: [](ch_dmbase), `DM`, `DMProjectFunction()`, `DMComputeL2GradientDiff()`
8827: @*/
8828: PetscErrorCode DMComputeL2FieldDiff(DM dm, PetscReal time, PetscErrorCode (**funcs)(PetscInt, PetscReal, const PetscReal[], PetscInt, PetscScalar *, void *), void **ctxs, Vec X, PetscReal diff[])
8829: {
8830:   PetscFunctionBegin;
8833:   PetscUseTypeMethod(dm, computel2fielddiff, time, funcs, ctxs, X, diff);
8834:   PetscFunctionReturn(PETSC_SUCCESS);
8835: }

8837: /*@C
8838:   DMGetNeighbors - Gets an array containing the MPI ranks of all the processes neighbors

8840:   Not Collective

8842:   Input Parameter:
8843: . dm - The `DM`

8845:   Output Parameters:
8846: + nranks - the number of neighbours
8847: - ranks  - the neighbors ranks

8849:   Level: beginner

8851:   Note:
8852:   Do not free the array, it is freed when the `DM` is destroyed.

8854: .seealso: [](ch_dmbase), `DM`, `DMDAGetNeighbors()`, `PetscSFGetRootRanks()`
8855: @*/
8856: PetscErrorCode DMGetNeighbors(DM dm, PetscInt *nranks, const PetscMPIInt *ranks[])
8857: {
8858:   PetscFunctionBegin;
8860:   PetscUseTypeMethod(dm, getneighbors, nranks, ranks);
8861:   PetscFunctionReturn(PETSC_SUCCESS);
8862: }

8864: #include <petsc/private/matimpl.h>

8866: /*
8867:     Converts the input vector to a ghosted vector and then calls the standard coloring code.
8868:     This must be a different function because it requires DM which is not defined in the Mat library
8869: */
8870: static PetscErrorCode MatFDColoringApply_AIJDM(Mat J, MatFDColoring coloring, Vec x1, void *sctx)
8871: {
8872:   PetscFunctionBegin;
8873:   if (coloring->ctype == IS_COLORING_LOCAL) {
8874:     Vec x1local;
8875:     DM  dm;
8876:     PetscCall(MatGetDM(J, &dm));
8877:     PetscCheck(dm, PetscObjectComm((PetscObject)J), PETSC_ERR_ARG_INCOMP, "IS_COLORING_LOCAL requires a DM");
8878:     PetscCall(DMGetLocalVector(dm, &x1local));
8879:     PetscCall(DMGlobalToLocalBegin(dm, x1, INSERT_VALUES, x1local));
8880:     PetscCall(DMGlobalToLocalEnd(dm, x1, INSERT_VALUES, x1local));
8881:     x1 = x1local;
8882:   }
8883:   PetscCall(MatFDColoringApply_AIJ(J, coloring, x1, sctx));
8884:   if (coloring->ctype == IS_COLORING_LOCAL) {
8885:     DM dm;
8886:     PetscCall(MatGetDM(J, &dm));
8887:     PetscCall(DMRestoreLocalVector(dm, &x1));
8888:   }
8889:   PetscFunctionReturn(PETSC_SUCCESS);
8890: }

8892: /*@
8893:   MatFDColoringUseDM - allows a `MatFDColoring` object to use the `DM` associated with the matrix to compute a `IS_COLORING_LOCAL` coloring

8895:   Input Parameters:
8896: + coloring   - The matrix to get the `DM` from
8897: - fdcoloring - the `MatFDColoring` object

8899:   Level: advanced

8901:   Developer Note:
8902:   This routine exists because the PETSc `Mat` library does not know about the `DM` objects

8904: .seealso: [](ch_dmbase), `DM`, `MatFDColoring`, `MatFDColoringCreate()`, `ISColoringType`
8905: @*/
8906: PetscErrorCode MatFDColoringUseDM(Mat coloring, MatFDColoring fdcoloring)
8907: {
8908:   PetscFunctionBegin;
8909:   coloring->ops->fdcoloringapply = MatFDColoringApply_AIJDM;
8910:   PetscFunctionReturn(PETSC_SUCCESS);
8911: }

8913: /*@
8914:   DMGetCompatibility - determine if two `DM`s are compatible

8916:   Collective

8918:   Input Parameters:
8919: + dm1 - the first `DM`
8920: - dm2 - the second `DM`

8922:   Output Parameters:
8923: + compatible - whether or not the two `DM`s are compatible
8924: - set        - whether or not the compatible value was actually determined and set

8926:   Level: advanced

8928:   Notes:
8929:   Two `DM`s are deemed compatible if they represent the same parallel decomposition
8930:   of the same topology. This implies that the section (field data) on one
8931:   "makes sense" with respect to the topology and parallel decomposition of the other.
8932:   Loosely speaking, compatible `DM`s represent the same domain and parallel
8933:   decomposition, but hold different data.

8935:   Typically, one would confirm compatibility if intending to simultaneously iterate
8936:   over a pair of vectors obtained from different `DM`s.

8938:   For example, two `DMDA` objects are compatible if they have the same local
8939:   and global sizes and the same stencil width. They can have different numbers
8940:   of degrees of freedom per node. Thus, one could use the node numbering from
8941:   either `DM` in bounds for a loop over vectors derived from either `DM`.

8943:   Consider the operation of summing data living on a 2-dof `DMDA` to data living
8944:   on a 1-dof `DMDA`, which should be compatible, as in the following snippet.
8945: .vb
8946:   ...
8947:   PetscCall(DMGetCompatibility(da1,da2,&compatible,&set));
8948:   if (set && compatible)  {
8949:     PetscCall(DMDAVecGetArrayDOF(da1,vec1,&arr1));
8950:     PetscCall(DMDAVecGetArrayDOF(da2,vec2,&arr2));
8951:     PetscCall(DMDAGetCorners(da1,&x,&y,NULL,&m,&n,NULL));
8952:     for (j=y; j<y+n; ++j) {
8953:       for (i=x; i<x+m, ++i) {
8954:         arr1[j][i][0] = arr2[j][i][0] + arr2[j][i][1];
8955:       }
8956:     }
8957:     PetscCall(DMDAVecRestoreArrayDOF(da1,vec1,&arr1));
8958:     PetscCall(DMDAVecRestoreArrayDOF(da2,vec2,&arr2));
8959:   } else {
8960:     SETERRQ(PetscObjectComm((PetscObject)da1,PETSC_ERR_ARG_INCOMP,"DMDA objects incompatible");
8961:   }
8962:   ...
8963: .ve

8965:   Checking compatibility might be expensive for a given implementation of `DM`,
8966:   or might be impossible to unambiguously confirm or deny. For this reason,
8967:   this function may decline to determine compatibility, and hence users should
8968:   always check the "set" output parameter.

8970:   A `DM` is always compatible with itself.

8972:   In the current implementation, `DM`s which live on "unequal" communicators
8973:   (MPI_UNEQUAL in the terminology of MPI_Comm_compare()) are always deemed
8974:   incompatible.

8976:   This function is labeled "Collective," as information about all subdomains
8977:   is required on each rank. However, in `DM` implementations which store all this
8978:   information locally, this function may be merely "Logically Collective".

8980:   Developer Note:
8981:   Compatibility is assumed to be a symmetric concept; `DM` A is compatible with `DM` B
8982:   iff B is compatible with A. Thus, this function checks the implementations
8983:   of both dm and dmc (if they are of different types), attempting to determine
8984:   compatibility. It is left to `DM` implementers to ensure that symmetry is
8985:   preserved. The simplest way to do this is, when implementing type-specific
8986:   logic for this function, is to check for existing logic in the implementation
8987:   of other `DM` types and let *set = PETSC_FALSE if found.

8989: .seealso: [](ch_dmbase), `DM`, `DMDACreateCompatibleDMDA()`, `DMStagCreateCompatibleDMStag()`
8990: @*/
8991: PetscErrorCode DMGetCompatibility(DM dm1, DM dm2, PetscBool *compatible, PetscBool *set)
8992: {
8993:   PetscMPIInt compareResult;
8994:   DMType      type, type2;
8995:   PetscBool   sameType;

8997:   PetscFunctionBegin;

9001:   /* Declare a DM compatible with itself */
9002:   if (dm1 == dm2) {
9003:     *set        = PETSC_TRUE;
9004:     *compatible = PETSC_TRUE;
9005:     PetscFunctionReturn(PETSC_SUCCESS);
9006:   }

9008:   /* Declare a DM incompatible with a DM that lives on an "unequal"
9009:      communicator. Note that this does not preclude compatibility with
9010:      DMs living on "congruent" or "similar" communicators, but this must be
9011:      determined by the implementation-specific logic */
9012:   PetscCallMPI(MPI_Comm_compare(PetscObjectComm((PetscObject)dm1), PetscObjectComm((PetscObject)dm2), &compareResult));
9013:   if (compareResult == MPI_UNEQUAL) {
9014:     *set        = PETSC_TRUE;
9015:     *compatible = PETSC_FALSE;
9016:     PetscFunctionReturn(PETSC_SUCCESS);
9017:   }

9019:   /* Pass to the implementation-specific routine, if one exists. */
9020:   if (dm1->ops->getcompatibility) {
9021:     PetscUseTypeMethod(dm1, getcompatibility, dm2, compatible, set);
9022:     if (*set) PetscFunctionReturn(PETSC_SUCCESS);
9023:   }

9025:   /* If dm1 and dm2 are of different types, then attempt to check compatibility
9026:      with an implementation of this function from dm2 */
9027:   PetscCall(DMGetType(dm1, &type));
9028:   PetscCall(DMGetType(dm2, &type2));
9029:   PetscCall(PetscStrcmp(type, type2, &sameType));
9030:   if (!sameType && dm2->ops->getcompatibility) {
9031:     PetscUseTypeMethod(dm2, getcompatibility, dm1, compatible, set); /* Note argument order */
9032:   } else {
9033:     *set = PETSC_FALSE;
9034:   }
9035:   PetscFunctionReturn(PETSC_SUCCESS);
9036: }

9038: /*@C
9039:   DMMonitorSet - Sets an additional monitor function that is to be used after a solve to monitor discretization performance.

9041:   Logically Collective

9043:   Input Parameters:
9044: + dm             - the `DM`
9045: . f              - the monitor function
9046: . mctx           - [optional] context for private data for the monitor routine (use `NULL` if no context is desired)
9047: - monitordestroy - [optional] routine that frees monitor context (may be `NULL`), see `PetscCtxDestroyFn` for the calling sequence

9049:   Options Database Key:
9050: . -dm_monitor_cancel - cancels all monitors that have been hardwired into a code by calls to `DMMonitorSet()`, but
9051:                        does not cancel those set via the options database.

9053:   Level: intermediate

9055:   Note:
9056:   Several different monitoring routines may be set by calling
9057:   `DMMonitorSet()` multiple times or with `DMMonitorSetFromOptions()`; all will be called in the
9058:   order in which they were set.

9060:   Fortran Note:
9061:   Only a single monitor function can be set for each `DM` object

9063:   Developer Note:
9064:   This API has a generic name but seems specific to a very particular aspect of the use of `DM`

9066: .seealso: [](ch_dmbase), `DM`, `DMMonitorCancel()`, `DMMonitorSetFromOptions()`, `DMMonitor()`, `PetscCtxDestroyFn`
9067: @*/
9068: PetscErrorCode DMMonitorSet(DM dm, PetscErrorCode (*f)(DM, void *), void *mctx, PetscCtxDestroyFn *monitordestroy)
9069: {
9070:   PetscFunctionBegin;
9072:   for (PetscInt m = 0; m < dm->numbermonitors; ++m) {
9073:     PetscBool identical;

9075:     PetscCall(PetscMonitorCompare((PetscErrorCode (*)(void))(PetscVoidFn *)f, mctx, monitordestroy, (PetscErrorCode (*)(void))(PetscVoidFn *)dm->monitor[m], dm->monitorcontext[m], dm->monitordestroy[m], &identical));
9076:     if (identical) PetscFunctionReturn(PETSC_SUCCESS);
9077:   }
9078:   PetscCheck(dm->numbermonitors < MAXDMMONITORS, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Too many monitors set");
9079:   dm->monitor[dm->numbermonitors]          = f;
9080:   dm->monitordestroy[dm->numbermonitors]   = monitordestroy;
9081:   dm->monitorcontext[dm->numbermonitors++] = mctx;
9082:   PetscFunctionReturn(PETSC_SUCCESS);
9083: }

9085: /*@
9086:   DMMonitorCancel - Clears all the monitor functions for a `DM` object.

9088:   Logically Collective

9090:   Input Parameter:
9091: . dm - the DM

9093:   Options Database Key:
9094: . -dm_monitor_cancel - cancels all monitors that have been hardwired
9095:   into a code by calls to `DMonitorSet()`, but does not cancel those
9096:   set via the options database

9098:   Level: intermediate

9100:   Note:
9101:   There is no way to clear one specific monitor from a `DM` object.

9103: .seealso: [](ch_dmbase), `DM`, `DMMonitorSet()`, `DMMonitorSetFromOptions()`, `DMMonitor()`
9104: @*/
9105: PetscErrorCode DMMonitorCancel(DM dm)
9106: {
9107:   PetscInt m;

9109:   PetscFunctionBegin;
9111:   for (m = 0; m < dm->numbermonitors; ++m) {
9112:     if (dm->monitordestroy[m]) PetscCall((*dm->monitordestroy[m])(&dm->monitorcontext[m]));
9113:   }
9114:   dm->numbermonitors = 0;
9115:   PetscFunctionReturn(PETSC_SUCCESS);
9116: }

9118: /*@C
9119:   DMMonitorSetFromOptions - Sets a monitor function and viewer appropriate for the type indicated by the user

9121:   Collective

9123:   Input Parameters:
9124: + dm           - `DM` object you wish to monitor
9125: . name         - the monitor type one is seeking
9126: . help         - message indicating what monitoring is done
9127: . manual       - manual page for the monitor
9128: . monitor      - the monitor function, this must use a `PetscViewerFormat` as its context
9129: - 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

9131:   Output Parameter:
9132: . flg - Flag set if the monitor was created

9134:   Calling sequence of `monitor`:
9135: + dm  - the `DM` to be monitored
9136: - ctx - monitor context

9138:   Calling sequence of `monitorsetup`:
9139: + dm - the `DM` to be monitored
9140: - vf - the `PetscViewer` and format to be used by the monitor

9142:   Level: developer

9144: .seealso: [](ch_dmbase), `DM`, `PetscOptionsCreateViewer()`, `PetscOptionsGetReal()`, `PetscOptionsHasName()`, `PetscOptionsGetString()`,
9145:           `PetscOptionsGetIntArray()`, `PetscOptionsGetRealArray()`, `PetscOptionsBool()`,
9146:           `PetscOptionsInt()`, `PetscOptionsString()`, `PetscOptionsReal()`,
9147:           `PetscOptionsName()`, `PetscOptionsBegin()`, `PetscOptionsEnd()`, `PetscOptionsHeadBegin()`,
9148:           `PetscOptionsStringArray()`, `PetscOptionsRealArray()`, `PetscOptionsScalar()`,
9149:           `PetscOptionsBoolGroupBegin()`, `PetscOptionsBoolGroup()`, `PetscOptionsBoolGroupEnd()`,
9150:           `PetscOptionsFList()`, `PetscOptionsEList()`, `DMMonitor()`, `DMMonitorSet()`
9151: @*/
9152: 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)
9153: {
9154:   PetscViewer       viewer;
9155:   PetscViewerFormat format;

9157:   PetscFunctionBegin;
9159:   PetscCall(PetscOptionsCreateViewer(PetscObjectComm((PetscObject)dm), ((PetscObject)dm)->options, ((PetscObject)dm)->prefix, name, &viewer, &format, flg));
9160:   if (*flg) {
9161:     PetscViewerAndFormat *vf;

9163:     PetscCall(PetscViewerAndFormatCreate(viewer, format, &vf));
9164:     PetscCall(PetscViewerDestroy(&viewer));
9165:     if (monitorsetup) PetscCall((*monitorsetup)(dm, vf));
9166:     PetscCall(DMMonitorSet(dm, monitor, vf, (PetscCtxDestroyFn *)PetscViewerAndFormatDestroy));
9167:   }
9168:   PetscFunctionReturn(PETSC_SUCCESS);
9169: }

9171: /*@
9172:   DMMonitor - runs the user provided monitor routines, if they exist

9174:   Collective

9176:   Input Parameter:
9177: . dm - The `DM`

9179:   Level: developer

9181:   Developer Note:
9182:   Note should indicate when during the life of the `DM` the monitor is run. It appears to be
9183:   related to the discretization process seems rather specialized since some `DM` have no
9184:   concept of discretization.

9186: .seealso: [](ch_dmbase), `DM`, `DMMonitorSet()`, `DMMonitorSetFromOptions()`
9187: @*/
9188: PetscErrorCode DMMonitor(DM dm)
9189: {
9190:   PetscInt m;

9192:   PetscFunctionBegin;
9193:   if (!dm) PetscFunctionReturn(PETSC_SUCCESS);
9195:   for (m = 0; m < dm->numbermonitors; ++m) PetscCall((*dm->monitor[m])(dm, dm->monitorcontext[m]));
9196:   PetscFunctionReturn(PETSC_SUCCESS);
9197: }

9199: /*@
9200:   DMComputeError - Computes the error assuming the user has provided the exact solution functions

9202:   Collective

9204:   Input Parameters:
9205: + dm  - The `DM`
9206: - sol - The solution vector

9208:   Input/Output Parameter:
9209: . errors - An array of length Nf, the number of fields, or `NULL` for no output; on output
9210:            contains the error in each field

9212:   Output Parameter:
9213: . errorVec - A vector to hold the cellwise error (may be `NULL`)

9215:   Level: developer

9217:   Note:
9218:   The exact solutions come from the `PetscDS` object, and the time comes from `DMGetOutputSequenceNumber()`.

9220: .seealso: [](ch_dmbase), `DM`, `DMMonitorSet()`, `DMGetRegionNumDS()`, `PetscDSGetExactSolution()`, `DMGetOutputSequenceNumber()`
9221: @*/
9222: PetscErrorCode DMComputeError(DM dm, Vec sol, PetscReal errors[], Vec *errorVec)
9223: {
9224:   PetscErrorCode (**exactSol)(PetscInt, PetscReal, const PetscReal[], PetscInt, PetscScalar[], void *);
9225:   void    **ctxs;
9226:   PetscReal time;
9227:   PetscInt  Nf, f, Nds, s;

9229:   PetscFunctionBegin;
9230:   PetscCall(DMGetNumFields(dm, &Nf));
9231:   PetscCall(PetscCalloc2(Nf, &exactSol, Nf, &ctxs));
9232:   PetscCall(DMGetNumDS(dm, &Nds));
9233:   for (s = 0; s < Nds; ++s) {
9234:     PetscDS         ds;
9235:     DMLabel         label;
9236:     IS              fieldIS;
9237:     const PetscInt *fields;
9238:     PetscInt        dsNf;

9240:     PetscCall(DMGetRegionNumDS(dm, s, &label, &fieldIS, &ds, NULL));
9241:     PetscCall(PetscDSGetNumFields(ds, &dsNf));
9242:     if (fieldIS) PetscCall(ISGetIndices(fieldIS, &fields));
9243:     for (f = 0; f < dsNf; ++f) {
9244:       const PetscInt field = fields[f];
9245:       PetscCall(PetscDSGetExactSolution(ds, field, &exactSol[field], &ctxs[field]));
9246:     }
9247:     if (fieldIS) PetscCall(ISRestoreIndices(fieldIS, &fields));
9248:   }
9249:   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);
9250:   PetscCall(DMGetOutputSequenceNumber(dm, NULL, &time));
9251:   if (errors) PetscCall(DMComputeL2FieldDiff(dm, time, exactSol, ctxs, sol, errors));
9252:   if (errorVec) {
9253:     DM             edm;
9254:     DMPolytopeType ct;
9255:     PetscBool      simplex;
9256:     PetscInt       dim, cStart, Nf;

9258:     PetscCall(DMClone(dm, &edm));
9259:     PetscCall(DMGetDimension(edm, &dim));
9260:     PetscCall(DMPlexGetHeightStratum(dm, 0, &cStart, NULL));
9261:     PetscCall(DMPlexGetCellType(dm, cStart, &ct));
9262:     simplex = DMPolytopeTypeGetNumVertices(ct) == DMPolytopeTypeGetDim(ct) + 1 ? PETSC_TRUE : PETSC_FALSE;
9263:     PetscCall(DMGetNumFields(dm, &Nf));
9264:     for (f = 0; f < Nf; ++f) {
9265:       PetscFE         fe, efe;
9266:       PetscQuadrature q;
9267:       const char     *name;

9269:       PetscCall(DMGetField(dm, f, NULL, (PetscObject *)&fe));
9270:       PetscCall(PetscFECreateLagrange(PETSC_COMM_SELF, dim, Nf, simplex, 0, PETSC_DETERMINE, &efe));
9271:       PetscCall(PetscObjectGetName((PetscObject)fe, &name));
9272:       PetscCall(PetscObjectSetName((PetscObject)efe, name));
9273:       PetscCall(PetscFEGetQuadrature(fe, &q));
9274:       PetscCall(PetscFESetQuadrature(efe, q));
9275:       PetscCall(DMSetField(edm, f, NULL, (PetscObject)efe));
9276:       PetscCall(PetscFEDestroy(&efe));
9277:     }
9278:     PetscCall(DMCreateDS(edm));

9280:     PetscCall(DMCreateGlobalVector(edm, errorVec));
9281:     PetscCall(PetscObjectSetName((PetscObject)*errorVec, "Error"));
9282:     PetscCall(DMPlexComputeL2DiffVec(dm, time, exactSol, ctxs, sol, *errorVec));
9283:     PetscCall(DMDestroy(&edm));
9284:   }
9285:   PetscCall(PetscFree2(exactSol, ctxs));
9286:   PetscFunctionReturn(PETSC_SUCCESS);
9287: }

9289: /*@
9290:   DMGetNumAuxiliaryVec - Get the number of auxiliary vectors associated with this `DM`

9292:   Not Collective

9294:   Input Parameter:
9295: . dm - The `DM`

9297:   Output Parameter:
9298: . numAux - The number of auxiliary data vectors

9300:   Level: advanced

9302: .seealso: [](ch_dmbase), `DM`, `DMClearAuxiliaryVec()`, `DMSetAuxiliaryVec()`, `DMGetAuxiliaryLabels()`, `DMGetAuxiliaryVec()`
9303: @*/
9304: PetscErrorCode DMGetNumAuxiliaryVec(DM dm, PetscInt *numAux)
9305: {
9306:   PetscFunctionBegin;
9308:   PetscCall(PetscHMapAuxGetSize(dm->auxData, numAux));
9309:   PetscFunctionReturn(PETSC_SUCCESS);
9310: }

9312: /*@
9313:   DMGetAuxiliaryVec - Get the auxiliary vector for region specified by the given label and value, and equation part

9315:   Not Collective

9317:   Input Parameters:
9318: + dm    - The `DM`
9319: . label - The `DMLabel`
9320: . value - The label value indicating the region
9321: - part  - The equation part, or 0 if unused

9323:   Output Parameter:
9324: . aux - The `Vec` holding auxiliary field data

9326:   Level: advanced

9328:   Note:
9329:   If no auxiliary vector is found for this (label, value), (`NULL`, 0, 0) is checked as well.

9331: .seealso: [](ch_dmbase), `DM`, `DMClearAuxiliaryVec()`, `DMSetAuxiliaryVec()`, `DMGetNumAuxiliaryVec()`, `DMGetAuxiliaryLabels()`
9332: @*/
9333: PetscErrorCode DMGetAuxiliaryVec(DM dm, DMLabel label, PetscInt value, PetscInt part, Vec *aux)
9334: {
9335:   PetscHashAuxKey key, wild = {NULL, 0, 0};
9336:   PetscBool       has;

9338:   PetscFunctionBegin;
9341:   key.label = label;
9342:   key.value = value;
9343:   key.part  = part;
9344:   PetscCall(PetscHMapAuxHas(dm->auxData, key, &has));
9345:   if (has) PetscCall(PetscHMapAuxGet(dm->auxData, key, aux));
9346:   else PetscCall(PetscHMapAuxGet(dm->auxData, wild, aux));
9347:   PetscFunctionReturn(PETSC_SUCCESS);
9348: }

9350: /*@
9351:   DMSetAuxiliaryVec - Set an auxiliary vector for region specified by the given label and value, and equation part

9353:   Not Collective because auxiliary vectors are not parallel

9355:   Input Parameters:
9356: + dm    - The `DM`
9357: . label - The `DMLabel`
9358: . value - The label value indicating the region
9359: . part  - The equation part, or 0 if unused
9360: - aux   - The `Vec` holding auxiliary field data

9362:   Level: advanced

9364: .seealso: [](ch_dmbase), `DM`, `DMClearAuxiliaryVec()`, `DMGetAuxiliaryVec()`, `DMGetAuxiliaryLabels()`, `DMCopyAuxiliaryVec()`
9365: @*/
9366: PetscErrorCode DMSetAuxiliaryVec(DM dm, DMLabel label, PetscInt value, PetscInt part, Vec aux)
9367: {
9368:   Vec             old;
9369:   PetscHashAuxKey key;

9371:   PetscFunctionBegin;
9374:   key.label = label;
9375:   key.value = value;
9376:   key.part  = part;
9377:   PetscCall(PetscHMapAuxGet(dm->auxData, key, &old));
9378:   PetscCall(PetscObjectReference((PetscObject)aux));
9379:   if (!aux) PetscCall(PetscHMapAuxDel(dm->auxData, key));
9380:   else PetscCall(PetscHMapAuxSet(dm->auxData, key, aux));
9381:   PetscCall(VecDestroy(&old));
9382:   PetscFunctionReturn(PETSC_SUCCESS);
9383: }

9385: /*@
9386:   DMGetAuxiliaryLabels - Get the labels, values, and parts for all auxiliary vectors in this `DM`

9388:   Not Collective

9390:   Input Parameter:
9391: . dm - The `DM`

9393:   Output Parameters:
9394: + labels - The `DMLabel`s for each `Vec`
9395: . values - The label values for each `Vec`
9396: - parts  - The equation parts for each `Vec`

9398:   Level: advanced

9400:   Note:
9401:   The arrays passed in must be at least as large as `DMGetNumAuxiliaryVec()`.

9403: .seealso: [](ch_dmbase), `DM`, `DMClearAuxiliaryVec()`, `DMGetNumAuxiliaryVec()`, `DMGetAuxiliaryVec()`, `DMSetAuxiliaryVec()`, `DMCopyAuxiliaryVec()`
9404: @*/
9405: PetscErrorCode DMGetAuxiliaryLabels(DM dm, DMLabel labels[], PetscInt values[], PetscInt parts[])
9406: {
9407:   PetscHashAuxKey *keys;
9408:   PetscInt         n, i, off = 0;

9410:   PetscFunctionBegin;
9412:   PetscAssertPointer(labels, 2);
9413:   PetscAssertPointer(values, 3);
9414:   PetscAssertPointer(parts, 4);
9415:   PetscCall(DMGetNumAuxiliaryVec(dm, &n));
9416:   PetscCall(PetscMalloc1(n, &keys));
9417:   PetscCall(PetscHMapAuxGetKeys(dm->auxData, &off, keys));
9418:   for (i = 0; i < n; ++i) {
9419:     labels[i] = keys[i].label;
9420:     values[i] = keys[i].value;
9421:     parts[i]  = keys[i].part;
9422:   }
9423:   PetscCall(PetscFree(keys));
9424:   PetscFunctionReturn(PETSC_SUCCESS);
9425: }

9427: /*@
9428:   DMCopyAuxiliaryVec - Copy the auxiliary vector data on a `DM` to a new `DM`

9430:   Not Collective

9432:   Input Parameter:
9433: . dm - The `DM`

9435:   Output Parameter:
9436: . dmNew - The new `DM`, now with the same auxiliary data

9438:   Level: advanced

9440:   Note:
9441:   This is a shallow copy of the auxiliary vectors

9443: .seealso: [](ch_dmbase), `DM`, `DMClearAuxiliaryVec()`, `DMGetNumAuxiliaryVec()`, `DMGetAuxiliaryVec()`, `DMSetAuxiliaryVec()`
9444: @*/
9445: PetscErrorCode DMCopyAuxiliaryVec(DM dm, DM dmNew)
9446: {
9447:   PetscFunctionBegin;
9450:   if (dm == dmNew) PetscFunctionReturn(PETSC_SUCCESS);
9451:   PetscCall(DMClearAuxiliaryVec(dmNew));

9453:   PetscCall(PetscHMapAuxDestroy(&dmNew->auxData));
9454:   PetscCall(PetscHMapAuxDuplicate(dm->auxData, &dmNew->auxData));
9455:   {
9456:     Vec     *auxData;
9457:     PetscInt n, i, off = 0;

9459:     PetscCall(PetscHMapAuxGetSize(dmNew->auxData, &n));
9460:     PetscCall(PetscMalloc1(n, &auxData));
9461:     PetscCall(PetscHMapAuxGetVals(dmNew->auxData, &off, auxData));
9462:     for (i = 0; i < n; ++i) PetscCall(PetscObjectReference((PetscObject)auxData[i]));
9463:     PetscCall(PetscFree(auxData));
9464:   }
9465:   PetscFunctionReturn(PETSC_SUCCESS);
9466: }

9468: /*@
9469:   DMClearAuxiliaryVec - Destroys the auxiliary vector information and creates a new empty one

9471:   Not Collective

9473:   Input Parameter:
9474: . dm - The `DM`

9476:   Level: advanced

9478: .seealso: [](ch_dmbase), `DM`, `DMCopyAuxiliaryVec()`, `DMGetNumAuxiliaryVec()`, `DMGetAuxiliaryVec()`, `DMSetAuxiliaryVec()`
9479: @*/
9480: PetscErrorCode DMClearAuxiliaryVec(DM dm)
9481: {
9482:   Vec     *auxData;
9483:   PetscInt n, i, off = 0;

9485:   PetscFunctionBegin;
9486:   PetscCall(PetscHMapAuxGetSize(dm->auxData, &n));
9487:   PetscCall(PetscMalloc1(n, &auxData));
9488:   PetscCall(PetscHMapAuxGetVals(dm->auxData, &off, auxData));
9489:   for (i = 0; i < n; ++i) PetscCall(VecDestroy(&auxData[i]));
9490:   PetscCall(PetscFree(auxData));
9491:   PetscCall(PetscHMapAuxDestroy(&dm->auxData));
9492:   PetscCall(PetscHMapAuxCreate(&dm->auxData));
9493:   PetscFunctionReturn(PETSC_SUCCESS);
9494: }

9496: /*@
9497:   DMPolytopeMatchOrientation - Determine an orientation (transformation) that takes the source face arrangement to the target face arrangement

9499:   Not Collective

9501:   Input Parameters:
9502: + ct         - The `DMPolytopeType`
9503: . sourceCone - The source arrangement of faces
9504: - targetCone - The target arrangement of faces

9506:   Output Parameters:
9507: + ornt  - The orientation (transformation) which will take the source arrangement to the target arrangement
9508: - found - Flag indicating that a suitable orientation was found

9510:   Level: advanced

9512:   Note:
9513:   An arrangement is a face order combined with an orientation for each face

9515:   Each orientation (transformation) is labeled with an integer from negative `DMPolytopeTypeGetNumArrangements(ct)`/2 to `DMPolytopeTypeGetNumArrangements(ct)`/2
9516:   that labels each arrangement (face ordering plus orientation for each face).

9518:   See `DMPolytopeMatchVertexOrientation()` to find a new vertex orientation that takes the source vertex arrangement to the target vertex arrangement

9520: .seealso: [](ch_dmbase), `DM`, `DMPolytopeGetOrientation()`, `DMPolytopeMatchVertexOrientation()`, `DMPolytopeGetVertexOrientation()`
9521: @*/
9522: PetscErrorCode DMPolytopeMatchOrientation(DMPolytopeType ct, const PetscInt sourceCone[], const PetscInt targetCone[], PetscInt *ornt, PetscBool *found)
9523: {
9524:   const PetscInt cS = DMPolytopeTypeGetConeSize(ct);
9525:   const PetscInt nO = DMPolytopeTypeGetNumArrangements(ct) / 2;
9526:   PetscInt       o, c;

9528:   PetscFunctionBegin;
9529:   if (!nO) {
9530:     *ornt  = 0;
9531:     *found = PETSC_TRUE;
9532:     PetscFunctionReturn(PETSC_SUCCESS);
9533:   }
9534:   for (o = -nO; o < nO; ++o) {
9535:     const PetscInt *arr = DMPolytopeTypeGetArrangement(ct, o);

9537:     for (c = 0; c < cS; ++c)
9538:       if (sourceCone[arr[c * 2]] != targetCone[c]) break;
9539:     if (c == cS) {
9540:       *ornt = o;
9541:       break;
9542:     }
9543:   }
9544:   *found = o == nO ? PETSC_FALSE : PETSC_TRUE;
9545:   PetscFunctionReturn(PETSC_SUCCESS);
9546: }

9548: /*@
9549:   DMPolytopeGetOrientation - Determine an orientation (transformation) that takes the source face arrangement to the target face arrangement

9551:   Not Collective

9553:   Input Parameters:
9554: + ct         - The `DMPolytopeType`
9555: . sourceCone - The source arrangement of faces
9556: - targetCone - The target arrangement of faces

9558:   Output Parameter:
9559: . ornt - The orientation (transformation) which will take the source arrangement to the target arrangement

9561:   Level: advanced

9563:   Note:
9564:   This function is the same as `DMPolytopeMatchOrientation()` except it will generate an error if no suitable orientation can be found.

9566:   Developer Note:
9567:   It is unclear why this function needs to exist since one can simply call `DMPolytopeMatchOrientation()` and error if none is found

9569: .seealso: [](ch_dmbase), `DM`, `DMPolytopeType`, `DMPolytopeMatchOrientation()`, `DMPolytopeGetVertexOrientation()`, `DMPolytopeMatchVertexOrientation()`
9570: @*/
9571: PetscErrorCode DMPolytopeGetOrientation(DMPolytopeType ct, const PetscInt sourceCone[], const PetscInt targetCone[], PetscInt *ornt)
9572: {
9573:   PetscBool found;

9575:   PetscFunctionBegin;
9576:   PetscCall(DMPolytopeMatchOrientation(ct, sourceCone, targetCone, ornt, &found));
9577:   PetscCheck(found, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Could not find orientation for %s", DMPolytopeTypes[ct]);
9578:   PetscFunctionReturn(PETSC_SUCCESS);
9579: }

9581: /*@
9582:   DMPolytopeMatchVertexOrientation - Determine an orientation (transformation) that takes the source vertex arrangement to the target vertex arrangement

9584:   Not Collective

9586:   Input Parameters:
9587: + ct         - The `DMPolytopeType`
9588: . sourceVert - The source arrangement of vertices
9589: - targetVert - The target arrangement of vertices

9591:   Output Parameters:
9592: + ornt  - The orientation (transformation) which will take the source arrangement to the target arrangement
9593: - found - Flag indicating that a suitable orientation was found

9595:   Level: advanced

9597:   Notes:
9598:   An arrangement is a vertex order

9600:   Each orientation (transformation) is labeled with an integer from negative `DMPolytopeTypeGetNumArrangements(ct)`/2 to `DMPolytopeTypeGetNumArrangements(ct)`/2
9601:   that labels each arrangement (vertex ordering).

9603:   See `DMPolytopeMatchOrientation()` to find a new face orientation that takes the source face arrangement to the target face arrangement

9605: .seealso: [](ch_dmbase), `DM`, `DMPolytopeType`, `DMPolytopeGetOrientation()`, `DMPolytopeMatchOrientation()`, `DMPolytopeTypeGetNumVertices()`, `DMPolytopeTypeGetVertexArrangement()`
9606: @*/
9607: PetscErrorCode DMPolytopeMatchVertexOrientation(DMPolytopeType ct, const PetscInt sourceVert[], const PetscInt targetVert[], PetscInt *ornt, PetscBool *found)
9608: {
9609:   const PetscInt cS = DMPolytopeTypeGetNumVertices(ct);
9610:   const PetscInt nO = DMPolytopeTypeGetNumArrangements(ct) / 2;
9611:   PetscInt       o, c;

9613:   PetscFunctionBegin;
9614:   if (!nO) {
9615:     *ornt  = 0;
9616:     *found = PETSC_TRUE;
9617:     PetscFunctionReturn(PETSC_SUCCESS);
9618:   }
9619:   for (o = -nO; o < nO; ++o) {
9620:     const PetscInt *arr = DMPolytopeTypeGetVertexArrangement(ct, o);

9622:     for (c = 0; c < cS; ++c)
9623:       if (sourceVert[arr[c]] != targetVert[c]) break;
9624:     if (c == cS) {
9625:       *ornt = o;
9626:       break;
9627:     }
9628:   }
9629:   *found = o == nO ? PETSC_FALSE : PETSC_TRUE;
9630:   PetscFunctionReturn(PETSC_SUCCESS);
9631: }

9633: /*@
9634:   DMPolytopeGetVertexOrientation - Determine an orientation (transformation) that takes the source vertex arrangement to the target vertex arrangement

9636:   Not Collective

9638:   Input Parameters:
9639: + ct         - The `DMPolytopeType`
9640: . sourceCone - The source arrangement of vertices
9641: - targetCone - The target arrangement of vertices

9643:   Output Parameter:
9644: . ornt - The orientation (transformation) which will take the source arrangement to the target arrangement

9646:   Level: advanced

9648:   Note:
9649:   This function is the same as `DMPolytopeMatchVertexOrientation()` except it errors if not orientation is possible.

9651:   Developer Note:
9652:   It is unclear why this function needs to exist since one can simply call `DMPolytopeMatchVertexOrientation()` and error if none is found

9654: .seealso: [](ch_dmbase), `DM`, `DMPolytopeType`, `DMPolytopeMatchVertexOrientation()`, `DMPolytopeGetOrientation()`
9655: @*/
9656: PetscErrorCode DMPolytopeGetVertexOrientation(DMPolytopeType ct, const PetscInt sourceCone[], const PetscInt targetCone[], PetscInt *ornt)
9657: {
9658:   PetscBool found;

9660:   PetscFunctionBegin;
9661:   PetscCall(DMPolytopeMatchVertexOrientation(ct, sourceCone, targetCone, ornt, &found));
9662:   PetscCheck(found, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Could not find orientation for %s", DMPolytopeTypes[ct]);
9663:   PetscFunctionReturn(PETSC_SUCCESS);
9664: }

9666: /*@
9667:   DMPolytopeInCellTest - Check whether a point lies inside the reference cell of given type

9669:   Not Collective

9671:   Input Parameters:
9672: + ct    - The `DMPolytopeType`
9673: - point - Coordinates of the point

9675:   Output Parameter:
9676: . inside - Flag indicating whether the point is inside the reference cell of given type

9678:   Level: advanced

9680: .seealso: [](ch_dmbase), `DM`, `DMPolytopeType`, `DMLocatePoints()`
9681: @*/
9682: PetscErrorCode DMPolytopeInCellTest(DMPolytopeType ct, const PetscReal point[], PetscBool *inside)
9683: {
9684:   PetscReal sum = 0.0;
9685:   PetscInt  d;

9687:   PetscFunctionBegin;
9688:   *inside = PETSC_TRUE;
9689:   switch (ct) {
9690:   case DM_POLYTOPE_TRIANGLE:
9691:   case DM_POLYTOPE_TETRAHEDRON:
9692:     for (d = 0; d < DMPolytopeTypeGetDim(ct); ++d) {
9693:       if (point[d] < -1.0) {
9694:         *inside = PETSC_FALSE;
9695:         break;
9696:       }
9697:       sum += point[d];
9698:     }
9699:     if (sum > PETSC_SMALL) {
9700:       *inside = PETSC_FALSE;
9701:       break;
9702:     }
9703:     break;
9704:   case DM_POLYTOPE_QUADRILATERAL:
9705:   case DM_POLYTOPE_HEXAHEDRON:
9706:     for (d = 0; d < DMPolytopeTypeGetDim(ct); ++d)
9707:       if (PetscAbsReal(point[d]) > 1. + PETSC_SMALL) {
9708:         *inside = PETSC_FALSE;
9709:         break;
9710:       }
9711:     break;
9712:   default:
9713:     SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Unsupported polytope type %s", DMPolytopeTypes[ct]);
9714:   }
9715:   PetscFunctionReturn(PETSC_SUCCESS);
9716: }

9718: /*@
9719:   DMReorderSectionSetDefault - Set flag indicating whether the local section should be reordered by default

9721:   Logically collective

9723:   Input Parameters:
9724: + dm      - The DM
9725: - reorder - Flag for reordering

9727:   Level: intermediate

9729: .seealso: `DMReorderSectionGetDefault()`
9730: @*/
9731: PetscErrorCode DMReorderSectionSetDefault(DM dm, DMReorderDefaultFlag reorder)
9732: {
9733:   PetscFunctionBegin;
9735:   PetscTryMethod(dm, "DMReorderSectionSetDefault_C", (DM, DMReorderDefaultFlag), (dm, reorder));
9736:   PetscFunctionReturn(PETSC_SUCCESS);
9737: }

9739: /*@
9740:   DMReorderSectionGetDefault - Get flag indicating whether the local section should be reordered by default

9742:   Not collective

9744:   Input Parameter:
9745: . dm - The DM

9747:   Output Parameter:
9748: . reorder - Flag for reordering

9750:   Level: intermediate

9752: .seealso: `DMReorderSetDefault()`
9753: @*/
9754: PetscErrorCode DMReorderSectionGetDefault(DM dm, DMReorderDefaultFlag *reorder)
9755: {
9756:   PetscFunctionBegin;
9758:   PetscAssertPointer(reorder, 2);
9759:   *reorder = DM_REORDER_DEFAULT_NOTSET;
9760:   PetscTryMethod(dm, "DMReorderSectionGetDefault_C", (DM, DMReorderDefaultFlag *), (dm, reorder));
9761:   PetscFunctionReturn(PETSC_SUCCESS);
9762: }

9764: /*@
9765:   DMReorderSectionSetType - Set the type of local section reordering

9767:   Logically collective

9769:   Input Parameters:
9770: + dm      - The DM
9771: - reorder - The reordering method

9773:   Level: intermediate

9775: .seealso: `DMReorderSectionGetType()`, `DMReorderSectionSetDefault()`
9776: @*/
9777: PetscErrorCode DMReorderSectionSetType(DM dm, MatOrderingType reorder)
9778: {
9779:   PetscFunctionBegin;
9781:   PetscTryMethod(dm, "DMReorderSectionSetType_C", (DM, MatOrderingType), (dm, reorder));
9782:   PetscFunctionReturn(PETSC_SUCCESS);
9783: }

9785: /*@
9786:   DMReorderSectionGetType - Get the reordering type for the local section

9788:   Not collective

9790:   Input Parameter:
9791: . dm - The DM

9793:   Output Parameter:
9794: . reorder - The reordering method

9796:   Level: intermediate

9798: .seealso: `DMReorderSetDefault()`, `DMReorderSectionGetDefault()`
9799: @*/
9800: PetscErrorCode DMReorderSectionGetType(DM dm, MatOrderingType *reorder)
9801: {
9802:   PetscFunctionBegin;
9804:   PetscAssertPointer(reorder, 2);
9805:   *reorder = NULL;
9806:   PetscTryMethod(dm, "DMReorderSectionGetType_C", (DM, MatOrderingType *), (dm, reorder));
9807:   PetscFunctionReturn(PETSC_SUCCESS);
9808: }