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:   Level: intermediate

    926:   Note:
    927:   See `PetscObjectViewFromOptions()` for a list of values that can be provided in the options database to determine how the `DM` is viewed

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

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

    1176:   Not Collective

    1178:   Input Parameter:
    1179: . dm - the `DM` with block structure

    1181:   Output Parameter:
    1182: . bs - the block size, 1 implies no exploitable block structure

    1184:   Level: intermediate

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

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

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

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

    1208:   Collective

    1210:   Input Parameters:
    1211: + dmc - the `DM` object
    1212: - dmf - the second, finer `DM` object

    1214:   Output Parameters:
    1215: + mat - the interpolation
    1216: - vec - the scaling (optional, pass `NULL` if not needed), see `DMCreateInterpolationScale()`

    1218:   Level: developer

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

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

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

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

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

    1250:   Output Parameter:
    1251: . scale - the scaled vector

    1253:   Level: advanced

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

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

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

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

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

    1298:   Collective

    1300:   Input Parameters:
    1301: + dmc - the `DM` object
    1302: - dmf - the second, finer `DM` object

    1304:   Output Parameter:
    1305: . mat - the restriction

    1307:   Level: developer

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

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

    1327: /*@
    1328:   DMCreateInjection - Gets injection matrix between two `DM` objects.

    1330:   Collective

    1332:   Input Parameters:
    1333: + dac - the `DM` object
    1334: - daf - the second, finer `DM` object

    1336:   Output Parameter:
    1337: . mat - the injection

    1339:   Level: developer

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

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

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

    1367: /*@
    1368:   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
    1369:   a Galerkin finite element model on the `DM`

    1371:   Collective

    1373:   Input Parameters:
    1374: + dmc - the target `DM` object
    1375: - dmf - the source `DM` object, can be `NULL`

    1377:   Output Parameter:
    1378: . mat - the mass matrix

    1380:   Level: developer

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

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

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

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

    1405:   Collective

    1407:   Input Parameter:
    1408: . dm - the `DM` object

    1410:   Output Parameters:
    1411: + llm - the local lumped mass matrix, which is a diagonal matrix, represented as a vector
    1412: - lm  - the global lumped mass matrix, which is a diagonal matrix, represented as a vector

    1414:   Level: developer

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

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

    1431: /*@
    1432:   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`

    1434:   Collective

    1436:   Input Parameters:
    1437: + dmc - the target `DM` object
    1438: - dmf - the source `DM` object, can be `NULL`

    1440:   Output Parameter:
    1441: . mat - the gradient matrix

    1443:   Level: developer

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

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

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

    1465:   Collective

    1467:   Input Parameters:
    1468: + dm    - the `DM` object
    1469: - ctype - `IS_COLORING_LOCAL` or `IS_COLORING_GLOBAL`

    1471:   Output Parameter:
    1472: . coloring - the coloring

    1474:   Level: developer

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

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

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

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

    1498:   Collective

    1500:   Input Parameter:
    1501: . dm - the `DM` object

    1503:   Output Parameter:
    1504: . mat - the empty Jacobian

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

    1509:   Level: beginner

    1511:   Notes:
    1512:   This properly preallocates the number of nonzeros in the sparse matrix so you
    1513:   do not need to do it yourself.

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

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

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

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

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

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

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

    1571:   Logically Collective

    1573:   Input Parameters:
    1574: + dm   - the `DM`
    1575: - skip - `PETSC_TRUE` to skip preallocation

    1577:   Level: developer

    1579:   Note:
    1580:   This is most useful to reduce initialization costs when `MatSetPreallocationCOO()` and
    1581:   `MatSetValuesCOO()` will be used.

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

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

    1597:   Logically Collective

    1599:   Input Parameters:
    1600: + dm   - the `DM`
    1601: - only - `PETSC_TRUE` if only want preallocation

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

    1606:   Level: developer

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

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

    1622:   Logically Collective

    1624:   Input Parameters:
    1625: + dm   - the `DM`
    1626: - only - `PETSC_TRUE` if you only want matrix nonzero structure

    1628:   Level: developer

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

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

    1643:   Logically Collective

    1645:   Input Parameters:
    1646: + dm    - the `DM`
    1647: - btype - block by topological point or field node

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

    1652:   Level: advanced

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

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

    1667:   Not Collective

    1669:   Input Parameter:
    1670: . dm - the `DM`

    1672:   Output Parameter:
    1673: . btype - block by topological point or field node

    1675:   Level: advanced

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

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

    1691:   Not Collective

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

    1698:   Output Parameter:
    1699: . mem - the work array

    1701:   Level: developer

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

    1706:   The array may contain nonzero values

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

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

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

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

    1754:   Not Collective

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

    1761:   Output Parameter:
    1762: . mem - the work array

    1764:   Level: developer

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

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

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

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

    1796:   Logically Collective; No Fortran Support

    1798:   Input Parameters:
    1799: + dm     - The `DM`
    1800: . field  - The field number for the nullspace
    1801: - nullsp - A callback to create the nullspace

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

    1809:   Level: intermediate

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

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

    1826:   Not Collective; No Fortran Support

    1828:   Input Parameters:
    1829: + dm    - The `DM`
    1830: - field - The field number for the nullspace

    1832:   Output Parameter:
    1833: . nullsp - A callback to create the nullspace

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

    1841:   Level: intermediate

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

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

    1859:   Logically Collective; No Fortran Support

    1861:   Input Parameters:
    1862: + dm     - The `DM`
    1863: . field  - The field number for the nullspace
    1864: - nullsp - A callback to create the near-nullspace

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

    1872:   Level: intermediate

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

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

    1890:   Not Collective; No Fortran Support

    1892:   Input Parameters:
    1893: + dm    - The `DM`
    1894: - field - The field number for the nullspace

    1896:   Output Parameter:
    1897: . nullsp - A callback to create the near-nullspace

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

    1905:   Level: intermediate

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

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

    1924:   Not Collective; No Fortran Support

    1926:   Input Parameter:
    1927: . dm - the `DM` object

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

    1934:   Level: intermediate

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

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

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

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

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

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

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

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

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

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

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

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

    2049:   Not Collective; No Fortran Support

    2051:   Input Parameter:
    2052: . dm - the `DM` object

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

    2060:   Level: intermediate

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

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

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

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

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

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

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

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

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

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

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

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

    2151:   Not collective

    2153:   Input Parameters:
    2154: + dm        - The `DM` object
    2155: . numFields - The number of fields to select
    2156: - fields    - The field numbers of the selected fields

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

    2162:   Level: intermediate

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

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

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

    2183:   Not collective

    2185:   Input Parameters:
    2186: + dms - The `DM` objects
    2187: - n   - The number of `DM`s

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

    2193:   Level: intermediate

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

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

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

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

    2222:   Not Collective

    2224:   Input Parameter:
    2225: . dm - the `DM` object

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

    2234:   Level: intermediate

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

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

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

    2247:   Developer Notes:
    2248:   The `dmlist` is for the inner subdomains or the outer subdomains or all subdomains?

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

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

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

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

    2308:   Not Collective

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

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

    2320:   Level: developer

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

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

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

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

    2346:   Collective

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

    2352:   Output Parameter:
    2353: . dmf - the refined `DM`, or `NULL`

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

    2358:   Level: developer

    2360:   Note:
    2361:   If no refinement was done, the return value is `NULL`

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

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

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

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

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

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

    2395:   Logically Collective; No Fortran Support

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

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

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

    2414:   Level: advanced

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

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

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

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

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

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

    2448:   Logically Collective; No Fortran Support

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

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

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

    2467:   Level: advanced

    2469:   Note:
    2470:   This function does nothing if the hook is not in the list.

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

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

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

    2494:   Collective if any hooks are

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

    2501:   Level: developer

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

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

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

    2520: /*@
    2521:   DMInterpolateSolution - Interpolates a solution from a coarse mesh to a fine mesh.

    2523:   Collective

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

    2533:   Output Parameter:
    2534: . fineSol - the interpolation of coarseSol to the fine mesh

    2536:   Level: developer

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

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

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

    2553:   PetscFunctionBegin;

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

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

    2571:   Not Collective

    2573:   Input Parameter:
    2574: . dm - the `DM` object

    2576:   Output Parameter:
    2577: . level - number of refinements

    2579:   Level: developer

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

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

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

    2597:   Not Collective

    2599:   Input Parameters:
    2600: + dm    - the `DM` object
    2601: - level - number of refinements

    2603:   Level: advanced

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

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

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

    2620: /*@
    2621:   DMExtrude - Extrude a `DM` object from a surface

    2623:   Collective

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

    2629:   Output Parameter:
    2630: . dme - the extruded `DM`, or `NULL`

    2632:   Level: developer

    2634:   Note:
    2635:   If no extrusion was done, the return value is `NULL`

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

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

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

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

    2674:   Input Parameter:
    2675: . dm - The `DM`

    2677:   Output Parameter:
    2678: . flg - `PETSC_TRUE` if a basis transformation should be done

    2680:   Level: developer

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

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

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

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

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

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

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

    2760:   Logically Collective

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

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

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

    2782:   Level: advanced

    2784:   Note:
    2785:   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.

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

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

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

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

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

    2840: /*@
    2841:   DMGlobalToLocal - update local vectors from global vector

    2843:   Neighbor-wise Collective

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

    2851:   Level: beginner

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

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

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

    2871: /*@
    2872:   DMGlobalToLocalBegin - Begins updating local vectors from global vector

    2874:   Neighbor-wise Collective

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

    2882:   Level: intermediate

    2884:   Notes:
    2885:   The operation is completed with `DMGlobalToLocalEnd()`

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

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

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

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

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

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

    2923: /*@
    2924:   DMGlobalToLocalEnd - Ends updating local vectors from global vector

    2926:   Neighbor-wise Collective

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

    2934:   Level: intermediate

    2936:   Note:
    2937:   See `DMGlobalToLocalBegin()` for details.

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

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

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

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

    2976:   Logically Collective

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

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

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

    2998:   Level: advanced

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

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

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

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

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

    3059:   Neighbor-wise Collective

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

    3067:   Level: beginner

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

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

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

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

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

    3089: /*@
    3090:   DMLocalToGlobalBegin - begins updating global vectors from local vectors

    3092:   Neighbor-wise Collective

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

    3100:   Level: intermediate

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

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

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

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

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

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

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

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

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

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

    3225: /*@
    3226:   DMLocalToGlobalEnd - updates global vectors from local vectors

    3228:   Neighbor-wise Collective

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

    3236:   Level: intermediate

    3238:   Note:
    3239:   See `DMLocalToGlobalBegin()` for full details

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

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

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

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

    3302:   Neighbor-wise Collective

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

    3309:   Output Parameter:
    3310: . l - the local vector with correct ghost values

    3312:   Level: intermediate

    3314:   Note:
    3315:   Must be followed by `DMLocalToLocalEnd()`.

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

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

    3333:   Neighbor-wise Collective

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

    3340:   Output Parameter:
    3341: . l - the local vector with correct ghost values

    3343:   Level: intermediate

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

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

    3360:   Collective

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

    3366:   Output Parameter:
    3367: . dmc - the coarsened `DM`

    3369:   Level: developer

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

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

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

    3403:   Logically Collective; No Fortran Support

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

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

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

    3424:   Level: advanced

    3426:   Notes:
    3427:   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`.

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

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

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

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

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

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

    3459:   Logically Collective; No Fortran Support

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

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

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

    3480:   Level: advanced

    3482:   Notes:
    3483:   This function does nothing if the `coarsenhook` is not in the list.

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

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

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

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

    3509:   Collective if any hooks are

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

    3518:   Level: developer

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

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

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

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

    3539:   Logically Collective; No Fortran Support

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

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

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

    3559:   Level: advanced

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

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

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

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

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

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

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

    3595:   Logically Collective; No Fortran Support

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

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

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

    3615:   Level: advanced

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

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

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

    3640:   Collective if any hooks are

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

    3648:   Level: developer

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

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

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

    3666:   Not Collective

    3668:   Input Parameter:
    3669: . dm - the `DM` object

    3671:   Output Parameter:
    3672: . level - number of coarsenings

    3674:   Level: developer

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

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

    3690:   Collective

    3692:   Input Parameters:
    3693: + dm    - the `DM` object
    3694: - level - number of coarsenings

    3696:   Level: developer

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

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

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

    3714:   Collective

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

    3720:   Output Parameter:
    3721: . dmf - the refined `DM` hierarchy

    3723:   Level: developer

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

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

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

    3746:   Collective

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

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

    3755:   Level: developer

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

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

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

    3778:   Logically Collective if the function is collective

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

    3784:   Level: intermediate

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

    3797: /*@
    3798:   DMSetApplicationContext - Set a user context into a `DM` object

    3800:   Not Collective

    3802:   Input Parameters:
    3803: + dm  - the `DM` object
    3804: - ctx - the user context

    3806:   Level: intermediate

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

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

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

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

    3832:   Not Collective

    3834:   Input Parameter:
    3835: . dm - the `DM` object

    3837:   Output Parameter:
    3838: . ctx - a pointer to the user context

    3840:   Level: intermediate

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

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

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

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

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

    3878:   Logically Collective

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

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

    3889:   Level: intermediate

    3891:   Developer Note:
    3892:   Should be called `DMSetComputeVIBounds()` or something similar

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

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

    3908:   Not Collective

    3910:   Input Parameter:
    3911: . dm - the `DM` object to destroy

    3913:   Output Parameter:
    3914: . flg - `PETSC_TRUE` if the variable bounds function exists

    3916:   Level: developer

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

    3929: /*@
    3930:   DMComputeVariableBounds - compute variable bounds used by `SNESVI`.

    3932:   Logically Collective

    3934:   Input Parameter:
    3935: . dm - the `DM` object

    3937:   Output Parameters:
    3938: + xl - lower bound
    3939: - xu - upper bound

    3941:   Level: advanced

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

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

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

    3961:   Not Collective

    3963:   Input Parameter:
    3964: . dm - the DM object

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

    3969:   Level: developer

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

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

    3985:   Not Collective

    3987:   Input Parameter:
    3988: . dm - the `DM` object

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

    3993:   Level: developer

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

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

    4009:   Not Collective

    4011:   Input Parameter:
    4012: . dm - the `DM` object

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

    4017:   Level: developer

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

    4031: PetscFunctionList DMList              = NULL;
    4032: PetscBool         DMRegisterAllCalled = PETSC_FALSE;

    4034: /*@
    4035:   DMSetType - Builds a `DM`, for a particular `DM` implementation.

    4037:   Collective

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

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

    4046:   Level: intermediate

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

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

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

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

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

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

    4077:   Not Collective

    4079:   Input Parameter:
    4080: . dm - The `DM`

    4082:   Output Parameter:
    4083: . type - The `DMType` name

    4085:   Level: intermediate

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

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

    4102:   Collective

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

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

    4111:   Level: intermediate

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

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

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

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

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

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

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

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

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

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

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

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

    4209:   Not Collective, No Fortran Support

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

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

    4218:   Level: advanced

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

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

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

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

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

    4251:   Collective

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

    4259:   Level: intermediate

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

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

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

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

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

    4297: /* FEM Support */

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

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

    4309: PetscErrorCode DMPrintCellVector(PetscInt c, const char name[], PetscInt len, const PetscScalar x[])
    4310: {
    4311:   PetscInt f;

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

    4319: PetscErrorCode DMPrintCellVectorReal(PetscInt c, const char name[], PetscInt len, const PetscReal x[])
    4320: {
    4321:   PetscInt f;

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

    4329: PetscErrorCode DMPrintCellMatrix(PetscInt c, const char name[], PetscInt rows, PetscInt cols, const PetscScalar A[])
    4330: {
    4331:   PetscInt f, g;

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

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

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

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

    4376:   Input Parameter:
    4377: . dm - The `DM`

    4379:   Output Parameter:
    4380: . section - The `PetscSection`

    4382:   Options Database Key:
    4383: . -dm_petscsection_view - View the section created by the `DM`

    4385:   Level: intermediate

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

    4390: .seealso: [](ch_dmbase), `DM`, `DMSetLocalSection()`, `DMGetGlobalSection()`
    4391: @*/
    4392: PetscErrorCode DMGetLocalSection(DM dm, PetscSection *section)
    4393: {
    4394:   PetscFunctionBegin;
    4396:   PetscAssertPointer(section, 2);
    4397:   if (!dm->localSection && dm->ops->createlocalsection) {
    4398:     PetscInt d;

    4400:     if (dm->setfromoptionscalled) {
    4401:       PetscObject       obj = (PetscObject)dm;
    4402:       PetscViewer       viewer;
    4403:       PetscViewerFormat format;
    4404:       PetscBool         flg;

    4406:       PetscCall(PetscOptionsCreateViewer(PetscObjectComm(obj), obj->options, obj->prefix, "-dm_petscds_view", &viewer, &format, &flg));
    4407:       if (flg) PetscCall(PetscViewerPushFormat(viewer, format));
    4408:       for (d = 0; d < dm->Nds; ++d) {
    4409:         PetscCall(PetscDSSetFromOptions(dm->probs[d].ds));
    4410:         if (flg) PetscCall(PetscDSView(dm->probs[d].ds, viewer));
    4411:       }
    4412:       if (flg) {
    4413:         PetscCall(PetscViewerFlush(viewer));
    4414:         PetscCall(PetscViewerPopFormat(viewer));
    4415:         PetscCall(PetscViewerDestroy(&viewer));
    4416:       }
    4417:     }
    4418:     PetscUseTypeMethod(dm, createlocalsection);
    4419:     if (dm->localSection) PetscCall(PetscObjectViewFromOptions((PetscObject)dm->localSection, NULL, "-dm_petscsection_view"));
    4420:   }
    4421:   *section = dm->localSection;
    4422:   PetscFunctionReturn(PETSC_SUCCESS);
    4423: }

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

    4428:   Input Parameters:
    4429: + dm      - The `DM`
    4430: - section - The `PetscSection`

    4432:   Level: intermediate

    4434:   Note:
    4435:   Any existing Section will be destroyed

    4437: .seealso: [](ch_dmbase), `DM`, `PetscSection`, `DMGetLocalSection()`, `DMSetGlobalSection()`
    4438: @*/
    4439: PetscErrorCode DMSetLocalSection(DM dm, PetscSection section)
    4440: {
    4441:   PetscInt numFields = 0;
    4442:   PetscInt f;

    4444:   PetscFunctionBegin;
    4447:   PetscCall(PetscObjectReference((PetscObject)section));
    4448:   PetscCall(PetscSectionDestroy(&dm->localSection));
    4449:   dm->localSection = section;
    4450:   if (section) PetscCall(PetscSectionGetNumFields(dm->localSection, &numFields));
    4451:   if (numFields) {
    4452:     PetscCall(DMSetNumFields(dm, numFields));
    4453:     for (f = 0; f < numFields; ++f) {
    4454:       PetscObject disc;
    4455:       const char *name;

    4457:       PetscCall(PetscSectionGetFieldName(dm->localSection, f, &name));
    4458:       PetscCall(DMGetField(dm, f, NULL, &disc));
    4459:       PetscCall(PetscObjectSetName(disc, name));
    4460:     }
    4461:   }
    4462:   /* The global section and the SectionSF will be rebuilt
    4463:      in the next call to DMGetGlobalSection() and DMGetSectionSF(). */
    4464:   PetscCall(PetscSectionDestroy(&dm->globalSection));
    4465:   PetscCall(PetscSFDestroy(&dm->sectionSF));
    4466:   PetscCall(PetscSFCreate(PetscObjectComm((PetscObject)dm), &dm->sectionSF));

    4468:   /* Clear scratch vectors */
    4469:   PetscCall(DMClearGlobalVectors(dm));
    4470:   PetscCall(DMClearLocalVectors(dm));
    4471:   PetscCall(DMClearNamedGlobalVectors(dm));
    4472:   PetscCall(DMClearNamedLocalVectors(dm));
    4473:   PetscFunctionReturn(PETSC_SUCCESS);
    4474: }

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

    4479:   Input Parameter:
    4480: . dm - The `DM`

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

    4486:   Level: developer

    4488: .seealso: [](ch_dmbase), `DM`, `PetscSection`, `DMGetLocalSection()`, `DMGetGlobalSection()`
    4489: @*/
    4490: PetscErrorCode DMCreateSectionPermutation(DM dm, IS *perm, PetscBT *blockStarts)
    4491: {
    4492:   PetscFunctionBegin;
    4493:   *perm        = NULL;
    4494:   *blockStarts = NULL;
    4495:   PetscTryTypeMethod(dm, createsectionpermutation, perm, blockStarts);
    4496:   PetscFunctionReturn(PETSC_SUCCESS);
    4497: }

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

    4502:   not Collective

    4504:   Input Parameter:
    4505: . dm - The `DM`

    4507:   Output Parameters:
    4508: + 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.
    4509: . 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.
    4510: - bias    - Vector containing bias to be added to constrained dofs

    4512:   Level: advanced

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

    4517: .seealso: [](ch_dmbase), `DM`, `DMSetDefaultConstraints()`
    4518: @*/
    4519: PetscErrorCode DMGetDefaultConstraints(DM dm, PetscSection *section, Mat *mat, Vec *bias)
    4520: {
    4521:   PetscFunctionBegin;
    4523:   if (!dm->defaultConstraint.section && !dm->defaultConstraint.mat && dm->ops->createdefaultconstraints) PetscUseTypeMethod(dm, createdefaultconstraints);
    4524:   if (section) *section = dm->defaultConstraint.section;
    4525:   if (mat) *mat = dm->defaultConstraint.mat;
    4526:   if (bias) *bias = dm->defaultConstraint.bias;
    4527:   PetscFunctionReturn(PETSC_SUCCESS);
    4528: }

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

    4533:   Collective

    4535:   Input Parameters:
    4536: + dm      - The `DM`
    4537: . 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).
    4538: . 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).
    4539: - 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).

    4541:   Level: advanced

    4543:   Notes:
    4544:   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()`.

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

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

    4550: .seealso: [](ch_dmbase), `DM`, `DMGetDefaultConstraints()`
    4551: @*/
    4552: PetscErrorCode DMSetDefaultConstraints(DM dm, PetscSection section, Mat mat, Vec bias)
    4553: {
    4554:   PetscMPIInt result;

    4556:   PetscFunctionBegin;
    4558:   if (section) {
    4560:     PetscCallMPI(MPI_Comm_compare(PETSC_COMM_SELF, PetscObjectComm((PetscObject)section), &result));
    4561:     PetscCheck(result == MPI_CONGRUENT || result == MPI_IDENT, PETSC_COMM_SELF, PETSC_ERR_ARG_NOTSAMECOMM, "constraint section must have local communicator");
    4562:   }
    4563:   if (mat) {
    4565:     PetscCallMPI(MPI_Comm_compare(PETSC_COMM_SELF, PetscObjectComm((PetscObject)mat), &result));
    4566:     PetscCheck(result == MPI_CONGRUENT || result == MPI_IDENT, PETSC_COMM_SELF, PETSC_ERR_ARG_NOTSAMECOMM, "constraint matrix must have local communicator");
    4567:   }
    4568:   if (bias) {
    4570:     PetscCallMPI(MPI_Comm_compare(PETSC_COMM_SELF, PetscObjectComm((PetscObject)bias), &result));
    4571:     PetscCheck(result == MPI_CONGRUENT || result == MPI_IDENT, PETSC_COMM_SELF, PETSC_ERR_ARG_NOTSAMECOMM, "constraint bias must have local communicator");
    4572:   }
    4573:   PetscCall(PetscObjectReference((PetscObject)section));
    4574:   PetscCall(PetscSectionDestroy(&dm->defaultConstraint.section));
    4575:   dm->defaultConstraint.section = section;
    4576:   PetscCall(PetscObjectReference((PetscObject)mat));
    4577:   PetscCall(MatDestroy(&dm->defaultConstraint.mat));
    4578:   dm->defaultConstraint.mat = mat;
    4579:   PetscCall(PetscObjectReference((PetscObject)bias));
    4580:   PetscCall(VecDestroy(&dm->defaultConstraint.bias));
    4581:   dm->defaultConstraint.bias = bias;
    4582:   PetscFunctionReturn(PETSC_SUCCESS);
    4583: }

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

    4589:   Input Parameters:
    4590: + dm - The `DM`
    4591: . localSection - `PetscSection` describing the local data layout
    4592: - globalSection - `PetscSection` describing the global data layout

    4594:   Level: intermediate

    4596: .seealso: [](ch_dmbase), `DM`, `DMGetSectionSF()`, `DMSetSectionSF()`
    4597: */
    4598: static PetscErrorCode DMDefaultSectionCheckConsistency_Internal(DM dm, PetscSection localSection, PetscSection globalSection)
    4599: {
    4600:   MPI_Comm        comm;
    4601:   PetscLayout     layout;
    4602:   const PetscInt *ranges;
    4603:   PetscInt        pStart, pEnd, p, nroots;
    4604:   PetscMPIInt     size, rank;
    4605:   PetscBool       valid = PETSC_TRUE, gvalid;

    4607:   PetscFunctionBegin;
    4608:   PetscCall(PetscObjectGetComm((PetscObject)dm, &comm));
    4610:   PetscCallMPI(MPI_Comm_size(comm, &size));
    4611:   PetscCallMPI(MPI_Comm_rank(comm, &rank));
    4612:   PetscCall(PetscSectionGetChart(globalSection, &pStart, &pEnd));
    4613:   PetscCall(PetscSectionGetConstrainedStorageSize(globalSection, &nroots));
    4614:   PetscCall(PetscLayoutCreate(comm, &layout));
    4615:   PetscCall(PetscLayoutSetBlockSize(layout, 1));
    4616:   PetscCall(PetscLayoutSetLocalSize(layout, nroots));
    4617:   PetscCall(PetscLayoutSetUp(layout));
    4618:   PetscCall(PetscLayoutGetRanges(layout, &ranges));
    4619:   for (p = pStart; p < pEnd; ++p) {
    4620:     PetscInt dof, cdof, off, gdof, gcdof, goff, gsize, d;

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

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

    4663: PetscErrorCode DMGetIsoperiodicPointSF_Internal(DM dm, PetscSF *sf)
    4664: {
    4665:   PetscErrorCode (*f)(DM, PetscSF *);

    4667:   PetscFunctionBegin;
    4669:   PetscAssertPointer(sf, 2);
    4670:   PetscCall(PetscObjectQueryFunction((PetscObject)dm, "DMGetIsoperiodicPointSF_C", &f));
    4671:   if (f) PetscCall(f(dm, sf));
    4672:   else *sf = dm->sf;
    4673:   PetscFunctionReturn(PETSC_SUCCESS);
    4674: }

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

    4679:   Collective

    4681:   Input Parameter:
    4682: . dm - The `DM`

    4684:   Output Parameter:
    4685: . section - The `PetscSection`

    4687:   Level: intermediate

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

    4692: .seealso: [](ch_dmbase), `DM`, `DMSetLocalSection()`, `DMGetLocalSection()`
    4693: @*/
    4694: PetscErrorCode DMGetGlobalSection(DM dm, PetscSection *section)
    4695: {
    4696:   PetscFunctionBegin;
    4698:   PetscAssertPointer(section, 2);
    4699:   if (!dm->globalSection) {
    4700:     PetscSection s;
    4701:     PetscSF      sf;

    4703:     PetscCall(DMGetLocalSection(dm, &s));
    4704:     PetscCheck(s, PetscObjectComm((PetscObject)dm), PETSC_ERR_ARG_WRONGSTATE, "DM must have a default PetscSection in order to create a global PetscSection");
    4705:     PetscCheck(dm->sf, PetscObjectComm((PetscObject)dm), PETSC_ERR_ARG_WRONGSTATE, "DM must have a point PetscSF in order to create a global PetscSection");
    4706:     PetscCall(DMGetIsoperiodicPointSF_Internal(dm, &sf));
    4707:     PetscCall(PetscSectionCreateGlobalSection(s, sf, PETSC_TRUE, PETSC_FALSE, PETSC_FALSE, &dm->globalSection));
    4708:     PetscCall(PetscLayoutDestroy(&dm->map));
    4709:     PetscCall(PetscSectionGetValueLayout(PetscObjectComm((PetscObject)dm), dm->globalSection, &dm->map));
    4710:     PetscCall(PetscSectionViewFromOptions(dm->globalSection, NULL, "-global_section_view"));
    4711:   }
    4712:   *section = dm->globalSection;
    4713:   PetscFunctionReturn(PETSC_SUCCESS);
    4714: }

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

    4719:   Input Parameters:
    4720: + dm      - The `DM`
    4721: - section - The PetscSection, or `NULL`

    4723:   Level: intermediate

    4725:   Note:
    4726:   Any existing `PetscSection` will be destroyed

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

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

    4753:   Input Parameter:
    4754: . dm - The `DM`

    4756:   Output Parameter:
    4757: . sf - The `PetscSF`

    4759:   Level: intermediate

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

    4764: .seealso: [](ch_dmbase), `DM`, `DMSetSectionSF()`, `DMCreateSectionSF()`
    4765: @*/
    4766: PetscErrorCode DMGetSectionSF(DM dm, PetscSF *sf)
    4767: {
    4768:   PetscInt nroots;

    4770:   PetscFunctionBegin;
    4772:   PetscAssertPointer(sf, 2);
    4773:   if (!dm->sectionSF) PetscCall(PetscSFCreate(PetscObjectComm((PetscObject)dm), &dm->sectionSF));
    4774:   PetscCall(PetscSFGetGraph(dm->sectionSF, &nroots, NULL, NULL, NULL));
    4775:   if (nroots < 0) {
    4776:     PetscSection section, gSection;

    4778:     PetscCall(DMGetLocalSection(dm, &section));
    4779:     if (section) {
    4780:       PetscCall(DMGetGlobalSection(dm, &gSection));
    4781:       PetscCall(DMCreateSectionSF(dm, section, gSection));
    4782:     } else {
    4783:       *sf = NULL;
    4784:       PetscFunctionReturn(PETSC_SUCCESS);
    4785:     }
    4786:   }
    4787:   *sf = dm->sectionSF;
    4788:   PetscFunctionReturn(PETSC_SUCCESS);
    4789: }

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

    4794:   Input Parameters:
    4795: + dm - The `DM`
    4796: - sf - The `PetscSF`

    4798:   Level: intermediate

    4800:   Note:
    4801:   Any previous `PetscSF` is destroyed

    4803: .seealso: [](ch_dmbase), `DM`, `DMGetSectionSF()`, `DMCreateSectionSF()`
    4804: @*/
    4805: PetscErrorCode DMSetSectionSF(DM dm, PetscSF sf)
    4806: {
    4807:   PetscFunctionBegin;
    4810:   PetscCall(PetscObjectReference((PetscObject)sf));
    4811:   PetscCall(PetscSFDestroy(&dm->sectionSF));
    4812:   dm->sectionSF = sf;
    4813:   PetscFunctionReturn(PETSC_SUCCESS);
    4814: }

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

    4820:   Input Parameters:
    4821: + dm            - The `DM`
    4822: . localSection  - `PetscSection` describing the local data layout
    4823: - globalSection - `PetscSection` describing the global data layout

    4825:   Level: developer

    4827:   Note:
    4828:   One usually uses `DMGetSectionSF()` to obtain the `PetscSF`

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

    4836: .seealso: [](ch_dmbase), `DM`, `DMGetSectionSF()`, `DMSetSectionSF()`, `DMGetLocalSection()`, `DMGetGlobalSection()`
    4837: @*/
    4838: PetscErrorCode DMCreateSectionSF(DM dm, PetscSection localSection, PetscSection globalSection)
    4839: {
    4840:   PetscFunctionBegin;
    4842:   PetscCall(PetscSFSetGraphSection(dm->sectionSF, localSection, globalSection));
    4843:   PetscFunctionReturn(PETSC_SUCCESS);
    4844: }

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

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

    4851:   Input Parameter:
    4852: . dm - The `DM`

    4854:   Output Parameter:
    4855: . sf - The `PetscSF`

    4857:   Level: intermediate

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

    4862: .seealso: [](ch_dmbase), `DM`, `DMSetPointSF()`, `DMGetSectionSF()`, `DMSetSectionSF()`, `DMCreateSectionSF()`
    4863: @*/
    4864: PetscErrorCode DMGetPointSF(DM dm, PetscSF *sf)
    4865: {
    4866:   PetscFunctionBegin;
    4868:   PetscAssertPointer(sf, 2);
    4869:   *sf = dm->sf;
    4870:   PetscFunctionReturn(PETSC_SUCCESS);
    4871: }

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

    4876:   Collective

    4878:   Input Parameters:
    4879: + dm - The `DM`
    4880: - sf - The `PetscSF`

    4882:   Level: intermediate

    4884: .seealso: [](ch_dmbase), `DM`, `DMGetPointSF()`, `DMGetSectionSF()`, `DMSetSectionSF()`, `DMCreateSectionSF()`
    4885: @*/
    4886: PetscErrorCode DMSetPointSF(DM dm, PetscSF sf)
    4887: {
    4888:   PetscFunctionBegin;
    4891:   PetscCall(PetscObjectReference((PetscObject)sf));
    4892:   PetscCall(PetscSFDestroy(&dm->sf));
    4893:   dm->sf = sf;
    4894:   PetscFunctionReturn(PETSC_SUCCESS);
    4895: }

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

    4900:   Input Parameter:
    4901: . dm - The `DM`

    4903:   Output Parameter:
    4904: . sf - The `PetscSF`

    4906:   Level: intermediate

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

    4911: .seealso: [](ch_dmbase), `DM`, `DMSetNaturalSF()`, `DMSetUseNatural()`, `DMGetUseNatural()`, `DMPlexCreateGlobalToNaturalSF()`, `DMPlexDistribute()`
    4912: @*/
    4913: PetscErrorCode DMGetNaturalSF(DM dm, PetscSF *sf)
    4914: {
    4915:   PetscFunctionBegin;
    4917:   PetscAssertPointer(sf, 2);
    4918:   *sf = dm->sfNatural;
    4919:   PetscFunctionReturn(PETSC_SUCCESS);
    4920: }

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

    4925:   Input Parameters:
    4926: + dm - The DM
    4927: - sf - The PetscSF

    4929:   Level: intermediate

    4931: .seealso: [](ch_dmbase), `DM`, `DMGetNaturalSF()`, `DMSetUseNatural()`, `DMGetUseNatural()`, `DMPlexCreateGlobalToNaturalSF()`, `DMPlexDistribute()`
    4932: @*/
    4933: PetscErrorCode DMSetNaturalSF(DM dm, PetscSF sf)
    4934: {
    4935:   PetscFunctionBegin;
    4938:   PetscCall(PetscObjectReference((PetscObject)sf));
    4939:   PetscCall(PetscSFDestroy(&dm->sfNatural));
    4940:   dm->sfNatural = sf;
    4941:   PetscFunctionReturn(PETSC_SUCCESS);
    4942: }

    4944: static PetscErrorCode DMSetDefaultAdjacency_Private(DM dm, PetscInt f, PetscObject disc)
    4945: {
    4946:   PetscClassId id;

    4948:   PetscFunctionBegin;
    4949:   PetscCall(PetscObjectGetClassId(disc, &id));
    4950:   if (id == PETSCFE_CLASSID) PetscCall(DMSetAdjacency(dm, f, PETSC_FALSE, PETSC_TRUE));
    4951:   else if (id == PETSCFV_CLASSID) PetscCall(DMSetAdjacency(dm, f, PETSC_TRUE, PETSC_FALSE));
    4952:   else PetscCall(DMSetAdjacency(dm, f, PETSC_FALSE, PETSC_TRUE));
    4953:   PetscFunctionReturn(PETSC_SUCCESS);
    4954: }

    4956: static PetscErrorCode DMFieldEnlarge_Static(DM dm, PetscInt NfNew)
    4957: {
    4958:   RegionField *tmpr;
    4959:   PetscInt     Nf = dm->Nf, f;

    4961:   PetscFunctionBegin;
    4962:   if (Nf >= NfNew) PetscFunctionReturn(PETSC_SUCCESS);
    4963:   PetscCall(PetscMalloc1(NfNew, &tmpr));
    4964:   for (f = 0; f < Nf; ++f) tmpr[f] = dm->fields[f];
    4965:   for (f = Nf; f < NfNew; ++f) {
    4966:     tmpr[f].disc        = NULL;
    4967:     tmpr[f].label       = NULL;
    4968:     tmpr[f].avoidTensor = PETSC_FALSE;
    4969:   }
    4970:   PetscCall(PetscFree(dm->fields));
    4971:   dm->Nf     = NfNew;
    4972:   dm->fields = tmpr;
    4973:   PetscFunctionReturn(PETSC_SUCCESS);
    4974: }

    4976: /*@
    4977:   DMClearFields - Remove all fields from the `DM`

    4979:   Logically Collective

    4981:   Input Parameter:
    4982: . dm - The `DM`

    4984:   Level: intermediate

    4986: .seealso: [](ch_dmbase), `DM`, `DMGetNumFields()`, `DMSetNumFields()`, `DMSetField()`
    4987: @*/
    4988: PetscErrorCode DMClearFields(DM dm)
    4989: {
    4990:   PetscInt f;

    4992:   PetscFunctionBegin;
    4994:   if (!dm->fields) PetscFunctionReturn(PETSC_SUCCESS); // DMDA does not use fields field in DM
    4995:   for (f = 0; f < dm->Nf; ++f) {
    4996:     PetscCall(PetscObjectDestroy(&dm->fields[f].disc));
    4997:     PetscCall(DMLabelDestroy(&dm->fields[f].label));
    4998:   }
    4999:   PetscCall(PetscFree(dm->fields));
    5000:   dm->fields = NULL;
    5001:   dm->Nf     = 0;
    5002:   PetscFunctionReturn(PETSC_SUCCESS);
    5003: }

    5005: /*@
    5006:   DMGetNumFields - Get the number of fields in the `DM`

    5008:   Not Collective

    5010:   Input Parameter:
    5011: . dm - The `DM`

    5013:   Output Parameter:
    5014: . numFields - The number of fields

    5016:   Level: intermediate

    5018: .seealso: [](ch_dmbase), `DM`, `DMSetNumFields()`, `DMSetField()`
    5019: @*/
    5020: PetscErrorCode DMGetNumFields(DM dm, PetscInt *numFields)
    5021: {
    5022:   PetscFunctionBegin;
    5024:   PetscAssertPointer(numFields, 2);
    5025:   *numFields = dm->Nf;
    5026:   PetscFunctionReturn(PETSC_SUCCESS);
    5027: }

    5029: /*@
    5030:   DMSetNumFields - Set the number of fields in the `DM`

    5032:   Logically Collective

    5034:   Input Parameters:
    5035: + dm        - The `DM`
    5036: - numFields - The number of fields

    5038:   Level: intermediate

    5040: .seealso: [](ch_dmbase), `DM`, `DMGetNumFields()`, `DMSetField()`
    5041: @*/
    5042: PetscErrorCode DMSetNumFields(DM dm, PetscInt numFields)
    5043: {
    5044:   PetscInt Nf, f;

    5046:   PetscFunctionBegin;
    5048:   PetscCall(DMGetNumFields(dm, &Nf));
    5049:   for (f = Nf; f < numFields; ++f) {
    5050:     PetscContainer obj;

    5052:     PetscCall(PetscContainerCreate(PetscObjectComm((PetscObject)dm), &obj));
    5053:     PetscCall(DMAddField(dm, NULL, (PetscObject)obj));
    5054:     PetscCall(PetscContainerDestroy(&obj));
    5055:   }
    5056:   PetscFunctionReturn(PETSC_SUCCESS);
    5057: }

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

    5062:   Not Collective

    5064:   Input Parameters:
    5065: + dm - The `DM`
    5066: - f  - The field number

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

    5072:   Level: intermediate

    5074: .seealso: [](ch_dmbase), `DM`, `DMAddField()`, `DMSetField()`
    5075: @*/
    5076: PetscErrorCode DMGetField(DM dm, PetscInt f, DMLabel *label, PetscObject *disc)
    5077: {
    5078:   PetscFunctionBegin;
    5080:   PetscAssertPointer(disc, 4);
    5081:   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);
    5082:   if (!dm->fields) {
    5083:     if (label) *label = NULL;
    5084:     if (disc) *disc = NULL;
    5085:   } else { // some DM such as DMDA do not have dm->fields
    5086:     if (label) *label = dm->fields[f].label;
    5087:     if (disc) *disc = dm->fields[f].disc;
    5088:   }
    5089:   PetscFunctionReturn(PETSC_SUCCESS);
    5090: }

    5092: /* Does not clear the DS */
    5093: PetscErrorCode DMSetField_Internal(DM dm, PetscInt f, DMLabel label, PetscObject disc)
    5094: {
    5095:   PetscFunctionBegin;
    5096:   PetscCall(DMFieldEnlarge_Static(dm, f + 1));
    5097:   PetscCall(DMLabelDestroy(&dm->fields[f].label));
    5098:   PetscCall(PetscObjectDestroy(&dm->fields[f].disc));
    5099:   dm->fields[f].label = label;
    5100:   dm->fields[f].disc  = disc;
    5101:   PetscCall(PetscObjectReference((PetscObject)label));
    5102:   PetscCall(PetscObjectReference(disc));
    5103:   PetscFunctionReturn(PETSC_SUCCESS);
    5104: }

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

    5110:   Logically Collective

    5112:   Input Parameters:
    5113: + dm    - The `DM`
    5114: . f     - The field number
    5115: . label - The label indicating the support of the field, or `NULL` for the entire mesh
    5116: - disc  - The discretization object

    5118:   Level: intermediate

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

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

    5139:   Logically Collective

    5141:   Input Parameters:
    5142: + dm    - The `DM`
    5143: . label - The label indicating the support of the field, or `NULL` for the entire mesh
    5144: - disc  - The discretization object

    5146:   Level: intermediate

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

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

    5155:   Fortran Note:
    5156:   Use the argument `PetscObjectCast(disc)` as the second argument

    5158: .seealso: [](ch_dmbase), `DM`, `DMSetLabel()`, `DMSetField()`, `DMGetField()`, `PetscFE`
    5159: @*/
    5160: PetscErrorCode DMAddField(DM dm, DMLabel label, PetscObject disc)
    5161: {
    5162:   PetscInt Nf = dm->Nf;

    5164:   PetscFunctionBegin;
    5168:   PetscCall(DMFieldEnlarge_Static(dm, Nf + 1));
    5169:   dm->fields[Nf].label = label;
    5170:   dm->fields[Nf].disc  = disc;
    5171:   PetscCall(PetscObjectReference((PetscObject)label));
    5172:   PetscCall(PetscObjectReference(disc));
    5173:   PetscCall(DMSetDefaultAdjacency_Private(dm, Nf, disc));
    5174:   PetscCall(DMClearDS(dm));
    5175:   PetscFunctionReturn(PETSC_SUCCESS);
    5176: }

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

    5181:   Logically Collective

    5183:   Input Parameters:
    5184: + dm          - The `DM`
    5185: . f           - The field index
    5186: - avoidTensor - `PETSC_TRUE` to skip defining the field on tensor cells

    5188:   Level: intermediate

    5190: .seealso: [](ch_dmbase), `DM`, `DMGetFieldAvoidTensor()`, `DMSetField()`, `DMGetField()`
    5191: @*/
    5192: PetscErrorCode DMSetFieldAvoidTensor(DM dm, PetscInt f, PetscBool avoidTensor)
    5193: {
    5194:   PetscFunctionBegin;
    5195:   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);
    5196:   dm->fields[f].avoidTensor = avoidTensor;
    5197:   PetscFunctionReturn(PETSC_SUCCESS);
    5198: }

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

    5203:   Not Collective

    5205:   Input Parameters:
    5206: + dm - The `DM`
    5207: - f  - The field index

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

    5212:   Level: intermediate

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

    5224: /*@
    5225:   DMCopyFields - Copy the discretizations for the `DM` into another `DM`

    5227:   Collective

    5229:   Input Parameters:
    5230: + dm        - The `DM`
    5231: . minDegree - Minimum degree for a discretization, or `PETSC_DETERMINE` for no limit
    5232: - maxDegree - Maximum degree for a discretization, or `PETSC_DETERMINE` for no limit

    5234:   Output Parameter:
    5235: . newdm - The `DM`

    5237:   Level: advanced

    5239: .seealso: [](ch_dmbase), `DM`, `DMGetField()`, `DMSetField()`, `DMAddField()`, `DMCopyDS()`, `DMGetDS()`, `DMGetCellDS()`
    5240: @*/
    5241: PetscErrorCode DMCopyFields(DM dm, PetscInt minDegree, PetscInt maxDegree, DM newdm)
    5242: {
    5243:   PetscInt Nf, f;

    5245:   PetscFunctionBegin;
    5246:   if (dm == newdm) PetscFunctionReturn(PETSC_SUCCESS);
    5247:   PetscCall(DMGetNumFields(dm, &Nf));
    5248:   PetscCall(DMClearFields(newdm));
    5249:   for (f = 0; f < Nf; ++f) {
    5250:     DMLabel      label;
    5251:     PetscObject  field;
    5252:     PetscClassId id;
    5253:     PetscBool    useCone, useClosure;

    5255:     PetscCall(DMGetField(dm, f, &label, &field));
    5256:     PetscCall(PetscObjectGetClassId(field, &id));
    5257:     if (id == PETSCFE_CLASSID) {
    5258:       PetscFE newfe;

    5260:       PetscCall(PetscFELimitDegree((PetscFE)field, minDegree, maxDegree, &newfe));
    5261:       PetscCall(DMSetField(newdm, f, label, (PetscObject)newfe));
    5262:       PetscCall(PetscFEDestroy(&newfe));
    5263:     } else {
    5264:       PetscCall(DMSetField(newdm, f, label, field));
    5265:     }
    5266:     PetscCall(DMGetAdjacency(dm, f, &useCone, &useClosure));
    5267:     PetscCall(DMSetAdjacency(newdm, f, useCone, useClosure));
    5268:   }
    5269:   // Create nullspace constructor slots
    5270:   if (dm->nullspaceConstructors) {
    5271:     PetscCall(PetscFree2(newdm->nullspaceConstructors, newdm->nearnullspaceConstructors));
    5272:     PetscCall(PetscCalloc2(Nf, &newdm->nullspaceConstructors, Nf, &newdm->nearnullspaceConstructors));
    5273:   }
    5274:   PetscFunctionReturn(PETSC_SUCCESS);
    5275: }

    5277: /*@
    5278:   DMGetAdjacency - Returns the flags for determining variable influence

    5280:   Not Collective

    5282:   Input Parameters:
    5283: + dm - The `DM` object
    5284: - f  - The field number, or `PETSC_DEFAULT` for the default adjacency

    5286:   Output Parameters:
    5287: + useCone    - Flag for variable influence starting with the cone operation
    5288: - useClosure - Flag for variable influence using transitive closure

    5290:   Level: developer

    5292:   Notes:
    5293: .vb
    5294:      FEM:   Two points p and q are adjacent if q \in closure(star(p)),   useCone = PETSC_FALSE, useClosure = PETSC_TRUE
    5295:      FVM:   Two points p and q are adjacent if q \in support(p+cone(p)), useCone = PETSC_TRUE,  useClosure = PETSC_FALSE
    5296:      FVM++: Two points p and q are adjacent if q \in star(closure(p)),   useCone = PETSC_TRUE,  useClosure = PETSC_TRUE
    5297: .ve
    5298:   Further explanation can be found in the User's Manual Section on the Influence of Variables on One Another.

    5300: .seealso: [](ch_dmbase), `DM`, `DMSetAdjacency()`, `DMGetField()`, `DMSetField()`
    5301: @*/
    5302: PetscErrorCode DMGetAdjacency(DM dm, PetscInt f, PetscBool *useCone, PetscBool *useClosure)
    5303: {
    5304:   PetscFunctionBegin;
    5306:   if (useCone) PetscAssertPointer(useCone, 3);
    5307:   if (useClosure) PetscAssertPointer(useClosure, 4);
    5308:   if (f < 0) {
    5309:     if (useCone) *useCone = dm->adjacency[0];
    5310:     if (useClosure) *useClosure = dm->adjacency[1];
    5311:   } else {
    5312:     PetscInt Nf;

    5314:     PetscCall(DMGetNumFields(dm, &Nf));
    5315:     PetscCheck(f < Nf, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Field number %" PetscInt_FMT " must be in [0, %" PetscInt_FMT ")", f, Nf);
    5316:     if (useCone) *useCone = dm->fields[f].adjacency[0];
    5317:     if (useClosure) *useClosure = dm->fields[f].adjacency[1];
    5318:   }
    5319:   PetscFunctionReturn(PETSC_SUCCESS);
    5320: }

    5322: /*@
    5323:   DMSetAdjacency - Set the flags for determining variable influence

    5325:   Not Collective

    5327:   Input Parameters:
    5328: + dm         - The `DM` object
    5329: . f          - The field number
    5330: . useCone    - Flag for variable influence starting with the cone operation
    5331: - useClosure - Flag for variable influence using transitive closure

    5333:   Level: developer

    5335:   Notes:
    5336: .vb
    5337:      FEM:   Two points p and q are adjacent if q \in closure(star(p)),   useCone = PETSC_FALSE, useClosure = PETSC_TRUE
    5338:      FVM:   Two points p and q are adjacent if q \in support(p+cone(p)), useCone = PETSC_TRUE,  useClosure = PETSC_FALSE
    5339:      FVM++: Two points p and q are adjacent if q \in star(closure(p)),   useCone = PETSC_TRUE,  useClosure = PETSC_TRUE
    5340: .ve
    5341:   Further explanation can be found in the User's Manual Section on the Influence of Variables on One Another.

    5343: .seealso: [](ch_dmbase), `DM`, `DMGetAdjacency()`, `DMGetField()`, `DMSetField()`
    5344: @*/
    5345: PetscErrorCode DMSetAdjacency(DM dm, PetscInt f, PetscBool useCone, PetscBool useClosure)
    5346: {
    5347:   PetscFunctionBegin;
    5349:   if (f < 0) {
    5350:     dm->adjacency[0] = useCone;
    5351:     dm->adjacency[1] = useClosure;
    5352:   } else {
    5353:     PetscInt Nf;

    5355:     PetscCall(DMGetNumFields(dm, &Nf));
    5356:     PetscCheck(f < Nf, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Field number %" PetscInt_FMT " must be in [0, %" PetscInt_FMT ")", f, Nf);
    5357:     dm->fields[f].adjacency[0] = useCone;
    5358:     dm->fields[f].adjacency[1] = useClosure;
    5359:   }
    5360:   PetscFunctionReturn(PETSC_SUCCESS);
    5361: }

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

    5366:   Not collective

    5368:   Input Parameter:
    5369: . dm - The `DM` object

    5371:   Output Parameters:
    5372: + useCone    - Flag for variable influence starting with the cone operation
    5373: - useClosure - Flag for variable influence using transitive closure

    5375:   Level: developer

    5377:   Notes:
    5378: .vb
    5379:      FEM:   Two points p and q are adjacent if q \in closure(star(p)),   useCone = PETSC_FALSE, useClosure = PETSC_TRUE
    5380:      FVM:   Two points p and q are adjacent if q \in support(p+cone(p)), useCone = PETSC_TRUE,  useClosure = PETSC_FALSE
    5381:      FVM++: Two points p and q are adjacent if q \in star(closure(p)),   useCone = PETSC_TRUE,  useClosure = PETSC_TRUE
    5382: .ve

    5384: .seealso: [](ch_dmbase), `DM`, `DMSetBasicAdjacency()`, `DMGetField()`, `DMSetField()`
    5385: @*/
    5386: PetscErrorCode DMGetBasicAdjacency(DM dm, PetscBool *useCone, PetscBool *useClosure)
    5387: {
    5388:   PetscInt Nf;

    5390:   PetscFunctionBegin;
    5392:   if (useCone) PetscAssertPointer(useCone, 2);
    5393:   if (useClosure) PetscAssertPointer(useClosure, 3);
    5394:   PetscCall(DMGetNumFields(dm, &Nf));
    5395:   if (!Nf) {
    5396:     PetscCall(DMGetAdjacency(dm, PETSC_DEFAULT, useCone, useClosure));
    5397:   } else {
    5398:     PetscCall(DMGetAdjacency(dm, 0, useCone, useClosure));
    5399:   }
    5400:   PetscFunctionReturn(PETSC_SUCCESS);
    5401: }

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

    5406:   Not Collective

    5408:   Input Parameters:
    5409: + dm         - The `DM` object
    5410: . useCone    - Flag for variable influence starting with the cone operation
    5411: - useClosure - Flag for variable influence using transitive closure

    5413:   Level: developer

    5415:   Notes:
    5416: .vb
    5417:      FEM:   Two points p and q are adjacent if q \in closure(star(p)),   useCone = PETSC_FALSE, useClosure = PETSC_TRUE
    5418:      FVM:   Two points p and q are adjacent if q \in support(p+cone(p)), useCone = PETSC_TRUE,  useClosure = PETSC_FALSE
    5419:      FVM++: Two points p and q are adjacent if q \in star(closure(p)),   useCone = PETSC_TRUE,  useClosure = PETSC_TRUE
    5420: .ve

    5422: .seealso: [](ch_dmbase), `DM`, `DMGetBasicAdjacency()`, `DMGetField()`, `DMSetField()`
    5423: @*/
    5424: PetscErrorCode DMSetBasicAdjacency(DM dm, PetscBool useCone, PetscBool useClosure)
    5425: {
    5426:   PetscInt Nf;

    5428:   PetscFunctionBegin;
    5430:   PetscCall(DMGetNumFields(dm, &Nf));
    5431:   if (!Nf) {
    5432:     PetscCall(DMSetAdjacency(dm, PETSC_DEFAULT, useCone, useClosure));
    5433:   } else {
    5434:     PetscCall(DMSetAdjacency(dm, 0, useCone, useClosure));
    5435:   }
    5436:   PetscFunctionReturn(PETSC_SUCCESS);
    5437: }

    5439: PetscErrorCode DMCompleteBCLabels_Internal(DM dm)
    5440: {
    5441:   DM           plex;
    5442:   DMLabel     *labels, *glabels;
    5443:   const char **names;
    5444:   char        *sendNames, *recvNames;
    5445:   PetscInt     Nds, s, maxLabels = 0, maxLen = 0, gmaxLen, Nl = 0, gNl, l, gl, m;
    5446:   size_t       len;
    5447:   MPI_Comm     comm;
    5448:   PetscMPIInt  rank, size, p, *counts, *displs;

    5450:   PetscFunctionBegin;
    5451:   PetscCall(PetscObjectGetComm((PetscObject)dm, &comm));
    5452:   PetscCallMPI(MPI_Comm_size(comm, &size));
    5453:   PetscCallMPI(MPI_Comm_rank(comm, &rank));
    5454:   PetscCall(DMGetNumDS(dm, &Nds));
    5455:   for (s = 0; s < Nds; ++s) {
    5456:     PetscDS  dsBC;
    5457:     PetscInt numBd;

    5459:     PetscCall(DMGetRegionNumDS(dm, s, NULL, NULL, &dsBC, NULL));
    5460:     PetscCall(PetscDSGetNumBoundary(dsBC, &numBd));
    5461:     maxLabels += numBd;
    5462:   }
    5463:   PetscCall(PetscCalloc1(maxLabels, &labels));
    5464:   /* Get list of labels to be completed */
    5465:   for (s = 0; s < Nds; ++s) {
    5466:     PetscDS  dsBC;
    5467:     PetscInt numBd, bd;

    5469:     PetscCall(DMGetRegionNumDS(dm, s, NULL, NULL, &dsBC, NULL));
    5470:     PetscCall(PetscDSGetNumBoundary(dsBC, &numBd));
    5471:     for (bd = 0; bd < numBd; ++bd) {
    5472:       DMLabel      label;
    5473:       PetscInt     field;
    5474:       PetscObject  obj;
    5475:       PetscClassId id;

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

    5527: static PetscErrorCode DMDSEnlarge_Static(DM dm, PetscInt NdsNew)
    5528: {
    5529:   DMSpace *tmpd;
    5530:   PetscInt Nds = dm->Nds, s;

    5532:   PetscFunctionBegin;
    5533:   if (Nds >= NdsNew) PetscFunctionReturn(PETSC_SUCCESS);
    5534:   PetscCall(PetscMalloc1(NdsNew, &tmpd));
    5535:   for (s = 0; s < Nds; ++s) tmpd[s] = dm->probs[s];
    5536:   for (s = Nds; s < NdsNew; ++s) {
    5537:     tmpd[s].ds     = NULL;
    5538:     tmpd[s].label  = NULL;
    5539:     tmpd[s].fields = NULL;
    5540:   }
    5541:   PetscCall(PetscFree(dm->probs));
    5542:   dm->Nds   = NdsNew;
    5543:   dm->probs = tmpd;
    5544:   PetscFunctionReturn(PETSC_SUCCESS);
    5545: }

    5547: /*@
    5548:   DMGetNumDS - Get the number of discrete systems in the `DM`

    5550:   Not Collective

    5552:   Input Parameter:
    5553: . dm - The `DM`

    5555:   Output Parameter:
    5556: . Nds - The number of `PetscDS` objects

    5558:   Level: intermediate

    5560: .seealso: [](ch_dmbase), `DM`, `DMGetDS()`, `DMGetCellDS()`
    5561: @*/
    5562: PetscErrorCode DMGetNumDS(DM dm, PetscInt *Nds)
    5563: {
    5564:   PetscFunctionBegin;
    5566:   PetscAssertPointer(Nds, 2);
    5567:   *Nds = dm->Nds;
    5568:   PetscFunctionReturn(PETSC_SUCCESS);
    5569: }

    5571: /*@
    5572:   DMClearDS - Remove all discrete systems from the `DM`

    5574:   Logically Collective

    5576:   Input Parameter:
    5577: . dm - The `DM`

    5579:   Level: intermediate

    5581: .seealso: [](ch_dmbase), `DM`, `DMGetNumDS()`, `DMGetDS()`, `DMSetField()`
    5582: @*/
    5583: PetscErrorCode DMClearDS(DM dm)
    5584: {
    5585:   PetscInt s;

    5587:   PetscFunctionBegin;
    5589:   for (s = 0; s < dm->Nds; ++s) {
    5590:     PetscCall(PetscDSDestroy(&dm->probs[s].ds));
    5591:     PetscCall(PetscDSDestroy(&dm->probs[s].dsIn));
    5592:     PetscCall(DMLabelDestroy(&dm->probs[s].label));
    5593:     PetscCall(ISDestroy(&dm->probs[s].fields));
    5594:   }
    5595:   PetscCall(PetscFree(dm->probs));
    5596:   dm->probs = NULL;
    5597:   dm->Nds   = 0;
    5598:   PetscFunctionReturn(PETSC_SUCCESS);
    5599: }

    5601: /*@
    5602:   DMGetDS - Get the default `PetscDS`

    5604:   Not Collective

    5606:   Input Parameter:
    5607: . dm - The `DM`

    5609:   Output Parameter:
    5610: . ds - The default `PetscDS`

    5612:   Level: intermediate

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

    5617: .seealso: [](ch_dmbase), `DM`, `DMGetCellDS()`, `DMGetRegionDS()`
    5618: @*/
    5619: PetscErrorCode DMGetDS(DM dm, PetscDS *ds)
    5620: {
    5621:   PetscFunctionBeginHot;
    5623:   PetscAssertPointer(ds, 2);
    5624:   PetscCheck(dm->Nds > 0, PetscObjectComm((PetscObject)dm), PETSC_ERR_ARG_WRONGSTATE, "Need to call DMCreateDS() before calling DMGetDS()");
    5625:   *ds = dm->probs[0].ds;
    5626:   PetscFunctionReturn(PETSC_SUCCESS);
    5627: }

    5629: /*@
    5630:   DMGetCellDS - Get the `PetscDS` defined on a given cell

    5632:   Not Collective

    5634:   Input Parameters:
    5635: + dm    - The `DM`
    5636: - point - Cell for the `PetscDS`

    5638:   Output Parameters:
    5639: + ds   - The `PetscDS` defined on the given cell
    5640: - dsIn - The `PetscDS` for input on the given cell, or `NULL` if the same ds

    5642:   Level: developer

    5644: .seealso: [](ch_dmbase), `DM`, `DMGetDS()`, `DMSetRegionDS()`
    5645: @*/
    5646: PetscErrorCode DMGetCellDS(DM dm, PetscInt point, PetscDS *ds, PetscDS *dsIn)
    5647: {
    5648:   PetscDS  dsDef = NULL;
    5649:   PetscInt s;

    5651:   PetscFunctionBeginHot;
    5653:   if (ds) PetscAssertPointer(ds, 3);
    5654:   if (dsIn) PetscAssertPointer(dsIn, 4);
    5655:   PetscCheck(point >= 0, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Mesh point cannot be negative: %" PetscInt_FMT, point);
    5656:   if (ds) *ds = NULL;
    5657:   if (dsIn) *dsIn = NULL;
    5658:   for (s = 0; s < dm->Nds; ++s) {
    5659:     PetscInt val;

    5661:     if (!dm->probs[s].label) {
    5662:       dsDef = dm->probs[s].ds;
    5663:     } else {
    5664:       PetscCall(DMLabelGetValue(dm->probs[s].label, point, &val));
    5665:       if (val >= 0) {
    5666:         if (ds) *ds = dm->probs[s].ds;
    5667:         if (dsIn) *dsIn = dm->probs[s].dsIn;
    5668:         break;
    5669:       }
    5670:     }
    5671:   }
    5672:   if (ds && !*ds) *ds = dsDef;
    5673:   PetscFunctionReturn(PETSC_SUCCESS);
    5674: }

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

    5679:   Not Collective

    5681:   Input Parameters:
    5682: + dm    - The `DM`
    5683: - label - The `DMLabel` defining the mesh region, or `NULL` for the entire mesh

    5685:   Output Parameters:
    5686: + fields - The `IS` containing the `DM` field numbers for the fields in this `PetscDS`, or `NULL`
    5687: . ds     - The `PetscDS` defined on the given region, or `NULL`
    5688: - dsIn   - The `PetscDS` for input in the given region, or `NULL`

    5690:   Level: advanced

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

    5697: .seealso: [](ch_dmbase), `DM`, `DMGetRegionNumDS()`, `DMSetRegionDS()`, `DMGetDS()`, `DMGetCellDS()`
    5698: @*/
    5699: PetscErrorCode DMGetRegionDS(DM dm, DMLabel label, IS *fields, PetscDS *ds, PetscDS *dsIn)
    5700: {
    5701:   PetscInt Nds = dm->Nds, s;

    5703:   PetscFunctionBegin;
    5706:   if (fields) {
    5707:     PetscAssertPointer(fields, 3);
    5708:     *fields = NULL;
    5709:   }
    5710:   if (ds) {
    5711:     PetscAssertPointer(ds, 4);
    5712:     *ds = NULL;
    5713:   }
    5714:   if (dsIn) {
    5715:     PetscAssertPointer(dsIn, 5);
    5716:     *dsIn = NULL;
    5717:   }
    5718:   for (s = 0; s < Nds; ++s) {
    5719:     if (dm->probs[s].label == label || !dm->probs[s].label) {
    5720:       if (fields) *fields = dm->probs[s].fields;
    5721:       if (ds) *ds = dm->probs[s].ds;
    5722:       if (dsIn) *dsIn = dm->probs[s].dsIn;
    5723:       if (dm->probs[s].label) PetscFunctionReturn(PETSC_SUCCESS);
    5724:     }
    5725:   }
    5726:   PetscFunctionReturn(PETSC_SUCCESS);
    5727: }

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

    5732:   Collective

    5734:   Input Parameters:
    5735: + dm     - The `DM`
    5736: . label  - The `DMLabel` defining the mesh region, or `NULL` for the entire mesh
    5737: . fields - The `IS` containing the `DM` field numbers for the fields in this `PetscDS`, or `NULL` for all fields
    5738: . ds     - The `PetscDS` defined on the given region
    5739: - dsIn   - The `PetscDS` for input on the given cell, or `NULL` if it is the same `PetscDS`

    5741:   Level: advanced

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

    5747: .seealso: [](ch_dmbase), `DM`, `DMGetRegionDS()`, `DMSetRegionNumDS()`, `DMGetDS()`, `DMGetCellDS()`
    5748: @*/
    5749: PetscErrorCode DMSetRegionDS(DM dm, DMLabel label, IS fields, PetscDS ds, PetscDS dsIn)
    5750: {
    5751:   PetscInt Nds = dm->Nds, s;

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

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

    5788:   Not Collective

    5790:   Input Parameters:
    5791: + dm  - The `DM`
    5792: - num - The region number, in [0, Nds)

    5794:   Output Parameters:
    5795: + label  - The region label, or `NULL`
    5796: . fields - The `IS` containing the `DM` field numbers for the fields in this `PetscDS`, or `NULL`
    5797: . ds     - The `PetscDS` defined on the given region, or `NULL`
    5798: - dsIn   - The `PetscDS` for input in the given region, or `NULL`

    5800:   Level: advanced

    5802: .seealso: [](ch_dmbase), `DM`, `DMGetRegionDS()`, `DMSetRegionDS()`, `DMGetDS()`, `DMGetCellDS()`
    5803: @*/
    5804: PetscErrorCode DMGetRegionNumDS(DM dm, PetscInt num, DMLabel *label, IS *fields, PetscDS *ds, PetscDS *dsIn)
    5805: {
    5806:   PetscInt Nds;

    5808:   PetscFunctionBegin;
    5810:   PetscCall(DMGetNumDS(dm, &Nds));
    5811:   PetscCheck((num >= 0) && (num < Nds), PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Region number %" PetscInt_FMT " is not in [0, %" PetscInt_FMT ")", num, Nds);
    5812:   if (label) {
    5813:     PetscAssertPointer(label, 3);
    5814:     *label = dm->probs[num].label;
    5815:   }
    5816:   if (fields) {
    5817:     PetscAssertPointer(fields, 4);
    5818:     *fields = dm->probs[num].fields;
    5819:   }
    5820:   if (ds) {
    5821:     PetscAssertPointer(ds, 5);
    5822:     *ds = dm->probs[num].ds;
    5823:   }
    5824:   if (dsIn) {
    5825:     PetscAssertPointer(dsIn, 6);
    5826:     *dsIn = dm->probs[num].dsIn;
    5827:   }
    5828:   PetscFunctionReturn(PETSC_SUCCESS);
    5829: }

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

    5834:   Not Collective

    5836:   Input Parameters:
    5837: + dm     - The `DM`
    5838: . num    - The region number, in [0, Nds)
    5839: . label  - The region label, or `NULL`
    5840: . fields - The `IS` containing the `DM` field numbers for the fields in this `PetscDS`, or `NULL` to prevent setting
    5841: . ds     - The `PetscDS` defined on the given region, or `NULL` to prevent setting
    5842: - dsIn   - The `PetscDS` for input on the given cell, or `NULL` if it is the same `PetscDS`

    5844:   Level: advanced

    5846: .seealso: [](ch_dmbase), `DM`, `DMGetRegionDS()`, `DMSetRegionDS()`, `DMGetDS()`, `DMGetCellDS()`
    5847: @*/
    5848: PetscErrorCode DMSetRegionNumDS(DM dm, PetscInt num, DMLabel label, IS fields, PetscDS ds, PetscDS dsIn)
    5849: {
    5850:   PetscInt Nds;

    5852:   PetscFunctionBegin;
    5855:   PetscCall(DMGetNumDS(dm, &Nds));
    5856:   PetscCheck((num >= 0) && (num < Nds), PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Region number %" PetscInt_FMT " is not in [0, %" PetscInt_FMT ")", num, Nds);
    5857:   PetscCall(PetscObjectReference((PetscObject)label));
    5858:   PetscCall(DMLabelDestroy(&dm->probs[num].label));
    5859:   dm->probs[num].label = label;
    5860:   if (fields) {
    5862:     PetscCall(PetscObjectReference((PetscObject)fields));
    5863:     PetscCall(ISDestroy(&dm->probs[num].fields));
    5864:     dm->probs[num].fields = fields;
    5865:   }
    5866:   if (ds) {
    5868:     PetscCall(PetscObjectReference((PetscObject)ds));
    5869:     PetscCall(PetscDSDestroy(&dm->probs[num].ds));
    5870:     dm->probs[num].ds = ds;
    5871:   }
    5872:   if (dsIn) {
    5874:     PetscCall(PetscObjectReference((PetscObject)dsIn));
    5875:     PetscCall(PetscDSDestroy(&dm->probs[num].dsIn));
    5876:     dm->probs[num].dsIn = dsIn;
    5877:   }
    5878:   PetscFunctionReturn(PETSC_SUCCESS);
    5879: }

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

    5884:   Not Collective

    5886:   Input Parameters:
    5887: + dm - The `DM`
    5888: - ds - The `PetscDS` defined on the given region

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

    5893:   Level: advanced

    5895: .seealso: [](ch_dmbase), `DM`, `DMGetRegionNumDS()`, `DMGetRegionDS()`, `DMSetRegionDS()`, `DMGetDS()`, `DMGetCellDS()`
    5896: @*/
    5897: PetscErrorCode DMFindRegionNum(DM dm, PetscDS ds, PetscInt *num)
    5898: {
    5899:   PetscInt Nds, n;

    5901:   PetscFunctionBegin;
    5904:   PetscAssertPointer(num, 3);
    5905:   PetscCall(DMGetNumDS(dm, &Nds));
    5906:   for (n = 0; n < Nds; ++n)
    5907:     if (ds == dm->probs[n].ds) break;
    5908:   if (n >= Nds) *num = -1;
    5909:   else *num = n;
    5910:   PetscFunctionReturn(PETSC_SUCCESS);
    5911: }

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

    5916:   Not Collective

    5918:   Input Parameters:
    5919: + dm     - The `DM`
    5920: . Nc     - The number of components for the field
    5921: . prefix - The options prefix for the output `PetscFE`, or `NULL`
    5922: - qorder - The quadrature order or `PETSC_DETERMINE` to use `PetscSpace` polynomial degree

    5924:   Output Parameter:
    5925: . fem - The `PetscFE`

    5927:   Level: intermediate

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

    5932: .seealso: [](ch_dmbase), `DM`, `PetscFECreateByCell()`, `DMAddField()`, `DMCreateDS()`, `DMGetCellDS()`, `DMGetRegionDS()`
    5933: @*/
    5934: PetscErrorCode DMCreateFEDefault(DM dm, PetscInt Nc, const char prefix[], PetscInt qorder, PetscFE *fem)
    5935: {
    5936:   DMPolytopeType ct;
    5937:   PetscInt       dim, cStart;

    5939:   PetscFunctionBegin;
    5942:   if (prefix) PetscAssertPointer(prefix, 3);
    5944:   PetscAssertPointer(fem, 5);
    5945:   PetscCall(DMGetDimension(dm, &dim));
    5946:   PetscCall(DMPlexGetHeightStratum(dm, 0, &cStart, NULL));
    5947:   PetscCall(DMPlexGetCellType(dm, cStart, &ct));
    5948:   PetscCall(PetscFECreateByCell(PETSC_COMM_SELF, dim, Nc, ct, prefix, qorder, fem));
    5949:   PetscFunctionReturn(PETSC_SUCCESS);
    5950: }

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

    5955:   Collective

    5957:   Input Parameter:
    5958: . dm - The `DM`

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

    5963:   Level: intermediate

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

    5968: .seealso: [](ch_dmbase), `DM`, `DMSetField`, `DMAddField()`, `DMGetDS()`, `DMGetCellDS()`, `DMGetRegionDS()`, `DMSetRegionDS()`
    5969: @*/
    5970: PetscErrorCode DMCreateDS(DM dm)
    5971: {
    5972:   MPI_Comm  comm;
    5973:   PetscDS   dsDef;
    5974:   DMLabel  *labelSet;
    5975:   PetscInt  dE, Nf = dm->Nf, f, s, Nl, l, Ndef, k;
    5976:   PetscBool doSetup = PETSC_TRUE, flg;

    5978:   PetscFunctionBegin;
    5980:   if (!dm->fields) PetscFunctionReturn(PETSC_SUCCESS);
    5981:   PetscCall(PetscObjectGetComm((PetscObject)dm, &comm));
    5982:   PetscCall(DMGetCoordinateDim(dm, &dE));
    5983:   // Create nullspace constructor slots
    5984:   PetscCall(PetscFree2(dm->nullspaceConstructors, dm->nearnullspaceConstructors));
    5985:   PetscCall(PetscCalloc2(Nf, &dm->nullspaceConstructors, Nf, &dm->nearnullspaceConstructors));
    5986:   /* Determine how many regions we have */
    5987:   PetscCall(PetscMalloc1(Nf, &labelSet));
    5988:   Nl   = 0;
    5989:   Ndef = 0;
    5990:   for (f = 0; f < Nf; ++f) {
    5991:     DMLabel  label = dm->fields[f].label;
    5992:     PetscInt l;

    5994: #ifdef PETSC_HAVE_LIBCEED
    5995:     /* Move CEED context to discretizations */
    5996:     {
    5997:       PetscClassId id;

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

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

    6023:     for (f = 0, nf = 0; f < Nf; ++f)
    6024:       if (!dm->fields[f].label) ++nf;
    6025:     PetscCheck(nf, comm, PETSC_ERR_PLIB, "All fields have labels, but we are trying to create a default DS");
    6026:     PetscCall(PetscMalloc1(nf, &fld));
    6027:     for (f = 0, nf = 0; f < Nf; ++f)
    6028:       if (!dm->fields[f].label) fld[nf++] = f;
    6029:     PetscCall(ISCreate(PETSC_COMM_SELF, &fields));
    6030:     PetscCall(PetscObjectSetOptionsPrefix((PetscObject)fields, "dm_fields_"));
    6031:     PetscCall(ISSetType(fields, ISGENERAL));
    6032:     PetscCall(ISGeneralSetIndices(fields, nf, fld, PETSC_OWN_POINTER));

    6034:     PetscCall(PetscDSCreate(PETSC_COMM_SELF, &dsDef));
    6035:     PetscCall(DMSetRegionDS(dm, NULL, fields, dsDef, NULL));
    6036:     PetscCall(PetscDSDestroy(&dsDef));
    6037:     PetscCall(ISDestroy(&fields));
    6038:   }
    6039:   PetscCall(DMGetRegionDS(dm, NULL, NULL, &dsDef, NULL));
    6040:   if (dsDef) PetscCall(PetscDSSetCoordinateDimension(dsDef, dE));
    6041:   /* Intersect labels with default fields */
    6042:   if (Ndef && Nl) {
    6043:     DM              plex;
    6044:     DMLabel         cellLabel;
    6045:     IS              fieldIS, allcellIS, defcellIS = NULL;
    6046:     PetscInt       *fields;
    6047:     const PetscInt *cells;
    6048:     PetscInt        depth, nf = 0, n, c;

    6050:     PetscCall(DMConvert(dm, DMPLEX, &plex));
    6051:     PetscCall(DMPlexGetDepth(plex, &depth));
    6052:     PetscCall(DMGetStratumIS(plex, "dim", depth, &allcellIS));
    6053:     if (!allcellIS) PetscCall(DMGetStratumIS(plex, "depth", depth, &allcellIS));
    6054:     /* TODO This looks like it only works for one label */
    6055:     for (l = 0; l < Nl; ++l) {
    6056:       DMLabel label = labelSet[l];
    6057:       IS      pointIS;

    6059:       PetscCall(ISDestroy(&defcellIS));
    6060:       PetscCall(DMLabelGetStratumIS(label, 1, &pointIS));
    6061:       PetscCall(ISDifference(allcellIS, pointIS, &defcellIS));
    6062:       PetscCall(ISDestroy(&pointIS));
    6063:     }
    6064:     PetscCall(ISDestroy(&allcellIS));

    6066:     PetscCall(DMLabelCreate(PETSC_COMM_SELF, "defaultCells", &cellLabel));
    6067:     PetscCall(ISGetLocalSize(defcellIS, &n));
    6068:     PetscCall(ISGetIndices(defcellIS, &cells));
    6069:     for (c = 0; c < n; ++c) PetscCall(DMLabelSetValue(cellLabel, cells[c], 1));
    6070:     PetscCall(ISRestoreIndices(defcellIS, &cells));
    6071:     PetscCall(ISDestroy(&defcellIS));
    6072:     PetscCall(DMPlexLabelComplete(plex, cellLabel));

    6074:     PetscCall(PetscMalloc1(Ndef, &fields));
    6075:     for (f = 0; f < Nf; ++f)
    6076:       if (!dm->fields[f].label) fields[nf++] = f;
    6077:     PetscCall(ISCreate(PETSC_COMM_SELF, &fieldIS));
    6078:     PetscCall(PetscObjectSetOptionsPrefix((PetscObject)fieldIS, "dm_fields_"));
    6079:     PetscCall(ISSetType(fieldIS, ISGENERAL));
    6080:     PetscCall(ISGeneralSetIndices(fieldIS, nf, fields, PETSC_OWN_POINTER));

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

    6100:     PetscCall(PetscDSCreate(PETSC_COMM_SELF, &ds));
    6101:     for (f = 0, nf = 0; f < Nf; ++f)
    6102:       if (label == dm->fields[f].label || !dm->fields[f].label) ++nf;
    6103:     PetscCall(PetscMalloc1(nf, &fld));
    6104:     for (f = 0, nf = 0; f < Nf; ++f)
    6105:       if (label == dm->fields[f].label || !dm->fields[f].label) fld[nf++] = f;
    6106:     PetscCall(ISCreate(PETSC_COMM_SELF, &fields));
    6107:     PetscCall(PetscObjectSetOptionsPrefix((PetscObject)fields, "dm_fields_"));
    6108:     PetscCall(ISSetType(fields, ISGENERAL));
    6109:     PetscCall(ISGeneralSetIndices(fields, nf, fld, PETSC_OWN_POINTER));
    6110:     PetscCall(PetscDSSetCoordinateDimension(ds, dE));
    6111:     {
    6112:       DMPolytopeType ct;
    6113:       PetscInt       lStart, lEnd;
    6114:       PetscBool      isCohesiveLocal = PETSC_FALSE, isCohesive;

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

    6164:     PetscCall(PetscDSGetNumFields(ds, &dsnf));
    6165:     PetscCall(PetscDSIsCohesive(ds, &isCohesive));
    6166:     PetscCall(ISGetLocalSize(fields, &nf));
    6167:     PetscCall(ISGetIndices(fields, &fld));
    6168:     for (f = 0; f < nf; ++f) {
    6169:       PetscObject  disc = dm->fields[fld[f]].disc;
    6170:       PetscBool    isCohesiveField;
    6171:       PetscClassId id;

    6173:       /* Handle DS with no fields */
    6174:       if (dsnf) PetscCall(PetscDSGetCohesive(ds, f, &isCohesiveField));
    6175:       /* If this is a cohesive cell, then regular fields need the lower dimensional discretization */
    6176:       if (isCohesive) {
    6177:         if (!isCohesiveField) {
    6178:           PetscObject bdDisc;

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

    6204:       PetscCall(PetscDSGetNumFields(ds, &Nf));
    6205:       for (f = 0; f < Nf; ++f) {
    6206:         PetscCall(PetscDSSetJetDegree(ds, f, k));
    6207:         if (dsIn) PetscCall(PetscDSSetJetDegree(dsIn, f, k));
    6208:       }
    6209:     }
    6210:   }
    6211:   /* Setup DSes */
    6212:   if (doSetup) {
    6213:     for (s = 0; s < dm->Nds; ++s) {
    6214:       if (dm->setfromoptionscalled) {
    6215:         PetscCall(PetscDSSetFromOptions(dm->probs[s].ds));
    6216:         if (dm->probs[s].dsIn) PetscCall(PetscDSSetFromOptions(dm->probs[s].dsIn));
    6217:       }
    6218:       PetscCall(PetscDSSetUp(dm->probs[s].ds));
    6219:       if (dm->probs[s].dsIn) PetscCall(PetscDSSetUp(dm->probs[s].dsIn));
    6220:     }
    6221:   }
    6222:   PetscFunctionReturn(PETSC_SUCCESS);
    6223: }

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

    6228:   Input Parameters:
    6229: + dm     - The DM
    6230: - tensor - Flag for tensor order

    6232:   Level: developer

    6234: .seealso: `DMPlexSetClosurePermutationTensor()`, `PetscSectionResetClosurePermutation()`
    6235: @*/
    6236: PetscErrorCode DMUseTensorOrder(DM dm, PetscBool tensor)
    6237: {
    6238:   PetscInt  Nf;
    6239:   PetscBool reorder = PETSC_TRUE, isPlex;

    6241:   PetscFunctionBegin;
    6242:   PetscCall(PetscObjectTypeCompare((PetscObject)dm, DMPLEX, &isPlex));
    6243:   PetscCall(DMGetNumFields(dm, &Nf));
    6244:   for (PetscInt f = 0; f < Nf; ++f) {
    6245:     PetscObject  obj;
    6246:     PetscClassId id;

    6248:     PetscCall(DMGetField(dm, f, NULL, &obj));
    6249:     PetscCall(PetscObjectGetClassId(obj, &id));
    6250:     if (id == PETSCFE_CLASSID) {
    6251:       PetscSpace sp;
    6252:       PetscBool  tensor;

    6254:       PetscCall(PetscFEGetBasisSpace((PetscFE)obj, &sp));
    6255:       PetscCall(PetscSpacePolynomialGetTensor(sp, &tensor));
    6256:       reorder = reorder && tensor ? PETSC_TRUE : PETSC_FALSE;
    6257:     } else reorder = PETSC_FALSE;
    6258:   }
    6259:   if (tensor) {
    6260:     if (reorder && isPlex) PetscCall(DMPlexSetClosurePermutationTensor(dm, PETSC_DETERMINE, NULL));
    6261:   } else {
    6262:     PetscSection s;

    6264:     PetscCall(DMGetLocalSection(dm, &s));
    6265:     if (s) PetscCall(PetscSectionResetClosurePermutation(s));
    6266:   }
    6267:   PetscFunctionReturn(PETSC_SUCCESS);
    6268: }

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

    6273:   Collective

    6275:   Input Parameters:
    6276: + dm   - The `DM`
    6277: - time - The time

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

    6283:   Level: developer

    6285:   Note:
    6286:   The user must call `PetscDSSetExactSolution()` before using this routine

    6288: .seealso: [](ch_dmbase), `DM`, `PetscDSSetExactSolution()`
    6289: @*/
    6290: PetscErrorCode DMComputeExactSolution(DM dm, PetscReal time, Vec u, Vec u_t)
    6291: {
    6292:   PetscErrorCode (**exacts)(PetscInt, PetscReal, const PetscReal x[], PetscInt, PetscScalar *u, PetscCtx ctx);
    6293:   void   **ectxs;
    6294:   Vec      locu, locu_t;
    6295:   PetscInt Nf, Nds, s;

    6297:   PetscFunctionBegin;
    6299:   if (u) {
    6301:     PetscCall(DMGetLocalVector(dm, &locu));
    6302:     PetscCall(VecSet(locu, 0.));
    6303:   }
    6304:   if (u_t) {
    6306:     PetscCall(DMGetLocalVector(dm, &locu_t));
    6307:     PetscCall(VecSet(locu_t, 0.));
    6308:   }
    6309:   PetscCall(DMGetNumFields(dm, &Nf));
    6310:   PetscCall(PetscMalloc2(Nf, &exacts, Nf, &ectxs));
    6311:   PetscCall(DMGetNumDS(dm, &Nds));
    6312:   for (s = 0; s < Nds; ++s) {
    6313:     PetscDS         ds;
    6314:     DMLabel         label;
    6315:     IS              fieldIS;
    6316:     const PetscInt *fields, id = 1;
    6317:     PetscInt        dsNf, f;

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

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

    6364:   PetscFunctionBegin;
    6365:   PetscCall(PetscDSCreate(PetscObjectComm((PetscObject)ds), &dsNew));
    6366:   PetscCall(PetscDSCopy(ds, minDegree, maxDegree, dm, dsNew));
    6367:   if (dsIn) {
    6368:     PetscCall(PetscDSCreate(PetscObjectComm((PetscObject)dsIn), &dsInNew));
    6369:     PetscCall(PetscDSCopy(dsIn, minDegree, maxDegree, dm, dsInNew));
    6370:   }
    6371:   PetscCall(DMSetRegionDS(dm, label, fields, dsNew, dsInNew));
    6372:   PetscCall(PetscDSDestroy(&dsNew));
    6373:   PetscCall(PetscDSDestroy(&dsInNew));
    6374:   PetscFunctionReturn(PETSC_SUCCESS);
    6375: }

    6377: /*@
    6378:   DMCopyDS - Copy the discrete systems for the `DM` into another `DM`

    6380:   Collective

    6382:   Input Parameters:
    6383: + dm        - The `DM`
    6384: . minDegree - Minimum degree for a discretization, or `PETSC_DETERMINE` for no limit
    6385: - maxDegree - Maximum degree for a discretization, or `PETSC_DETERMINE` for no limit

    6387:   Output Parameter:
    6388: . newdm - The `DM`

    6390:   Level: advanced

    6392: .seealso: [](ch_dmbase), `DM`, `DMCopyFields()`, `DMAddField()`, `DMGetDS()`, `DMGetCellDS()`, `DMGetRegionDS()`, `DMSetRegionDS()`
    6393: @*/
    6394: PetscErrorCode DMCopyDS(DM dm, PetscInt minDegree, PetscInt maxDegree, DM newdm)
    6395: {
    6396:   PetscInt Nds, s;

    6398:   PetscFunctionBegin;
    6399:   if (dm == newdm) PetscFunctionReturn(PETSC_SUCCESS);
    6400:   PetscCall(DMGetNumDS(dm, &Nds));
    6401:   PetscCall(DMClearDS(newdm));
    6402:   for (s = 0; s < Nds; ++s) {
    6403:     DMLabel  label;
    6404:     IS       fields;
    6405:     PetscDS  ds, dsIn, newds;
    6406:     PetscInt Nbd, bd;

    6408:     PetscCall(DMGetRegionNumDS(dm, s, &label, &fields, &ds, &dsIn));
    6409:     /* TODO: We need to change all keys from labels in the old DM to labels in the new DM */
    6410:     PetscCall(DMTransferDS_Internal(newdm, label, fields, minDegree, maxDegree, ds, dsIn));
    6411:     /* Complete new labels in the new DS */
    6412:     PetscCall(DMGetRegionDS(newdm, label, NULL, &newds, NULL));
    6413:     PetscCall(PetscDSGetNumBoundary(newds, &Nbd));
    6414:     for (bd = 0; bd < Nbd; ++bd) {
    6415:       PetscWeakForm wf;
    6416:       DMLabel       label;
    6417:       PetscInt      field;

    6419:       PetscCall(PetscDSGetBoundary(newds, bd, &wf, NULL, NULL, &label, NULL, NULL, &field, NULL, NULL, NULL, NULL, NULL));
    6420:       PetscCall(PetscWeakFormReplaceLabel(wf, label));
    6421:     }
    6422:   }
    6423:   PetscCall(DMCompleteBCLabels_Internal(newdm));
    6424:   PetscFunctionReturn(PETSC_SUCCESS);
    6425: }

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

    6430:   Collective

    6432:   Input Parameter:
    6433: . dm - The `DM`

    6435:   Output Parameter:
    6436: . newdm - The `DM`

    6438:   Level: advanced

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

    6443: .seealso: [](ch_dmbase), `DM`, `DMCopyFields()`, `DMCopyDS()`
    6444: @*/
    6445: PetscErrorCode DMCopyDisc(DM dm, DM newdm)
    6446: {
    6447:   PetscFunctionBegin;
    6448:   PetscCall(DMCopyFields(dm, PETSC_DETERMINE, PETSC_DETERMINE, newdm));
    6449:   PetscCall(DMCopyDS(dm, PETSC_DETERMINE, PETSC_DETERMINE, newdm));
    6450:   PetscFunctionReturn(PETSC_SUCCESS);
    6451: }

    6453: /*@
    6454:   DMGetDimension - Return the topological dimension of the `DM`

    6456:   Not Collective

    6458:   Input Parameter:
    6459: . dm - The `DM`

    6461:   Output Parameter:
    6462: . dim - The topological dimension

    6464:   Level: beginner

    6466: .seealso: [](ch_dmbase), `DM`, `DMSetDimension()`, `DMCreate()`
    6467: @*/
    6468: PetscErrorCode DMGetDimension(DM dm, PetscInt *dim)
    6469: {
    6470:   PetscFunctionBegin;
    6472:   PetscAssertPointer(dim, 2);
    6473:   *dim = dm->dim;
    6474:   PetscFunctionReturn(PETSC_SUCCESS);
    6475: }

    6477: /*@
    6478:   DMSetDimension - Set the topological dimension of the `DM`

    6480:   Collective

    6482:   Input Parameters:
    6483: + dm  - The `DM`
    6484: - dim - The topological dimension

    6486:   Level: beginner

    6488: .seealso: [](ch_dmbase), `DM`, `DMGetDimension()`, `DMCreate()`
    6489: @*/
    6490: PetscErrorCode DMSetDimension(DM dm, PetscInt dim)
    6491: {
    6492:   PetscDS  ds;
    6493:   PetscInt Nds, n;

    6495:   PetscFunctionBegin;
    6498:   if (dm->dim != dim) PetscCall(DMSetPeriodicity(dm, NULL, NULL, NULL));
    6499:   dm->dim = dim;
    6500:   if (dm->dim >= 0) {
    6501:     PetscCall(DMGetNumDS(dm, &Nds));
    6502:     for (n = 0; n < Nds; ++n) {
    6503:       PetscCall(DMGetRegionNumDS(dm, n, NULL, NULL, &ds, NULL));
    6504:       if (ds->dimEmbed < 0) PetscCall(PetscDSSetCoordinateDimension(ds, dim));
    6505:     }
    6506:   }
    6507:   PetscFunctionReturn(PETSC_SUCCESS);
    6508: }

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

    6513:   Collective

    6515:   Input Parameters:
    6516: + dm  - the `DM`
    6517: - dim - the dimension

    6519:   Output Parameters:
    6520: + pStart - The first point of the given dimension
    6521: - pEnd   - The first point following points of the given dimension

    6523:   Level: intermediate

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

    6530: .seealso: [](ch_dmbase), `DM`, `DMPLEX`, `DMPlexGetDepthStratum()`, `DMPlexGetHeightStratum()`
    6531: @*/
    6532: PetscErrorCode DMGetDimPoints(DM dm, PetscInt dim, PetscInt *pStart, PetscInt *pEnd)
    6533: {
    6534:   PetscInt d;

    6536:   PetscFunctionBegin;
    6538:   PetscCall(DMGetDimension(dm, &d));
    6539:   PetscCheck((dim >= 0) && (dim <= d), PetscObjectComm((PetscObject)dm), PETSC_ERR_ARG_OUTOFRANGE, "Invalid dimension %" PetscInt_FMT, dim);
    6540:   PetscUseTypeMethod(dm, getdimpoints, dim, pStart, pEnd);
    6541:   PetscFunctionReturn(PETSC_SUCCESS);
    6542: }

    6544: /*@
    6545:   DMGetOutputDM - Retrieve the `DM` associated with the layout for output

    6547:   Collective

    6549:   Input Parameter:
    6550: . dm - The original `DM`

    6552:   Output Parameter:
    6553: . odm - The `DM` which provides the layout for output

    6555:   Level: intermediate

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

    6562: .seealso: [](ch_dmbase), `DM`, `VecView()`, `DMGetGlobalSection()`, `DMCreateGlobalVector()`, `PetscSectionHasConstraints()`, `DMSetGlobalSection()`
    6563: @*/
    6564: PetscErrorCode DMGetOutputDM(DM dm, DM *odm)
    6565: {
    6566:   PetscSection section;
    6567:   IS           perm;
    6568:   PetscBool    hasConstraints, newDM, gnewDM;
    6569:   PetscInt     num_face_sfs = 0;

    6571:   PetscFunctionBegin;
    6573:   PetscAssertPointer(odm, 2);
    6574:   PetscCall(DMGetLocalSection(dm, &section));
    6575:   PetscCall(PetscSectionHasConstraints(section, &hasConstraints));
    6576:   PetscCall(PetscSectionGetPermutation(section, &perm));
    6577:   PetscCall(DMPlexGetIsoperiodicFaceSF(dm, &num_face_sfs, NULL));
    6578:   newDM = hasConstraints || perm || (num_face_sfs > 0) ? PETSC_TRUE : PETSC_FALSE;
    6579:   PetscCallMPI(MPIU_Allreduce(&newDM, &gnewDM, 1, MPI_C_BOOL, MPI_LOR, PetscObjectComm((PetscObject)dm)));
    6580:   if (!gnewDM) {
    6581:     *odm = dm;
    6582:     PetscFunctionReturn(PETSC_SUCCESS);
    6583:   }
    6584:   if (!dm->dmBC) {
    6585:     PetscSection newSection, gsection;
    6586:     PetscSF      sf, sfNatural;
    6587:     PetscBool    usePerm = dm->ignorePermOutput ? PETSC_FALSE : PETSC_TRUE;

    6589:     PetscCall(DMClone(dm, &dm->dmBC));
    6590:     PetscCall(DMCopyDisc(dm, dm->dmBC));
    6591:     PetscCall(PetscSectionClone(section, &newSection));
    6592:     PetscCall(DMSetLocalSection(dm->dmBC, newSection));
    6593:     PetscCall(PetscSectionDestroy(&newSection));
    6594:     PetscCall(DMGetNaturalSF(dm, &sfNatural));
    6595:     PetscCall(DMSetNaturalSF(dm->dmBC, sfNatural));
    6596:     PetscCall(DMGetPointSF(dm->dmBC, &sf));
    6597:     PetscCall(PetscSectionCreateGlobalSection(section, sf, usePerm, PETSC_TRUE, PETSC_FALSE, &gsection));
    6598:     PetscCall(DMSetGlobalSection(dm->dmBC, gsection));
    6599:     PetscCall(PetscSectionDestroy(&gsection));
    6600:   }
    6601:   *odm = dm->dmBC;
    6602:   PetscFunctionReturn(PETSC_SUCCESS);
    6603: }

    6605: /*@
    6606:   DMGetOutputSequenceNumber - Retrieve the sequence number/value for output

    6608:   Input Parameter:
    6609: . dm - The original `DM`

    6611:   Output Parameters:
    6612: + num - The output sequence number
    6613: - val - The output sequence value

    6615:   Level: intermediate

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

    6621:   Developer Note:
    6622:   The `DM` serves as a convenient place to store the current iteration value. The iteration is not
    6623:   not directly related to the `DM`.

    6625: .seealso: [](ch_dmbase), `DM`, `VecView()`
    6626: @*/
    6627: PetscErrorCode DMGetOutputSequenceNumber(DM dm, PetscInt *num, PetscReal *val)
    6628: {
    6629:   PetscFunctionBegin;
    6631:   if (num) {
    6632:     PetscAssertPointer(num, 2);
    6633:     *num = dm->outputSequenceNum;
    6634:   }
    6635:   if (val) {
    6636:     PetscAssertPointer(val, 3);
    6637:     *val = dm->outputSequenceVal;
    6638:   }
    6639:   PetscFunctionReturn(PETSC_SUCCESS);
    6640: }

    6642: /*@
    6643:   DMSetOutputSequenceNumber - Set the sequence number/value for output

    6645:   Input Parameters:
    6646: + dm  - The original `DM`
    6647: . num - The output sequence number
    6648: - val - The output sequence value

    6650:   Level: intermediate

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

    6656: .seealso: [](ch_dmbase), `DM`, `VecView()`
    6657: @*/
    6658: PetscErrorCode DMSetOutputSequenceNumber(DM dm, PetscInt num, PetscReal val)
    6659: {
    6660:   PetscFunctionBegin;
    6662:   dm->outputSequenceNum = num;
    6663:   dm->outputSequenceVal = val;
    6664:   PetscFunctionReturn(PETSC_SUCCESS);
    6665: }

    6667: /*@
    6668:   DMOutputSequenceLoad - Retrieve the sequence value from a `PetscViewer`

    6670:   Input Parameters:
    6671: + dm     - The original `DM`
    6672: . viewer - The `PetscViewer` to get it from
    6673: . name   - The sequence name
    6674: - num    - The output sequence number

    6676:   Output Parameter:
    6677: . val - The output sequence value

    6679:   Level: intermediate

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

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

    6688: .seealso: [](ch_dmbase), `DM`, `DMGetOutputSequenceNumber()`, `DMSetOutputSequenceNumber()`, `VecView()`
    6689: @*/
    6690: PetscErrorCode DMOutputSequenceLoad(DM dm, PetscViewer viewer, const char name[], PetscInt num, PetscReal *val)
    6691: {
    6692:   PetscBool ishdf5;

    6694:   PetscFunctionBegin;
    6697:   PetscAssertPointer(name, 3);
    6698:   PetscAssertPointer(val, 5);
    6699:   PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERHDF5, &ishdf5));
    6700:   PetscCheck(ishdf5, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Invalid viewer; open viewer with PetscViewerHDF5Open()");
    6701: #if defined(PETSC_HAVE_HDF5)
    6702:   PetscScalar value;

    6704:   PetscCall(DMSequenceLoad_HDF5_Internal(dm, name, num, &value, viewer));
    6705:   *val = PetscRealPart(value);
    6706: #endif
    6707:   PetscFunctionReturn(PETSC_SUCCESS);
    6708: }

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

    6713:   Input Parameters:
    6714: + dm     - The original `DM`
    6715: . viewer - The `PetscViewer` to get it from
    6716: - name   - The sequence name

    6718:   Output Parameter:
    6719: . len - The length of the output sequence

    6721:   Level: intermediate

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

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

    6730: .seealso: [](ch_dmbase), `DM`, `DMGetOutputSequenceNumber()`, `DMSetOutputSequenceNumber()`, `VecView()`
    6731: @*/
    6732: PetscErrorCode DMGetOutputSequenceLength(DM dm, PetscViewer viewer, const char name[], PetscInt *len)
    6733: {
    6734:   PetscBool ishdf5;

    6736:   PetscFunctionBegin;
    6739:   PetscAssertPointer(name, 3);
    6740:   PetscAssertPointer(len, 4);
    6741:   PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERHDF5, &ishdf5));
    6742:   PetscCheck(ishdf5, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Invalid viewer; open viewer with PetscViewerHDF5Open()");
    6743: #if defined(PETSC_HAVE_HDF5)
    6744:   PetscCall(DMSequenceGetLength_HDF5_Internal(dm, name, len, viewer));
    6745: #endif
    6746:   PetscFunctionReturn(PETSC_SUCCESS);
    6747: }

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

    6752:   Not Collective

    6754:   Input Parameter:
    6755: . dm - The `DM`

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

    6760:   Level: beginner

    6762: .seealso: [](ch_dmbase), `DM`, `DMSetUseNatural()`, `DMCreate()`
    6763: @*/
    6764: PetscErrorCode DMGetUseNatural(DM dm, PetscBool *useNatural)
    6765: {
    6766:   PetscFunctionBegin;
    6768:   PetscAssertPointer(useNatural, 2);
    6769:   *useNatural = dm->useNatural;
    6770:   PetscFunctionReturn(PETSC_SUCCESS);
    6771: }

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

    6776:   Collective

    6778:   Input Parameters:
    6779: + dm         - The `DM`
    6780: - useNatural - `PETSC_TRUE` to build the mapping to a natural order during distribution

    6782:   Level: beginner

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

    6787: .seealso: [](ch_dmbase), `DM`, `DMGetUseNatural()`, `DMCreate()`, `DMPlexDistribute()`, `DMCreateSubDM()`, `DMCreateSuperDM()`
    6788: @*/
    6789: PetscErrorCode DMSetUseNatural(DM dm, PetscBool useNatural)
    6790: {
    6791:   PetscFunctionBegin;
    6794:   dm->useNatural = useNatural;
    6795:   PetscFunctionReturn(PETSC_SUCCESS);
    6796: }

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

    6801:   Not Collective

    6803:   Input Parameters:
    6804: + dm   - The `DM` object
    6805: - name - The label name

    6807:   Level: intermediate

    6809: .seealso: [](ch_dmbase), `DM`, `DMLabelCreate()`, `DMHasLabel()`, `DMGetLabelValue()`, `DMSetLabelValue()`, `DMGetStratumIS()`
    6810: @*/
    6811: PetscErrorCode DMCreateLabel(DM dm, const char name[])
    6812: {
    6813:   PetscBool flg;
    6814:   DMLabel   label;

    6816:   PetscFunctionBegin;
    6818:   PetscAssertPointer(name, 2);
    6819:   PetscCall(DMHasLabel(dm, name, &flg));
    6820:   if (!flg) {
    6821:     PetscCall(DMLabelCreate(PETSC_COMM_SELF, name, &label));
    6822:     PetscCall(DMAddLabel(dm, label));
    6823:     PetscCall(DMLabelDestroy(&label));
    6824:   }
    6825:   PetscFunctionReturn(PETSC_SUCCESS);
    6826: }

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

    6831:   Not Collective

    6833:   Input Parameters:
    6834: + dm   - The `DM` object
    6835: . l    - The index for the label
    6836: - name - The label name

    6838:   Level: intermediate

    6840: .seealso: [](ch_dmbase), `DM`, `DMCreateLabel()`, `DMLabelCreate()`, `DMHasLabel()`, `DMGetLabelValue()`, `DMSetLabelValue()`, `DMGetStratumIS()`
    6841: @*/
    6842: PetscErrorCode DMCreateLabelAtIndex(DM dm, PetscInt l, const char name[])
    6843: {
    6844:   DMLabelLink orig, prev = NULL;
    6845:   DMLabel     label;
    6846:   PetscInt    Nl, m;
    6847:   PetscBool   flg, match;
    6848:   const char *lname;

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

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

    6883:   Not Collective

    6885:   Input Parameters:
    6886: + dm    - The `DM` object
    6887: . name  - The label name
    6888: - point - The mesh point

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

    6893:   Level: beginner

    6895: .seealso: [](ch_dmbase), `DM`, `DMLabelGetValue()`, `DMSetLabelValue()`, `DMGetStratumIS()`
    6896: @*/
    6897: PetscErrorCode DMGetLabelValue(DM dm, const char name[], PetscInt point, PetscInt *value)
    6898: {
    6899:   DMLabel label;

    6901:   PetscFunctionBegin;
    6903:   PetscAssertPointer(name, 2);
    6904:   PetscCall(DMGetLabel(dm, name, &label));
    6905:   PetscCheck(label, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "No label named %s was found", name);
    6906:   PetscCall(DMLabelGetValue(label, point, value));
    6907:   PetscFunctionReturn(PETSC_SUCCESS);
    6908: }

    6910: /*@
    6911:   DMSetLabelValue - Add a point to a `DMLabel` with given value

    6913:   Not Collective

    6915:   Input Parameters:
    6916: + dm    - The `DM` object
    6917: . name  - The label name
    6918: . point - The mesh point
    6919: - value - The label value for this point

    6921:   Output Parameter:

    6923:   Level: beginner

    6925: .seealso: [](ch_dmbase), `DM`, `DMLabelSetValue()`, `DMGetStratumIS()`, `DMClearLabelValue()`
    6926: @*/
    6927: PetscErrorCode DMSetLabelValue(DM dm, const char name[], PetscInt point, PetscInt value)
    6928: {
    6929:   DMLabel label;

    6931:   PetscFunctionBegin;
    6933:   PetscAssertPointer(name, 2);
    6934:   PetscCall(DMGetLabel(dm, name, &label));
    6935:   if (!label) {
    6936:     PetscCall(DMCreateLabel(dm, name));
    6937:     PetscCall(DMGetLabel(dm, name, &label));
    6938:   }
    6939:   PetscCall(DMLabelSetValue(label, point, value));
    6940:   PetscFunctionReturn(PETSC_SUCCESS);
    6941: }

    6943: /*@
    6944:   DMClearLabelValue - Remove a point from a `DMLabel` with given value

    6946:   Not Collective

    6948:   Input Parameters:
    6949: + dm    - The `DM` object
    6950: . name  - The label name
    6951: . point - The mesh point
    6952: - value - The label value for this point

    6954:   Level: beginner

    6956: .seealso: [](ch_dmbase), `DM`, `DMLabelClearValue()`, `DMSetLabelValue()`, `DMGetStratumIS()`
    6957: @*/
    6958: PetscErrorCode DMClearLabelValue(DM dm, const char name[], PetscInt point, PetscInt value)
    6959: {
    6960:   DMLabel label;

    6962:   PetscFunctionBegin;
    6964:   PetscAssertPointer(name, 2);
    6965:   PetscCall(DMGetLabel(dm, name, &label));
    6966:   if (!label) PetscFunctionReturn(PETSC_SUCCESS);
    6967:   PetscCall(DMLabelClearValue(label, point, value));
    6968:   PetscFunctionReturn(PETSC_SUCCESS);
    6969: }

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

    6974:   Not Collective

    6976:   Input Parameters:
    6977: + dm   - The `DM` object
    6978: - name - The label name

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

    6983:   Level: beginner

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

    6988: .seealso: [](ch_dmbase), `DM`, `DMLabelGetNumValues()`, `DMSetLabelValue()`, `DMGetLabel()`
    6989: @*/
    6990: PetscErrorCode DMGetLabelSize(DM dm, const char name[], PetscInt *size)
    6991: {
    6992:   DMLabel label;

    6994:   PetscFunctionBegin;
    6996:   PetscAssertPointer(name, 2);
    6997:   PetscAssertPointer(size, 3);
    6998:   PetscCall(DMGetLabel(dm, name, &label));
    6999:   *size = 0;
    7000:   if (!label) PetscFunctionReturn(PETSC_SUCCESS);
    7001:   PetscCall(DMLabelGetNumValues(label, size));
    7002:   PetscFunctionReturn(PETSC_SUCCESS);
    7003: }

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

    7008:   Not Collective

    7010:   Input Parameters:
    7011: + dm   - The `DM` object
    7012: - name - The label name

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

    7017:   Level: beginner

    7019: .seealso: [](ch_dmbase), `DM`, `DMLabelGetValueIS()`, `DMGetLabelSize()`
    7020: @*/
    7021: PetscErrorCode DMGetLabelIdIS(DM dm, const char name[], IS *ids)
    7022: {
    7023:   DMLabel label;

    7025:   PetscFunctionBegin;
    7027:   PetscAssertPointer(name, 2);
    7028:   PetscAssertPointer(ids, 3);
    7029:   PetscCall(DMGetLabel(dm, name, &label));
    7030:   *ids = NULL;
    7031:   if (label) PetscCall(DMLabelGetValueIS(label, ids));
    7032:   else {
    7033:     /* returning an empty IS */
    7034:     PetscCall(ISCreateGeneral(PETSC_COMM_SELF, 0, NULL, PETSC_USE_POINTER, ids));
    7035:   }
    7036:   PetscFunctionReturn(PETSC_SUCCESS);
    7037: }

    7039: /*@
    7040:   DMGetStratumSize - Get the number of points in a label stratum

    7042:   Not Collective

    7044:   Input Parameters:
    7045: + dm    - The `DM` object
    7046: . name  - The label name of the stratum
    7047: - value - The stratum value

    7049:   Output Parameter:
    7050: . size - The number of points, also called the stratum size

    7052:   Level: beginner

    7054: .seealso: [](ch_dmbase), `DM`, `DMLabelGetStratumSize()`, `DMGetLabelSize()`, `DMGetLabelIds()`
    7055: @*/
    7056: PetscErrorCode DMGetStratumSize(DM dm, const char name[], PetscInt value, PetscInt *size)
    7057: {
    7058:   DMLabel label;

    7060:   PetscFunctionBegin;
    7062:   PetscAssertPointer(name, 2);
    7063:   PetscAssertPointer(size, 4);
    7064:   PetscCall(DMGetLabel(dm, name, &label));
    7065:   *size = 0;
    7066:   if (!label) PetscFunctionReturn(PETSC_SUCCESS);
    7067:   PetscCall(DMLabelGetStratumSize(label, value, size));
    7068:   PetscFunctionReturn(PETSC_SUCCESS);
    7069: }

    7071: /*@
    7072:   DMGetStratumIS - Get the points in a label stratum

    7074:   Not Collective

    7076:   Input Parameters:
    7077: + dm    - The `DM` object
    7078: . name  - The label name
    7079: - value - The stratum value

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

    7084:   Level: beginner

    7086: .seealso: [](ch_dmbase), `DM`, `DMLabelGetStratumIS()`, `DMGetStratumSize()`
    7087: @*/
    7088: PetscErrorCode DMGetStratumIS(DM dm, const char name[], PetscInt value, IS *points)
    7089: {
    7090:   DMLabel label;

    7092:   PetscFunctionBegin;
    7094:   PetscAssertPointer(name, 2);
    7095:   PetscAssertPointer(points, 4);
    7096:   PetscCall(DMGetLabel(dm, name, &label));
    7097:   *points = NULL;
    7098:   if (!label) PetscFunctionReturn(PETSC_SUCCESS);
    7099:   PetscCall(DMLabelGetStratumIS(label, value, points));
    7100:   PetscFunctionReturn(PETSC_SUCCESS);
    7101: }

    7103: /*@
    7104:   DMSetStratumIS - Set the points in a label stratum

    7106:   Not Collective

    7108:   Input Parameters:
    7109: + dm     - The `DM` object
    7110: . name   - The label name
    7111: . value  - The stratum value
    7112: - points - The stratum points

    7114:   Level: beginner

    7116: .seealso: [](ch_dmbase), `DM`, `DMLabel`, `DMClearLabelStratum()`, `DMLabelClearStratum()`, `DMLabelSetStratumIS()`, `DMGetStratumSize()`
    7117: @*/
    7118: PetscErrorCode DMSetStratumIS(DM dm, const char name[], PetscInt value, IS points)
    7119: {
    7120:   DMLabel label;

    7122:   PetscFunctionBegin;
    7124:   PetscAssertPointer(name, 2);
    7126:   PetscCall(DMGetLabel(dm, name, &label));
    7127:   if (!label) PetscFunctionReturn(PETSC_SUCCESS);
    7128:   PetscCall(DMLabelSetStratumIS(label, value, points));
    7129:   PetscFunctionReturn(PETSC_SUCCESS);
    7130: }

    7132: /*@
    7133:   DMClearLabelStratum - Remove all points from a stratum from a `DMLabel`

    7135:   Not Collective

    7137:   Input Parameters:
    7138: + dm    - The `DM` object
    7139: . name  - The label name
    7140: - value - The label value for this point

    7142:   Output Parameter:

    7144:   Level: beginner

    7146: .seealso: [](ch_dmbase), `DM`, `DMLabel`, `DMLabelClearStratum()`, `DMSetLabelValue()`, `DMGetStratumIS()`, `DMClearLabelValue()`
    7147: @*/
    7148: PetscErrorCode DMClearLabelStratum(DM dm, const char name[], PetscInt value)
    7149: {
    7150:   DMLabel label;

    7152:   PetscFunctionBegin;
    7154:   PetscAssertPointer(name, 2);
    7155:   PetscCall(DMGetLabel(dm, name, &label));
    7156:   if (!label) PetscFunctionReturn(PETSC_SUCCESS);
    7157:   PetscCall(DMLabelClearStratum(label, value));
    7158:   PetscFunctionReturn(PETSC_SUCCESS);
    7159: }

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

    7164:   Not Collective

    7166:   Input Parameter:
    7167: . dm - The `DM` object

    7169:   Output Parameter:
    7170: . numLabels - the number of Labels

    7172:   Level: intermediate

    7174: .seealso: [](ch_dmbase), `DM`, `DMLabel`, `DMGetLabelByNum()`, `DMGetLabelName()`, `DMGetLabelValue()`, `DMSetLabelValue()`, `DMGetStratumIS()`
    7175: @*/
    7176: PetscErrorCode DMGetNumLabels(DM dm, PetscInt *numLabels)
    7177: {
    7178:   DMLabelLink next = dm->labels;
    7179:   PetscInt    n    = 0;

    7181:   PetscFunctionBegin;
    7183:   PetscAssertPointer(numLabels, 2);
    7184:   while (next) {
    7185:     ++n;
    7186:     next = next->next;
    7187:   }
    7188:   *numLabels = n;
    7189:   PetscFunctionReturn(PETSC_SUCCESS);
    7190: }

    7192: /*@
    7193:   DMGetLabelName - Return the name of nth label

    7195:   Not Collective

    7197:   Input Parameters:
    7198: + dm - The `DM` object
    7199: - n  - the label number

    7201:   Output Parameter:
    7202: . name - the label name

    7204:   Level: intermediate

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

    7209: .seealso: [](ch_dmbase), `DM`, `DMLabel`, `DMGetLabelByNum()`, `DMGetLabel()`, `DMGetLabelValue()`, `DMSetLabelValue()`, `DMGetStratumIS()`
    7210: @*/
    7211: PetscErrorCode DMGetLabelName(DM dm, PetscInt n, const char *name[])
    7212: {
    7213:   DMLabelLink next = dm->labels;
    7214:   PetscInt    l    = 0;

    7216:   PetscFunctionBegin;
    7218:   PetscAssertPointer(name, 3);
    7219:   while (next) {
    7220:     if (l == n) {
    7221:       PetscCall(PetscObjectGetName((PetscObject)next->label, name));
    7222:       PetscFunctionReturn(PETSC_SUCCESS);
    7223:     }
    7224:     ++l;
    7225:     next = next->next;
    7226:   }
    7227:   SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Label %" PetscInt_FMT " does not exist in this DM", n);
    7228: }

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

    7233:   Not Collective

    7235:   Input Parameters:
    7236: + dm   - The `DM` object
    7237: - name - The label name

    7239:   Output Parameter:
    7240: . hasLabel - `PETSC_TRUE` if the label is present

    7242:   Level: intermediate

    7244: .seealso: [](ch_dmbase), `DM`, `DMLabel`, `DMGetLabel()`, `DMGetLabelByNum()`, `DMCreateLabel()`, `DMGetLabelValue()`, `DMSetLabelValue()`, `DMGetStratumIS()`
    7245: @*/
    7246: PetscErrorCode DMHasLabel(DM dm, const char name[], PetscBool *hasLabel)
    7247: {
    7248:   DMLabelLink next = dm->labels;
    7249:   const char *lname;

    7251:   PetscFunctionBegin;
    7253:   PetscAssertPointer(name, 2);
    7254:   PetscAssertPointer(hasLabel, 3);
    7255:   *hasLabel = PETSC_FALSE;
    7256:   while (next) {
    7257:     PetscCall(PetscObjectGetName((PetscObject)next->label, &lname));
    7258:     PetscCall(PetscStrcmp(name, lname, hasLabel));
    7259:     if (*hasLabel) break;
    7260:     next = next->next;
    7261:   }
    7262:   PetscFunctionReturn(PETSC_SUCCESS);
    7263: }

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

    7269:   Not Collective

    7271:   Input Parameters:
    7272: + dm   - The `DM` object
    7273: - name - The label name

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

    7278:   Default labels in a `DMPLEX`:
    7279: + "depth"       - Holds the depth (co-dimension) of each mesh point
    7280: . "celltype"    - Holds the topological type of each cell
    7281: . "ghost"       - If the DM is distributed with overlap, this marks the cells and faces in the overlap
    7282: . "Cell Sets"   - Mirrors the cell sets defined by GMsh and ExodusII
    7283: . "Face Sets"   - Mirrors the face sets defined by GMsh and ExodusII
    7284: - "Vertex Sets" - Mirrors the vertex sets defined by GMsh

    7286:   Level: intermediate

    7288: .seealso: [](ch_dmbase), `DM`, `DMLabel`, `DMHasLabel()`, `DMGetLabelByNum()`, `DMAddLabel()`, `DMCreateLabel()`, `DMPlexGetDepthLabel()`, `DMPlexGetCellType()`
    7289: @*/
    7290: PetscErrorCode DMGetLabel(DM dm, const char name[], DMLabel *label)
    7291: {
    7292:   DMLabelLink next = dm->labels;
    7293:   PetscBool   hasLabel;
    7294:   const char *lname;

    7296:   PetscFunctionBegin;
    7298:   PetscAssertPointer(name, 2);
    7299:   PetscAssertPointer(label, 3);
    7300:   *label = NULL;
    7301:   while (next) {
    7302:     PetscCall(PetscObjectGetName((PetscObject)next->label, &lname));
    7303:     PetscCall(PetscStrcmp(name, lname, &hasLabel));
    7304:     if (hasLabel) {
    7305:       *label = next->label;
    7306:       break;
    7307:     }
    7308:     next = next->next;
    7309:   }
    7310:   PetscFunctionReturn(PETSC_SUCCESS);
    7311: }

    7313: /*@
    7314:   DMGetLabelByNum - Return the nth label on a `DM`

    7316:   Not Collective

    7318:   Input Parameters:
    7319: + dm - The `DM` object
    7320: - n  - the label number

    7322:   Output Parameter:
    7323: . label - the label

    7325:   Level: intermediate

    7327: .seealso: [](ch_dmbase), `DM`, `DMLabel`, `DMAddLabel()`, `DMGetLabelValue()`, `DMSetLabelValue()`, `DMGetStratumIS()`
    7328: @*/
    7329: PetscErrorCode DMGetLabelByNum(DM dm, PetscInt n, DMLabel *label)
    7330: {
    7331:   DMLabelLink next = dm->labels;
    7332:   PetscInt    l    = 0;

    7334:   PetscFunctionBegin;
    7336:   PetscAssertPointer(label, 3);
    7337:   while (next) {
    7338:     if (l == n) {
    7339:       *label = next->label;
    7340:       PetscFunctionReturn(PETSC_SUCCESS);
    7341:     }
    7342:     ++l;
    7343:     next = next->next;
    7344:   }
    7345:   SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Label %" PetscInt_FMT " does not exist in this DM", n);
    7346: }

    7348: /*@
    7349:   DMAddLabel - Add the label to this `DM`

    7351:   Not Collective

    7353:   Input Parameters:
    7354: + dm    - The `DM` object
    7355: - label - The `DMLabel`

    7357:   Level: developer

    7359: .seealso: [](ch_dmbase), `DM`, `DMLabel`, `DMCreateLabel()`, `DMHasLabel()`, `DMGetLabelValue()`, `DMSetLabelValue()`, `DMGetStratumIS()`
    7360: @*/
    7361: PetscErrorCode DMAddLabel(DM dm, DMLabel label)
    7362: {
    7363:   DMLabelLink l, *p, tmpLabel;
    7364:   PetscBool   hasLabel;
    7365:   const char *lname;
    7366:   PetscBool   flg;

    7368:   PetscFunctionBegin;
    7370:   PetscCall(PetscObjectGetName((PetscObject)label, &lname));
    7371:   PetscCall(DMHasLabel(dm, lname, &hasLabel));
    7372:   PetscCheck(!hasLabel, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Label %s already exists in this DM", lname);
    7373:   PetscCall(PetscCalloc1(1, &tmpLabel));
    7374:   tmpLabel->label  = label;
    7375:   tmpLabel->output = PETSC_TRUE;
    7376:   for (p = &dm->labels; (l = *p); p = &l->next) { }
    7377:   *p = tmpLabel;
    7378:   PetscCall(PetscObjectReference((PetscObject)label));
    7379:   PetscCall(PetscStrcmp(lname, "depth", &flg));
    7380:   if (flg) dm->depthLabel = label;
    7381:   PetscCall(PetscStrcmp(lname, "celltype", &flg));
    7382:   if (flg) dm->celltypeLabel = label;
    7383:   PetscFunctionReturn(PETSC_SUCCESS);
    7384: }

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

    7390:   Not Collective

    7392:   Input Parameters:
    7393: + dm    - The `DM` object
    7394: - label - The `DMLabel`, having the same name, to substitute

    7396:   Default labels in a `DMPLEX`:
    7397: + "depth"       - Holds the depth (co-dimension) of each mesh point
    7398: . "celltype"    - Holds the topological type of each cell
    7399: . "ghost"       - If the DM is distributed with overlap, this marks the cells and faces in the overlap
    7400: . "Cell Sets"   - Mirrors the cell sets defined by GMsh and ExodusII
    7401: . "Face Sets"   - Mirrors the face sets defined by GMsh and ExodusII
    7402: - "Vertex Sets" - Mirrors the vertex sets defined by GMsh

    7404:   Level: intermediate

    7406: .seealso: [](ch_dmbase), `DM`, `DMLabel`, `DMCreateLabel()`, `DMHasLabel()`, `DMPlexGetDepthLabel()`, `DMPlexGetCellType()`
    7407: @*/
    7408: PetscErrorCode DMSetLabel(DM dm, DMLabel label)
    7409: {
    7410:   DMLabelLink next = dm->labels;
    7411:   PetscBool   hasLabel, flg;
    7412:   const char *name, *lname;

    7414:   PetscFunctionBegin;
    7417:   PetscCall(PetscObjectGetName((PetscObject)label, &name));
    7418:   while (next) {
    7419:     PetscCall(PetscObjectGetName((PetscObject)next->label, &lname));
    7420:     PetscCall(PetscStrcmp(name, lname, &hasLabel));
    7421:     if (hasLabel) {
    7422:       PetscCall(PetscObjectReference((PetscObject)label));
    7423:       PetscCall(PetscStrcmp(lname, "depth", &flg));
    7424:       if (flg) dm->depthLabel = label;
    7425:       PetscCall(PetscStrcmp(lname, "celltype", &flg));
    7426:       if (flg) dm->celltypeLabel = label;
    7427:       PetscCall(DMLabelDestroy(&next->label));
    7428:       next->label = label;
    7429:       break;
    7430:     }
    7431:     next = next->next;
    7432:   }
    7433:   PetscFunctionReturn(PETSC_SUCCESS);
    7434: }

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

    7439:   Not Collective

    7441:   Input Parameters:
    7442: + dm   - The `DM` object
    7443: - name - The label name

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

    7449:   Level: developer

    7451: .seealso: [](ch_dmbase), `DM`, `DMLabel`, `DMCreateLabel()`, `DMHasLabel()`, `DMGetLabel()`, `DMGetLabelValue()`, `DMSetLabelValue()`, `DMLabelDestroy()`, `DMRemoveLabelBySelf()`
    7452: @*/
    7453: PetscErrorCode DMRemoveLabel(DM dm, const char name[], DMLabel *label)
    7454: {
    7455:   DMLabelLink link, *pnext;
    7456:   PetscBool   hasLabel;
    7457:   const char *lname;

    7459:   PetscFunctionBegin;
    7461:   PetscAssertPointer(name, 2);
    7462:   if (label) {
    7463:     PetscAssertPointer(label, 3);
    7464:     *label = NULL;
    7465:   }
    7466:   for (pnext = &dm->labels; (link = *pnext); pnext = &link->next) {
    7467:     PetscCall(PetscObjectGetName((PetscObject)link->label, &lname));
    7468:     PetscCall(PetscStrcmp(name, lname, &hasLabel));
    7469:     if (hasLabel) {
    7470:       *pnext = link->next; /* Remove from list */
    7471:       PetscCall(PetscStrcmp(name, "depth", &hasLabel));
    7472:       if (hasLabel) dm->depthLabel = NULL;
    7473:       PetscCall(PetscStrcmp(name, "celltype", &hasLabel));
    7474:       if (hasLabel) dm->celltypeLabel = NULL;
    7475:       if (label) *label = link->label;
    7476:       else PetscCall(DMLabelDestroy(&link->label));
    7477:       PetscCall(PetscFree(link));
    7478:       break;
    7479:     }
    7480:   }
    7481:   PetscFunctionReturn(PETSC_SUCCESS);
    7482: }

    7484: /*@
    7485:   DMRemoveLabelBySelf - Remove the label from this `DM`

    7487:   Not Collective

    7489:   Input Parameters:
    7490: + dm           - The `DM` object
    7491: . label        - The `DMLabel` to be removed from the `DM`
    7492: - failNotFound - Should it fail if the label is not found in the `DM`?

    7494:   Level: developer

    7496:   Note:
    7497:   Only exactly the same instance is removed if found, name match is ignored.
    7498:   If the `DM` has an exclusive reference to the label, the label gets destroyed and
    7499:   *label nullified.

    7501: .seealso: [](ch_dmbase), `DM`, `DMLabel`, `DMCreateLabel()`, `DMHasLabel()`, `DMGetLabel()`, `DMGetLabelValue()`, `DMSetLabelValue()`, `DMLabelDestroy()`, `DMRemoveLabel()`
    7502: @*/
    7503: PetscErrorCode DMRemoveLabelBySelf(DM dm, DMLabel *label, PetscBool failNotFound)
    7504: {
    7505:   DMLabelLink link, *pnext;
    7506:   PetscBool   hasLabel = PETSC_FALSE;

    7508:   PetscFunctionBegin;
    7510:   PetscAssertPointer(label, 2);
    7511:   if (!*label && !failNotFound) PetscFunctionReturn(PETSC_SUCCESS);
    7514:   for (pnext = &dm->labels; (link = *pnext); pnext = &link->next) {
    7515:     if (*label == link->label) {
    7516:       hasLabel = PETSC_TRUE;
    7517:       *pnext   = link->next; /* Remove from list */
    7518:       if (*label == dm->depthLabel) dm->depthLabel = NULL;
    7519:       if (*label == dm->celltypeLabel) dm->celltypeLabel = NULL;
    7520:       if (((PetscObject)link->label)->refct < 2) *label = NULL; /* nullify if exclusive reference */
    7521:       PetscCall(DMLabelDestroy(&link->label));
    7522:       PetscCall(PetscFree(link));
    7523:       break;
    7524:     }
    7525:   }
    7526:   PetscCheck(hasLabel || !failNotFound, PetscObjectComm((PetscObject)dm), PETSC_ERR_ARG_WRONG, "Given label not found in DM");
    7527:   PetscFunctionReturn(PETSC_SUCCESS);
    7528: }

    7530: /*@
    7531:   DMGetLabelOutput - Get the output flag for a given label

    7533:   Not Collective

    7535:   Input Parameters:
    7536: + dm   - The `DM` object
    7537: - name - The label name

    7539:   Output Parameter:
    7540: . output - The flag for output

    7542:   Level: developer

    7544: .seealso: [](ch_dmbase), `DM`, `DMLabel`, `DMSetLabelOutput()`, `DMCreateLabel()`, `DMHasLabel()`, `DMGetLabelValue()`, `DMSetLabelValue()`, `DMGetStratumIS()`
    7545: @*/
    7546: PetscErrorCode DMGetLabelOutput(DM dm, const char name[], PetscBool *output)
    7547: {
    7548:   DMLabelLink next = dm->labels;
    7549:   const char *lname;

    7551:   PetscFunctionBegin;
    7553:   PetscAssertPointer(name, 2);
    7554:   PetscAssertPointer(output, 3);
    7555:   while (next) {
    7556:     PetscBool flg;

    7558:     PetscCall(PetscObjectGetName((PetscObject)next->label, &lname));
    7559:     PetscCall(PetscStrcmp(name, lname, &flg));
    7560:     if (flg) {
    7561:       *output = next->output;
    7562:       PetscFunctionReturn(PETSC_SUCCESS);
    7563:     }
    7564:     next = next->next;
    7565:   }
    7566:   SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "No label named %s was present in this dm", name);
    7567: }

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

    7572:   Not Collective

    7574:   Input Parameters:
    7575: + dm     - The `DM` object
    7576: . name   - The label name
    7577: - output - `PETSC_TRUE` to save the label to the viewer

    7579:   Level: developer

    7581: .seealso: [](ch_dmbase), `DM`, `DMLabel`, `DMGetOutputFlag()`, `DMGetLabelOutput()`, `DMCreateLabel()`, `DMHasLabel()`, `DMGetLabelValue()`, `DMSetLabelValue()`, `DMGetStratumIS()`
    7582: @*/
    7583: PetscErrorCode DMSetLabelOutput(DM dm, const char name[], PetscBool output)
    7584: {
    7585:   DMLabelLink next = dm->labels;
    7586:   const char *lname;

    7588:   PetscFunctionBegin;
    7590:   PetscAssertPointer(name, 2);
    7591:   while (next) {
    7592:     PetscBool flg;

    7594:     PetscCall(PetscObjectGetName((PetscObject)next->label, &lname));
    7595:     PetscCall(PetscStrcmp(name, lname, &flg));
    7596:     if (flg) {
    7597:       next->output = output;
    7598:       PetscFunctionReturn(PETSC_SUCCESS);
    7599:     }
    7600:     next = next->next;
    7601:   }
    7602:   SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "No label named %s was present in this dm", name);
    7603: }

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

    7608:   Collective

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

    7617:   Level: intermediate

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

    7622: .seealso: [](ch_dmbase), `DM`, `DMLabel`, `DMAddLabel()`, `DMCopyLabelsMode`
    7623: @*/
    7624: PetscErrorCode DMCopyLabels(DM dmA, DM dmB, PetscCopyMode mode, PetscBool all, DMCopyLabelsMode emode)
    7625: {
    7626:   DMLabel     label, labelNew, labelOld;
    7627:   const char *name;
    7628:   PetscBool   flg;
    7629:   DMLabelLink link;

    7631:   PetscFunctionBegin;
    7636:   PetscCheck(mode != PETSC_USE_POINTER, PetscObjectComm((PetscObject)dmA), PETSC_ERR_SUP, "PETSC_USE_POINTER not supported for objects");
    7637:   if (dmA == dmB) PetscFunctionReturn(PETSC_SUCCESS);
    7638:   for (link = dmA->labels; link; link = link->next) {
    7639:     label = link->label;
    7640:     PetscCall(PetscObjectGetName((PetscObject)label, &name));
    7641:     if (!all) {
    7642:       PetscCall(PetscStrcmp(name, "depth", &flg));
    7643:       if (flg) continue;
    7644:       PetscCall(PetscStrcmp(name, "dim", &flg));
    7645:       if (flg) continue;
    7646:       PetscCall(PetscStrcmp(name, "celltype", &flg));
    7647:       if (flg) continue;
    7648:     }
    7649:     PetscCall(DMGetLabel(dmB, name, &labelOld));
    7650:     if (labelOld) {
    7651:       switch (emode) {
    7652:       case DM_COPY_LABELS_KEEP:
    7653:         continue;
    7654:       case DM_COPY_LABELS_REPLACE:
    7655:         PetscCall(DMRemoveLabelBySelf(dmB, &labelOld, PETSC_TRUE));
    7656:         break;
    7657:       case DM_COPY_LABELS_FAIL:
    7658:         SETERRQ(PetscObjectComm((PetscObject)dmA), PETSC_ERR_ARG_OUTOFRANGE, "Label %s already exists in destination DM", name);
    7659:       default:
    7660:         SETERRQ(PetscObjectComm((PetscObject)dmA), PETSC_ERR_ARG_OUTOFRANGE, "Unhandled DMCopyLabelsMode %d", (int)emode);
    7661:       }
    7662:     }
    7663:     if (mode == PETSC_COPY_VALUES) PetscCall(DMLabelDuplicate(label, &labelNew));
    7664:     else labelNew = label;
    7665:     PetscCall(DMAddLabel(dmB, labelNew));
    7666:     if (mode == PETSC_COPY_VALUES) PetscCall(DMLabelDestroy(&labelNew));
    7667:   }
    7668:   PetscFunctionReturn(PETSC_SUCCESS);
    7669: }

    7671: /*@C
    7672:   DMCompareLabels - Compare labels between two `DM` objects

    7674:   Collective; No Fortran Support

    7676:   Input Parameters:
    7677: + dm0 - First `DM` object
    7678: - dm1 - Second `DM` object

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

    7684:   Level: intermediate

    7686:   Notes:
    7687:   The output flag equal will be the same on all processes.

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

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

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

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

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

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

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

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

    7707: .seealso: [](ch_dmbase), `DM`, `DMLabel`, `DMAddLabel()`, `DMCopyLabelsMode`, `DMLabelCompare()`
    7708: @*/
    7709: PetscErrorCode DMCompareLabels(DM dm0, DM dm1, PetscBool *equal, char *message[]) PeNS
    7710: {
    7711:   PetscInt    n, i;
    7712:   char        msg[PETSC_MAX_PATH_LEN] = "";
    7713:   PetscBool   eq;
    7714:   MPI_Comm    comm;
    7715:   PetscMPIInt rank;

    7717:   PetscFunctionBegin;
    7720:   PetscCheckSameComm(dm0, 1, dm1, 2);
    7721:   if (equal) PetscAssertPointer(equal, 3);
    7722:   if (message) PetscAssertPointer(message, 4);
    7723:   PetscCall(PetscObjectGetComm((PetscObject)dm0, &comm));
    7724:   PetscCallMPI(MPI_Comm_rank(comm, &rank));
    7725:   {
    7726:     PetscInt n1;

    7728:     PetscCall(DMGetNumLabels(dm0, &n));
    7729:     PetscCall(DMGetNumLabels(dm1, &n1));
    7730:     eq = (PetscBool)(n == n1);
    7731:     if (!eq) PetscCall(PetscSNPrintf(msg, sizeof(msg), "Number of labels in dm0 = %" PetscInt_FMT " != %" PetscInt_FMT " = Number of labels in dm1", n, n1));
    7732:     PetscCallMPI(MPIU_Allreduce(MPI_IN_PLACE, &eq, 1, MPI_C_BOOL, MPI_LAND, comm));
    7733:     if (!eq) goto finish;
    7734:   }
    7735:   for (i = 0; i < n; i++) {
    7736:     DMLabel     l0, l1;
    7737:     const char *name;
    7738:     char       *msgInner;

    7740:     /* Ignore label order */
    7741:     PetscCall(DMGetLabelByNum(dm0, i, &l0));
    7742:     PetscCall(PetscObjectGetName((PetscObject)l0, &name));
    7743:     PetscCall(DMGetLabel(dm1, name, &l1));
    7744:     if (!l1) {
    7745:       PetscCall(PetscSNPrintf(msg, sizeof(msg), "Label \"%s\" (#%" PetscInt_FMT " in dm0) not found in dm1", name, i));
    7746:       eq = PETSC_FALSE;
    7747:       break;
    7748:     }
    7749:     PetscCall(DMLabelCompare(comm, l0, l1, &eq, &msgInner));
    7750:     PetscCall(PetscStrncpy(msg, msgInner, sizeof(msg)));
    7751:     PetscCall(PetscFree(msgInner));
    7752:     if (!eq) break;
    7753:   }
    7754:   PetscCallMPI(MPIU_Allreduce(MPI_IN_PLACE, &eq, 1, MPI_C_BOOL, MPI_LAND, comm));
    7755: finish:
    7756:   /* If message output arg not set, print to stderr */
    7757:   if (message) {
    7758:     *message = NULL;
    7759:     if (msg[0]) PetscCall(PetscStrallocpy(msg, message));
    7760:   } else {
    7761:     if (msg[0]) PetscCall(PetscSynchronizedFPrintf(comm, PETSC_STDERR, "[%d] %s\n", rank, msg));
    7762:     PetscCall(PetscSynchronizedFlush(comm, PETSC_STDERR));
    7763:   }
    7764:   /* If same output arg not ser and labels are not equal, throw error */
    7765:   if (equal) *equal = eq;
    7766:   else PetscCheck(eq, comm, PETSC_ERR_ARG_INCOMP, "DMLabels are not the same in dm0 and dm1");
    7767:   PetscFunctionReturn(PETSC_SUCCESS);
    7768: }

    7770: PetscErrorCode DMSetLabelValue_Fast(DM dm, DMLabel *label, const char name[], PetscInt point, PetscInt value)
    7771: {
    7772:   PetscFunctionBegin;
    7773:   PetscAssertPointer(label, 2);
    7774:   if (!*label) {
    7775:     PetscCall(DMCreateLabel(dm, name));
    7776:     PetscCall(DMGetLabel(dm, name, label));
    7777:   }
    7778:   PetscCall(DMLabelSetValue(*label, point, value));
    7779:   PetscFunctionReturn(PETSC_SUCCESS);
    7780: }

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

    7787:   However, a mesh point can have multiple labels, so we must separate all these values. We will assign a bit range to
    7788:   each label.
    7789: */
    7790: PetscErrorCode DMUniversalLabelCreate(DM dm, DMUniversalLabel *universal)
    7791: {
    7792:   DMUniversalLabel ul;
    7793:   PetscBool       *active;
    7794:   PetscInt         pStart, pEnd, p, Nl, l, m;

    7796:   PetscFunctionBegin;
    7797:   PetscCall(PetscMalloc1(1, &ul));
    7798:   PetscCall(DMLabelCreate(PETSC_COMM_SELF, "universal", &ul->label));
    7799:   PetscCall(DMGetNumLabels(dm, &Nl));
    7800:   PetscCall(PetscCalloc1(Nl, &active));
    7801:   ul->Nl = 0;
    7802:   for (l = 0; l < Nl; ++l) {
    7803:     PetscBool   isdepth, iscelltype;
    7804:     const char *name;

    7806:     PetscCall(DMGetLabelName(dm, l, &name));
    7807:     PetscCall(PetscStrncmp(name, "depth", 6, &isdepth));
    7808:     PetscCall(PetscStrncmp(name, "celltype", 9, &iscelltype));
    7809:     active[l] = !(isdepth || iscelltype) ? PETSC_TRUE : PETSC_FALSE;
    7810:     if (active[l]) ++ul->Nl;
    7811:   }
    7812:   PetscCall(PetscCalloc5(ul->Nl, &ul->names, ul->Nl, &ul->indices, ul->Nl + 1, &ul->offsets, ul->Nl + 1, &ul->bits, ul->Nl, &ul->masks));
    7813:   ul->Nv = 0;
    7814:   for (l = 0, m = 0; l < Nl; ++l) {
    7815:     DMLabel     label;
    7816:     PetscInt    nv;
    7817:     const char *name;

    7819:     if (!active[l]) continue;
    7820:     PetscCall(DMGetLabelName(dm, l, &name));
    7821:     PetscCall(DMGetLabelByNum(dm, l, &label));
    7822:     PetscCall(DMLabelGetNumValues(label, &nv));
    7823:     PetscCall(PetscStrallocpy(name, &ul->names[m]));
    7824:     ul->indices[m] = l;
    7825:     ul->Nv += nv;
    7826:     ul->offsets[m + 1] = nv;
    7827:     ul->bits[m + 1]    = PetscCeilReal(PetscLog2Real(nv + 1));
    7828:     ++m;
    7829:   }
    7830:   for (l = 1; l <= ul->Nl; ++l) {
    7831:     ul->offsets[l] = ul->offsets[l - 1] + ul->offsets[l];
    7832:     ul->bits[l]    = ul->bits[l - 1] + ul->bits[l];
    7833:   }
    7834:   for (l = 0; l < ul->Nl; ++l) {
    7835:     PetscInt b;

    7837:     ul->masks[l] = 0;
    7838:     for (b = ul->bits[l]; b < ul->bits[l + 1]; ++b) ul->masks[l] |= 1 << b;
    7839:   }
    7840:   PetscCall(PetscMalloc1(ul->Nv, &ul->values));
    7841:   for (l = 0, m = 0; l < Nl; ++l) {
    7842:     DMLabel         label;
    7843:     IS              valueIS;
    7844:     const PetscInt *varr;
    7845:     PetscInt        nv, v;

    7847:     if (!active[l]) continue;
    7848:     PetscCall(DMGetLabelByNum(dm, l, &label));
    7849:     PetscCall(DMLabelGetNumValues(label, &nv));
    7850:     PetscCall(DMLabelGetValueIS(label, &valueIS));
    7851:     PetscCall(ISGetIndices(valueIS, &varr));
    7852:     for (v = 0; v < nv; ++v) ul->values[ul->offsets[m] + v] = varr[v];
    7853:     PetscCall(ISRestoreIndices(valueIS, &varr));
    7854:     PetscCall(ISDestroy(&valueIS));
    7855:     PetscCall(PetscSortInt(nv, &ul->values[ul->offsets[m]]));
    7856:     ++m;
    7857:   }
    7858:   PetscCall(DMPlexGetChart(dm, &pStart, &pEnd));
    7859:   for (p = pStart; p < pEnd; ++p) {
    7860:     PetscInt  uval   = 0;
    7861:     PetscBool marked = PETSC_FALSE;

    7863:     for (l = 0, m = 0; l < Nl; ++l) {
    7864:       DMLabel  label;
    7865:       PetscInt val, defval, loc, nv;

    7867:       if (!active[l]) continue;
    7868:       PetscCall(DMGetLabelByNum(dm, l, &label));
    7869:       PetscCall(DMLabelGetValue(label, p, &val));
    7870:       PetscCall(DMLabelGetDefaultValue(label, &defval));
    7871:       if (val == defval) {
    7872:         ++m;
    7873:         continue;
    7874:       }
    7875:       nv     = ul->offsets[m + 1] - ul->offsets[m];
    7876:       marked = PETSC_TRUE;
    7877:       PetscCall(PetscFindInt(val, nv, &ul->values[ul->offsets[m]], &loc));
    7878:       PetscCheck(loc >= 0, PETSC_COMM_SELF, PETSC_ERR_PLIB, "Label value %" PetscInt_FMT " not found in compression array", val);
    7879:       uval += (loc + 1) << ul->bits[m];
    7880:       ++m;
    7881:     }
    7882:     if (marked) PetscCall(DMLabelSetValue(ul->label, p, uval));
    7883:   }
    7884:   PetscCall(PetscFree(active));
    7885:   *universal = ul;
    7886:   PetscFunctionReturn(PETSC_SUCCESS);
    7887: }

    7889: PetscErrorCode DMUniversalLabelDestroy(DMUniversalLabel *universal)
    7890: {
    7891:   PetscInt l;

    7893:   PetscFunctionBegin;
    7894:   for (l = 0; l < (*universal)->Nl; ++l) PetscCall(PetscFree((*universal)->names[l]));
    7895:   PetscCall(DMLabelDestroy(&(*universal)->label));
    7896:   PetscCall(PetscFree5((*universal)->names, (*universal)->indices, (*universal)->offsets, (*universal)->bits, (*universal)->masks));
    7897:   PetscCall(PetscFree((*universal)->values));
    7898:   PetscCall(PetscFree(*universal));
    7899:   *universal = NULL;
    7900:   PetscFunctionReturn(PETSC_SUCCESS);
    7901: }

    7903: PetscErrorCode DMUniversalLabelGetLabel(DMUniversalLabel ul, DMLabel *ulabel)
    7904: {
    7905:   PetscFunctionBegin;
    7906:   PetscAssertPointer(ulabel, 2);
    7907:   *ulabel = ul->label;
    7908:   PetscFunctionReturn(PETSC_SUCCESS);
    7909: }

    7911: PetscErrorCode DMUniversalLabelCreateLabels(DMUniversalLabel ul, PetscBool preserveOrder, DM dm)
    7912: {
    7913:   PetscInt Nl = ul->Nl, l;

    7915:   PetscFunctionBegin;
    7917:   for (l = 0; l < Nl; ++l) {
    7918:     if (preserveOrder) PetscCall(DMCreateLabelAtIndex(dm, ul->indices[l], ul->names[l]));
    7919:     else PetscCall(DMCreateLabel(dm, ul->names[l]));
    7920:   }
    7921:   if (preserveOrder) {
    7922:     for (l = 0; l < ul->Nl; ++l) {
    7923:       const char *name;
    7924:       PetscBool   match;

    7926:       PetscCall(DMGetLabelName(dm, ul->indices[l], &name));
    7927:       PetscCall(PetscStrcmp(name, ul->names[l], &match));
    7928:       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]);
    7929:     }
    7930:   }
    7931:   PetscFunctionReturn(PETSC_SUCCESS);
    7932: }

    7934: PetscErrorCode DMUniversalLabelSetLabelValue(DMUniversalLabel ul, DM dm, PetscBool useIndex, PetscInt p, PetscInt value)
    7935: {
    7936:   PetscInt l;

    7938:   PetscFunctionBegin;
    7939:   for (l = 0; l < ul->Nl; ++l) {
    7940:     DMLabel  label;
    7941:     PetscInt lval = (value & ul->masks[l]) >> ul->bits[l];

    7943:     if (lval) {
    7944:       if (useIndex) PetscCall(DMGetLabelByNum(dm, ul->indices[l], &label));
    7945:       else PetscCall(DMGetLabel(dm, ul->names[l], &label));
    7946:       PetscCall(DMLabelSetValue(label, p, ul->values[ul->offsets[l] + lval - 1]));
    7947:     }
    7948:   }
    7949:   PetscFunctionReturn(PETSC_SUCCESS);
    7950: }

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

    7955:   Not Collective

    7957:   Input Parameter:
    7958: . dm - The `DM` object

    7960:   Output Parameter:
    7961: . cdm - The coarse `DM`

    7963:   Level: intermediate

    7965: .seealso: [](ch_dmbase), `DM`, `DMSetCoarseDM()`, `DMCoarsen()`
    7966: @*/
    7967: PetscErrorCode DMGetCoarseDM(DM dm, DM *cdm)
    7968: {
    7969:   PetscFunctionBegin;
    7971:   PetscAssertPointer(cdm, 2);
    7972:   *cdm = dm->coarseMesh;
    7973:   PetscFunctionReturn(PETSC_SUCCESS);
    7974: }

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

    7979:   Input Parameters:
    7980: + dm  - The `DM` object
    7981: - cdm - The coarse `DM`

    7983:   Level: intermediate

    7985:   Note:
    7986:   Normally this is set automatically by `DMRefine()`

    7988: .seealso: [](ch_dmbase), `DM`, `DMGetCoarseDM()`, `DMCoarsen()`, `DMSetRefine()`, `DMSetFineDM()`
    7989: @*/
    7990: PetscErrorCode DMSetCoarseDM(DM dm, DM cdm)
    7991: {
    7992:   PetscFunctionBegin;
    7995:   if (dm == cdm) cdm = NULL;
    7996:   PetscCall(PetscObjectReference((PetscObject)cdm));
    7997:   PetscCall(DMDestroy(&dm->coarseMesh));
    7998:   dm->coarseMesh = cdm;
    7999:   PetscFunctionReturn(PETSC_SUCCESS);
    8000: }

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

    8005:   Input Parameter:
    8006: . dm - The `DM` object

    8008:   Output Parameter:
    8009: . fdm - The fine `DM`

    8011:   Level: intermediate

    8013: .seealso: [](ch_dmbase), `DM`, `DMSetFineDM()`, `DMCoarsen()`, `DMRefine()`
    8014: @*/
    8015: PetscErrorCode DMGetFineDM(DM dm, DM *fdm)
    8016: {
    8017:   PetscFunctionBegin;
    8019:   PetscAssertPointer(fdm, 2);
    8020:   *fdm = dm->fineMesh;
    8021:   PetscFunctionReturn(PETSC_SUCCESS);
    8022: }

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

    8027:   Input Parameters:
    8028: + dm  - The `DM` object
    8029: - fdm - The fine `DM`

    8031:   Level: developer

    8033:   Note:
    8034:   Normally this is set automatically by `DMCoarsen()`

    8036: .seealso: [](ch_dmbase), `DM`, `DMGetFineDM()`, `DMCoarsen()`, `DMRefine()`
    8037: @*/
    8038: PetscErrorCode DMSetFineDM(DM dm, DM fdm)
    8039: {
    8040:   PetscFunctionBegin;
    8043:   if (dm == fdm) fdm = NULL;
    8044:   PetscCall(PetscObjectReference((PetscObject)fdm));
    8045:   PetscCall(DMDestroy(&dm->fineMesh));
    8046:   dm->fineMesh = fdm;
    8047:   PetscFunctionReturn(PETSC_SUCCESS);
    8048: }

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

    8053:   Collective

    8055:   Input Parameters:
    8056: + dm       - The `DM`, with a `PetscDS` that matches the problem being constrained
    8057: . type     - The type of condition, e.g. `DM_BC_ESSENTIAL_ANALYTIC`, `DM_BC_ESSENTIAL_FIELD` (Dirichlet), or `DM_BC_NATURAL` (Neumann)
    8058: . name     - The BC name
    8059: . label    - The label defining constrained points
    8060: . Nv       - The number of `DMLabel` values for constrained points
    8061: . values   - An array of values for constrained points
    8062: . field    - The field to constrain
    8063: . Nc       - The number of constrained field components (0 will constrain all components)
    8064: . comps    - An array of constrained component numbers
    8065: . bcFunc   - A pointwise function giving boundary values
    8066: . bcFunc_t - A pointwise function giving the time derivative of the boundary values, or `NULL`
    8067: - ctx      - An optional user context for bcFunc

    8069:   Output Parameter:
    8070: . bd - (Optional) Boundary number

    8072:   Options Database Keys:
    8073: + -bc_NAME values     - Overrides the boundary ids for boundary named NAME
    8074: - -bc_NAME_comp comps - Overrides the boundary components for boundary named NAME

    8076:   Level: intermediate

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

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

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

    8088: .vb
    8089:   void bcFunc(PetscInt dim, PetscInt Nf, PetscInt NfAux,
    8090:               const PetscInt uOff[], const PetscInt uOff_x[], const PetscScalar u[], const PetscScalar u_t[], const PetscScalar u_x[],
    8091:               const PetscInt aOff[], const PetscInt aOff_x[], const PetscScalar a[], const PetscScalar a_t[], const PetscScalar a_x[],
    8092:               PetscReal time, const PetscReal x[], PetscScalar bcval[])
    8093: .ve
    8094: + dim - the spatial dimension
    8095: . Nf - the number of fields
    8096: . uOff - the offset into u[] and u_t[] for each field
    8097: . uOff_x - the offset into u_x[] for each field
    8098: . u - each field evaluated at the current point
    8099: . u_t - the time derivative of each field evaluated at the current point
    8100: . u_x - the gradient of each field evaluated at the current point
    8101: . aOff - the offset into a[] and a_t[] for each auxiliary field
    8102: . aOff_x - the offset into a_x[] for each auxiliary field
    8103: . a - each auxiliary field evaluated at the current point
    8104: . a_t - the time derivative of each auxiliary field evaluated at the current point
    8105: . a_x - the gradient of auxiliary each field evaluated at the current point
    8106: . t - current time
    8107: . x - coordinates of the current point
    8108: . numConstants - number of constant parameters
    8109: . constants - constant parameters
    8110: - bcval - output values at the current point

    8112: .seealso: [](ch_dmbase), `DM`, `DSGetBoundary()`, `PetscDSAddBoundary()`
    8113: @*/
    8114: 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)
    8115: {
    8116:   PetscDS ds;

    8118:   PetscFunctionBegin;
    8125:   PetscCheck(!dm->localSection, PetscObjectComm((PetscObject)dm), PETSC_ERR_ARG_WRONGSTATE, "Cannot add boundary to DM after creating local section");
    8126:   PetscCall(DMGetDS(dm, &ds));
    8127:   /* Complete label */
    8128:   if (label) {
    8129:     PetscObject  obj;
    8130:     PetscClassId id;

    8132:     PetscCall(DMGetField(dm, field, NULL, &obj));
    8133:     PetscCall(PetscObjectGetClassId(obj, &id));
    8134:     if (id == PETSCFE_CLASSID) {
    8135:       DM plex;

    8137:       PetscCall(DMConvert(dm, DMPLEX, &plex));
    8138:       if (plex) PetscCall(DMPlexLabelComplete(plex, label));
    8139:       PetscCall(DMDestroy(&plex));
    8140:     }
    8141:   }
    8142:   PetscCall(PetscDSAddBoundary(ds, type, name, label, Nv, values, field, Nc, comps, bcFunc, bcFunc_t, ctx, bd));
    8143:   PetscFunctionReturn(PETSC_SUCCESS);
    8144: }

    8146: /* TODO Remove this since now the structures are the same */
    8147: static PetscErrorCode DMPopulateBoundary(DM dm)
    8148: {
    8149:   PetscDS     ds;
    8150:   DMBoundary *lastnext;
    8151:   DSBoundary  dsbound;

    8153:   PetscFunctionBegin;
    8154:   PetscCall(DMGetDS(dm, &ds));
    8155:   dsbound = ds->boundary;
    8156:   if (dm->boundary) {
    8157:     DMBoundary next = dm->boundary;

    8159:     /* quick check to see if the PetscDS has changed */
    8160:     if (next->dsboundary == dsbound) PetscFunctionReturn(PETSC_SUCCESS);
    8161:     /* the PetscDS has changed: tear down and rebuild */
    8162:     while (next) {
    8163:       DMBoundary b = next;

    8165:       next = b->next;
    8166:       PetscCall(PetscFree(b));
    8167:     }
    8168:     dm->boundary = NULL;
    8169:   }

    8171:   lastnext = &dm->boundary;
    8172:   while (dsbound) {
    8173:     DMBoundary dmbound;

    8175:     PetscCall(PetscNew(&dmbound));
    8176:     dmbound->dsboundary = dsbound;
    8177:     dmbound->label      = dsbound->label;
    8178:     /* push on the back instead of the front so that it is in the same order as in the PetscDS */
    8179:     *lastnext = dmbound;
    8180:     lastnext  = &dmbound->next;
    8181:     dsbound   = dsbound->next;
    8182:   }
    8183:   PetscFunctionReturn(PETSC_SUCCESS);
    8184: }

    8186: /* TODO: missing manual page */
    8187: PetscErrorCode DMIsBoundaryPoint(DM dm, PetscInt point, PetscBool *isBd)
    8188: {
    8189:   DMBoundary b;

    8191:   PetscFunctionBegin;
    8193:   PetscAssertPointer(isBd, 3);
    8194:   *isBd = PETSC_FALSE;
    8195:   PetscCall(DMPopulateBoundary(dm));
    8196:   b = dm->boundary;
    8197:   while (b && !*isBd) {
    8198:     DMLabel    label = b->label;
    8199:     DSBoundary dsb   = b->dsboundary;
    8200:     PetscInt   i;

    8202:     if (label) {
    8203:       for (i = 0; i < dsb->Nv && !*isBd; ++i) PetscCall(DMLabelStratumHasPoint(label, dsb->values[i], point, isBd));
    8204:     }
    8205:     b = b->next;
    8206:   }
    8207:   PetscFunctionReturn(PETSC_SUCCESS);
    8208: }

    8210: /*@
    8211:   DMHasBound - Determine whether a bound condition was specified

    8213:   Logically collective

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

    8218:   Output Parameter:
    8219: . hasBound - Flag indicating if a bound condition was specified

    8221:   Level: intermediate

    8223: .seealso: [](ch_dmbase), `DM`, `DSAddBoundary()`, `PetscDSAddBoundary()`
    8224: @*/
    8225: PetscErrorCode DMHasBound(DM dm, PetscBool *hasBound)
    8226: {
    8227:   PetscDS  ds;
    8228:   PetscInt Nf, numBd;

    8230:   PetscFunctionBegin;
    8231:   *hasBound = PETSC_FALSE;
    8232:   PetscCall(DMGetDS(dm, &ds));
    8233:   PetscCall(PetscDSGetNumFields(ds, &Nf));
    8234:   for (PetscInt f = 0; f < Nf; ++f) {
    8235:     PetscSimplePointFn *lfunc, *ufunc;

    8237:     PetscCall(PetscDSGetLowerBound(ds, f, &lfunc, NULL));
    8238:     PetscCall(PetscDSGetUpperBound(ds, f, &ufunc, NULL));
    8239:     if (lfunc || ufunc) *hasBound = PETSC_TRUE;
    8240:   }

    8242:   PetscCall(PetscDSGetNumBoundary(ds, &numBd));
    8243:   PetscCall(PetscDSUpdateBoundaryLabels(ds, dm));
    8244:   for (PetscInt b = 0; b < numBd; ++b) {
    8245:     PetscWeakForm           wf;
    8246:     DMBoundaryConditionType type;
    8247:     const char             *name;
    8248:     DMLabel                 label;
    8249:     PetscInt                numids;
    8250:     const PetscInt         *ids;
    8251:     PetscInt                field, Nc;
    8252:     const PetscInt         *comps;
    8253:     PetscVoidFn            *bvfunc;
    8254:     void                   *ctx;

    8256:     PetscCall(PetscDSGetBoundary(ds, b, &wf, &type, &name, &label, &numids, &ids, &field, &Nc, &comps, &bvfunc, NULL, &ctx));
    8257:     if (type == DM_BC_LOWER_BOUND || type == DM_BC_UPPER_BOUND) *hasBound = PETSC_TRUE;
    8258:   }
    8259:   PetscFunctionReturn(PETSC_SUCCESS);
    8260: }

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

    8265:   Collective

    8267:   Input Parameters:
    8268: + dm    - The `DM`
    8269: . time  - The time
    8270: . funcs - The coordinate functions to evaluate, one per field
    8271: . ctxs  - Optional array of contexts to pass to each coordinate function.  ctxs itself may be null.
    8272: - mode  - The insertion mode for values

    8274:   Output Parameter:
    8275: . X - vector

    8277:   Calling sequence of `funcs`:
    8278: + dim  - The spatial dimension
    8279: . time - The time at which to sample
    8280: . x    - The coordinates
    8281: . Nc   - The number of components
    8282: . u    - The output field values
    8283: - ctx  - optional function context

    8285:   Level: developer

    8287:   Developer Notes:
    8288:   This API is specific to only particular usage of `DM`

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

    8292: .seealso: [](ch_dmbase), `DM`, `DMProjectFunctionLocal()`, `DMProjectFunctionLabel()`, `DMComputeL2Diff()`
    8293: @*/
    8294: 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)
    8295: {
    8296:   Vec localX;

    8298:   PetscFunctionBegin;
    8300:   PetscCall(PetscLogEventBegin(DM_ProjectFunction, dm, X, 0, 0));
    8301:   PetscCall(DMGetLocalVector(dm, &localX));
    8302:   PetscCall(VecSet(localX, 0.));
    8303:   PetscCall(DMProjectFunctionLocal(dm, time, funcs, ctxs, mode, localX));
    8304:   PetscCall(DMLocalToGlobalBegin(dm, localX, mode, X));
    8305:   PetscCall(DMLocalToGlobalEnd(dm, localX, mode, X));
    8306:   PetscCall(DMRestoreLocalVector(dm, &localX));
    8307:   PetscCall(PetscLogEventEnd(DM_ProjectFunction, dm, X, 0, 0));
    8308:   PetscFunctionReturn(PETSC_SUCCESS);
    8309: }

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

    8314:   Not Collective

    8316:   Input Parameters:
    8317: + dm    - The `DM`
    8318: . time  - The time
    8319: . funcs - The coordinate functions to evaluate, one per field
    8320: . ctxs  - Optional array of contexts to pass to each coordinate function.  ctxs itself may be null.
    8321: - mode  - The insertion mode for values

    8323:   Output Parameter:
    8324: . localX - vector

    8326:   Calling sequence of `funcs`:
    8327: + dim  - The spatial dimension
    8328: . time - The current timestep
    8329: . x    - The coordinates
    8330: . Nc   - The number of components
    8331: . u    - The output field values
    8332: - ctx  - optional function context

    8334:   Level: developer

    8336:   Developer Notes:
    8337:   This API is specific to only particular usage of `DM`

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

    8341: .seealso: [](ch_dmbase), `DM`, `DMProjectFunction()`, `DMProjectFunctionLabel()`, `DMComputeL2Diff()`
    8342: @*/
    8343: 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)
    8344: {
    8345:   PetscFunctionBegin;
    8348:   PetscUseTypeMethod(dm, projectfunctionlocal, time, funcs, ctxs, mode, localX);
    8349:   PetscFunctionReturn(PETSC_SUCCESS);
    8350: }

    8352: /*@C
    8353:   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.

    8355:   Collective

    8357:   Input Parameters:
    8358: + dm     - The `DM`
    8359: . time   - The time
    8360: . numIds - The number of ids
    8361: . ids    - The ids
    8362: . Nc     - The number of components
    8363: . comps  - The components
    8364: . label  - The `DMLabel` selecting the portion of the mesh for projection
    8365: . funcs  - The coordinate functions to evaluate, one per field
    8366: . ctxs   - Optional array of contexts to pass to each coordinate function.  ctxs may be null.
    8367: - mode   - The insertion mode for values

    8369:   Output Parameter:
    8370: . X - vector

    8372:   Calling sequence of `funcs`:
    8373: + dim  - The spatial dimension
    8374: . time - The current timestep
    8375: . x    - The coordinates
    8376: . Nc   - The number of components
    8377: . u    - The output field values
    8378: - ctx  - optional function context

    8380:   Level: developer

    8382:   Developer Notes:
    8383:   This API is specific to only particular usage of `DM`

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

    8387: .seealso: [](ch_dmbase), `DM`, `DMProjectFunction()`, `DMProjectFunctionLocal()`, `DMProjectFunctionLabelLocal()`, `DMComputeL2Diff()`
    8388: @*/
    8389: 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)
    8390: {
    8391:   Vec localX;

    8393:   PetscFunctionBegin;
    8395:   PetscCall(DMGetLocalVector(dm, &localX));
    8396:   PetscCall(VecSet(localX, 0.));
    8397:   PetscCall(DMProjectFunctionLabelLocal(dm, time, label, numIds, ids, Nc, comps, funcs, ctxs, mode, localX));
    8398:   PetscCall(DMLocalToGlobalBegin(dm, localX, mode, X));
    8399:   PetscCall(DMLocalToGlobalEnd(dm, localX, mode, X));
    8400:   PetscCall(DMRestoreLocalVector(dm, &localX));
    8401:   PetscFunctionReturn(PETSC_SUCCESS);
    8402: }

    8404: /*@C
    8405:   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.

    8407:   Not Collective

    8409:   Input Parameters:
    8410: + dm     - The `DM`
    8411: . time   - The time
    8412: . label  - The `DMLabel` selecting the portion of the mesh for projection
    8413: . numIds - The number of ids
    8414: . ids    - The ids
    8415: . Nc     - The number of components
    8416: . comps  - The components
    8417: . funcs  - The coordinate functions to evaluate, one per field
    8418: . ctxs   - Optional array of contexts to pass to each coordinate function.  ctxs itself may be null.
    8419: - mode   - The insertion mode for values

    8421:   Output Parameter:
    8422: . localX - vector

    8424:   Calling sequence of `funcs`:
    8425: + dim  - The spatial dimension
    8426: . time - The current time
    8427: . x    - The coordinates
    8428: . Nc   - The number of components
    8429: . u    - The output field values
    8430: - ctx  - optional function context

    8432:   Level: developer

    8434:   Developer Notes:
    8435:   This API is specific to only particular usage of `DM`

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

    8439: .seealso: [](ch_dmbase), `DM`, `DMProjectFunction()`, `DMProjectFunctionLocal()`, `DMProjectFunctionLabel()`, `DMComputeL2Diff()`
    8440: @*/
    8441: 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)
    8442: {
    8443:   PetscFunctionBegin;
    8446:   PetscUseTypeMethod(dm, projectfunctionlabellocal, time, label, numIds, ids, Nc, comps, funcs, ctxs, mode, localX);
    8447:   PetscFunctionReturn(PETSC_SUCCESS);
    8448: }

    8450: /*@C
    8451:   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.

    8453:   Not Collective

    8455:   Input Parameters:
    8456: + dm     - The `DM`
    8457: . time   - The time
    8458: . localU - The input field vector; may be `NULL` if projection is defined purely by coordinates
    8459: . funcs  - The functions to evaluate, one per field
    8460: - mode   - The insertion mode for values

    8462:   Output Parameter:
    8463: . localX - The output vector

    8465:   Calling sequence of `funcs`:
    8466: + dim          - The spatial dimension
    8467: . Nf           - The number of input fields
    8468: . NfAux        - The number of input auxiliary fields
    8469: . uOff         - The offset of each field in u[]
    8470: . uOff_x       - The offset of each field in u_x[]
    8471: . u            - The field values at this point in space
    8472: . u_t          - The field time derivative at this point in space (or `NULL`)
    8473: . u_x          - The field derivatives at this point in space
    8474: . aOff         - The offset of each auxiliary field in u[]
    8475: . aOff_x       - The offset of each auxiliary field in u_x[]
    8476: . a            - The auxiliary field values at this point in space
    8477: . a_t          - The auxiliary field time derivative at this point in space (or `NULL`)
    8478: . a_x          - The auxiliary field derivatives at this point in space
    8479: . t            - The current time
    8480: . x            - The coordinates of this point
    8481: . numConstants - The number of constants
    8482: . constants    - The value of each constant
    8483: - f            - The value of the function at this point in space

    8485:   Level: intermediate

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

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

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

    8498: .seealso: [](ch_dmbase), `DM`, `DMProjectField()`, `DMProjectFieldLabelLocal()`,
    8499: `DMProjectFunction()`, `DMComputeL2Diff()`
    8500: @*/
    8501: 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)
    8502: {
    8503:   PetscFunctionBegin;
    8507:   PetscUseTypeMethod(dm, projectfieldlocal, time, localU, funcs, mode, localX);
    8508:   PetscFunctionReturn(PETSC_SUCCESS);
    8509: }

    8511: /*@C
    8512:   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.

    8514:   Not Collective

    8516:   Input Parameters:
    8517: + dm     - The `DM`
    8518: . time   - The time
    8519: . label  - The `DMLabel` marking the portion of the domain to output
    8520: . numIds - The number of label ids to use
    8521: . ids    - The label ids to use for marking
    8522: . Nc     - The number of components to set in the output, or `PETSC_DETERMINE` for all components
    8523: . comps  - The components to set in the output, or `NULL` for all components
    8524: . localU - The input field vector
    8525: . funcs  - The functions to evaluate, one per field
    8526: - mode   - The insertion mode for values

    8528:   Output Parameter:
    8529: . localX - The output vector

    8531:   Calling sequence of `funcs`:
    8532: + dim          - The spatial dimension
    8533: . Nf           - The number of input fields
    8534: . NfAux        - The number of input auxiliary fields
    8535: . uOff         - The offset of each field in u[]
    8536: . uOff_x       - The offset of each field in u_x[]
    8537: . u            - The field values at this point in space
    8538: . u_t          - The field time derivative at this point in space (or `NULL`)
    8539: . u_x          - The field derivatives at this point in space
    8540: . aOff         - The offset of each auxiliary field in u[]
    8541: . aOff_x       - The offset of each auxiliary field in u_x[]
    8542: . a            - The auxiliary field values at this point in space
    8543: . a_t          - The auxiliary field time derivative at this point in space (or `NULL`)
    8544: . a_x          - The auxiliary field derivatives at this point in space
    8545: . t            - The current time
    8546: . x            - The coordinates of this point
    8547: . numConstants - The number of constants
    8548: . constants    - The value of each constant
    8549: - f            - The value of the function at this point in space

    8551:   Level: intermediate

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

    8559:   Developer Notes:
    8560:   This API is specific to only particular usage of `DM`

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

    8564: .seealso: [](ch_dmbase), `DM`, `DMProjectField()`, `DMProjectFieldLabel()`, `DMProjectFunction()`, `DMComputeL2Diff()`
    8565: @*/
    8566: 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)
    8567: {
    8568:   PetscFunctionBegin;
    8572:   PetscUseTypeMethod(dm, projectfieldlabellocal, time, label, numIds, ids, Nc, comps, localU, funcs, mode, localX);
    8573:   PetscFunctionReturn(PETSC_SUCCESS);
    8574: }

    8576: /*@C
    8577:   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.

    8579:   Not Collective

    8581:   Input Parameters:
    8582: + dm     - The `DM`
    8583: . time   - The time
    8584: . label  - The `DMLabel` marking the portion of the domain to output
    8585: . numIds - The number of label ids to use
    8586: . ids    - The label ids to use for marking
    8587: . Nc     - The number of components to set in the output, or `PETSC_DETERMINE` for all components
    8588: . comps  - The components to set in the output, or `NULL` for all components
    8589: . U      - The input field vector
    8590: . funcs  - The functions to evaluate, one per field
    8591: - mode   - The insertion mode for values

    8593:   Output Parameter:
    8594: . X - The output vector

    8596:   Calling sequence of `funcs`:
    8597: + dim          - The spatial dimension
    8598: . Nf           - The number of input fields
    8599: . NfAux        - The number of input auxiliary fields
    8600: . uOff         - The offset of each field in u[]
    8601: . uOff_x       - The offset of each field in u_x[]
    8602: . u            - The field values at this point in space
    8603: . u_t          - The field time derivative at this point in space (or `NULL`)
    8604: . u_x          - The field derivatives at this point in space
    8605: . aOff         - The offset of each auxiliary field in u[]
    8606: . aOff_x       - The offset of each auxiliary field in u_x[]
    8607: . a            - The auxiliary field values at this point in space
    8608: . a_t          - The auxiliary field time derivative at this point in space (or `NULL`)
    8609: . a_x          - The auxiliary field derivatives at this point in space
    8610: . t            - The current time
    8611: . x            - The coordinates of this point
    8612: . numConstants - The number of constants
    8613: . constants    - The value of each constant
    8614: - f            - The value of the function at this point in space

    8616:   Level: intermediate

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

    8624:   Developer Notes:
    8625:   This API is specific to only particular usage of `DM`

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

    8629: .seealso: [](ch_dmbase), `DM`, `DMProjectField()`, `DMProjectFieldLabelLocal()`, `DMProjectFunction()`, `DMComputeL2Diff()`
    8630: @*/
    8631: 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)
    8632: {
    8633:   DM  dmIn;
    8634:   Vec localU, localX;

    8636:   PetscFunctionBegin;
    8638:   PetscCall(VecGetDM(U, &dmIn));
    8639:   PetscCall(DMGetLocalVector(dmIn, &localU));
    8640:   PetscCall(DMGetLocalVector(dm, &localX));
    8641:   PetscCall(VecSet(localX, 0.));
    8642:   PetscCall(DMGlobalToLocalBegin(dmIn, U, mode, localU));
    8643:   PetscCall(DMGlobalToLocalEnd(dmIn, U, mode, localU));
    8644:   PetscCall(DMProjectFieldLabelLocal(dm, time, label, numIds, ids, Nc, comps, localU, funcs, mode, localX));
    8645:   PetscCall(DMLocalToGlobalBegin(dm, localX, mode, X));
    8646:   PetscCall(DMLocalToGlobalEnd(dm, localX, mode, X));
    8647:   PetscCall(DMRestoreLocalVector(dm, &localX));
    8648:   PetscCall(DMRestoreLocalVector(dmIn, &localU));
    8649:   PetscFunctionReturn(PETSC_SUCCESS);
    8650: }

    8652: /*@C
    8653:   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.

    8655:   Not Collective

    8657:   Input Parameters:
    8658: + dm     - The `DM`
    8659: . time   - The time
    8660: . label  - The `DMLabel` marking the portion of the domain boundary to output
    8661: . numIds - The number of label ids to use
    8662: . ids    - The label ids to use for marking
    8663: . Nc     - The number of components to set in the output, or `PETSC_DETERMINE` for all components
    8664: . comps  - The components to set in the output, or `NULL` for all components
    8665: . localU - The input field vector
    8666: . funcs  - The functions to evaluate, one per field
    8667: - mode   - The insertion mode for values

    8669:   Output Parameter:
    8670: . localX - The output vector

    8672:   Calling sequence of `funcs`:
    8673: + dim          - The spatial dimension
    8674: . Nf           - The number of input fields
    8675: . NfAux        - The number of input auxiliary fields
    8676: . uOff         - The offset of each field in u[]
    8677: . uOff_x       - The offset of each field in u_x[]
    8678: . u            - The field values at this point in space
    8679: . u_t          - The field time derivative at this point in space (or `NULL`)
    8680: . u_x          - The field derivatives at this point in space
    8681: . aOff         - The offset of each auxiliary field in u[]
    8682: . aOff_x       - The offset of each auxiliary field in u_x[]
    8683: . a            - The auxiliary field values at this point in space
    8684: . a_t          - The auxiliary field time derivative at this point in space (or `NULL`)
    8685: . a_x          - The auxiliary field derivatives at this point in space
    8686: . t            - The current time
    8687: . x            - The coordinates of this point
    8688: . n            - The face normal
    8689: . numConstants - The number of constants
    8690: . constants    - The value of each constant
    8691: - f            - The value of the function at this point in space

    8693:   Level: intermediate

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

    8701:   Developer Notes:
    8702:   This API is specific to only particular usage of `DM`

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

    8706: .seealso: [](ch_dmbase), `DM`, `DMProjectField()`, `DMProjectFieldLabelLocal()`, `DMProjectFunction()`, `DMComputeL2Diff()`
    8707: @*/
    8708: 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)
    8709: {
    8710:   PetscFunctionBegin;
    8714:   PetscUseTypeMethod(dm, projectbdfieldlabellocal, time, label, numIds, ids, Nc, comps, localU, funcs, mode, localX);
    8715:   PetscFunctionReturn(PETSC_SUCCESS);
    8716: }

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

    8721:   Collective

    8723:   Input Parameters:
    8724: + dm    - The `DM`
    8725: . time  - The time
    8726: . funcs - The functions to evaluate for each field component
    8727: . ctxs  - Optional array of contexts to pass to each function, or `NULL`.
    8728: - X     - The coefficient vector u_h, a global vector

    8730:   Output Parameter:
    8731: . diff - The diff ||u - u_h||_2

    8733:   Level: developer

    8735:   Developer Notes:
    8736:   This API is specific to only particular usage of `DM`

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

    8740: .seealso: [](ch_dmbase), `DM`, `DMProjectFunction()`, `DMComputeL2FieldDiff()`, `DMComputeL2GradientDiff()`
    8741: @*/
    8742: PetscErrorCode DMComputeL2Diff(DM dm, PetscReal time, PetscErrorCode (**funcs)(PetscInt, PetscReal, const PetscReal[], PetscInt, PetscScalar *, void *), void **ctxs, Vec X, PetscReal *diff)
    8743: {
    8744:   PetscFunctionBegin;
    8747:   PetscUseTypeMethod(dm, computel2diff, time, funcs, ctxs, X, diff);
    8748:   PetscFunctionReturn(PETSC_SUCCESS);
    8749: }

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

    8754:   Collective

    8756:   Input Parameters:
    8757: + dm    - The `DM`
    8758: . time  - The time
    8759: . funcs - The gradient functions to evaluate for each field component
    8760: . ctxs  - Optional array of contexts to pass to each function, or `NULL`.
    8761: . X     - The coefficient vector u_h, a global vector
    8762: - n     - The vector to project along

    8764:   Output Parameter:
    8765: . diff - The diff ||(grad u - grad u_h) . n||_2

    8767:   Level: developer

    8769:   Developer Notes:
    8770:   This API is specific to only particular usage of `DM`

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

    8774: .seealso: [](ch_dmbase), `DM`, `DMProjectFunction()`, `DMComputeL2Diff()`, `DMComputeL2FieldDiff()`
    8775: @*/
    8776: 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)
    8777: {
    8778:   PetscFunctionBegin;
    8781:   PetscUseTypeMethod(dm, computel2gradientdiff, time, funcs, ctxs, X, n, diff);
    8782:   PetscFunctionReturn(PETSC_SUCCESS);
    8783: }

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

    8788:   Collective

    8790:   Input Parameters:
    8791: + dm    - The `DM`
    8792: . time  - The time
    8793: . funcs - The functions to evaluate for each field component
    8794: . ctxs  - Optional array of contexts to pass to each function, or `NULL`.
    8795: - X     - The coefficient vector u_h, a global vector

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

    8800:   Level: developer

    8802:   Developer Notes:
    8803:   This API is specific to only particular usage of `DM`

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

    8807: .seealso: [](ch_dmbase), `DM`, `DMProjectFunction()`, `DMComputeL2GradientDiff()`
    8808: @*/
    8809: PetscErrorCode DMComputeL2FieldDiff(DM dm, PetscReal time, PetscErrorCode (**funcs)(PetscInt, PetscReal, const PetscReal[], PetscInt, PetscScalar *, void *), void **ctxs, Vec X, PetscReal diff[])
    8810: {
    8811:   PetscFunctionBegin;
    8814:   PetscUseTypeMethod(dm, computel2fielddiff, time, funcs, ctxs, X, diff);
    8815:   PetscFunctionReturn(PETSC_SUCCESS);
    8816: }

    8818: /*@C
    8819:   DMGetNeighbors - Gets an array containing the MPI ranks of all the processes neighbors

    8821:   Not Collective

    8823:   Input Parameter:
    8824: . dm - The `DM`

    8826:   Output Parameters:
    8827: + nranks - the number of neighbours
    8828: - ranks  - the neighbors ranks

    8830:   Level: beginner

    8832:   Note:
    8833:   Do not free the array, it is freed when the `DM` is destroyed.

    8835: .seealso: [](ch_dmbase), `DM`, `DMDAGetNeighbors()`, `PetscSFGetRootRanks()`
    8836: @*/
    8837: PetscErrorCode DMGetNeighbors(DM dm, PetscInt *nranks, const PetscMPIInt *ranks[])
    8838: {
    8839:   PetscFunctionBegin;
    8841:   PetscUseTypeMethod(dm, getneighbors, nranks, ranks);
    8842:   PetscFunctionReturn(PETSC_SUCCESS);
    8843: }

    8845: #include <petsc/private/matimpl.h>

    8847: /*
    8848:     Converts the input vector to a ghosted vector and then calls the standard coloring code.
    8849:     This must be a different function because it requires DM which is not defined in the Mat library
    8850: */
    8851: static PetscErrorCode MatFDColoringApply_AIJDM(Mat J, MatFDColoring coloring, Vec x1, void *sctx)
    8852: {
    8853:   PetscFunctionBegin;
    8854:   if (coloring->ctype == IS_COLORING_LOCAL) {
    8855:     Vec x1local;
    8856:     DM  dm;
    8857:     PetscCall(MatGetDM(J, &dm));
    8858:     PetscCheck(dm, PetscObjectComm((PetscObject)J), PETSC_ERR_ARG_INCOMP, "IS_COLORING_LOCAL requires a DM");
    8859:     PetscCall(DMGetLocalVector(dm, &x1local));
    8860:     PetscCall(DMGlobalToLocalBegin(dm, x1, INSERT_VALUES, x1local));
    8861:     PetscCall(DMGlobalToLocalEnd(dm, x1, INSERT_VALUES, x1local));
    8862:     x1 = x1local;
    8863:   }
    8864:   PetscCall(MatFDColoringApply_AIJ(J, coloring, x1, sctx));
    8865:   if (coloring->ctype == IS_COLORING_LOCAL) {
    8866:     DM dm;
    8867:     PetscCall(MatGetDM(J, &dm));
    8868:     PetscCall(DMRestoreLocalVector(dm, &x1));
    8869:   }
    8870:   PetscFunctionReturn(PETSC_SUCCESS);
    8871: }

    8873: /*@
    8874:   MatFDColoringUseDM - allows a `MatFDColoring` object to use the `DM` associated with the matrix to compute a `IS_COLORING_LOCAL` coloring

    8876:   Input Parameters:
    8877: + coloring   - The matrix to get the `DM` from
    8878: - fdcoloring - the `MatFDColoring` object

    8880:   Level: advanced

    8882:   Developer Note:
    8883:   This routine exists because the PETSc `Mat` library does not know about the `DM` objects

    8885: .seealso: [](ch_dmbase), `DM`, `MatFDColoring`, `MatFDColoringCreate()`, `ISColoringType`
    8886: @*/
    8887: PetscErrorCode MatFDColoringUseDM(Mat coloring, MatFDColoring fdcoloring)
    8888: {
    8889:   PetscFunctionBegin;
    8890:   coloring->ops->fdcoloringapply = MatFDColoringApply_AIJDM;
    8891:   PetscFunctionReturn(PETSC_SUCCESS);
    8892: }

    8894: /*@
    8895:   DMGetCompatibility - determine if two `DM`s are compatible

    8897:   Collective

    8899:   Input Parameters:
    8900: + dm1 - the first `DM`
    8901: - dm2 - the second `DM`

    8903:   Output Parameters:
    8904: + compatible - whether or not the two `DM`s are compatible
    8905: - set        - whether or not the compatible value was actually determined and set

    8907:   Level: advanced

    8909:   Notes:
    8910:   Two `DM`s are deemed compatible if they represent the same parallel decomposition
    8911:   of the same topology. This implies that the section (field data) on one
    8912:   "makes sense" with respect to the topology and parallel decomposition of the other.
    8913:   Loosely speaking, compatible `DM`s represent the same domain and parallel
    8914:   decomposition, but hold different data.

    8916:   Typically, one would confirm compatibility if intending to simultaneously iterate
    8917:   over a pair of vectors obtained from different `DM`s.

    8919:   For example, two `DMDA` objects are compatible if they have the same local
    8920:   and global sizes and the same stencil width. They can have different numbers
    8921:   of degrees of freedom per node. Thus, one could use the node numbering from
    8922:   either `DM` in bounds for a loop over vectors derived from either `DM`.

    8924:   Consider the operation of summing data living on a 2-dof `DMDA` to data living
    8925:   on a 1-dof `DMDA`, which should be compatible, as in the following snippet.
    8926: .vb
    8927:   ...
    8928:   PetscCall(DMGetCompatibility(da1,da2,&compatible,&set));
    8929:   if (set && compatible)  {
    8930:     PetscCall(DMDAVecGetArrayDOF(da1,vec1,&arr1));
    8931:     PetscCall(DMDAVecGetArrayDOF(da2,vec2,&arr2));
    8932:     PetscCall(DMDAGetCorners(da1,&x,&y,NULL,&m,&n,NULL));
    8933:     for (j=y; j<y+n; ++j) {
    8934:       for (i=x; i<x+m, ++i) {
    8935:         arr1[j][i][0] = arr2[j][i][0] + arr2[j][i][1];
    8936:       }
    8937:     }
    8938:     PetscCall(DMDAVecRestoreArrayDOF(da1,vec1,&arr1));
    8939:     PetscCall(DMDAVecRestoreArrayDOF(da2,vec2,&arr2));
    8940:   } else {
    8941:     SETERRQ(PetscObjectComm((PetscObject)da1,PETSC_ERR_ARG_INCOMP,"DMDA objects incompatible");
    8942:   }
    8943:   ...
    8944: .ve

    8946:   Checking compatibility might be expensive for a given implementation of `DM`,
    8947:   or might be impossible to unambiguously confirm or deny. For this reason,
    8948:   this function may decline to determine compatibility, and hence users should
    8949:   always check the "set" output parameter.

    8951:   A `DM` is always compatible with itself.

    8953:   In the current implementation, `DM`s which live on "unequal" communicators
    8954:   (MPI_UNEQUAL in the terminology of MPI_Comm_compare()) are always deemed
    8955:   incompatible.

    8957:   This function is labeled "Collective," as information about all subdomains
    8958:   is required on each rank. However, in `DM` implementations which store all this
    8959:   information locally, this function may be merely "Logically Collective".

    8961:   Developer Note:
    8962:   Compatibility is assumed to be a symmetric concept; `DM` A is compatible with `DM` B
    8963:   iff B is compatible with A. Thus, this function checks the implementations
    8964:   of both dm and dmc (if they are of different types), attempting to determine
    8965:   compatibility. It is left to `DM` implementers to ensure that symmetry is
    8966:   preserved. The simplest way to do this is, when implementing type-specific
    8967:   logic for this function, is to check for existing logic in the implementation
    8968:   of other `DM` types and let *set = PETSC_FALSE if found.

    8970: .seealso: [](ch_dmbase), `DM`, `DMDACreateCompatibleDMDA()`, `DMStagCreateCompatibleDMStag()`
    8971: @*/
    8972: PetscErrorCode DMGetCompatibility(DM dm1, DM dm2, PetscBool *compatible, PetscBool *set)
    8973: {
    8974:   PetscMPIInt compareResult;
    8975:   DMType      type, type2;
    8976:   PetscBool   sameType;

    8978:   PetscFunctionBegin;

    8982:   /* Declare a DM compatible with itself */
    8983:   if (dm1 == dm2) {
    8984:     *set        = PETSC_TRUE;
    8985:     *compatible = PETSC_TRUE;
    8986:     PetscFunctionReturn(PETSC_SUCCESS);
    8987:   }

    8989:   /* Declare a DM incompatible with a DM that lives on an "unequal"
    8990:      communicator. Note that this does not preclude compatibility with
    8991:      DMs living on "congruent" or "similar" communicators, but this must be
    8992:      determined by the implementation-specific logic */
    8993:   PetscCallMPI(MPI_Comm_compare(PetscObjectComm((PetscObject)dm1), PetscObjectComm((PetscObject)dm2), &compareResult));
    8994:   if (compareResult == MPI_UNEQUAL) {
    8995:     *set        = PETSC_TRUE;
    8996:     *compatible = PETSC_FALSE;
    8997:     PetscFunctionReturn(PETSC_SUCCESS);
    8998:   }

    9000:   /* Pass to the implementation-specific routine, if one exists. */
    9001:   if (dm1->ops->getcompatibility) {
    9002:     PetscUseTypeMethod(dm1, getcompatibility, dm2, compatible, set);
    9003:     if (*set) PetscFunctionReturn(PETSC_SUCCESS);
    9004:   }

    9006:   /* If dm1 and dm2 are of different types, then attempt to check compatibility
    9007:      with an implementation of this function from dm2 */
    9008:   PetscCall(DMGetType(dm1, &type));
    9009:   PetscCall(DMGetType(dm2, &type2));
    9010:   PetscCall(PetscStrcmp(type, type2, &sameType));
    9011:   if (!sameType && dm2->ops->getcompatibility) {
    9012:     PetscUseTypeMethod(dm2, getcompatibility, dm1, compatible, set); /* Note argument order */
    9013:   } else {
    9014:     *set = PETSC_FALSE;
    9015:   }
    9016:   PetscFunctionReturn(PETSC_SUCCESS);
    9017: }

    9019: /*@C
    9020:   DMMonitorSet - Sets an additional monitor function that is to be used after a solve to monitor discretization performance.

    9022:   Logically Collective

    9024:   Input Parameters:
    9025: + dm             - the `DM`
    9026: . f              - the monitor function
    9027: . mctx           - [optional] context for private data for the monitor routine (use `NULL` if no context is desired)
    9028: - monitordestroy - [optional] routine that frees monitor context (may be `NULL`), see `PetscCtxDestroyFn` for the calling sequence

    9030:   Options Database Key:
    9031: . -dm_monitor_cancel - cancels all monitors that have been hardwired into a code by calls to `DMMonitorSet()`, but
    9032:                        does not cancel those set via the options database.

    9034:   Level: intermediate

    9036:   Note:
    9037:   Several different monitoring routines may be set by calling
    9038:   `DMMonitorSet()` multiple times or with `DMMonitorSetFromOptions()`; all will be called in the
    9039:   order in which they were set.

    9041:   Fortran Note:
    9042:   Only a single monitor function can be set for each `DM` object

    9044:   Developer Note:
    9045:   This API has a generic name but seems specific to a very particular aspect of the use of `DM`

    9047: .seealso: [](ch_dmbase), `DM`, `DMMonitorCancel()`, `DMMonitorSetFromOptions()`, `DMMonitor()`, `PetscCtxDestroyFn`
    9048: @*/
    9049: PetscErrorCode DMMonitorSet(DM dm, PetscErrorCode (*f)(DM, void *), void *mctx, PetscCtxDestroyFn *monitordestroy)
    9050: {
    9051:   PetscFunctionBegin;
    9053:   for (PetscInt m = 0; m < dm->numbermonitors; ++m) {
    9054:     PetscBool identical;

    9056:     PetscCall(PetscMonitorCompare((PetscErrorCode (*)(void))(PetscVoidFn *)f, mctx, monitordestroy, (PetscErrorCode (*)(void))(PetscVoidFn *)dm->monitor[m], dm->monitorcontext[m], dm->monitordestroy[m], &identical));
    9057:     if (identical) PetscFunctionReturn(PETSC_SUCCESS);
    9058:   }
    9059:   PetscCheck(dm->numbermonitors < MAXDMMONITORS, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Too many monitors set");
    9060:   dm->monitor[dm->numbermonitors]          = f;
    9061:   dm->monitordestroy[dm->numbermonitors]   = monitordestroy;
    9062:   dm->monitorcontext[dm->numbermonitors++] = mctx;
    9063:   PetscFunctionReturn(PETSC_SUCCESS);
    9064: }

    9066: /*@
    9067:   DMMonitorCancel - Clears all the monitor functions for a `DM` object.

    9069:   Logically Collective

    9071:   Input Parameter:
    9072: . dm - the DM

    9074:   Options Database Key:
    9075: . -dm_monitor_cancel - cancels all monitors that have been hardwired
    9076:   into a code by calls to `DMonitorSet()`, but does not cancel those
    9077:   set via the options database

    9079:   Level: intermediate

    9081:   Note:
    9082:   There is no way to clear one specific monitor from a `DM` object.

    9084: .seealso: [](ch_dmbase), `DM`, `DMMonitorSet()`, `DMMonitorSetFromOptions()`, `DMMonitor()`
    9085: @*/
    9086: PetscErrorCode DMMonitorCancel(DM dm)
    9087: {
    9088:   PetscInt m;

    9090:   PetscFunctionBegin;
    9092:   for (m = 0; m < dm->numbermonitors; ++m) {
    9093:     if (dm->monitordestroy[m]) PetscCall((*dm->monitordestroy[m])(&dm->monitorcontext[m]));
    9094:   }
    9095:   dm->numbermonitors = 0;
    9096:   PetscFunctionReturn(PETSC_SUCCESS);
    9097: }

    9099: /*@C
    9100:   DMMonitorSetFromOptions - Sets a monitor function and viewer appropriate for the type indicated by the user

    9102:   Collective

    9104:   Input Parameters:
    9105: + dm           - `DM` object you wish to monitor
    9106: . name         - the monitor type one is seeking
    9107: . help         - message indicating what monitoring is done
    9108: . manual       - manual page for the monitor
    9109: . monitor      - the monitor function, this must use a `PetscViewerFormat` as its context
    9110: - 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

    9112:   Output Parameter:
    9113: . flg - Flag set if the monitor was created

    9115:   Calling sequence of `monitor`:
    9116: + dm  - the `DM` to be monitored
    9117: - ctx - monitor context

    9119:   Calling sequence of `monitorsetup`:
    9120: + dm - the `DM` to be monitored
    9121: - vf - the `PetscViewer` and format to be used by the monitor

    9123:   Level: developer

    9125: .seealso: [](ch_dmbase), `DM`, `PetscOptionsCreateViewer()`, `PetscOptionsGetReal()`, `PetscOptionsHasName()`, `PetscOptionsGetString()`,
    9126:           `PetscOptionsGetIntArray()`, `PetscOptionsGetRealArray()`, `PetscOptionsBool()`,
    9127:           `PetscOptionsInt()`, `PetscOptionsString()`, `PetscOptionsReal()`,
    9128:           `PetscOptionsName()`, `PetscOptionsBegin()`, `PetscOptionsEnd()`, `PetscOptionsHeadBegin()`,
    9129:           `PetscOptionsStringArray()`, `PetscOptionsRealArray()`, `PetscOptionsScalar()`,
    9130:           `PetscOptionsBoolGroupBegin()`, `PetscOptionsBoolGroup()`, `PetscOptionsBoolGroupEnd()`,
    9131:           `PetscOptionsFList()`, `PetscOptionsEList()`, `DMMonitor()`, `DMMonitorSet()`
    9132: @*/
    9133: 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)
    9134: {
    9135:   PetscViewer       viewer;
    9136:   PetscViewerFormat format;

    9138:   PetscFunctionBegin;
    9140:   PetscCall(PetscOptionsCreateViewer(PetscObjectComm((PetscObject)dm), ((PetscObject)dm)->options, ((PetscObject)dm)->prefix, name, &viewer, &format, flg));
    9141:   if (*flg) {
    9142:     PetscViewerAndFormat *vf;

    9144:     PetscCall(PetscViewerAndFormatCreate(viewer, format, &vf));
    9145:     PetscCall(PetscViewerDestroy(&viewer));
    9146:     if (monitorsetup) PetscCall((*monitorsetup)(dm, vf));
    9147:     PetscCall(DMMonitorSet(dm, monitor, vf, (PetscCtxDestroyFn *)PetscViewerAndFormatDestroy));
    9148:   }
    9149:   PetscFunctionReturn(PETSC_SUCCESS);
    9150: }

    9152: /*@
    9153:   DMMonitor - runs the user provided monitor routines, if they exist

    9155:   Collective

    9157:   Input Parameter:
    9158: . dm - The `DM`

    9160:   Level: developer

    9162:   Developer Note:
    9163:   Note should indicate when during the life of the `DM` the monitor is run. It appears to be
    9164:   related to the discretization process seems rather specialized since some `DM` have no
    9165:   concept of discretization.

    9167: .seealso: [](ch_dmbase), `DM`, `DMMonitorSet()`, `DMMonitorSetFromOptions()`
    9168: @*/
    9169: PetscErrorCode DMMonitor(DM dm)
    9170: {
    9171:   PetscInt m;

    9173:   PetscFunctionBegin;
    9174:   if (!dm) PetscFunctionReturn(PETSC_SUCCESS);
    9176:   for (m = 0; m < dm->numbermonitors; ++m) PetscCall((*dm->monitor[m])(dm, dm->monitorcontext[m]));
    9177:   PetscFunctionReturn(PETSC_SUCCESS);
    9178: }

    9180: /*@
    9181:   DMComputeError - Computes the error assuming the user has provided the exact solution functions

    9183:   Collective

    9185:   Input Parameters:
    9186: + dm  - The `DM`
    9187: - sol - The solution vector

    9189:   Input/Output Parameter:
    9190: . errors - An array of length Nf, the number of fields, or `NULL` for no output; on output
    9191:            contains the error in each field

    9193:   Output Parameter:
    9194: . errorVec - A vector to hold the cellwise error (may be `NULL`)

    9196:   Level: developer

    9198:   Note:
    9199:   The exact solutions come from the `PetscDS` object, and the time comes from `DMGetOutputSequenceNumber()`.

    9201: .seealso: [](ch_dmbase), `DM`, `DMMonitorSet()`, `DMGetRegionNumDS()`, `PetscDSGetExactSolution()`, `DMGetOutputSequenceNumber()`
    9202: @*/
    9203: PetscErrorCode DMComputeError(DM dm, Vec sol, PetscReal errors[], Vec *errorVec)
    9204: {
    9205:   PetscErrorCode (**exactSol)(PetscInt, PetscReal, const PetscReal[], PetscInt, PetscScalar[], void *);
    9206:   void    **ctxs;
    9207:   PetscReal time;
    9208:   PetscInt  Nf, f, Nds, s;

    9210:   PetscFunctionBegin;
    9211:   PetscCall(DMGetNumFields(dm, &Nf));
    9212:   PetscCall(PetscCalloc2(Nf, &exactSol, Nf, &ctxs));
    9213:   PetscCall(DMGetNumDS(dm, &Nds));
    9214:   for (s = 0; s < Nds; ++s) {
    9215:     PetscDS         ds;
    9216:     DMLabel         label;
    9217:     IS              fieldIS;
    9218:     const PetscInt *fields;
    9219:     PetscInt        dsNf;

    9221:     PetscCall(DMGetRegionNumDS(dm, s, &label, &fieldIS, &ds, NULL));
    9222:     PetscCall(PetscDSGetNumFields(ds, &dsNf));
    9223:     if (fieldIS) PetscCall(ISGetIndices(fieldIS, &fields));
    9224:     for (f = 0; f < dsNf; ++f) {
    9225:       const PetscInt field = fields[f];
    9226:       PetscCall(PetscDSGetExactSolution(ds, field, &exactSol[field], &ctxs[field]));
    9227:     }
    9228:     if (fieldIS) PetscCall(ISRestoreIndices(fieldIS, &fields));
    9229:   }
    9230:   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);
    9231:   PetscCall(DMGetOutputSequenceNumber(dm, NULL, &time));
    9232:   if (errors) PetscCall(DMComputeL2FieldDiff(dm, time, exactSol, ctxs, sol, errors));
    9233:   if (errorVec) {
    9234:     DM             edm;
    9235:     DMPolytopeType ct;
    9236:     PetscBool      simplex;
    9237:     PetscInt       dim, cStart, Nf;

    9239:     PetscCall(DMClone(dm, &edm));
    9240:     PetscCall(DMGetDimension(edm, &dim));
    9241:     PetscCall(DMPlexGetHeightStratum(dm, 0, &cStart, NULL));
    9242:     PetscCall(DMPlexGetCellType(dm, cStart, &ct));
    9243:     simplex = DMPolytopeTypeGetNumVertices(ct) == DMPolytopeTypeGetDim(ct) + 1 ? PETSC_TRUE : PETSC_FALSE;
    9244:     PetscCall(DMGetNumFields(dm, &Nf));
    9245:     for (f = 0; f < Nf; ++f) {
    9246:       PetscFE         fe, efe;
    9247:       PetscQuadrature q;
    9248:       const char     *name;

    9250:       PetscCall(DMGetField(dm, f, NULL, (PetscObject *)&fe));
    9251:       PetscCall(PetscFECreateLagrange(PETSC_COMM_SELF, dim, Nf, simplex, 0, PETSC_DETERMINE, &efe));
    9252:       PetscCall(PetscObjectGetName((PetscObject)fe, &name));
    9253:       PetscCall(PetscObjectSetName((PetscObject)efe, name));
    9254:       PetscCall(PetscFEGetQuadrature(fe, &q));
    9255:       PetscCall(PetscFESetQuadrature(efe, q));
    9256:       PetscCall(DMSetField(edm, f, NULL, (PetscObject)efe));
    9257:       PetscCall(PetscFEDestroy(&efe));
    9258:     }
    9259:     PetscCall(DMCreateDS(edm));

    9261:     PetscCall(DMCreateGlobalVector(edm, errorVec));
    9262:     PetscCall(PetscObjectSetName((PetscObject)*errorVec, "Error"));
    9263:     PetscCall(DMPlexComputeL2DiffVec(dm, time, exactSol, ctxs, sol, *errorVec));
    9264:     PetscCall(DMDestroy(&edm));
    9265:   }
    9266:   PetscCall(PetscFree2(exactSol, ctxs));
    9267:   PetscFunctionReturn(PETSC_SUCCESS);
    9268: }

    9270: /*@
    9271:   DMGetNumAuxiliaryVec - Get the number of auxiliary vectors associated with this `DM`

    9273:   Not Collective

    9275:   Input Parameter:
    9276: . dm - The `DM`

    9278:   Output Parameter:
    9279: . numAux - The number of auxiliary data vectors

    9281:   Level: advanced

    9283: .seealso: [](ch_dmbase), `DM`, `DMClearAuxiliaryVec()`, `DMSetAuxiliaryVec()`, `DMGetAuxiliaryLabels()`, `DMGetAuxiliaryVec()`
    9284: @*/
    9285: PetscErrorCode DMGetNumAuxiliaryVec(DM dm, PetscInt *numAux)
    9286: {
    9287:   PetscFunctionBegin;
    9289:   PetscCall(PetscHMapAuxGetSize(dm->auxData, numAux));
    9290:   PetscFunctionReturn(PETSC_SUCCESS);
    9291: }

    9293: /*@
    9294:   DMGetAuxiliaryVec - Get the auxiliary vector for region specified by the given label and value, and equation part

    9296:   Not Collective

    9298:   Input Parameters:
    9299: + dm    - The `DM`
    9300: . label - The `DMLabel`
    9301: . value - The label value indicating the region
    9302: - part  - The equation part, or 0 if unused

    9304:   Output Parameter:
    9305: . aux - The `Vec` holding auxiliary field data

    9307:   Level: advanced

    9309:   Note:
    9310:   If no auxiliary vector is found for this (label, value), (`NULL`, 0, 0) is checked as well.

    9312: .seealso: [](ch_dmbase), `DM`, `DMClearAuxiliaryVec()`, `DMSetAuxiliaryVec()`, `DMGetNumAuxiliaryVec()`, `DMGetAuxiliaryLabels()`
    9313: @*/
    9314: PetscErrorCode DMGetAuxiliaryVec(DM dm, DMLabel label, PetscInt value, PetscInt part, Vec *aux)
    9315: {
    9316:   PetscHashAuxKey key, wild = {NULL, 0, 0};
    9317:   PetscBool       has;

    9319:   PetscFunctionBegin;
    9322:   key.label = label;
    9323:   key.value = value;
    9324:   key.part  = part;
    9325:   PetscCall(PetscHMapAuxHas(dm->auxData, key, &has));
    9326:   if (has) PetscCall(PetscHMapAuxGet(dm->auxData, key, aux));
    9327:   else PetscCall(PetscHMapAuxGet(dm->auxData, wild, aux));
    9328:   PetscFunctionReturn(PETSC_SUCCESS);
    9329: }

    9331: /*@
    9332:   DMSetAuxiliaryVec - Set an auxiliary vector for region specified by the given label and value, and equation part

    9334:   Not Collective because auxiliary vectors are not parallel

    9336:   Input Parameters:
    9337: + dm    - The `DM`
    9338: . label - The `DMLabel`
    9339: . value - The label value indicating the region
    9340: . part  - The equation part, or 0 if unused
    9341: - aux   - The `Vec` holding auxiliary field data

    9343:   Level: advanced

    9345: .seealso: [](ch_dmbase), `DM`, `DMClearAuxiliaryVec()`, `DMGetAuxiliaryVec()`, `DMGetAuxiliaryLabels()`, `DMCopyAuxiliaryVec()`
    9346: @*/
    9347: PetscErrorCode DMSetAuxiliaryVec(DM dm, DMLabel label, PetscInt value, PetscInt part, Vec aux)
    9348: {
    9349:   Vec             old;
    9350:   PetscHashAuxKey key;

    9352:   PetscFunctionBegin;
    9355:   key.label = label;
    9356:   key.value = value;
    9357:   key.part  = part;
    9358:   PetscCall(PetscHMapAuxGet(dm->auxData, key, &old));
    9359:   PetscCall(PetscObjectReference((PetscObject)aux));
    9360:   if (!aux) PetscCall(PetscHMapAuxDel(dm->auxData, key));
    9361:   else PetscCall(PetscHMapAuxSet(dm->auxData, key, aux));
    9362:   PetscCall(VecDestroy(&old));
    9363:   PetscFunctionReturn(PETSC_SUCCESS);
    9364: }

    9366: /*@
    9367:   DMGetAuxiliaryLabels - Get the labels, values, and parts for all auxiliary vectors in this `DM`

    9369:   Not Collective

    9371:   Input Parameter:
    9372: . dm - The `DM`

    9374:   Output Parameters:
    9375: + labels - The `DMLabel`s for each `Vec`
    9376: . values - The label values for each `Vec`
    9377: - parts  - The equation parts for each `Vec`

    9379:   Level: advanced

    9381:   Note:
    9382:   The arrays passed in must be at least as large as `DMGetNumAuxiliaryVec()`.

    9384: .seealso: [](ch_dmbase), `DM`, `DMClearAuxiliaryVec()`, `DMGetNumAuxiliaryVec()`, `DMGetAuxiliaryVec()`, `DMSetAuxiliaryVec()`, `DMCopyAuxiliaryVec()`
    9385: @*/
    9386: PetscErrorCode DMGetAuxiliaryLabels(DM dm, DMLabel labels[], PetscInt values[], PetscInt parts[])
    9387: {
    9388:   PetscHashAuxKey *keys;
    9389:   PetscInt         n, i, off = 0;

    9391:   PetscFunctionBegin;
    9393:   PetscAssertPointer(labels, 2);
    9394:   PetscAssertPointer(values, 3);
    9395:   PetscAssertPointer(parts, 4);
    9396:   PetscCall(DMGetNumAuxiliaryVec(dm, &n));
    9397:   PetscCall(PetscMalloc1(n, &keys));
    9398:   PetscCall(PetscHMapAuxGetKeys(dm->auxData, &off, keys));
    9399:   for (i = 0; i < n; ++i) {
    9400:     labels[i] = keys[i].label;
    9401:     values[i] = keys[i].value;
    9402:     parts[i]  = keys[i].part;
    9403:   }
    9404:   PetscCall(PetscFree(keys));
    9405:   PetscFunctionReturn(PETSC_SUCCESS);
    9406: }

    9408: /*@
    9409:   DMCopyAuxiliaryVec - Copy the auxiliary vector data on a `DM` to a new `DM`

    9411:   Not Collective

    9413:   Input Parameter:
    9414: . dm - The `DM`

    9416:   Output Parameter:
    9417: . dmNew - The new `DM`, now with the same auxiliary data

    9419:   Level: advanced

    9421:   Note:
    9422:   This is a shallow copy of the auxiliary vectors

    9424: .seealso: [](ch_dmbase), `DM`, `DMClearAuxiliaryVec()`, `DMGetNumAuxiliaryVec()`, `DMGetAuxiliaryVec()`, `DMSetAuxiliaryVec()`
    9425: @*/
    9426: PetscErrorCode DMCopyAuxiliaryVec(DM dm, DM dmNew)
    9427: {
    9428:   PetscFunctionBegin;
    9431:   if (dm == dmNew) PetscFunctionReturn(PETSC_SUCCESS);
    9432:   PetscCall(DMClearAuxiliaryVec(dmNew));

    9434:   PetscCall(PetscHMapAuxDestroy(&dmNew->auxData));
    9435:   PetscCall(PetscHMapAuxDuplicate(dm->auxData, &dmNew->auxData));
    9436:   {
    9437:     Vec     *auxData;
    9438:     PetscInt n, i, off = 0;

    9440:     PetscCall(PetscHMapAuxGetSize(dmNew->auxData, &n));
    9441:     PetscCall(PetscMalloc1(n, &auxData));
    9442:     PetscCall(PetscHMapAuxGetVals(dmNew->auxData, &off, auxData));
    9443:     for (i = 0; i < n; ++i) PetscCall(PetscObjectReference((PetscObject)auxData[i]));
    9444:     PetscCall(PetscFree(auxData));
    9445:   }
    9446:   PetscFunctionReturn(PETSC_SUCCESS);
    9447: }

    9449: /*@
    9450:   DMClearAuxiliaryVec - Destroys the auxiliary vector information and creates a new empty one

    9452:   Not Collective

    9454:   Input Parameter:
    9455: . dm - The `DM`

    9457:   Level: advanced

    9459: .seealso: [](ch_dmbase), `DM`, `DMCopyAuxiliaryVec()`, `DMGetNumAuxiliaryVec()`, `DMGetAuxiliaryVec()`, `DMSetAuxiliaryVec()`
    9460: @*/
    9461: PetscErrorCode DMClearAuxiliaryVec(DM dm)
    9462: {
    9463:   Vec     *auxData;
    9464:   PetscInt n, i, off = 0;

    9466:   PetscFunctionBegin;
    9467:   PetscCall(PetscHMapAuxGetSize(dm->auxData, &n));
    9468:   PetscCall(PetscMalloc1(n, &auxData));
    9469:   PetscCall(PetscHMapAuxGetVals(dm->auxData, &off, auxData));
    9470:   for (i = 0; i < n; ++i) PetscCall(VecDestroy(&auxData[i]));
    9471:   PetscCall(PetscFree(auxData));
    9472:   PetscCall(PetscHMapAuxDestroy(&dm->auxData));
    9473:   PetscCall(PetscHMapAuxCreate(&dm->auxData));
    9474:   PetscFunctionReturn(PETSC_SUCCESS);
    9475: }

    9477: /*@
    9478:   DMPolytopeMatchOrientation - Determine an orientation (transformation) that takes the source face arrangement to the target face arrangement

    9480:   Not Collective

    9482:   Input Parameters:
    9483: + ct         - The `DMPolytopeType`
    9484: . sourceCone - The source arrangement of faces
    9485: - targetCone - The target arrangement of faces

    9487:   Output Parameters:
    9488: + ornt  - The orientation (transformation) which will take the source arrangement to the target arrangement
    9489: - found - Flag indicating that a suitable orientation was found

    9491:   Level: advanced

    9493:   Note:
    9494:   An arrangement is a face order combined with an orientation for each face

    9496:   Each orientation (transformation) is labeled with an integer from negative `DMPolytopeTypeGetNumArrangements(ct)`/2 to `DMPolytopeTypeGetNumArrangements(ct)`/2
    9497:   that labels each arrangement (face ordering plus orientation for each face).

    9499:   See `DMPolytopeMatchVertexOrientation()` to find a new vertex orientation that takes the source vertex arrangement to the target vertex arrangement

    9501: .seealso: [](ch_dmbase), `DM`, `DMPolytopeGetOrientation()`, `DMPolytopeMatchVertexOrientation()`, `DMPolytopeGetVertexOrientation()`
    9502: @*/
    9503: PetscErrorCode DMPolytopeMatchOrientation(DMPolytopeType ct, const PetscInt sourceCone[], const PetscInt targetCone[], PetscInt *ornt, PetscBool *found)
    9504: {
    9505:   const PetscInt cS = DMPolytopeTypeGetConeSize(ct);
    9506:   const PetscInt nO = DMPolytopeTypeGetNumArrangements(ct) / 2;
    9507:   PetscInt       o, c;

    9509:   PetscFunctionBegin;
    9510:   if (!nO) {
    9511:     *ornt  = 0;
    9512:     *found = PETSC_TRUE;
    9513:     PetscFunctionReturn(PETSC_SUCCESS);
    9514:   }
    9515:   for (o = -nO; o < nO; ++o) {
    9516:     const PetscInt *arr = DMPolytopeTypeGetArrangement(ct, o);

    9518:     for (c = 0; c < cS; ++c)
    9519:       if (sourceCone[arr[c * 2]] != targetCone[c]) break;
    9520:     if (c == cS) {
    9521:       *ornt = o;
    9522:       break;
    9523:     }
    9524:   }
    9525:   *found = o == nO ? PETSC_FALSE : PETSC_TRUE;
    9526:   PetscFunctionReturn(PETSC_SUCCESS);
    9527: }

    9529: /*@
    9530:   DMPolytopeGetOrientation - Determine an orientation (transformation) that takes the source face arrangement to the target face arrangement

    9532:   Not Collective

    9534:   Input Parameters:
    9535: + ct         - The `DMPolytopeType`
    9536: . sourceCone - The source arrangement of faces
    9537: - targetCone - The target arrangement of faces

    9539:   Output Parameter:
    9540: . ornt - The orientation (transformation) which will take the source arrangement to the target arrangement

    9542:   Level: advanced

    9544:   Note:
    9545:   This function is the same as `DMPolytopeMatchOrientation()` except it will generate an error if no suitable orientation can be found.

    9547:   Developer Note:
    9548:   It is unclear why this function needs to exist since one can simply call `DMPolytopeMatchOrientation()` and error if none is found

    9550: .seealso: [](ch_dmbase), `DM`, `DMPolytopeType`, `DMPolytopeMatchOrientation()`, `DMPolytopeGetVertexOrientation()`, `DMPolytopeMatchVertexOrientation()`
    9551: @*/
    9552: PetscErrorCode DMPolytopeGetOrientation(DMPolytopeType ct, const PetscInt sourceCone[], const PetscInt targetCone[], PetscInt *ornt)
    9553: {
    9554:   PetscBool found;

    9556:   PetscFunctionBegin;
    9557:   PetscCall(DMPolytopeMatchOrientation(ct, sourceCone, targetCone, ornt, &found));
    9558:   PetscCheck(found, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Could not find orientation for %s", DMPolytopeTypes[ct]);
    9559:   PetscFunctionReturn(PETSC_SUCCESS);
    9560: }

    9562: /*@
    9563:   DMPolytopeMatchVertexOrientation - Determine an orientation (transformation) that takes the source vertex arrangement to the target vertex arrangement

    9565:   Not Collective

    9567:   Input Parameters:
    9568: + ct         - The `DMPolytopeType`
    9569: . sourceVert - The source arrangement of vertices
    9570: - targetVert - The target arrangement of vertices

    9572:   Output Parameters:
    9573: + ornt  - The orientation (transformation) which will take the source arrangement to the target arrangement
    9574: - found - Flag indicating that a suitable orientation was found

    9576:   Level: advanced

    9578:   Notes:
    9579:   An arrangement is a vertex order

    9581:   Each orientation (transformation) is labeled with an integer from negative `DMPolytopeTypeGetNumArrangements(ct)`/2 to `DMPolytopeTypeGetNumArrangements(ct)`/2
    9582:   that labels each arrangement (vertex ordering).

    9584:   See `DMPolytopeMatchOrientation()` to find a new face orientation that takes the source face arrangement to the target face arrangement

    9586: .seealso: [](ch_dmbase), `DM`, `DMPolytopeType`, `DMPolytopeGetOrientation()`, `DMPolytopeMatchOrientation()`, `DMPolytopeTypeGetNumVertices()`, `DMPolytopeTypeGetVertexArrangement()`
    9587: @*/
    9588: PetscErrorCode DMPolytopeMatchVertexOrientation(DMPolytopeType ct, const PetscInt sourceVert[], const PetscInt targetVert[], PetscInt *ornt, PetscBool *found)
    9589: {
    9590:   const PetscInt cS = DMPolytopeTypeGetNumVertices(ct);
    9591:   const PetscInt nO = DMPolytopeTypeGetNumArrangements(ct) / 2;
    9592:   PetscInt       o, c;

    9594:   PetscFunctionBegin;
    9595:   if (!nO) {
    9596:     *ornt  = 0;
    9597:     *found = PETSC_TRUE;
    9598:     PetscFunctionReturn(PETSC_SUCCESS);
    9599:   }
    9600:   for (o = -nO; o < nO; ++o) {
    9601:     const PetscInt *arr = DMPolytopeTypeGetVertexArrangement(ct, o);

    9603:     for (c = 0; c < cS; ++c)
    9604:       if (sourceVert[arr[c]] != targetVert[c]) break;
    9605:     if (c == cS) {
    9606:       *ornt = o;
    9607:       break;
    9608:     }
    9609:   }
    9610:   *found = o == nO ? PETSC_FALSE : PETSC_TRUE;
    9611:   PetscFunctionReturn(PETSC_SUCCESS);
    9612: }

    9614: /*@
    9615:   DMPolytopeGetVertexOrientation - Determine an orientation (transformation) that takes the source vertex arrangement to the target vertex arrangement

    9617:   Not Collective

    9619:   Input Parameters:
    9620: + ct         - The `DMPolytopeType`
    9621: . sourceCone - The source arrangement of vertices
    9622: - targetCone - The target arrangement of vertices

    9624:   Output Parameter:
    9625: . ornt - The orientation (transformation) which will take the source arrangement to the target arrangement

    9627:   Level: advanced

    9629:   Note:
    9630:   This function is the same as `DMPolytopeMatchVertexOrientation()` except it errors if not orientation is possible.

    9632:   Developer Note:
    9633:   It is unclear why this function needs to exist since one can simply call `DMPolytopeMatchVertexOrientation()` and error if none is found

    9635: .seealso: [](ch_dmbase), `DM`, `DMPolytopeType`, `DMPolytopeMatchVertexOrientation()`, `DMPolytopeGetOrientation()`
    9636: @*/
    9637: PetscErrorCode DMPolytopeGetVertexOrientation(DMPolytopeType ct, const PetscInt sourceCone[], const PetscInt targetCone[], PetscInt *ornt)
    9638: {
    9639:   PetscBool found;

    9641:   PetscFunctionBegin;
    9642:   PetscCall(DMPolytopeMatchVertexOrientation(ct, sourceCone, targetCone, ornt, &found));
    9643:   PetscCheck(found, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Could not find orientation for %s", DMPolytopeTypes[ct]);
    9644:   PetscFunctionReturn(PETSC_SUCCESS);
    9645: }

    9647: /*@
    9648:   DMPolytopeInCellTest - Check whether a point lies inside the reference cell of given type

    9650:   Not Collective

    9652:   Input Parameters:
    9653: + ct    - The `DMPolytopeType`
    9654: - point - Coordinates of the point

    9656:   Output Parameter:
    9657: . inside - Flag indicating whether the point is inside the reference cell of given type

    9659:   Level: advanced

    9661: .seealso: [](ch_dmbase), `DM`, `DMPolytopeType`, `DMLocatePoints()`
    9662: @*/
    9663: PetscErrorCode DMPolytopeInCellTest(DMPolytopeType ct, const PetscReal point[], PetscBool *inside)
    9664: {
    9665:   PetscReal sum = 0.0;
    9666:   PetscInt  d;

    9668:   PetscFunctionBegin;
    9669:   *inside = PETSC_TRUE;
    9670:   switch (ct) {
    9671:   case DM_POLYTOPE_TRIANGLE:
    9672:   case DM_POLYTOPE_TETRAHEDRON:
    9673:     for (d = 0; d < DMPolytopeTypeGetDim(ct); ++d) {
    9674:       if (point[d] < -1.0) {
    9675:         *inside = PETSC_FALSE;
    9676:         break;
    9677:       }
    9678:       sum += point[d];
    9679:     }
    9680:     if (sum > PETSC_SMALL) {
    9681:       *inside = PETSC_FALSE;
    9682:       break;
    9683:     }
    9684:     break;
    9685:   case DM_POLYTOPE_QUADRILATERAL:
    9686:   case DM_POLYTOPE_HEXAHEDRON:
    9687:     for (d = 0; d < DMPolytopeTypeGetDim(ct); ++d)
    9688:       if (PetscAbsReal(point[d]) > 1. + PETSC_SMALL) {
    9689:         *inside = PETSC_FALSE;
    9690:         break;
    9691:       }
    9692:     break;
    9693:   default:
    9694:     SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Unsupported polytope type %s", DMPolytopeTypes[ct]);
    9695:   }
    9696:   PetscFunctionReturn(PETSC_SUCCESS);
    9697: }

    9699: /*@
    9700:   DMReorderSectionSetDefault - Set flag indicating whether the local section should be reordered by default

    9702:   Logically collective

    9704:   Input Parameters:
    9705: + dm      - The DM
    9706: - reorder - Flag for reordering

    9708:   Level: intermediate

    9710: .seealso: `DMReorderSectionGetDefault()`
    9711: @*/
    9712: PetscErrorCode DMReorderSectionSetDefault(DM dm, DMReorderDefaultFlag reorder)
    9713: {
    9714:   PetscFunctionBegin;
    9716:   PetscTryMethod(dm, "DMReorderSectionSetDefault_C", (DM, DMReorderDefaultFlag), (dm, reorder));
    9717:   PetscFunctionReturn(PETSC_SUCCESS);
    9718: }

    9720: /*@
    9721:   DMReorderSectionGetDefault - Get flag indicating whether the local section should be reordered by default

    9723:   Not collective

    9725:   Input Parameter:
    9726: . dm - The DM

    9728:   Output Parameter:
    9729: . reorder - Flag for reordering

    9731:   Level: intermediate

    9733: .seealso: `DMReorderSetDefault()`
    9734: @*/
    9735: PetscErrorCode DMReorderSectionGetDefault(DM dm, DMReorderDefaultFlag *reorder)
    9736: {
    9737:   PetscFunctionBegin;
    9739:   PetscAssertPointer(reorder, 2);
    9740:   *reorder = DM_REORDER_DEFAULT_NOTSET;
    9741:   PetscTryMethod(dm, "DMReorderSectionGetDefault_C", (DM, DMReorderDefaultFlag *), (dm, reorder));
    9742:   PetscFunctionReturn(PETSC_SUCCESS);
    9743: }

    9745: /*@
    9746:   DMReorderSectionSetType - Set the type of local section reordering

    9748:   Logically collective

    9750:   Input Parameters:
    9751: + dm      - The DM
    9752: - reorder - The reordering method

    9754:   Level: intermediate

    9756: .seealso: `DMReorderSectionGetType()`, `DMReorderSectionSetDefault()`
    9757: @*/
    9758: PetscErrorCode DMReorderSectionSetType(DM dm, MatOrderingType reorder)
    9759: {
    9760:   PetscFunctionBegin;
    9762:   PetscTryMethod(dm, "DMReorderSectionSetType_C", (DM, MatOrderingType), (dm, reorder));
    9763:   PetscFunctionReturn(PETSC_SUCCESS);
    9764: }

    9766: /*@
    9767:   DMReorderSectionGetType - Get the reordering type for the local section

    9769:   Not collective

    9771:   Input Parameter:
    9772: . dm - The DM

    9774:   Output Parameter:
    9775: . reorder - The reordering method

    9777:   Level: intermediate

    9779: .seealso: `DMReorderSetDefault()`, `DMReorderSectionGetDefault()`
    9780: @*/
    9781: PetscErrorCode DMReorderSectionGetType(DM dm, MatOrderingType *reorder)
    9782: {
    9783:   PetscFunctionBegin;
    9785:   PetscAssertPointer(reorder, 2);
    9786:   *reorder = NULL;
    9787:   PetscTryMethod(dm, "DMReorderSectionGetType_C", (DM, MatOrderingType *), (dm, reorder));
    9788:   PetscFunctionReturn(PETSC_SUCCESS);
    9789: }