Actual source code: dm.c
1: #include <petscvec.h>
2: #include <petsc/private/dmimpl.h>
3: #include <petsc/private/dmlabelimpl.h>
4: #include <petsc/private/petscdsimpl.h>
5: #include <petscdmplex.h>
6: #include <petscdmceed.h>
7: #include <petscdmfield.h>
8: #include <petscsf.h>
9: #include <petscds.h>
11: #ifdef PETSC_HAVE_LIBCEED
12: #include <petscfeceed.h>
13: #endif
15: PetscClassId DM_CLASSID;
16: PetscClassId DMLABEL_CLASSID;
17: PetscLogEvent DM_Convert, DM_GlobalToLocal, DM_LocalToGlobal, DM_LocalToLocal, DM_LocatePoints, DM_Coarsen, DM_Refine, DM_CreateInterpolation, DM_CreateRestriction, DM_CreateInjection, DM_CreateMatrix, DM_CreateMassMatrix, DM_Load, DM_View, DM_AdaptInterpolator, DM_ProjectFunction;
19: const char *const DMBoundaryTypes[] = {"NONE", "GHOSTED", "MIRROR", "PERIODIC", "TWIST", "DMBoundaryType", "DM_BOUNDARY_", NULL};
20: const char *const DMBoundaryConditionTypes[] = {"INVALID", "ESSENTIAL", "NATURAL", "INVALID", "LOWER_BOUND", "ESSENTIAL_FIELD", "NATURAL_FIELD", "INVALID", "UPPER_BOUND", "ESSENTIAL_BD_FIELD", "NATURAL_RIEMANN", "DMBoundaryConditionType",
21: "DM_BC_", NULL};
22: const char *const DMBlockingTypes[] = {"TOPOLOGICAL_POINT", "FIELD_NODE", "DMBlockingType", "DM_BLOCKING_", NULL};
23: const char *const DMPolytopeTypes[] =
24: {"vertex", "segment", "tensor_segment", "triangle", "quadrilateral", "tensor_quad", "tetrahedron", "hexahedron", "triangular_prism", "tensor_triangular_prism", "tensor_quadrilateral_prism", "pyramid", "FV_ghost_cell", "interior_ghost_cell",
25: "unknown", "unknown_cell", "unknown_face", "invalid", "DMPolytopeType", "DM_POLYTOPE_", NULL};
26: const char *const DMCopyLabelsModes[] = {"replace", "keep", "fail", "DMCopyLabelsMode", "DM_COPY_LABELS_", NULL};
28: /*@
29: DMCreate - Creates an empty `DM` object. `DM`s are the abstract objects in PETSc that mediate between meshes and discretizations and the
30: algebraic solvers, time integrators, and optimization algorithms in PETSc.
32: Collective
34: Input Parameter:
35: . comm - The communicator for the `DM` object
37: Output Parameter:
38: . dm - The `DM` object
40: Level: beginner
42: Notes:
43: See `DMType` for a brief summary of available `DM`.
45: The type must then be set with `DMSetType()`. If you never call `DMSetType()` it will generate an
46: error when you try to use the `dm`.
48: `DM` is an orphan initialism or orphan acronym, the letters have no meaning and never did.
50: .seealso: [](ch_dmbase), `DM`, `DMSetType()`, `DMType`, `DMDACreate()`, `DMDA`, `DMSLICED`, `DMCOMPOSITE`, `DMPLEX`, `DMMOAB`, `DMNETWORK`
51: @*/
52: PetscErrorCode DMCreate(MPI_Comm comm, DM *dm)
53: {
54: DM v;
55: PetscDS ds;
57: PetscFunctionBegin;
58: PetscAssertPointer(dm, 2);
60: PetscCall(DMInitializePackage());
61: PetscCall(PetscHeaderCreate(v, DM_CLASSID, "DM", "Distribution Manager", "DM", comm, DMDestroy, DMView));
62: ((PetscObject)v)->non_cyclic_references = &DMCountNonCyclicReferences;
63: v->setupcalled = PETSC_FALSE;
64: v->setfromoptionscalled = PETSC_FALSE;
65: v->ltogmap = NULL;
66: v->bind_below = 0;
67: v->bs = 1;
68: v->coloringtype = IS_COLORING_GLOBAL;
69: PetscCall(PetscSFCreate(comm, &v->sf));
70: PetscCall(PetscSFCreate(comm, &v->sectionSF));
71: v->labels = NULL;
72: v->adjacency[0] = PETSC_FALSE;
73: v->adjacency[1] = PETSC_TRUE;
74: v->depthLabel = NULL;
75: v->celltypeLabel = NULL;
76: v->localSection = NULL;
77: v->globalSection = NULL;
78: v->defaultConstraint.section = NULL;
79: v->defaultConstraint.mat = NULL;
80: v->defaultConstraint.bias = NULL;
81: v->coordinates[0].dim = PETSC_DEFAULT;
82: v->coordinates[1].dim = PETSC_DEFAULT;
83: v->sparseLocalize = PETSC_TRUE;
84: v->dim = PETSC_DETERMINE;
85: PetscCall(PetscDSCreate(PETSC_COMM_SELF, &ds));
86: PetscCall(DMSetRegionDS(v, NULL, NULL, ds, NULL));
87: PetscCall(PetscDSDestroy(&ds));
88: PetscCall(PetscHMapAuxCreate(&v->auxData));
89: v->dmBC = NULL;
90: v->coarseMesh = NULL;
91: v->outputSequenceNum = -1;
92: v->outputSequenceVal = 0.0;
93: PetscCall(DMSetVecType(v, VECSTANDARD));
94: PetscCall(DMSetMatType(v, MATAIJ));
96: *dm = v;
97: PetscFunctionReturn(PETSC_SUCCESS);
98: }
100: /*@
101: DMClone - Creates a `DM` object with the same topology as the original.
103: Collective
105: Input Parameter:
106: . dm - The original `DM` object
108: Output Parameter:
109: . newdm - The new `DM` object
111: Level: beginner
113: Notes:
114: For some `DM` implementations this is a shallow clone, the result of which may share (reference counted) information with its parent. For example,
115: `DMClone()` applied to a `DMPLEX` object will result in a new `DMPLEX` that shares the topology with the original `DMPLEX`. It does not
116: share the `PetscSection` of the original `DM`.
118: The clone is considered set up if the original has been set up.
120: Use `DMConvert()` for a general way to create new `DM` from a given `DM`
122: .seealso: [](ch_dmbase), `DM`, `DMDestroy()`, `DMCreate()`, `DMSetType()`, `DMSetLocalSection()`, `DMSetGlobalSection()`, `DMPLEX`, `DMConvert()`
123: @*/
124: PetscErrorCode DMClone(DM dm, DM *newdm)
125: {
126: PetscSF sf;
127: Vec coords;
128: void *ctx;
129: MatOrderingType otype;
130: DMReorderDefaultFlag flg;
131: PetscInt dim, cdim, i;
132: PetscBool sparse;
134: PetscFunctionBegin;
136: PetscAssertPointer(newdm, 2);
137: PetscCall(DMCreate(PetscObjectComm((PetscObject)dm), newdm));
138: PetscCall(DMCopyLabels(dm, *newdm, PETSC_COPY_VALUES, PETSC_TRUE, DM_COPY_LABELS_FAIL));
139: (*newdm)->leveldown = dm->leveldown;
140: (*newdm)->levelup = dm->levelup;
141: (*newdm)->prealloc_only = dm->prealloc_only;
142: (*newdm)->prealloc_skip = dm->prealloc_skip;
143: PetscCall(PetscFree((*newdm)->vectype));
144: PetscCall(PetscStrallocpy(dm->vectype, (char **)&(*newdm)->vectype));
145: PetscCall(PetscFree((*newdm)->mattype));
146: PetscCall(PetscStrallocpy(dm->mattype, (char **)&(*newdm)->mattype));
147: PetscCall(DMGetDimension(dm, &dim));
148: PetscCall(DMSetDimension(*newdm, dim));
149: PetscTryTypeMethod(dm, clone, newdm);
150: (*newdm)->setupcalled = dm->setupcalled;
151: PetscCall(DMGetPointSF(dm, &sf));
152: PetscCall(DMSetPointSF(*newdm, sf));
153: PetscCall(DMGetApplicationContext(dm, &ctx));
154: PetscCall(DMSetApplicationContext(*newdm, ctx));
155: PetscCall(DMReorderSectionGetDefault(dm, &flg));
156: PetscCall(DMReorderSectionSetDefault(*newdm, flg));
157: PetscCall(DMReorderSectionGetType(dm, &otype));
158: PetscCall(DMReorderSectionSetType(*newdm, otype));
159: for (i = 0; i < 2; ++i) {
160: if (dm->coordinates[i].dm) {
161: DM ncdm;
162: PetscSection cs;
163: PetscInt pEnd = -1, pEndMax = -1;
165: PetscCall(DMGetLocalSection(dm->coordinates[i].dm, &cs));
166: if (cs) PetscCall(PetscSectionGetChart(cs, NULL, &pEnd));
167: PetscCallMPI(MPIU_Allreduce(&pEnd, &pEndMax, 1, MPIU_INT, MPI_MAX, PetscObjectComm((PetscObject)dm)));
168: if (pEndMax >= 0) {
169: PetscCall(DMClone(dm->coordinates[i].dm, &ncdm));
170: PetscCall(DMCopyDisc(dm->coordinates[i].dm, ncdm));
171: PetscCall(DMSetLocalSection(ncdm, cs));
172: if (dm->coordinates[i].dm->periodic.setup) {
173: ncdm->periodic.setup = dm->coordinates[i].dm->periodic.setup;
174: PetscCall(ncdm->periodic.setup(ncdm));
175: }
176: if (i) PetscCall(DMSetCellCoordinateDM(*newdm, ncdm));
177: else PetscCall(DMSetCoordinateDM(*newdm, ncdm));
178: PetscCall(DMDestroy(&ncdm));
179: }
180: }
181: }
182: PetscCall(DMGetCoordinateDim(dm, &cdim));
183: PetscCall(DMSetCoordinateDim(*newdm, cdim));
184: PetscCall(DMGetCoordinatesLocal(dm, &coords));
185: if (coords) {
186: PetscCall(DMSetCoordinatesLocal(*newdm, coords));
187: } else {
188: PetscCall(DMGetCoordinates(dm, &coords));
189: if (coords) PetscCall(DMSetCoordinates(*newdm, coords));
190: }
191: PetscCall(DMGetSparseLocalize(dm, &sparse));
192: PetscCall(DMSetSparseLocalize(*newdm, sparse));
193: PetscCall(DMGetCellCoordinatesLocal(dm, &coords));
194: if (coords) {
195: PetscCall(DMSetCellCoordinatesLocal(*newdm, coords));
196: } else {
197: PetscCall(DMGetCellCoordinates(dm, &coords));
198: if (coords) PetscCall(DMSetCellCoordinates(*newdm, coords));
199: }
200: {
201: const PetscReal *maxCell, *Lstart, *L;
203: PetscCall(DMGetPeriodicity(dm, &maxCell, &Lstart, &L));
204: PetscCall(DMSetPeriodicity(*newdm, maxCell, Lstart, L));
205: }
206: {
207: PetscBool useCone, useClosure;
209: PetscCall(DMGetAdjacency(dm, PETSC_DEFAULT, &useCone, &useClosure));
210: PetscCall(DMSetAdjacency(*newdm, PETSC_DEFAULT, useCone, useClosure));
211: }
212: PetscFunctionReturn(PETSC_SUCCESS);
213: }
215: /*@
216: DMSetVecType - Sets the type of vector to be created with `DMCreateLocalVector()` and `DMCreateGlobalVector()`
218: Logically Collective
220: Input Parameters:
221: + dm - initial distributed array
222: - ctype - the vector type, for example `VECSTANDARD`, `VECCUDA`, or `VECVIENNACL`
224: Options Database Key:
225: . -dm_vec_type ctype - the type of vector to create
227: Level: intermediate
229: .seealso: [](ch_dmbase), `DM`, `DMCreate()`, `DMDestroy()`, `DMDAInterpolationType`, `VecType`, `DMGetVecType()`, `DMSetMatType()`, `DMGetMatType()`,
230: `VECSTANDARD`, `VECCUDA`, `VECVIENNACL`, `DMCreateLocalVector()`, `DMCreateGlobalVector()`
231: @*/
232: PetscErrorCode DMSetVecType(DM dm, VecType ctype)
233: {
234: char *tmp;
236: PetscFunctionBegin;
238: PetscAssertPointer(ctype, 2);
239: tmp = (char *)dm->vectype;
240: PetscCall(PetscStrallocpy(ctype, (char **)&dm->vectype));
241: PetscCall(PetscFree(tmp));
242: PetscFunctionReturn(PETSC_SUCCESS);
243: }
245: /*@
246: DMGetVecType - Gets the type of vector created with `DMCreateLocalVector()` and `DMCreateGlobalVector()`
248: Logically Collective
250: Input Parameter:
251: . da - initial distributed array
253: Output Parameter:
254: . ctype - the vector type
256: Level: intermediate
258: .seealso: [](ch_dmbase), `DM`, `DMCreate()`, `DMDestroy()`, `DMDAInterpolationType`, `VecType`, `DMSetMatType()`, `DMGetMatType()`, `DMSetVecType()`
259: @*/
260: PetscErrorCode DMGetVecType(DM da, VecType *ctype)
261: {
262: PetscFunctionBegin;
264: *ctype = da->vectype;
265: PetscFunctionReturn(PETSC_SUCCESS);
266: }
268: /*@
269: VecGetDM - Gets the `DM` defining the data layout of the vector
271: Not Collective
273: Input Parameter:
274: . v - The `Vec`
276: Output Parameter:
277: . dm - The `DM`
279: Level: intermediate
281: Note:
282: A `Vec` may not have a `DM` associated with it.
284: .seealso: [](ch_dmbase), `DM`, `VecSetDM()`, `DMGetLocalVector()`, `DMGetGlobalVector()`, `DMSetVecType()`
285: @*/
286: PetscErrorCode VecGetDM(Vec v, DM *dm)
287: {
288: PetscFunctionBegin;
290: PetscAssertPointer(dm, 2);
291: PetscCall(PetscObjectQuery((PetscObject)v, "__PETSc_dm", (PetscObject *)dm));
292: PetscFunctionReturn(PETSC_SUCCESS);
293: }
295: /*@
296: VecSetDM - Sets the `DM` defining the data layout of the vector.
298: Not Collective
300: Input Parameters:
301: + v - The `Vec`
302: - dm - The `DM`
304: Level: developer
306: Notes:
307: This is rarely used, generally one uses `DMGetLocalVector()` or `DMGetGlobalVector()` to create a vector associated with a given `DM`
309: This is NOT the same as `DMCreateGlobalVector()` since it does not change the view methods or perform other customization, but merely sets the `DM` member.
311: .seealso: [](ch_dmbase), `DM`, `VecGetDM()`, `DMGetLocalVector()`, `DMGetGlobalVector()`, `DMSetVecType()`
312: @*/
313: PetscErrorCode VecSetDM(Vec v, DM dm)
314: {
315: PetscFunctionBegin;
318: PetscCall(PetscObjectCompose((PetscObject)v, "__PETSc_dm", (PetscObject)dm));
319: PetscFunctionReturn(PETSC_SUCCESS);
320: }
322: /*@
323: DMSetISColoringType - Sets the type of coloring, `IS_COLORING_GLOBAL` or `IS_COLORING_LOCAL` that is created by the `DM`
325: Logically Collective
327: Input Parameters:
328: + dm - the `DM` context
329: - ctype - the matrix type
331: Options Database Key:
332: . -dm_is_coloring_type (global|local) - see `ISColoringType`
334: Level: intermediate
336: .seealso: [](ch_dmbase), `DM`, `DMDACreate1d()`, `DMDACreate2d()`, `DMDACreate3d()`, `DMCreateMatrix()`, `DMCreateMassMatrix()`, `DMSetMatrixPreallocateOnly()`, `MatType`, `DMGetMatType()`,
337: `DMGetISColoringType()`, `ISColoringType`, `IS_COLORING_GLOBAL`, `IS_COLORING_LOCAL`
338: @*/
339: PetscErrorCode DMSetISColoringType(DM dm, ISColoringType ctype)
340: {
341: PetscFunctionBegin;
343: dm->coloringtype = ctype;
344: PetscFunctionReturn(PETSC_SUCCESS);
345: }
347: /*@
348: DMGetISColoringType - Gets the type of coloring, `IS_COLORING_GLOBAL` or `IS_COLORING_LOCAL` that is created by the `DM`
350: Logically Collective
352: Input Parameter:
353: . dm - the `DM` context
355: Output Parameter:
356: . ctype - the matrix type
358: Level: intermediate
360: .seealso: [](ch_dmbase), `DM`, `DMDACreate1d()`, `DMDACreate2d()`, `DMDACreate3d()`, `DMCreateMatrix()`, `DMCreateMassMatrix()`, `DMSetMatrixPreallocateOnly()`, `MatType`, `DMGetMatType()`,
361: `ISColoringType`, `IS_COLORING_GLOBAL`, `IS_COLORING_LOCAL`
362: @*/
363: PetscErrorCode DMGetISColoringType(DM dm, ISColoringType *ctype)
364: {
365: PetscFunctionBegin;
367: *ctype = dm->coloringtype;
368: PetscFunctionReturn(PETSC_SUCCESS);
369: }
371: /*@
372: DMSetMatType - Sets the type of matrix created with `DMCreateMatrix()`
374: Logically Collective
376: Input Parameters:
377: + dm - the `DM` context
378: - ctype - the matrix type, for example `MATMPIAIJ`
380: Options Database Key:
381: . -dm_mat_type ctype - the type of the matrix to create, see `MatType`
383: Level: intermediate
385: .seealso: [](ch_dmbase), `DM`, `MatType`, `DMDACreate1d()`, `DMDACreate2d()`, `DMDACreate3d()`, `DMCreateMatrix()`, `DMCreateMassMatrix()`, `DMSetMatrixPreallocateOnly()`, `DMGetMatType()`, `DMCreateGlobalVector()`, `DMCreateLocalVector()`
386: @*/
387: PetscErrorCode DMSetMatType(DM dm, MatType ctype)
388: {
389: char *tmp;
391: PetscFunctionBegin;
393: PetscAssertPointer(ctype, 2);
394: tmp = (char *)dm->mattype;
395: PetscCall(PetscStrallocpy(ctype, (char **)&dm->mattype));
396: PetscCall(PetscFree(tmp));
397: PetscFunctionReturn(PETSC_SUCCESS);
398: }
400: /*@
401: DMGetMatType - Gets the type of matrix that would be created with `DMCreateMatrix()`
403: Logically Collective
405: Input Parameter:
406: . dm - the `DM` context
408: Output Parameter:
409: . ctype - the matrix type
411: Level: intermediate
413: .seealso: [](ch_dmbase), `DM`, `DMDACreate1d()`, `DMDACreate2d()`, `DMDACreate3d()`, `DMCreateMatrix()`, `DMCreateMassMatrix()`, `DMSetMatrixPreallocateOnly()`, `MatType`, `DMSetMatType()`
414: @*/
415: PetscErrorCode DMGetMatType(DM dm, MatType *ctype)
416: {
417: PetscFunctionBegin;
419: *ctype = dm->mattype;
420: PetscFunctionReturn(PETSC_SUCCESS);
421: }
423: /*@
424: MatGetDM - Gets the `DM` defining the data layout of the matrix
426: Not Collective
428: Input Parameter:
429: . A - The `Mat`
431: Output Parameter:
432: . dm - The `DM`
434: Level: intermediate
436: Note:
437: A matrix may not have a `DM` associated with it
439: Developer Note:
440: Since the `Mat` class doesn't know about the `DM` class the `DM` object is associated with the `Mat` through a `PetscObjectCompose()` operation
442: .seealso: [](ch_dmbase), `DM`, `MatSetDM()`, `DMCreateMatrix()`, `DMSetMatType()`
443: @*/
444: PetscErrorCode MatGetDM(Mat A, DM *dm)
445: {
446: PetscFunctionBegin;
448: PetscAssertPointer(dm, 2);
449: PetscCall(PetscObjectQuery((PetscObject)A, "__PETSc_dm", (PetscObject *)dm));
450: PetscFunctionReturn(PETSC_SUCCESS);
451: }
453: /*@
454: MatSetDM - Sets the `DM` defining the data layout of the matrix
456: Not Collective
458: Input Parameters:
459: + A - The `Mat`
460: - dm - The `DM`
462: Level: developer
464: Note:
465: This is rarely used in practice, rather `DMCreateMatrix()` is used to create a matrix associated with a particular `DM`
467: Developer Note:
468: Since the `Mat` class doesn't know about the `DM` class the `DM` object is associated with
469: the `Mat` through a `PetscObjectCompose()` operation
471: .seealso: [](ch_dmbase), `DM`, `MatGetDM()`, `DMCreateMatrix()`, `DMSetMatType()`
472: @*/
473: PetscErrorCode MatSetDM(Mat A, DM dm)
474: {
475: PetscFunctionBegin;
478: PetscCall(PetscObjectCompose((PetscObject)A, "__PETSc_dm", (PetscObject)dm));
479: PetscFunctionReturn(PETSC_SUCCESS);
480: }
482: /*@
483: DMSetOptionsPrefix - Sets the prefix prepended to all option names when searching through the options database
485: Logically Collective
487: Input Parameters:
488: + dm - the `DM` context
489: - prefix - the prefix to prepend
491: Level: advanced
493: Note:
494: A hyphen (-) must NOT be given at the beginning of the prefix name.
495: The first character of all runtime options is AUTOMATICALLY the hyphen.
497: .seealso: [](ch_dmbase), `DM`, `PetscObjectSetOptionsPrefix()`, `DMSetFromOptions()`
498: @*/
499: PetscErrorCode DMSetOptionsPrefix(DM dm, const char prefix[])
500: {
501: PetscFunctionBegin;
503: PetscCall(PetscObjectSetOptionsPrefix((PetscObject)dm, prefix));
504: if (dm->sf) PetscCall(PetscObjectSetOptionsPrefix((PetscObject)dm->sf, prefix));
505: if (dm->sectionSF) PetscCall(PetscObjectSetOptionsPrefix((PetscObject)dm->sectionSF, prefix));
506: PetscFunctionReturn(PETSC_SUCCESS);
507: }
509: /*@
510: DMAppendOptionsPrefix - Appends an additional string to an already existing prefix used for searching for
511: `DM` options in the options database.
513: Logically Collective
515: Input Parameters:
516: + dm - the `DM` context
517: - prefix - the string to append to the current prefix
519: Level: advanced
521: Note:
522: If the `DM` does not currently have an options prefix then this value is used alone as the prefix as if `DMSetOptionsPrefix()` had been called.
523: A hyphen (-) must NOT be given at the beginning of the prefix name.
524: The first character of all runtime options is AUTOMATICALLY the hyphen.
526: .seealso: [](ch_dmbase), `DM`, `DMSetOptionsPrefix()`, `DMGetOptionsPrefix()`, `PetscObjectAppendOptionsPrefix()`, `DMSetFromOptions()`
527: @*/
528: PetscErrorCode DMAppendOptionsPrefix(DM dm, const char prefix[])
529: {
530: PetscFunctionBegin;
532: PetscCall(PetscObjectAppendOptionsPrefix((PetscObject)dm, prefix));
533: PetscFunctionReturn(PETSC_SUCCESS);
534: }
536: /*@
537: DMGetOptionsPrefix - Gets the prefix used for searching for all
538: DM options in the options database.
540: Not Collective
542: Input Parameter:
543: . dm - the `DM` context
545: Output Parameter:
546: . prefix - pointer to the prefix string used is returned
548: Level: advanced
550: .seealso: [](ch_dmbase), `DM`, `DMSetOptionsPrefix()`, `DMAppendOptionsPrefix()`, `DMSetFromOptions()`
551: @*/
552: PetscErrorCode DMGetOptionsPrefix(DM dm, const char *prefix[])
553: {
554: PetscFunctionBegin;
556: PetscCall(PetscObjectGetOptionsPrefix((PetscObject)dm, prefix));
557: PetscFunctionReturn(PETSC_SUCCESS);
558: }
560: static PetscErrorCode DMCountNonCyclicReferences_Internal(DM dm, PetscBool recurseCoarse, PetscBool recurseFine, PetscInt *ncrefct)
561: {
562: PetscInt refct = ((PetscObject)dm)->refct;
564: PetscFunctionBegin;
565: *ncrefct = 0;
566: if (dm->coarseMesh && dm->coarseMesh->fineMesh == dm) {
567: refct--;
568: if (recurseCoarse) {
569: PetscInt coarseCount;
571: PetscCall(DMCountNonCyclicReferences_Internal(dm->coarseMesh, PETSC_TRUE, PETSC_FALSE, &coarseCount));
572: refct += coarseCount;
573: }
574: }
575: if (dm->fineMesh && dm->fineMesh->coarseMesh == dm) {
576: refct--;
577: if (recurseFine) {
578: PetscInt fineCount;
580: PetscCall(DMCountNonCyclicReferences_Internal(dm->fineMesh, PETSC_FALSE, PETSC_TRUE, &fineCount));
581: refct += fineCount;
582: }
583: }
584: *ncrefct = refct;
585: PetscFunctionReturn(PETSC_SUCCESS);
586: }
588: /* Generic wrapper for DMCountNonCyclicReferences_Internal() */
589: PetscErrorCode DMCountNonCyclicReferences(PetscObject dm, PetscInt *ncrefct)
590: {
591: PetscFunctionBegin;
592: PetscCall(DMCountNonCyclicReferences_Internal((DM)dm, PETSC_TRUE, PETSC_TRUE, ncrefct));
593: PetscFunctionReturn(PETSC_SUCCESS);
594: }
596: PetscErrorCode DMDestroyLabelLinkList_Internal(DM dm)
597: {
598: DMLabelLink next = dm->labels;
600: PetscFunctionBegin;
601: /* destroy the labels */
602: while (next) {
603: DMLabelLink tmp = next->next;
605: if (next->label == dm->depthLabel) dm->depthLabel = NULL;
606: if (next->label == dm->celltypeLabel) dm->celltypeLabel = NULL;
607: PetscCall(DMLabelDestroy(&next->label));
608: PetscCall(PetscFree(next));
609: next = tmp;
610: }
611: dm->labels = NULL;
612: PetscFunctionReturn(PETSC_SUCCESS);
613: }
615: PetscErrorCode DMDestroyCoordinates_Internal(DMCoordinates *c)
616: {
617: PetscFunctionBegin;
618: c->dim = PETSC_DEFAULT;
619: PetscCall(DMDestroy(&c->dm));
620: PetscCall(VecDestroy(&c->x));
621: PetscCall(VecDestroy(&c->xl));
622: PetscCall(DMFieldDestroy(&c->field));
623: PetscFunctionReturn(PETSC_SUCCESS);
624: }
626: /*@
627: DMDestroy - Destroys a `DM`.
629: Collective
631: Input Parameter:
632: . dm - the `DM` object to destroy
634: Level: developer
636: .seealso: [](ch_dmbase), `DM`, `DMCreate()`, `DMType`, `DMSetType()`, `DMView()`, `DMCreateGlobalVector()`, `DMCreateInterpolation()`, `DMCreateColoring()`, `DMCreateMatrix()`
637: @*/
638: PetscErrorCode DMDestroy(DM *dm)
639: {
640: PetscInt cnt;
642: PetscFunctionBegin;
643: if (!*dm) PetscFunctionReturn(PETSC_SUCCESS);
646: /* count all non-cyclic references in the doubly-linked list of coarse<->fine meshes */
647: PetscCall(DMCountNonCyclicReferences_Internal(*dm, PETSC_TRUE, PETSC_TRUE, &cnt));
648: --((PetscObject)*dm)->refct;
649: if (--cnt > 0) {
650: *dm = NULL;
651: PetscFunctionReturn(PETSC_SUCCESS);
652: }
653: if (((PetscObject)*dm)->refct < 0) PetscFunctionReturn(PETSC_SUCCESS);
654: ((PetscObject)*dm)->refct = 0;
656: PetscCall(DMClearGlobalVectors(*dm));
657: PetscCall(DMClearLocalVectors(*dm));
658: PetscCall(DMClearNamedGlobalVectors(*dm));
659: PetscCall(DMClearNamedLocalVectors(*dm));
661: /* Destroy the list of hooks */
662: {
663: DMCoarsenHookLink link, next;
664: for (link = (*dm)->coarsenhook; link; link = next) {
665: next = link->next;
666: PetscCall(PetscFree(link));
667: }
668: (*dm)->coarsenhook = NULL;
669: }
670: {
671: DMRefineHookLink link, next;
672: for (link = (*dm)->refinehook; link; link = next) {
673: next = link->next;
674: PetscCall(PetscFree(link));
675: }
676: (*dm)->refinehook = NULL;
677: }
678: {
679: DMSubDomainHookLink link, next;
680: for (link = (*dm)->subdomainhook; link; link = next) {
681: next = link->next;
682: PetscCall(PetscFree(link));
683: }
684: (*dm)->subdomainhook = NULL;
685: }
686: {
687: DMGlobalToLocalHookLink link, next;
688: for (link = (*dm)->gtolhook; link; link = next) {
689: next = link->next;
690: PetscCall(PetscFree(link));
691: }
692: (*dm)->gtolhook = NULL;
693: }
694: {
695: DMLocalToGlobalHookLink link, next;
696: for (link = (*dm)->ltoghook; link; link = next) {
697: next = link->next;
698: PetscCall(PetscFree(link));
699: }
700: (*dm)->ltoghook = NULL;
701: }
702: /* Destroy the work arrays */
703: {
704: DMWorkLink link, next;
705: PetscCheck(!(*dm)->workout, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Work array still checked out %p %p", (void *)(*dm)->workout, (*dm)->workout->mem);
706: for (link = (*dm)->workin; link; link = next) {
707: next = link->next;
708: PetscCall(PetscFree(link->mem));
709: PetscCall(PetscFree(link));
710: }
711: (*dm)->workin = NULL;
712: }
713: /* destroy the labels */
714: PetscCall(DMDestroyLabelLinkList_Internal(*dm));
715: /* destroy the fields */
716: PetscCall(DMClearFields(*dm));
717: /* destroy the boundaries */
718: {
719: DMBoundary next = (*dm)->boundary;
720: while (next) {
721: DMBoundary b = next;
723: next = b->next;
724: PetscCall(PetscFree(b));
725: }
726: }
728: PetscCall(PetscObjectDestroy(&(*dm)->dmksp));
729: PetscCall(PetscObjectDestroy(&(*dm)->dmsnes));
730: PetscCall(PetscObjectDestroy(&(*dm)->dmts));
732: if ((*dm)->ctx && (*dm)->ctxdestroy) PetscCall((*(*dm)->ctxdestroy)(&(*dm)->ctx));
733: PetscCall(MatFDColoringDestroy(&(*dm)->fd));
734: PetscCall(ISLocalToGlobalMappingDestroy(&(*dm)->ltogmap));
735: PetscCall(PetscFree((*dm)->vectype));
736: PetscCall(PetscFree((*dm)->mattype));
738: PetscCall(PetscSectionDestroy(&(*dm)->localSection));
739: PetscCall(PetscSectionDestroy(&(*dm)->globalSection));
740: PetscCall(PetscFree((*dm)->reorderSectionType));
741: PetscCall(PetscLayoutDestroy(&(*dm)->map));
742: PetscCall(PetscSectionDestroy(&(*dm)->defaultConstraint.section));
743: PetscCall(MatDestroy(&(*dm)->defaultConstraint.mat));
744: PetscCall(PetscSFDestroy(&(*dm)->sf));
745: PetscCall(PetscSFDestroy(&(*dm)->sectionSF));
746: PetscCall(PetscSFDestroy(&(*dm)->sfNatural));
747: PetscCall(PetscObjectDereference((PetscObject)(*dm)->sfMigration));
748: PetscCall(DMClearAuxiliaryVec(*dm));
749: PetscCall(PetscHMapAuxDestroy(&(*dm)->auxData));
750: if ((*dm)->coarseMesh && (*dm)->coarseMesh->fineMesh == *dm) PetscCall(DMSetFineDM((*dm)->coarseMesh, NULL));
752: PetscCall(DMDestroy(&(*dm)->coarseMesh));
753: if ((*dm)->fineMesh && (*dm)->fineMesh->coarseMesh == *dm) PetscCall(DMSetCoarseDM((*dm)->fineMesh, NULL));
754: PetscCall(DMDestroy(&(*dm)->fineMesh));
755: PetscCall(PetscFree((*dm)->Lstart));
756: PetscCall(PetscFree((*dm)->L));
757: PetscCall(PetscFree((*dm)->maxCell));
758: PetscCall(PetscFree2((*dm)->nullspaceConstructors, (*dm)->nearnullspaceConstructors));
759: PetscCall(DMDestroyCoordinates_Internal(&(*dm)->coordinates[0]));
760: PetscCall(DMDestroyCoordinates_Internal(&(*dm)->coordinates[1]));
761: if ((*dm)->transformDestroy) PetscCall((*(*dm)->transformDestroy)(*dm, (*dm)->transformCtx));
762: PetscCall(DMDestroy(&(*dm)->transformDM));
763: PetscCall(VecDestroy(&(*dm)->transform));
764: for (PetscInt i = 0; i < (*dm)->periodic.num_affines; i++) {
765: PetscCall(VecScatterDestroy(&(*dm)->periodic.affine_to_local[i]));
766: PetscCall(VecDestroy(&(*dm)->periodic.affine[i]));
767: }
768: if ((*dm)->periodic.num_affines > 0) PetscCall(PetscFree2((*dm)->periodic.affine_to_local, (*dm)->periodic.affine));
770: PetscCall(DMClearDS(*dm));
771: PetscCall(DMDestroy(&(*dm)->dmBC));
772: /* if memory was published with SAWs then destroy it */
773: PetscCall(PetscObjectSAWsViewOff((PetscObject)*dm));
775: PetscTryTypeMethod(*dm, destroy);
776: PetscCall(DMMonitorCancel(*dm));
777: PetscCall(DMCeedDestroy(&(*dm)->dmceed));
778: #ifdef PETSC_HAVE_LIBCEED
779: PetscCallCEED(CeedElemRestrictionDestroy(&(*dm)->ceedERestrict));
780: PetscCallCEED(CeedDestroy(&(*dm)->ceed));
781: #endif
782: /* We do not destroy (*dm)->data here so that we can reference count backend objects */
783: PetscCall(PetscHeaderDestroy(dm));
784: PetscFunctionReturn(PETSC_SUCCESS);
785: }
787: /*@
788: DMSetUp - sets up the data structures inside a `DM` object
790: Collective
792: Input Parameter:
793: . dm - the `DM` object to setup
795: Level: intermediate
797: Note:
798: This is usually called after various parameter setting operations and `DMSetFromOptions()` are called on the `DM`
800: .seealso: [](ch_dmbase), `DM`, `DMCreate()`, `DMSetType()`, `DMView()`, `DMCreateGlobalVector()`, `DMCreateInterpolation()`, `DMCreateColoring()`, `DMCreateMatrix()`
801: @*/
802: PetscErrorCode DMSetUp(DM dm)
803: {
804: PetscFunctionBegin;
806: if (dm->setupcalled) PetscFunctionReturn(PETSC_SUCCESS);
807: PetscTryTypeMethod(dm, setup);
808: dm->setupcalled = PETSC_TRUE;
809: PetscFunctionReturn(PETSC_SUCCESS);
810: }
812: /*@
813: DMSetFromOptions - sets parameters in a `DM` from the options database
815: Collective
817: Input Parameter:
818: . dm - the `DM` object to set options for
820: Options Database Keys:
821: + -dm_preallocate_only (true|false) - Only preallocate the matrix for `DMCreateMatrix()` and `DMCreateMassMatrix()`, but do not fill it with zeros
822: . -dm_vec_type type - type of vector to create inside `DM`
823: . -dm_mat_type type - type of matrix to create inside `DM`
824: . -dm_is_coloring_type (global|local) - see `ISColoringType`
825: . -dm_bind_below n - bind (force execution on CPU) for `Vec` and `Mat` objects with local size (number of vector entries or matrix rows) below n; currently only supported for `DMDA`
826: . -dm_plex_option_phases ph0_, ph1_, ... - List of prefixes for option processing phases
827: . -dm_plex_filename str - File containing a mesh
828: . -dm_plex_boundary_filename str - File containing a mesh boundary
829: . -dm_plex_name str - Name of the mesh in the file
830: . -dm_plex_shape shape - The domain shape, such as `BOX`, `SPHERE`, etc.
831: . -dm_plex_cell ct - Cell shape
832: . -dm_plex_reference_cell_domain (true|false) - Use a reference cell domain
833: . -dm_plex_dim dim - Set the topological dimension
834: . -dm_plex_simplex (true|false) - `PETSC_TRUE` for simplex elements, `PETSC_FALSE` for tensor elements
835: . -dm_plex_interpolate (true|false) - `PETSC_TRUE` turns on topological interpolation (creating edges and faces)
836: . -dm_plex_orient (true|false) - `PETSC_TRUE` turns on topological orientation (flipping edges and faces)
837: . -dm_plex_scale sc - Scale factor for mesh coordinates
838: . -dm_coord_remap (true|false) - Map coordinates using a function
839: . -dm_plex_coordinate_dim dim - Change the coordinate dimension of a mesh (usually given with cdm_ prefix)
840: . -dm_coord_map mapname - Select a builtin coordinate map
841: . -dm_coord_map_params p0,p1,p2,... - Set coordinate mapping parameters
842: . -dm_plex_box_faces m,n,p - Number of faces along each dimension
843: . -dm_plex_box_lower x,y,z - Specify lower-left-bottom coordinates for the box
844: . -dm_plex_box_upper x,y,z - Specify upper-right-top coordinates for the box
845: . -dm_plex_box_bd bx,by,bz - Specify the `DMBoundaryType` for each direction
846: . -dm_plex_sphere_radius r - The sphere radius
847: . -dm_plex_ball_radius r - Radius of the ball
848: . -dm_plex_cylinder_bd bz - Boundary type in the z direction
849: . -dm_plex_cylinder_num_wedges n - Number of wedges around the cylinder
850: . -dm_plex_reorder order - Reorder the mesh using the specified algorithm
851: . -dm_refine_pre n - The number of refinements before distribution
852: . -dm_refine_uniform_pre (true|false) - Flag for uniform refinement before distribution
853: . -dm_refine_volume_limit_pre v - The maximum cell volume after refinement before distribution
854: . -dm_refine n - The number of refinements after distribution
855: . -dm_extrude l - Activate extrusion and specify the number of layers to extrude
856: . -dm_plex_save_transform (true|false) - Save the `DMPlexTransform` that produced this mesh
857: . -dm_plex_transform_extrude_thickness t - The total thickness of extruded layers
858: . -dm_plex_transform_extrude_use_tensor (true|false) - Use tensor cells when extruding
859: . -dm_plex_transform_extrude_symmetric (true|false) - Extrude layers symmetrically about the surface
860: . -dm_plex_transform_extrude_normal n0,...,nd - Specify the extrusion direction
861: . -dm_plex_transform_extrude_thicknesses t0,...,tl - Specify thickness of each layer
862: . -dm_plex_create_fv_ghost_cells - Flag to create finite volume ghost cells on the boundary
863: . -dm_plex_fv_ghost_cells_label name - Label name for ghost cells boundary
864: . -dm_distribute (true|false) - Flag to redistribute a mesh among processes
865: . -dm_distribute_overlap n - The size of the overlap halo
866: . -dm_plex_adj_cone (true|false) - Set adjacency direction
867: . -dm_plex_adj_closure (true|false) - Set adjacency size
868: . -dm_plex_use_ceed (true|false) - Use LibCEED as the FEM backend
869: . -dm_plex_check_symmetry (true|false) - Check that the adjacency information in the mesh is symmetric - `DMPlexCheckSymmetry()`
870: . -dm_plex_check_skeleton (true|false) - Check that each cell has the correct number of vertices (only for homogeneous simplex or tensor meshes) - `DMPlexCheckSkeleton()`
871: . -dm_plex_check_faces (true|false) - Check that the faces of each cell give a vertex order this is consistent with what we expect from the cell type - `DMPlexCheckFaces()`
872: . -dm_plex_check_geometry (true|false) - Check that cells have positive volume - `DMPlexCheckGeometry()`
873: . -dm_plex_check_pointsf (true|false) - Check some necessary conditions for `PointSF` - `DMPlexCheckPointSF()`
874: . -dm_plex_check_interface_cones (true|false) - Check points on inter-partition interfaces have conforming order of cone points - `DMPlexCheckInterfaceCones()`
875: - -dm_plex_check_all (true|false) - Perform all the checks above
877: Level: intermediate
879: Note:
880: For some `DMType` such as `DMDA` this cannot be called after `DMSetUp()` has been called.
882: .seealso: [](ch_dmbase), `DM`, `DMView()`, `DMCreateGlobalVector()`, `DMCreateInterpolation()`, `DMCreateColoring()`, `DMCreateMatrix()`,
883: `DMPlexCheckSymmetry()`, `DMPlexCheckSkeleton()`, `DMPlexCheckFaces()`, `DMPlexCheckGeometry()`, `DMPlexCheckPointSF()`, `DMPlexCheckInterfaceCones()`,
884: `DMSetOptionsPrefix()`, `DMType`, `DMPLEX`, `DMDA`, `DMSetUp()`
885: @*/
886: PetscErrorCode DMSetFromOptions(DM dm)
887: {
888: char typeName[256];
889: PetscBool flg;
891: PetscFunctionBegin;
893: dm->setfromoptionscalled = PETSC_TRUE;
894: if (dm->sf) PetscCall(PetscSFSetFromOptions(dm->sf));
895: if (dm->sectionSF) PetscCall(PetscSFSetFromOptions(dm->sectionSF));
896: if (dm->coordinates[0].dm) PetscCall(DMSetFromOptions(dm->coordinates[0].dm));
897: PetscObjectOptionsBegin((PetscObject)dm);
898: PetscCall(PetscOptionsBool("-dm_preallocate_only", "only preallocate matrix, but do not set column indices", "DMSetMatrixPreallocateOnly", dm->prealloc_only, &dm->prealloc_only, NULL));
899: PetscCall(PetscOptionsFList("-dm_vec_type", "Vector type used for created vectors", "DMSetVecType", VecList, dm->vectype, typeName, 256, &flg));
900: if (flg) PetscCall(DMSetVecType(dm, typeName));
901: PetscCall(PetscOptionsFList("-dm_mat_type", "Matrix type used for created matrices", "DMSetMatType", MatList, dm->mattype ? dm->mattype : typeName, typeName, sizeof(typeName), &flg));
902: if (flg) PetscCall(DMSetMatType(dm, typeName));
903: PetscCall(PetscOptionsEnum("-dm_blocking_type", "Topological point or field node blocking", "DMSetBlockingType", DMBlockingTypes, (PetscEnum)dm->blocking_type, (PetscEnum *)&dm->blocking_type, NULL));
904: PetscCall(PetscOptionsEnum("-dm_is_coloring_type", "Global or local coloring of Jacobian", "DMSetISColoringType", ISColoringTypes, (PetscEnum)dm->coloringtype, (PetscEnum *)&dm->coloringtype, NULL));
905: PetscCall(PetscOptionsInt("-dm_bind_below", "Set the size threshold (in entries) below which the Vec is bound to the CPU", "VecBindToCPU", dm->bind_below, &dm->bind_below, &flg));
906: PetscCall(PetscOptionsBool("-dm_ignore_perm_output", "Ignore the local section permutation on output", "DMGetOutputDM", dm->ignorePermOutput, &dm->ignorePermOutput, NULL));
907: PetscTryTypeMethod(dm, setfromoptions, PetscOptionsObject);
908: /* process any options handlers added with PetscObjectAddOptionsHandler() */
909: PetscCall(PetscObjectProcessOptionsHandlers((PetscObject)dm, PetscOptionsObject));
910: PetscOptionsEnd();
911: PetscFunctionReturn(PETSC_SUCCESS);
912: }
914: /*@
915: DMViewFromOptions - View a `DM` in a particular way based on a request in the options database
917: Collective
919: Input Parameters:
920: + dm - the `DM` object
921: . obj - optional object that provides the prefix for the options database (if `NULL` then the prefix in `obj` is used)
922: - name - option string that is used to activate viewing
924: Options Database Key:
925: . -name [viewertype][:...] - option name and values. See `PetscObjectViewFromOptions()` for the possible arguments
927: Level: intermediate
929: .seealso: [](ch_dmbase), `DM`, `DMView()`, `PetscObjectViewFromOptions()`, `DMCreate()`
930: @*/
931: PetscErrorCode DMViewFromOptions(DM dm, PeOp PetscObject obj, const char name[])
932: {
933: PetscFunctionBegin;
935: PetscCall(PetscObjectViewFromOptions((PetscObject)dm, obj, name));
936: PetscFunctionReturn(PETSC_SUCCESS);
937: }
939: /*@
940: DMView - Views a `DM`. Depending on the `PetscViewer` and its `PetscViewerFormat` it may print some ASCII information about the `DM` to the screen or a file or
941: save the `DM` in a binary file to be loaded later or create a visualization of the `DM`
943: Collective
945: Input Parameters:
946: + dm - the `DM` object to view
947: - v - the viewer
949: Options Database Keys:
950: + -view_pyvista_warp f - Warps the mesh by the active scalar with factor f
951: . -view_pyvista_clip xl,xu,yl,yu,zl,zu - Defines the clipping box
952: . -dm_view_draw_line_color color - Specify the X-window color for cell borders
953: . -dm_view_draw_cell_color color - Specify the X-window color for cells
954: - -dm_view_draw_affine (true|false) - Flag to ignore high-order edges
956: Level: beginner
958: Notes:
960: `PetscViewer` = `PETSCVIEWERHDF5` i.e. HDF5 format can be used with `PETSC_VIEWER_HDF5_PETSC` as the `PetscViewerFormat` to save multiple `DMPLEX`
961: meshes in a single HDF5 file. This in turn requires one to name the `DMPLEX` object with `PetscObjectSetName()`
962: before saving it with `DMView()` and before loading it with `DMLoad()` for identification of the mesh object.
964: `PetscViewer` = `PETSCVIEWEREXODUSII` i.e. ExodusII format assumes that element blocks (mapped to "Cell sets" labels)
965: consists of sequentially numbered cells.
967: If `dm` has been distributed, only the part of the `DM` on MPI rank 0 (including "ghost" cells and vertices) will be written.
969: Only TRI, TET, QUAD, and HEX cells are supported in ExodusII.
971: `DMPLEX` only represents geometry while most post-processing software expect that a mesh also provides information on the discretization space. This function assumes that the file represents Lagrange finite elements of order 1 or 2.
972: The order of the mesh shall be set using `PetscViewerExodusIISetOrder()`
974: Variable names can be set and queried using `PetscViewerExodusII[Set/Get][Nodal/Zonal]VariableNames[s]`.
976: .seealso: [](ch_dmbase), `DM`, `PetscViewer`, `PetscViewerFormat`, `PetscViewerSetFormat()`, `DMDestroy()`, `DMCreateGlobalVector()`, `DMCreateInterpolation()`, `DMCreateColoring()`, `DMCreateMatrix()`, `DMCreateMassMatrix()`, `DMLoad()`, `PetscObjectSetName()`
977: @*/
978: PetscErrorCode DMView(DM dm, PetscViewer v)
979: {
980: PetscBool isbinary;
981: PetscMPIInt size;
982: PetscViewerFormat format;
984: PetscFunctionBegin;
986: if (!v) PetscCall(PetscViewerASCIIGetStdout(PetscObjectComm((PetscObject)dm), &v));
988: /* Ideally, we would like to have this test on.
989: However, it currently breaks socket viz via GLVis.
990: During DMView(parallel_mesh,glvis_viewer), each
991: process opens a sequential ASCII socket to visualize
992: the local mesh, and PetscObjectView(dm,local_socket)
993: is internally called inside VecView_GLVis, incurring
994: in an error here */
995: /* PetscCheckSameComm(dm,1,v,2); */
996: PetscCall(PetscViewerCheckWritable(v));
998: PetscCall(PetscLogEventBegin(DM_View, v, 0, 0, 0));
999: PetscCall(PetscViewerGetFormat(v, &format));
1000: PetscCallMPI(MPI_Comm_size(PetscObjectComm((PetscObject)dm), &size));
1001: if (size == 1 && format == PETSC_VIEWER_LOAD_BALANCE) PetscFunctionReturn(PETSC_SUCCESS);
1002: PetscCall(PetscObjectPrintClassNamePrefixType((PetscObject)dm, v));
1003: PetscCall(PetscObjectTypeCompare((PetscObject)v, PETSCVIEWERBINARY, &isbinary));
1004: if (isbinary) {
1005: PetscInt classid = DM_FILE_CLASSID;
1006: char type[256];
1008: PetscCall(PetscViewerBinaryWrite(v, &classid, 1, PETSC_INT));
1009: PetscCall(PetscStrncpy(type, ((PetscObject)dm)->type_name, sizeof(type)));
1010: PetscCall(PetscViewerBinaryWrite(v, type, 256, PETSC_CHAR));
1011: }
1012: PetscTryTypeMethod(dm, view, v);
1013: PetscCall(PetscLogEventEnd(DM_View, v, 0, 0, 0));
1014: PetscFunctionReturn(PETSC_SUCCESS);
1015: }
1017: /*@
1018: DMCreateGlobalVector - Creates a global vector from a `DM` object. A global vector is a parallel vector that has no duplicate values shared between MPI ranks,
1019: that is it has no ghost locations.
1021: Collective
1023: Input Parameter:
1024: . dm - the `DM` object
1026: Output Parameter:
1027: . vec - the global vector
1029: Level: beginner
1031: Note:
1032: PETSc `Vec` always have all zero entries when created with `DMCreateGlobalVector()` until routines such as `VecSet()` or `VecSetValues()`
1033: are used to change the values. There is no reason to call `VecZeroEntries()` after creation.
1035: .seealso: [](ch_dmbase), `DM`, `Vec`, `DMCreateLocalVector()`, `DMGetGlobalVector()`, `DMDestroy()`, `DMView()`, `DMCreateInterpolation()`, `DMCreateColoring()`, `DMCreateMatrix()`,
1036: `DMGlobalToLocalBegin()`, `DMGlobalToLocalEnd()`
1037: @*/
1038: PetscErrorCode DMCreateGlobalVector(DM dm, Vec *vec)
1039: {
1040: PetscFunctionBegin;
1042: PetscAssertPointer(vec, 2);
1043: PetscUseTypeMethod(dm, createglobalvector, vec);
1044: if (PetscDefined(USE_DEBUG)) {
1045: DM vdm;
1047: PetscCall(VecGetDM(*vec, &vdm));
1048: PetscCheck(vdm, PETSC_COMM_SELF, PETSC_ERR_PLIB, "DM type '%s' did not attach the DM to the vector", ((PetscObject)dm)->type_name);
1049: }
1050: PetscFunctionReturn(PETSC_SUCCESS);
1051: }
1053: /*@
1054: DMCreateLocalVector - Creates a local vector from a `DM` object.
1056: Not Collective
1058: Input Parameter:
1059: . dm - the `DM` object
1061: Output Parameter:
1062: . vec - the local vector
1064: Level: beginner
1066: Notes:
1067: A local vector usually has ghost locations that contain values that are owned by different MPI ranks. A global vector has no ghost locations.
1069: PETSc `Vec` always have all zero entries when created with `DMCreateLocalVector()` until routines such as `VecSet()` or `VecSetValues()`
1070: are used to change the values. There is no reason to call `VecZeroEntries()` after creation.
1072: .seealso: [](ch_dmbase), `DM`, `Vec`, `DMCreateGlobalVector()`, `DMGetLocalVector()`, `DMDestroy()`, `DMView()`, `DMCreateInterpolation()`, `DMCreateColoring()`, `DMCreateMatrix()`,
1073: `DMGlobalToLocalBegin()`, `DMGlobalToLocalEnd()`
1074: @*/
1075: PetscErrorCode DMCreateLocalVector(DM dm, Vec *vec)
1076: {
1077: PetscFunctionBegin;
1079: PetscAssertPointer(vec, 2);
1080: PetscUseTypeMethod(dm, createlocalvector, vec);
1081: if (PetscDefined(USE_DEBUG)) {
1082: DM vdm;
1084: PetscCall(VecGetDM(*vec, &vdm));
1085: PetscCheck(vdm, PETSC_COMM_SELF, PETSC_ERR_LIB, "DM type '%s' did not attach the DM to the vector", ((PetscObject)dm)->type_name);
1086: }
1087: PetscFunctionReturn(PETSC_SUCCESS);
1088: }
1090: /*@
1091: DMGetLocalToGlobalMapping - Accesses the local-to-global mapping in a `DM`.
1093: Collective
1095: Input Parameter:
1096: . dm - the `DM` that provides the mapping
1098: Output Parameter:
1099: . ltog - the mapping
1101: Level: advanced
1103: Notes:
1104: The global to local mapping allows one to set values into the global vector or matrix using `VecSetValuesLocal()` and `MatSetValuesLocal()`
1106: Vectors obtained with `DMCreateGlobalVector()` and matrices obtained with `DMCreateMatrix()` already contain the global mapping so you do
1107: need to use this function with those objects.
1109: This mapping can then be used by `VecSetLocalToGlobalMapping()` or `MatSetLocalToGlobalMapping()`.
1111: .seealso: [](ch_dmbase), `DM`, `DMCreateLocalVector()`, `DMCreateGlobalVector()`, `VecSetLocalToGlobalMapping()`, `MatSetLocalToGlobalMapping()`,
1112: `DMCreateMatrix()`
1113: @*/
1114: PetscErrorCode DMGetLocalToGlobalMapping(DM dm, ISLocalToGlobalMapping *ltog)
1115: {
1116: PetscInt bs = -1, bsLocal[2], bsMinMax[2];
1118: PetscFunctionBegin;
1120: PetscAssertPointer(ltog, 2);
1121: if (!dm->ltogmap) {
1122: PetscSection section, sectionGlobal;
1124: PetscCall(DMGetLocalSection(dm, §ion));
1125: if (section) {
1126: const PetscInt *cdofs;
1127: PetscInt *ltog;
1128: PetscInt pStart, pEnd, n, p, k, l;
1130: PetscCall(DMGetGlobalSection(dm, §ionGlobal));
1131: PetscCall(PetscSectionGetChart(section, &pStart, &pEnd));
1132: PetscCall(PetscSectionGetStorageSize(section, &n));
1133: PetscCall(PetscMalloc1(n, <og)); /* We want the local+overlap size */
1134: for (p = pStart, l = 0; p < pEnd; ++p) {
1135: PetscInt bdof, cdof, dof, off, c, cind;
1137: /* Should probably use constrained dofs */
1138: PetscCall(PetscSectionGetDof(section, p, &dof));
1139: PetscCall(PetscSectionGetConstraintDof(section, p, &cdof));
1140: PetscCall(PetscSectionGetConstraintIndices(section, p, &cdofs));
1141: PetscCall(PetscSectionGetOffset(sectionGlobal, p, &off));
1142: /* If you have dofs, and constraints, and they are unequal, we set the blocksize to 1 */
1143: bdof = cdof && (dof - cdof) ? 1 : dof;
1144: if (dof) bs = bs < 0 ? bdof : PetscGCD(bs, bdof);
1146: for (c = 0, cind = 0; c < dof; ++c, ++l) {
1147: if (cind < cdof && c == cdofs[cind]) {
1148: ltog[l] = off < 0 ? off - c : -(off + c + 1);
1149: cind++;
1150: } else {
1151: ltog[l] = (off < 0 ? -(off + 1) : off) + c - cind;
1152: }
1153: }
1154: }
1155: /* Must have same blocksize on all procs (some might have no points) */
1156: bsLocal[0] = bs < 0 ? PETSC_INT_MAX : bs;
1157: bsLocal[1] = bs;
1158: PetscCall(PetscGlobalMinMaxInt(PetscObjectComm((PetscObject)dm), bsLocal, bsMinMax));
1159: if (bsMinMax[0] != bsMinMax[1]) {
1160: bs = 1;
1161: } else {
1162: bs = bsMinMax[0];
1163: }
1164: bs = bs < 0 ? 1 : bs;
1165: /* Must reduce indices by blocksize */
1166: if (bs > 1) {
1167: for (l = 0, k = 0; l < n; l += bs, ++k) {
1168: // Integer division of negative values truncates toward zero(!), not toward negative infinity
1169: ltog[k] = ltog[l] >= 0 ? ltog[l] / bs : -(-(ltog[l] + 1) / bs + 1);
1170: }
1171: n /= bs;
1172: }
1173: PetscCall(ISLocalToGlobalMappingCreate(PetscObjectComm((PetscObject)dm), bs, n, ltog, PETSC_OWN_POINTER, &dm->ltogmap));
1174: } else PetscUseTypeMethod(dm, getlocaltoglobalmapping);
1175: }
1176: *ltog = dm->ltogmap;
1177: PetscFunctionReturn(PETSC_SUCCESS);
1178: }
1180: /*@
1181: DMGetBlockSize - Gets the inherent block size associated with a `DM`
1183: Not Collective
1185: Input Parameter:
1186: . dm - the `DM` with block structure
1188: Output Parameter:
1189: . bs - the block size, 1 implies no exploitable block structure
1191: Level: intermediate
1193: Notes:
1194: This might be the number of degrees of freedom at each grid point for a structured grid.
1196: Complex `DM` that represent multiphysics or staggered grids or mixed-methods do not generally have a single inherent block size, but
1197: rather different locations in the vectors may have a different block size.
1199: .seealso: [](ch_dmbase), `DM`, `ISCreateBlock()`, `VecSetBlockSize()`, `MatSetBlockSize()`, `DMGetLocalToGlobalMapping()`
1200: @*/
1201: PetscErrorCode DMGetBlockSize(DM dm, PetscInt *bs)
1202: {
1203: PetscFunctionBegin;
1205: PetscAssertPointer(bs, 2);
1206: PetscCheck(dm->bs >= 1, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "DM does not have enough information to provide a block size yet");
1207: *bs = dm->bs;
1208: PetscFunctionReturn(PETSC_SUCCESS);
1209: }
1211: /*@
1212: DMCreateInterpolation - Gets the interpolation matrix between two `DM` objects. The resulting matrix map degrees of freedom in the vector obtained by
1213: `DMCreateGlobalVector()` on the coarse `DM` to similar vectors on the fine grid `DM`.
1215: Collective
1217: Input Parameters:
1218: + dmc - the `DM` object
1219: - dmf - the second, finer `DM` object
1221: Output Parameters:
1222: + mat - the interpolation
1223: - vec - the scaling (optional, pass `NULL` if not needed), see `DMCreateInterpolationScale()`
1225: Level: developer
1227: Notes:
1228: For `DMDA` objects this only works for "uniform refinement", that is the refined mesh was obtained `DMRefine()` or the coarse mesh was obtained by
1229: DMCoarsen(). The coordinates set into the `DMDA` are completely ignored in computing the interpolation.
1231: For `DMDA` objects you can use this interpolation (more precisely the interpolation from the `DMGetCoordinateDM()`) to interpolate the mesh coordinate
1232: vectors EXCEPT in the periodic case where it does not make sense since the coordinate vectors are not periodic.
1234: .seealso: [](ch_dmbase), `DM`, `DMDestroy()`, `DMView()`, `DMCreateGlobalVector()`, `DMCreateColoring()`, `DMCreateMatrix()`, `DMCreateMassMatrix()`, `DMRefine()`, `DMCoarsen()`, `DMCreateRestriction()`, `DMCreateInterpolationScale()`
1235: @*/
1236: PetscErrorCode DMCreateInterpolation(DM dmc, DM dmf, Mat *mat, Vec *vec)
1237: {
1238: PetscFunctionBegin;
1241: PetscAssertPointer(mat, 3);
1242: PetscCall(PetscLogEventBegin(DM_CreateInterpolation, dmc, dmf, 0, 0));
1243: PetscUseTypeMethod(dmc, createinterpolation, dmf, mat, vec);
1244: PetscCall(PetscLogEventEnd(DM_CreateInterpolation, dmc, dmf, 0, 0));
1245: PetscFunctionReturn(PETSC_SUCCESS);
1246: }
1248: /*@
1249: DMCreateInterpolationScale - Forms L = 1/(R*1) where 1 is the vector of all ones, and R is
1250: the transpose of the interpolation between the `DM`.
1252: Input Parameters:
1253: + dac - `DM` that defines a coarse mesh
1254: . daf - `DM` that defines a fine mesh
1255: - mat - the restriction (or interpolation operator) from fine to coarse
1257: Output Parameter:
1258: . scale - the scaled vector
1260: Level: advanced
1262: Note:
1263: xcoarse = diag(L)*R*xfine preserves scale and is thus suitable for state (versus residual)
1264: restriction. In other words xcoarse is the coarse representation of xfine.
1266: Developer Note:
1267: If the fine-scale `DMDA` has the -dm_bind_below option set to true, then `DMCreateInterpolationScale()` calls `MatSetBindingPropagates()`
1268: on the restriction/interpolation operator to set the bindingpropagates flag to true.
1270: .seealso: [](ch_dmbase), `DM`, `MatRestrict()`, `MatInterpolate()`, `DMCreateInterpolation()`, `DMCreateRestriction()`, `DMCreateGlobalVector()`
1271: @*/
1272: PetscErrorCode DMCreateInterpolationScale(DM dac, DM daf, Mat mat, Vec *scale)
1273: {
1274: Vec fine;
1275: PetscScalar one = 1.0;
1276: #if defined(PETSC_HAVE_CUDA)
1277: PetscBool bindingpropagates, isbound;
1278: #endif
1280: PetscFunctionBegin;
1281: PetscCall(DMCreateGlobalVector(daf, &fine));
1282: PetscCall(DMCreateGlobalVector(dac, scale));
1283: PetscCall(VecSet(fine, one));
1284: #if defined(PETSC_HAVE_CUDA)
1285: /* If the 'fine' Vec is bound to the CPU, it makes sense to bind 'mat' as well.
1286: * Note that we only do this for the CUDA case, right now, but if we add support for MatMultTranspose() via ViennaCL,
1287: * we'll need to do it for that case, too.*/
1288: PetscCall(VecGetBindingPropagates(fine, &bindingpropagates));
1289: if (bindingpropagates) {
1290: PetscCall(MatSetBindingPropagates(mat, PETSC_TRUE));
1291: PetscCall(VecBoundToCPU(fine, &isbound));
1292: PetscCall(MatBindToCPU(mat, isbound));
1293: }
1294: #endif
1295: PetscCall(MatRestrict(mat, fine, *scale));
1296: PetscCall(VecDestroy(&fine));
1297: PetscCall(VecReciprocal(*scale));
1298: PetscFunctionReturn(PETSC_SUCCESS);
1299: }
1301: /*@
1302: DMCreateRestriction - Gets restriction matrix between two `DM` objects. The resulting matrix map degrees of freedom in the vector obtained by
1303: `DMCreateGlobalVector()` on the fine `DM` to similar vectors on the coarse grid `DM`.
1305: Collective
1307: Input Parameters:
1308: + dmc - the `DM` object
1309: - dmf - the second, finer `DM` object
1311: Output Parameter:
1312: . mat - the restriction
1314: Level: developer
1316: Note:
1317: This only works for `DMSTAG`. For many situations either the transpose of the operator obtained with `DMCreateInterpolation()` or that
1318: matrix multiplied by the vector obtained with `DMCreateInterpolationScale()` provides the desired object.
1320: .seealso: [](ch_dmbase), `DM`, `DMRestrict()`, `DMInterpolate()`, `DMDestroy()`, `DMView()`, `DMCreateGlobalVector()`, `DMCreateColoring()`, `DMCreateMatrix()`, `DMCreateMassMatrix()`, `DMRefine()`, `DMCoarsen()`, `DMCreateInterpolation()`
1321: @*/
1322: PetscErrorCode DMCreateRestriction(DM dmc, DM dmf, Mat *mat)
1323: {
1324: PetscFunctionBegin;
1327: PetscAssertPointer(mat, 3);
1328: PetscCall(PetscLogEventBegin(DM_CreateRestriction, dmc, dmf, 0, 0));
1329: PetscUseTypeMethod(dmc, createrestriction, dmf, mat);
1330: PetscCall(PetscLogEventEnd(DM_CreateRestriction, dmc, dmf, 0, 0));
1331: PetscFunctionReturn(PETSC_SUCCESS);
1332: }
1334: /*@
1335: DMCreateInjection - Gets injection matrix between two `DM` objects.
1337: Collective
1339: Input Parameters:
1340: + dac - the `DM` object
1341: - daf - the second, finer `DM` object
1343: Output Parameter:
1344: . mat - the injection
1346: Level: developer
1348: Notes:
1349: This is an operator that applied to a vector obtained with `DMCreateGlobalVector()` on the
1350: fine grid maps the values to a vector on the vector on the coarse `DM` by simply selecting
1351: the values on the coarse grid points. This compares to the operator obtained by
1352: `DMCreateRestriction()` or the transpose of the operator obtained by
1353: `DMCreateInterpolation()` that uses a "local weighted average" of the values around the
1354: coarse grid point as the coarse grid value.
1356: For `DMDA` objects this only works for "uniform refinement", that is the refined mesh was obtained `DMRefine()` or the coarse mesh was obtained by
1357: `DMCoarsen()`. The coordinates set into the `DMDA` are completely ignored in computing the injection.
1359: .seealso: [](ch_dmbase), `DM`, `DMDestroy()`, `DMView()`, `DMCreateGlobalVector()`, `DMCreateColoring()`, `DMCreateMatrix()`, `DMCreateMassMatrix()`, `DMCreateInterpolation()`,
1360: `DMCreateRestriction()`, `MatRestrict()`, `MatInterpolate()`
1361: @*/
1362: PetscErrorCode DMCreateInjection(DM dac, DM daf, Mat *mat)
1363: {
1364: PetscFunctionBegin;
1367: PetscAssertPointer(mat, 3);
1368: PetscCall(PetscLogEventBegin(DM_CreateInjection, dac, daf, 0, 0));
1369: PetscUseTypeMethod(dac, createinjection, daf, mat);
1370: PetscCall(PetscLogEventEnd(DM_CreateInjection, dac, daf, 0, 0));
1371: PetscFunctionReturn(PETSC_SUCCESS);
1372: }
1374: /*@
1375: 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
1376: a Galerkin finite element model on the `DM`
1378: Collective
1380: Input Parameters:
1381: + dmc - the target `DM` object
1382: - dmf - the source `DM` object, can be `NULL`
1384: Output Parameter:
1385: . mat - the mass matrix
1387: Level: developer
1389: Notes:
1390: For `DMPLEX` the finite element model for the `DM` must have been already provided.
1392: 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()`
1394: .seealso: [](ch_dmbase), `DM`, `DMCreateMassMatrixLumped()`, `DMCreateMatrix()`, `DMRefine()`, `DMCoarsen()`, `DMCreateRestriction()`, `DMCreateInterpolation()`, `DMCreateInjection()`
1395: @*/
1396: PetscErrorCode DMCreateMassMatrix(DM dmc, DM dmf, Mat *mat)
1397: {
1398: PetscFunctionBegin;
1400: if (!dmf) dmf = dmc;
1402: PetscAssertPointer(mat, 3);
1403: PetscCall(PetscLogEventBegin(DM_CreateMassMatrix, dmc, dmf, 0, 0));
1404: PetscUseTypeMethod(dmc, createmassmatrix, dmf, mat);
1405: PetscCall(PetscLogEventEnd(DM_CreateMassMatrix, dmc, dmf, 0, 0));
1406: PetscFunctionReturn(PETSC_SUCCESS);
1407: }
1409: /*@
1410: DMCreateMassMatrixLumped - Gets the lumped mass matrix for a given `DM`
1412: Collective
1414: Input Parameter:
1415: . dm - the `DM` object
1417: Output Parameters:
1418: + llm - the local lumped mass matrix, which is a diagonal matrix, represented as a vector
1419: - lm - the global lumped mass matrix, which is a diagonal matrix, represented as a vector
1421: Level: developer
1423: Note:
1424: See `DMCreateMassMatrix()` for how to create the non-lumped version of the mass matrix.
1426: .seealso: [](ch_dmbase), `DM`, `DMCreateMassMatrix()`, `DMCreateMatrix()`, `DMRefine()`, `DMCoarsen()`, `DMCreateRestriction()`, `DMCreateInterpolation()`, `DMCreateInjection()`
1427: @*/
1428: PetscErrorCode DMCreateMassMatrixLumped(DM dm, Vec *llm, Vec *lm)
1429: {
1430: PetscFunctionBegin;
1432: if (llm) PetscAssertPointer(llm, 2);
1433: if (lm) PetscAssertPointer(lm, 3);
1434: if (llm || lm) PetscUseTypeMethod(dm, createmassmatrixlumped, llm, lm);
1435: PetscFunctionReturn(PETSC_SUCCESS);
1436: }
1438: /*@
1439: 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`
1441: Collective
1443: Input Parameters:
1444: + dmc - the target `DM` object
1445: - dmf - the source `DM` object, can be `NULL`
1447: Output Parameter:
1448: . mat - the gradient matrix
1450: Level: developer
1452: Notes:
1453: For `DMPLEX` the finite element model for the `DM` must have been already provided.
1455: .seealso: [](ch_dmbase), `DM`, `DMCreateMassMatrix()`, `DMCreateMassMatrixLumped()`, `DMCreateMatrix()`, `DMRefine()`, `DMCoarsen()`, `DMCreateRestriction()`, `DMCreateInterpolation()`, `DMCreateInjection()`
1456: @*/
1457: PetscErrorCode DMCreateGradientMatrix(DM dmc, DM dmf, Mat *mat)
1458: {
1459: PetscFunctionBegin;
1461: if (!dmf) dmf = dmc;
1463: PetscAssertPointer(mat, 3);
1464: PetscUseTypeMethod(dmc, creategradientmatrix, dmf, mat);
1465: PetscFunctionReturn(PETSC_SUCCESS);
1466: }
1468: /*@
1469: DMCreateColoring - Gets coloring of a graph associated with the `DM`. Often the graph represents the operator matrix associated with the discretization
1470: of a PDE on the `DM`.
1472: Collective
1474: Input Parameters:
1475: + dm - the `DM` object
1476: - ctype - `IS_COLORING_LOCAL` or `IS_COLORING_GLOBAL`
1478: Output Parameter:
1479: . coloring - the coloring
1481: Level: developer
1483: Notes:
1484: 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
1485: matrix comes from (what this function provides). In general using the mesh produces a more optimal coloring (fewer colors).
1487: This produces a coloring with the distance of 2, see `MatSetColoringDistance()` which can be used for efficiently computing Jacobians with `MatFDColoringCreate()`
1488: 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,
1489: otherwise an error will be generated.
1491: .seealso: [](ch_dmbase), `DM`, `ISColoring`, `DMDestroy()`, `DMView()`, `DMCreateGlobalVector()`, `DMCreateInterpolation()`, `DMCreateMatrix()`, `DMCreateMassMatrix()`, `DMSetMatType()`, `MatColoring`, `MatFDColoringCreate()`
1492: @*/
1493: PetscErrorCode DMCreateColoring(DM dm, ISColoringType ctype, ISColoring *coloring)
1494: {
1495: PetscFunctionBegin;
1497: PetscAssertPointer(coloring, 3);
1498: PetscUseTypeMethod(dm, getcoloring, ctype, coloring);
1499: PetscFunctionReturn(PETSC_SUCCESS);
1500: }
1502: /*@
1503: DMCreateMatrix - Creates a matrix of appropriate size and nonzero structure for a `DM`. The matrix is most commonly used to store the Jacobian
1504: of a discrete PDE operator.
1506: Collective
1508: Input Parameter:
1509: . dm - the `DM` object
1511: Output Parameter:
1512: . mat - the matrix
1514: Options Database Key:
1515: . -dm_preallocate_only (true|false) - Only preallocate the matrix for `DMCreateMatrix()` and `DMCreateMassMatrix()`, but do not fill its nonzero structure
1517: Level: beginner
1519: Notes:
1520: This properly preallocates the number of nonzeros in the sparse matrix so you
1521: do not need to do it yourself.
1523: By default it also sets the nonzero structure and puts in the zero entries. To prevent setting
1524: the nonzero pattern call `DMSetMatrixPreallocateOnly()`
1526: For `DMDA`, when you call `MatView()` on this matrix it is displayed using the global natural ordering, NOT in the ordering used
1527: internally by PETSc.
1529: For `DMDA`, in general it is easiest to use `MatSetValuesStencil()` or `MatSetValuesLocal()` to put values into the matrix because
1530: `MatSetValues()` requires the indices for the global numbering for the `DMDA` which is complic`ated to compute
1532: .seealso: [](ch_dmbase), `DM`, `DMDestroy()`, `DMView()`, `DMCreateGlobalVector()`, `DMCreateInterpolation()`, `DMSetMatType()`, `DMCreateMassMatrix()`
1533: @*/
1534: PetscErrorCode DMCreateMatrix(DM dm, Mat *mat)
1535: {
1536: PetscFunctionBegin;
1538: PetscAssertPointer(mat, 2);
1539: PetscCall(MatInitializePackage());
1540: PetscCall(PetscLogEventBegin(DM_CreateMatrix, 0, 0, 0, 0));
1541: PetscUseTypeMethod(dm, creatematrix, mat);
1542: if (PetscDefined(USE_DEBUG)) {
1543: DM mdm;
1545: PetscCall(MatGetDM(*mat, &mdm));
1546: PetscCheck(mdm, PETSC_COMM_SELF, PETSC_ERR_PLIB, "DM type '%s' did not attach the DM to the matrix", ((PetscObject)dm)->type_name);
1547: }
1548: /* Handle nullspace and near nullspace */
1549: if (dm->Nf) {
1550: MatNullSpace nullSpace;
1551: PetscInt Nf, f;
1553: PetscCall(DMGetNumFields(dm, &Nf));
1554: for (f = 0; f < Nf; ++f) {
1555: if (dm->nullspaceConstructors && dm->nullspaceConstructors[f]) {
1556: PetscCall((*dm->nullspaceConstructors[f])(dm, f, f, &nullSpace));
1557: PetscCall(MatSetNullSpace(*mat, nullSpace));
1558: PetscCall(MatNullSpaceDestroy(&nullSpace));
1559: break;
1560: }
1561: }
1562: for (f = 0; f < Nf; ++f) {
1563: if (dm->nearnullspaceConstructors && dm->nearnullspaceConstructors[f]) {
1564: PetscCall((*dm->nearnullspaceConstructors[f])(dm, f, f, &nullSpace));
1565: PetscCall(MatSetNearNullSpace(*mat, nullSpace));
1566: PetscCall(MatNullSpaceDestroy(&nullSpace));
1567: }
1568: }
1569: }
1570: PetscCall(PetscLogEventEnd(DM_CreateMatrix, 0, 0, 0, 0));
1571: PetscFunctionReturn(PETSC_SUCCESS);
1572: }
1574: /*@
1575: DMSetMatrixPreallocateSkip - When `DMCreateMatrix()` is called the matrix sizes and
1576: `ISLocalToGlobalMapping` will be properly set, but the data structures to store values in the
1577: matrices will not be preallocated.
1579: Logically Collective
1581: Input Parameters:
1582: + dm - the `DM`
1583: - skip - `PETSC_TRUE` to skip preallocation
1585: Level: developer
1587: Note:
1588: This is most useful to reduce initialization costs when `MatSetPreallocationCOO()` and
1589: `MatSetValuesCOO()` will be used.
1591: .seealso: [](ch_dmbase), `DM`, `DMCreateMatrix()`, `DMSetMatrixStructureOnly()`, `DMSetMatrixPreallocateOnly()`
1592: @*/
1593: PetscErrorCode DMSetMatrixPreallocateSkip(DM dm, PetscBool skip)
1594: {
1595: PetscFunctionBegin;
1597: dm->prealloc_skip = skip;
1598: PetscFunctionReturn(PETSC_SUCCESS);
1599: }
1601: /*@
1602: DMSetMatrixPreallocateOnly - When `DMCreateMatrix()` is called the matrix will be properly
1603: preallocated but the nonzero structure and zero values will not be set.
1605: Logically Collective
1607: Input Parameters:
1608: + dm - the `DM`
1609: - only - `PETSC_TRUE` if only want preallocation
1611: Options Database Key:
1612: . -dm_preallocate_only - Only preallocate the matrix for `DMCreateMatrix()`, `DMCreateMassMatrix()`, but do not fill it with zeros
1614: Level: developer
1616: .seealso: [](ch_dmbase), `DM`, `DMCreateMatrix()`, `DMCreateMassMatrix()`, `DMSetMatrixStructureOnly()`, `DMSetMatrixPreallocateSkip()`
1617: @*/
1618: PetscErrorCode DMSetMatrixPreallocateOnly(DM dm, PetscBool only)
1619: {
1620: PetscFunctionBegin;
1622: dm->prealloc_only = only;
1623: PetscFunctionReturn(PETSC_SUCCESS);
1624: }
1626: /*@
1627: DMSetMatrixStructureOnly - When `DMCreateMatrix()` is called, the matrix nonzero structure will be created
1628: but the array for numerical values will not be allocated.
1630: Logically Collective
1632: Input Parameters:
1633: + dm - the `DM`
1634: - only - `PETSC_TRUE` if you only want matrix nonzero structure
1636: Level: developer
1638: .seealso: [](ch_dmbase), `DM`, `DMCreateMatrix()`, `DMSetMatrixPreallocateOnly()`, `DMSetMatrixPreallocateSkip()`
1639: @*/
1640: PetscErrorCode DMSetMatrixStructureOnly(DM dm, PetscBool only)
1641: {
1642: PetscFunctionBegin;
1644: dm->structure_only = only;
1645: PetscFunctionReturn(PETSC_SUCCESS);
1646: }
1648: /*@
1649: DMSetBlockingType - set the blocking granularity to be used for variable block size `DMCreateMatrix()` is called
1651: Logically Collective
1653: Input Parameters:
1654: + dm - the `DM`
1655: - btype - block by topological point or field node
1657: Options Database Key:
1658: . -dm_blocking_type (topological_point|field_node) - use topological point blocking or field node blocking
1660: Level: advanced
1662: .seealso: [](ch_dmbase), `DM`, `DMCreateMatrix()`, `MatSetVariableBlockSizes()`
1663: @*/
1664: PetscErrorCode DMSetBlockingType(DM dm, DMBlockingType btype)
1665: {
1666: PetscFunctionBegin;
1668: dm->blocking_type = btype;
1669: PetscFunctionReturn(PETSC_SUCCESS);
1670: }
1672: /*@
1673: DMGetBlockingType - get the blocking granularity to be used for variable block size `DMCreateMatrix()` is called
1675: Not Collective
1677: Input Parameter:
1678: . dm - the `DM`
1680: Output Parameter:
1681: . btype - block by topological point or field node
1683: Level: advanced
1685: .seealso: [](ch_dmbase), `DM`, `DMCreateMatrix()`, `MatSetVariableBlockSizes()`
1686: @*/
1687: PetscErrorCode DMGetBlockingType(DM dm, DMBlockingType *btype)
1688: {
1689: PetscFunctionBegin;
1691: PetscAssertPointer(btype, 2);
1692: *btype = dm->blocking_type;
1693: PetscFunctionReturn(PETSC_SUCCESS);
1694: }
1696: /*@C
1697: DMGetWorkArray - Gets a work array guaranteed to be at least the input size, restore with `DMRestoreWorkArray()`
1699: Not Collective
1701: Input Parameters:
1702: + dm - the `DM` object
1703: . count - The minimum size
1704: - dtype - MPI data type, often `MPIU_REAL`, `MPIU_SCALAR`, or `MPIU_INT`)
1706: Output Parameter:
1707: . mem - the work array
1709: Level: developer
1711: Notes:
1712: A `DM` may stash the array between instantiations so using this routine may be more efficient than calling `PetscMalloc()`
1714: The array may contain nonzero values
1716: .seealso: [](ch_dmbase), `DM`, `DMDestroy()`, `DMCreate()`, `DMRestoreWorkArray()`, `PetscMalloc()`
1717: @*/
1718: PetscErrorCode DMGetWorkArray(DM dm, PetscInt count, MPI_Datatype dtype, void *mem)
1719: {
1720: DMWorkLink link;
1721: PetscMPIInt dsize;
1723: PetscFunctionBegin;
1725: PetscAssertPointer(mem, 4);
1726: if (!count) {
1727: *(void **)mem = NULL;
1728: PetscFunctionReturn(PETSC_SUCCESS);
1729: }
1730: if (dm->workin) {
1731: link = dm->workin;
1732: dm->workin = dm->workin->next;
1733: } else {
1734: PetscCall(PetscNew(&link));
1735: }
1736: /* Avoid MPI_Type_size for most used datatypes
1737: Get size directly */
1738: if (dtype == MPIU_INT) dsize = sizeof(PetscInt);
1739: else if (dtype == MPIU_REAL) dsize = sizeof(PetscReal);
1740: #if defined(PETSC_USE_64BIT_INDICES)
1741: else if (dtype == MPI_INT) dsize = sizeof(int);
1742: #endif
1743: #if defined(PETSC_USE_COMPLEX)
1744: else if (dtype == MPIU_SCALAR) dsize = sizeof(PetscScalar);
1745: #endif
1746: else PetscCallMPI(MPI_Type_size(dtype, &dsize));
1748: if (((size_t)dsize * count) > link->bytes) {
1749: PetscCall(PetscFree(link->mem));
1750: PetscCall(PetscMalloc(dsize * count, &link->mem));
1751: link->bytes = dsize * count;
1752: }
1753: link->next = dm->workout;
1754: dm->workout = link;
1755: *(void **)mem = link->mem;
1756: PetscFunctionReturn(PETSC_SUCCESS);
1757: }
1759: /*@C
1760: DMRestoreWorkArray - Restores a work array obtained with `DMCreateWorkArray()`
1762: Not Collective
1764: Input Parameters:
1765: + dm - the `DM` object
1766: . count - The minimum size
1767: - dtype - MPI data type, often `MPIU_REAL`, `MPIU_SCALAR`, `MPIU_INT`
1769: Output Parameter:
1770: . mem - the work array
1772: Level: developer
1774: Developer Note:
1775: count and dtype are ignored, they are only needed for `DMGetWorkArray()`
1777: .seealso: [](ch_dmbase), `DM`, `DMDestroy()`, `DMCreate()`, `DMGetWorkArray()`
1778: @*/
1779: PetscErrorCode DMRestoreWorkArray(DM dm, PetscInt count, MPI_Datatype dtype, void *mem)
1780: {
1781: DMWorkLink *p, link;
1783: PetscFunctionBegin;
1784: PetscAssertPointer(mem, 4);
1785: (void)count;
1786: (void)dtype;
1787: if (!*(void **)mem) PetscFunctionReturn(PETSC_SUCCESS);
1788: for (p = &dm->workout; (link = *p); p = &link->next) {
1789: if (link->mem == *(void **)mem) {
1790: *p = link->next;
1791: link->next = dm->workin;
1792: dm->workin = link;
1793: *(void **)mem = NULL;
1794: PetscFunctionReturn(PETSC_SUCCESS);
1795: }
1796: }
1797: SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Array was not checked out");
1798: }
1800: /*@C
1801: DMSetNullSpaceConstructor - Provide a callback function which constructs the nullspace for a given field, defined with `DMAddField()`, when function spaces
1802: are joined or split, such as in `DMCreateSubDM()`
1804: Logically Collective; No Fortran Support
1806: Input Parameters:
1807: + dm - The `DM`
1808: . field - The field number for the nullspace
1809: - nullsp - A callback to create the nullspace
1811: Calling sequence of `nullsp`:
1812: + dm - The present `DM`
1813: . origField - The field number given above, in the original `DM`
1814: . field - The field number in dm
1815: - nullSpace - The nullspace for the given field
1817: Level: intermediate
1819: .seealso: [](ch_dmbase), `DM`, `DMAddField()`, `DMGetNullSpaceConstructor()`, `DMSetNearNullSpaceConstructor()`, `DMGetNearNullSpaceConstructor()`, `DMCreateSubDM()`, `DMCreateSuperDM()`
1820: @*/
1821: PetscErrorCode DMSetNullSpaceConstructor(DM dm, PetscInt field, PetscErrorCode (*nullsp)(DM dm, PetscInt origField, PetscInt field, MatNullSpace *nullSpace))
1822: {
1823: PetscFunctionBegin;
1825: PetscCheck(field < dm->Nf, PetscObjectComm((PetscObject)dm), PETSC_ERR_ARG_OUTOFRANGE, "Cannot handle %" PetscInt_FMT " >= %" PetscInt_FMT " fields", field, dm->Nf);
1826: PetscCheck(dm->nullspaceConstructors, PetscObjectComm((PetscObject)dm), PETSC_ERR_ARG_WRONG, "Must call DMCreateDS() to setup nullspaces");
1827: dm->nullspaceConstructors[field] = nullsp;
1828: PetscFunctionReturn(PETSC_SUCCESS);
1829: }
1831: /*@C
1832: DMGetNullSpaceConstructor - Return the callback function which constructs the nullspace for a given field, defined with `DMAddField()`
1834: Not Collective; No Fortran Support
1836: Input Parameters:
1837: + dm - The `DM`
1838: - field - The field number for the nullspace
1840: Output Parameter:
1841: . nullsp - A callback to create the nullspace
1843: Calling sequence of `nullsp`:
1844: + dm - The present DM
1845: . origField - The field number given above, in the original DM
1846: . field - The field number in dm
1847: - nullSpace - The nullspace for the given field
1849: Level: intermediate
1851: .seealso: [](ch_dmbase), `DM`, `DMAddField()`, `DMGetField()`, `DMSetNullSpaceConstructor()`, `DMSetNearNullSpaceConstructor()`, `DMGetNearNullSpaceConstructor()`, `DMCreateSubDM()`, `DMCreateSuperDM()`
1852: @*/
1853: PetscErrorCode DMGetNullSpaceConstructor(DM dm, PetscInt field, PetscErrorCode (**nullsp)(DM dm, PetscInt origField, PetscInt field, MatNullSpace *nullSpace))
1854: {
1855: PetscFunctionBegin;
1857: PetscAssertPointer(nullsp, 3);
1858: PetscCheck(field < dm->Nf, PetscObjectComm((PetscObject)dm), PETSC_ERR_ARG_OUTOFRANGE, "Cannot handle %" PetscInt_FMT " >= %" PetscInt_FMT " fields", field, dm->Nf);
1859: PetscCheck(dm->nullspaceConstructors, PetscObjectComm((PetscObject)dm), PETSC_ERR_ARG_WRONG, "Must call DMCreateDS() to setup nullspaces");
1860: *nullsp = dm->nullspaceConstructors[field];
1861: PetscFunctionReturn(PETSC_SUCCESS);
1862: }
1864: /*@C
1865: DMSetNearNullSpaceConstructor - Provide a callback function which constructs the near-nullspace for a given field, defined with `DMAddField()`
1867: Logically Collective; No Fortran Support
1869: Input Parameters:
1870: + dm - The `DM`
1871: . field - The field number for the nullspace
1872: - nullsp - A callback to create the near-nullspace
1874: Calling sequence of `nullsp`:
1875: + dm - The present `DM`
1876: . origField - The field number given above, in the original `DM`
1877: . field - The field number in dm
1878: - nullSpace - The nullspace for the given field
1880: Level: intermediate
1882: .seealso: [](ch_dmbase), `DM`, `DMAddField()`, `DMGetNearNullSpaceConstructor()`, `DMSetNullSpaceConstructor()`, `DMGetNullSpaceConstructor()`, `DMCreateSubDM()`, `DMCreateSuperDM()`,
1883: `MatNullSpace`
1884: @*/
1885: PetscErrorCode DMSetNearNullSpaceConstructor(DM dm, PetscInt field, PetscErrorCode (*nullsp)(DM dm, PetscInt origField, PetscInt field, MatNullSpace *nullSpace))
1886: {
1887: PetscFunctionBegin;
1889: PetscCheck(field < dm->Nf, PetscObjectComm((PetscObject)dm), PETSC_ERR_ARG_OUTOFRANGE, "Cannot handle %" PetscInt_FMT " >= %" PetscInt_FMT " fields", field, dm->Nf);
1890: PetscCheck(dm->nearnullspaceConstructors, PetscObjectComm((PetscObject)dm), PETSC_ERR_ARG_WRONG, "Must call DMCreateDS() to setup nullspaces");
1891: dm->nearnullspaceConstructors[field] = nullsp;
1892: PetscFunctionReturn(PETSC_SUCCESS);
1893: }
1895: /*@C
1896: DMGetNearNullSpaceConstructor - Return the callback function which constructs the near-nullspace for a given field, defined with `DMAddField()`
1898: Not Collective; No Fortran Support
1900: Input Parameters:
1901: + dm - The `DM`
1902: - field - The field number for the nullspace
1904: Output Parameter:
1905: . nullsp - A callback to create the near-nullspace
1907: Calling sequence of `nullsp`:
1908: + dm - The present `DM`
1909: . origField - The field number given above, in the original `DM`
1910: . field - The field number in dm
1911: - nullSpace - The nullspace for the given field
1913: Level: intermediate
1915: .seealso: [](ch_dmbase), `DM`, `DMAddField()`, `DMGetField()`, `DMSetNearNullSpaceConstructor()`, `DMSetNullSpaceConstructor()`, `DMGetNullSpaceConstructor()`, `DMCreateSubDM()`,
1916: `MatNullSpace`, `DMCreateSuperDM()`
1917: @*/
1918: PetscErrorCode DMGetNearNullSpaceConstructor(DM dm, PetscInt field, PetscErrorCode (**nullsp)(DM dm, PetscInt origField, PetscInt field, MatNullSpace *nullSpace))
1919: {
1920: PetscFunctionBegin;
1922: PetscAssertPointer(nullsp, 3);
1923: PetscCheck(field < dm->Nf, PetscObjectComm((PetscObject)dm), PETSC_ERR_ARG_OUTOFRANGE, "Cannot handle %" PetscInt_FMT " >= %" PetscInt_FMT " fields", field, dm->Nf);
1924: PetscCheck(dm->nearnullspaceConstructors, PetscObjectComm((PetscObject)dm), PETSC_ERR_ARG_WRONG, "Must call DMCreateDS() to setup nullspaces");
1925: *nullsp = dm->nearnullspaceConstructors[field];
1926: PetscFunctionReturn(PETSC_SUCCESS);
1927: }
1929: /*@C
1930: DMCreateFieldIS - Creates a set of `IS` objects with the global indices of dofs for each field defined with `DMAddField()`
1932: Not Collective; No Fortran Support
1934: Input Parameter:
1935: . dm - the `DM` object
1937: Output Parameters:
1938: + numFields - The number of fields (or `NULL` if not requested)
1939: . fieldNames - The name of each field (or `NULL` if not requested)
1940: - fields - The global indices for each field (or `NULL` if not requested)
1942: Level: intermediate
1944: Note:
1945: The user is responsible for freeing all requested arrays. In particular, every entry of `fieldNames` should be freed with
1946: `PetscFree()`, every entry of `fields` should be destroyed with `ISDestroy()`, and both arrays should be freed with
1947: `PetscFree()`.
1949: Developer Note:
1950: It is not clear why both this function and `DMCreateFieldDecomposition()` exist. Having two seems redundant and confusing. This function should
1951: likely be removed.
1953: .seealso: [](ch_dmbase), `DM`, `DMAddField()`, `DMGetField()`, `DMDestroy()`, `DMView()`, `DMCreateInterpolation()`, `DMCreateColoring()`, `DMCreateMatrix()`,
1954: `DMCreateFieldDecomposition()`
1955: @*/
1956: PetscErrorCode DMCreateFieldIS(DM dm, PetscInt *numFields, char ***fieldNames, IS *fields[])
1957: {
1958: PetscSection section, sectionGlobal;
1960: PetscFunctionBegin;
1962: if (numFields) {
1963: PetscAssertPointer(numFields, 2);
1964: *numFields = 0;
1965: }
1966: if (fieldNames) {
1967: PetscAssertPointer(fieldNames, 3);
1968: *fieldNames = NULL;
1969: }
1970: if (fields) {
1971: PetscAssertPointer(fields, 4);
1972: *fields = NULL;
1973: }
1974: PetscCall(DMGetLocalSection(dm, §ion));
1975: if (section) {
1976: PetscInt *fieldSizes, *fieldNc, **fieldIndices;
1977: PetscInt nF, f, pStart, pEnd, p;
1979: PetscCall(DMGetGlobalSection(dm, §ionGlobal));
1980: PetscCall(PetscSectionGetNumFields(section, &nF));
1981: PetscCall(PetscMalloc3(nF, &fieldSizes, nF, &fieldNc, nF, &fieldIndices));
1982: PetscCall(PetscSectionGetChart(sectionGlobal, &pStart, &pEnd));
1983: for (f = 0; f < nF; ++f) {
1984: fieldSizes[f] = 0;
1985: PetscCall(PetscSectionGetFieldComponents(section, f, &fieldNc[f]));
1986: }
1987: for (p = pStart; p < pEnd; ++p) {
1988: PetscInt gdof;
1990: PetscCall(PetscSectionGetDof(sectionGlobal, p, &gdof));
1991: if (gdof > 0) {
1992: for (f = 0; f < nF; ++f) {
1993: PetscInt fdof, fcdof, fpdof;
1995: PetscCall(PetscSectionGetFieldDof(section, p, f, &fdof));
1996: PetscCall(PetscSectionGetFieldConstraintDof(section, p, f, &fcdof));
1997: fpdof = fdof - fcdof;
1998: if (fpdof && fpdof != fieldNc[f]) {
1999: /* Layout does not admit a pointwise block size */
2000: fieldNc[f] = 1;
2001: }
2002: fieldSizes[f] += fpdof;
2003: }
2004: }
2005: }
2006: for (f = 0; f < nF; ++f) {
2007: PetscCall(PetscMalloc1(fieldSizes[f], &fieldIndices[f]));
2008: fieldSizes[f] = 0;
2009: }
2010: for (p = pStart; p < pEnd; ++p) {
2011: PetscInt gdof, goff;
2013: PetscCall(PetscSectionGetDof(sectionGlobal, p, &gdof));
2014: if (gdof > 0) {
2015: PetscCall(PetscSectionGetOffset(sectionGlobal, p, &goff));
2016: for (f = 0; f < nF; ++f) {
2017: PetscInt fdof, fcdof, fc;
2019: PetscCall(PetscSectionGetFieldDof(section, p, f, &fdof));
2020: PetscCall(PetscSectionGetFieldConstraintDof(section, p, f, &fcdof));
2021: for (fc = 0; fc < fdof - fcdof; ++fc, ++fieldSizes[f]) fieldIndices[f][fieldSizes[f]] = goff++;
2022: }
2023: }
2024: }
2025: if (numFields) *numFields = nF;
2026: if (fieldNames) {
2027: PetscCall(PetscMalloc1(nF, fieldNames));
2028: for (f = 0; f < nF; ++f) {
2029: const char *fieldName;
2031: PetscCall(PetscSectionGetFieldName(section, f, &fieldName));
2032: PetscCall(PetscStrallocpy(fieldName, &(*fieldNames)[f]));
2033: }
2034: }
2035: if (fields) {
2036: PetscCall(PetscMalloc1(nF, fields));
2037: for (f = 0; f < nF; ++f) {
2038: PetscInt bs, in[2], out[2];
2040: PetscCall(ISCreateGeneral(PetscObjectComm((PetscObject)dm), fieldSizes[f], fieldIndices[f], PETSC_OWN_POINTER, &(*fields)[f]));
2041: in[0] = -fieldNc[f];
2042: in[1] = fieldNc[f];
2043: PetscCallMPI(MPIU_Allreduce(in, out, 2, MPIU_INT, MPI_MAX, PetscObjectComm((PetscObject)dm)));
2044: bs = (-out[0] == out[1]) ? out[1] : 1;
2045: PetscCall(ISSetBlockSize((*fields)[f], bs));
2046: }
2047: }
2048: PetscCall(PetscFree3(fieldSizes, fieldNc, fieldIndices));
2049: } else PetscTryTypeMethod(dm, createfieldis, numFields, fieldNames, fields);
2050: PetscFunctionReturn(PETSC_SUCCESS);
2051: }
2053: /*@C
2054: DMCreateFieldDecomposition - Returns a list of `IS` objects defining a decomposition of a problem into subproblems
2055: corresponding to different fields.
2057: Not Collective; No Fortran Support
2059: Input Parameter:
2060: . dm - the `DM` object
2062: Output Parameters:
2063: + len - The number of fields (or `NULL` if not requested)
2064: . namelist - The name for each field (or `NULL` if not requested)
2065: . islist - The global indices for each field (or `NULL` if not requested)
2066: - dmlist - The `DM`s for each field subproblem (or `NULL`, if not requested; if `NULL` is returned, no `DM`s are defined)
2068: Level: intermediate
2070: Notes:
2071: Each `IS` contains the global indices of the dofs of the corresponding field, defined by
2072: `DMAddField()`. The optional list of `DM`s define the `DM` for each subproblem.
2074: The same as `DMCreateFieldIS()` but also returns a `DM` for each field.
2076: The user is responsible for freeing all requested arrays. In particular, every entry of `namelist` should be freed with
2077: `PetscFree()`, every entry of `islist` should be destroyed with `ISDestroy()`, every entry of `dmlist` should be destroyed with `DMDestroy()`,
2078: and all of the arrays should be freed with `PetscFree()`.
2080: Fortran Notes:
2081: Use the declarations
2082: .vb
2083: character(80), pointer :: namelist(:)
2084: IS, pointer :: islist(:)
2085: DM, pointer :: dmlist(:)
2086: .ve
2088: `namelist` must be provided, `islist` may be `PETSC_NULL_IS_POINTER` and `dmlist` may be `PETSC_NULL_DM_POINTER`
2090: Use `DMDestroyFieldDecomposition()` to free the returned objects
2092: Developer Notes:
2093: It is not clear why this function and `DMCreateFieldIS()` exist. Having two seems redundant and confusing.
2095: Unlike `DMRefine()`, `DMCoarsen()`, and `DMCreateDomainDecomposition()` this provides no mechanism to provide hooks that are called after the
2096: decomposition is computed.
2098: .seealso: [](ch_dmbase), `DM`, `DMAddField()`, `DMCreateFieldIS()`, `DMCreateSubDM()`, `DMCreateDomainDecomposition()`, `DMDestroy()`, `DMView()`, `DMCreateInterpolation()`, `DMCreateColoring()`, `DMCreateMatrix()`, `DMCreateMassMatrix()`, `DMRefine()`, `DMCoarsen()`
2099: @*/
2100: PetscErrorCode DMCreateFieldDecomposition(DM dm, PetscInt *len, char ***namelist, IS *islist[], DM *dmlist[])
2101: {
2102: PetscFunctionBegin;
2104: if (len) {
2105: PetscAssertPointer(len, 2);
2106: *len = 0;
2107: }
2108: if (namelist) {
2109: PetscAssertPointer(namelist, 3);
2110: *namelist = NULL;
2111: }
2112: if (islist) {
2113: PetscAssertPointer(islist, 4);
2114: *islist = NULL;
2115: }
2116: if (dmlist) {
2117: PetscAssertPointer(dmlist, 5);
2118: *dmlist = NULL;
2119: }
2120: /*
2121: Is it a good idea to apply the following check across all impls?
2122: Perhaps some impls can have a well-defined decomposition before DMSetUp?
2123: This, however, follows the general principle that accessors are not well-behaved until the object is set up.
2124: */
2125: PetscCheck(dm->setupcalled, PetscObjectComm((PetscObject)dm), PETSC_ERR_ARG_WRONGSTATE, "Decomposition defined only after DMSetUp");
2126: if (!dm->ops->createfielddecomposition) {
2127: PetscSection section;
2128: PetscInt numFields, f;
2130: PetscCall(DMGetLocalSection(dm, §ion));
2131: if (section) PetscCall(PetscSectionGetNumFields(section, &numFields));
2132: if (section && numFields && dm->ops->createsubdm) {
2133: if (len) *len = numFields;
2134: if (namelist) PetscCall(PetscMalloc1(numFields, namelist));
2135: if (islist) PetscCall(PetscMalloc1(numFields, islist));
2136: if (dmlist) PetscCall(PetscMalloc1(numFields, dmlist));
2137: for (f = 0; f < numFields; ++f) {
2138: const char *fieldName;
2140: PetscCall(DMCreateSubDM(dm, 1, &f, islist ? &(*islist)[f] : NULL, dmlist ? &(*dmlist)[f] : NULL));
2141: if (namelist) {
2142: PetscCall(PetscSectionGetFieldName(section, f, &fieldName));
2143: PetscCall(PetscStrallocpy(fieldName, &(*namelist)[f]));
2144: }
2145: }
2146: } else {
2147: PetscCall(DMCreateFieldIS(dm, len, namelist, islist));
2148: /* By default there are no DMs associated with subproblems. */
2149: if (dmlist) *dmlist = NULL;
2150: }
2151: } else PetscUseTypeMethod(dm, createfielddecomposition, len, namelist, islist, dmlist);
2152: PetscFunctionReturn(PETSC_SUCCESS);
2153: }
2155: /*@
2156: DMCreateSubDM - Returns an `IS` and `DM` encapsulating a subproblem defined by the fields passed in.
2157: The fields are defined by `DMCreateFieldIS()`.
2159: Not collective
2161: Input Parameters:
2162: + dm - The `DM` object
2163: . numFields - The number of fields to select
2164: - fields - The field numbers of the selected fields
2166: Output Parameters:
2167: + is - The global indices for all the degrees of freedom in the new sub `DM`, use `NULL` if not needed
2168: - subdm - The `DM` for the subproblem, use `NULL` if not needed
2170: Level: intermediate
2172: Note:
2173: You need to call `DMPlexSetMigrationSF()` on the original `DM` if you want the Global-To-Natural map to be automatically constructed
2175: .seealso: [](ch_dmbase), `DM`, `DMCreateFieldIS()`, `DMCreateFieldDecomposition()`, `DMAddField()`, `DMCreateSuperDM()`, `IS`, `VecISCopy()`, `DMPlexSetMigrationSF()`, `DMDestroy()`, `DMView()`, `DMCreateInterpolation()`, `DMCreateColoring()`, `DMCreateMatrix()`, `DMCreateMassMatrix()`
2176: @*/
2177: PetscErrorCode DMCreateSubDM(DM dm, PetscInt numFields, const PetscInt fields[], IS *is, DM *subdm)
2178: {
2179: PetscFunctionBegin;
2181: PetscAssertPointer(fields, 3);
2182: if (is) PetscAssertPointer(is, 4);
2183: if (subdm) PetscAssertPointer(subdm, 5);
2184: PetscUseTypeMethod(dm, createsubdm, numFields, fields, is, subdm);
2185: PetscFunctionReturn(PETSC_SUCCESS);
2186: }
2188: /*@C
2189: DMCreateSuperDM - Returns an arrays of `IS` and a single `DM` encapsulating a superproblem defined by multiple `DM`s passed in.
2191: Not collective
2193: Input Parameters:
2194: + dms - The `DM` objects
2195: - n - The number of `DM`s
2197: Output Parameters:
2198: + is - The global indices for each of subproblem within the super `DM`, or `NULL`, its length is `n`
2199: - superdm - The `DM` for the superproblem
2201: Level: intermediate
2203: Note:
2204: You need to call `DMPlexSetMigrationSF()` on the original `DM` if you want the Global-To-Natural map to be automatically constructed
2206: .seealso: [](ch_dmbase), `DM`, `DMCreateSubDM()`, `DMPlexSetMigrationSF()`, `DMDestroy()`, `DMView()`, `DMCreateInterpolation()`, `DMCreateColoring()`, `DMCreateMatrix()`, `DMCreateMassMatrix()`, `DMCreateFieldIS()`, `DMCreateDomainDecomposition()`
2207: @*/
2208: PetscErrorCode DMCreateSuperDM(DM dms[], PetscInt n, IS *is[], DM *superdm)
2209: {
2210: PetscInt i;
2212: PetscFunctionBegin;
2213: PetscAssertPointer(dms, 1);
2215: if (is) PetscAssertPointer(is, 3);
2216: PetscAssertPointer(superdm, 4);
2217: PetscCheck(n >= 0, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Number of DMs must be nonnegative: %" PetscInt_FMT, n);
2218: if (n) {
2219: DM dm = dms[0];
2220: PetscCheck(dm->ops->createsuperdm, PetscObjectComm((PetscObject)dm), PETSC_ERR_SUP, "No method createsuperdm for DM of type %s", ((PetscObject)dm)->type_name);
2221: PetscCall((*dm->ops->createsuperdm)(dms, n, is, superdm));
2222: }
2223: PetscFunctionReturn(PETSC_SUCCESS);
2224: }
2226: /*@C
2227: DMCreateDomainDecomposition - Returns lists of `IS` objects defining a decomposition of a
2228: problem into subproblems corresponding to restrictions to pairs of nested subdomains.
2230: Not Collective
2232: Input Parameter:
2233: . dm - the `DM` object
2235: Output Parameters:
2236: + n - The number of subproblems in the domain decomposition (or `NULL` if not requested), also the length of the four arrays below
2237: . namelist - The name for each subdomain (or `NULL` if not requested)
2238: . innerislist - The global indices for each inner subdomain (or `NULL`, if not requested)
2239: . outerislist - The global indices for each outer subdomain (or `NULL`, if not requested)
2240: - dmlist - The `DM`s for each subdomain subproblem (or `NULL`, if not requested; if `NULL` is returned, no `DM`s are defined)
2242: Level: intermediate
2244: Notes:
2245: Each `IS` contains the global indices of the dofs of the corresponding subdomains with in the
2246: dofs of the original `DM`. The inner subdomains conceptually define a nonoverlapping
2247: covering, while outer subdomains can overlap.
2249: The optional list of `DM`s define a `DM` for each subproblem.
2251: The user is responsible for freeing all requested arrays. In particular, every entry of `namelist` should be freed with
2252: `PetscFree()`, every entry of `innerislist` and `outerislist` should be destroyed with `ISDestroy()`, every entry of `dmlist` should be destroyed with `DMDestroy()`,
2253: and all of the arrays should be freed with `PetscFree()`.
2255: Developer Notes:
2256: The `dmlist` is for the inner subdomains or the outer subdomains or all subdomains?
2258: The names are inconsistent, the hooks use `DMSubDomainHook` which is nothing like `DMCreateDomainDecomposition()` while `DMRefineHook` is used for `DMRefine()`.
2260: .seealso: [](ch_dmbase), `DM`, `DMCreateFieldDecomposition()`, `DMDestroy()`, `DMCreateDomainDecompositionScatters()`, `DMView()`, `DMCreateInterpolation()`,
2261: `DMSubDomainHookAdd()`, `DMSubDomainHookRemove()`, `DMCreateColoring()`, `DMCreateMatrix()`, `DMCreateMassMatrix()`, `DMRefine()`, `DMCoarsen()`
2262: @*/
2263: PetscErrorCode DMCreateDomainDecomposition(DM dm, PetscInt *n, char **namelist[], IS *innerislist[], IS *outerislist[], DM *dmlist[])
2264: {
2265: DMSubDomainHookLink link;
2266: PetscInt i, l;
2268: PetscFunctionBegin;
2270: if (n) {
2271: PetscAssertPointer(n, 2);
2272: *n = 0;
2273: }
2274: if (namelist) {
2275: PetscAssertPointer(namelist, 3);
2276: *namelist = NULL;
2277: }
2278: if (innerislist) {
2279: PetscAssertPointer(innerislist, 4);
2280: *innerislist = NULL;
2281: }
2282: if (outerislist) {
2283: PetscAssertPointer(outerislist, 5);
2284: *outerislist = NULL;
2285: }
2286: if (dmlist) {
2287: PetscAssertPointer(dmlist, 6);
2288: *dmlist = NULL;
2289: }
2290: /*
2291: Is it a good idea to apply the following check across all impls?
2292: Perhaps some impls can have a well-defined decomposition before DMSetUp?
2293: This, however, follows the general principle that accessors are not well-behaved until the object is set up.
2294: */
2295: PetscCheck(dm->setupcalled, PetscObjectComm((PetscObject)dm), PETSC_ERR_ARG_WRONGSTATE, "Decomposition defined only after DMSetUp");
2296: if (dm->ops->createdomaindecomposition) {
2297: PetscUseTypeMethod(dm, createdomaindecomposition, &l, namelist, innerislist, outerislist, dmlist);
2298: /* copy subdomain hooks and context over to the subdomain DMs */
2299: if (dmlist && *dmlist) {
2300: for (i = 0; i < l; i++) {
2301: for (link = dm->subdomainhook; link; link = link->next) {
2302: if (link->ddhook) PetscCall((*link->ddhook)(dm, (*dmlist)[i], link->ctx));
2303: }
2304: if (dm->ctx) (*dmlist)[i]->ctx = dm->ctx;
2305: }
2306: }
2307: if (n) *n = l;
2308: }
2309: PetscFunctionReturn(PETSC_SUCCESS);
2310: }
2312: /*@C
2313: DMCreateDomainDecompositionScatters - Returns scatters to the subdomain vectors from the global vector for subdomains created with
2314: `DMCreateDomainDecomposition()`
2316: Not Collective
2318: Input Parameters:
2319: + dm - the `DM` object
2320: . n - the number of subdomains
2321: - subdms - the local subdomains
2323: Output Parameters:
2324: + iscat - scatter from global vector to nonoverlapping global vector entries on subdomain
2325: . oscat - scatter from global vector to overlapping global vector entries on subdomain
2326: - gscat - scatter from global vector to local vector on subdomain (fills in ghosts)
2328: Level: developer
2330: Note:
2331: This is an alternative to the `iis` and `ois` arguments in `DMCreateDomainDecomposition()` that allow for the solution
2332: of general nonlinear problems with overlapping subdomain methods. While merely having index sets that enable subsets
2333: of the residual equations to be created is fine for linear problems, nonlinear problems require local assembly of
2334: solution and residual data.
2336: Developer Note:
2337: Can the `subdms` input be anything or are they exactly the `DM` obtained from
2338: `DMCreateDomainDecomposition()`?
2340: .seealso: [](ch_dmbase), `DM`, `DMCreateDomainDecomposition()`, `DMDestroy()`, `DMView()`, `DMCreateInterpolation()`, `DMCreateColoring()`, `DMCreateMatrix()`, `DMCreateMassMatrix()`, `DMCreateFieldIS()`
2341: @*/
2342: PetscErrorCode DMCreateDomainDecompositionScatters(DM dm, PetscInt n, DM subdms[], VecScatter *iscat[], VecScatter *oscat[], VecScatter *gscat[])
2343: {
2344: PetscFunctionBegin;
2346: PetscAssertPointer(subdms, 3);
2347: PetscUseTypeMethod(dm, createddscatters, n, subdms, iscat, oscat, gscat);
2348: PetscFunctionReturn(PETSC_SUCCESS);
2349: }
2351: /*@
2352: DMRefine - Refines a `DM` object using a standard nonadaptive refinement of the underlying mesh
2354: Collective
2356: Input Parameters:
2357: + dm - the `DM` object
2358: - comm - the communicator to contain the new `DM` object (or `MPI_COMM_NULL`)
2360: Output Parameter:
2361: . dmf - the refined `DM`, or `NULL`
2363: Options Database Key:
2364: . -dm_plex_cell_refiner strategy - chooses the refinement strategy, e.g. regular, tohex
2366: Level: developer
2368: Note:
2369: If no refinement was done, the return value is `NULL`
2371: .seealso: [](ch_dmbase), `DM`, `DMCoarsen()`, `DMDestroy()`, `DMView()`, `DMCreateGlobalVector()`, `DMCreateInterpolation()`, `DMCreateDomainDecomposition()`,
2372: `DMRefineHookAdd()`, `DMRefineHookRemove()`
2373: @*/
2374: PetscErrorCode DMRefine(DM dm, MPI_Comm comm, DM *dmf)
2375: {
2376: DMRefineHookLink link;
2378: PetscFunctionBegin;
2380: PetscCall(PetscLogEventBegin(DM_Refine, dm, 0, 0, 0));
2381: PetscUseTypeMethod(dm, refine, comm, dmf);
2382: if (*dmf) {
2383: (*dmf)->ops->creatematrix = dm->ops->creatematrix;
2385: PetscCall(PetscObjectCopyFortranFunctionPointers((PetscObject)dm, (PetscObject)*dmf));
2387: (*dmf)->ctx = dm->ctx;
2388: (*dmf)->leveldown = dm->leveldown;
2389: (*dmf)->levelup = dm->levelup + 1;
2391: PetscCall(DMSetMatType(*dmf, dm->mattype));
2392: for (link = dm->refinehook; link; link = link->next) {
2393: if (link->refinehook) PetscCall((*link->refinehook)(dm, *dmf, link->ctx));
2394: }
2395: }
2396: PetscCall(PetscLogEventEnd(DM_Refine, dm, 0, 0, 0));
2397: PetscFunctionReturn(PETSC_SUCCESS);
2398: }
2400: /*@C
2401: DMRefineHookAdd - adds a callback to be run when interpolating a nonlinear problem to a finer grid
2403: Logically Collective; No Fortran Support
2405: Input Parameters:
2406: + coarse - `DM` on which to run a hook when interpolating to a finer level
2407: . refinehook - function to run when setting up the finer level
2408: . interphook - function to run to update data on finer levels (once per `SNESSolve()`)
2409: - ctx - [optional] context for provide data for the hooks (may be `NULL`)
2411: Calling sequence of `refinehook`:
2412: + coarse - coarse level `DM`
2413: . fine - fine level `DM` to interpolate problem to
2414: - ctx - optional function context
2416: Calling sequence of `interphook`:
2417: + coarse - coarse level `DM`
2418: . interp - matrix interpolating a coarse-level solution to the finer grid
2419: . fine - fine level `DM` to update
2420: - ctx - optional function context
2422: Level: advanced
2424: Notes:
2425: This function is only needed if auxiliary data that is attached to the `DM`s via, for example, `PetscObjectCompose()`, needs to be
2426: passed to fine grids while grid sequencing.
2428: The actual interpolation is done when `DMInterpolate()` is called.
2430: If this function is called multiple times, the hooks will be run in the order they are added.
2432: .seealso: [](ch_dmbase), `DM`, `DMCoarsenHookAdd()`, `DMInterpolate()`, `SNESFASGetInterpolation()`, `SNESFASGetInjection()`, `PetscObjectCompose()`, `PetscContainerCreate()`
2433: @*/
2434: PetscErrorCode DMRefineHookAdd(DM coarse, PetscErrorCode (*refinehook)(DM coarse, DM fine, PetscCtx ctx), PetscErrorCode (*interphook)(DM coarse, Mat interp, DM fine, PetscCtx ctx), PetscCtx ctx)
2435: {
2436: DMRefineHookLink link, *p;
2438: PetscFunctionBegin;
2440: for (p = &coarse->refinehook; *p; p = &(*p)->next) { /* Scan to the end of the current list of hooks */
2441: if ((*p)->refinehook == refinehook && (*p)->interphook == interphook && (*p)->ctx == ctx) PetscFunctionReturn(PETSC_SUCCESS);
2442: }
2443: PetscCall(PetscNew(&link));
2444: link->refinehook = refinehook;
2445: link->interphook = interphook;
2446: link->ctx = ctx;
2447: link->next = NULL;
2448: *p = link;
2449: PetscFunctionReturn(PETSC_SUCCESS);
2450: }
2452: /*@C
2453: DMRefineHookRemove - remove a callback from the list of hooks, that have been set with `DMRefineHookAdd()`, to be run when interpolating
2454: a nonlinear problem to a finer grid
2456: Logically Collective; No Fortran Support
2458: Input Parameters:
2459: + coarse - the `DM` on which to run a hook when restricting to a coarser level
2460: . refinehook - function to run when setting up a finer level
2461: . interphook - function to run to update data on finer levels
2462: - ctx - [optional] application context for provide data for the hooks (may be `NULL`)
2464: Calling sequence of refinehook:
2465: + coarse - the coarse `DM`
2466: . fine - the fine `DM`
2467: - ctx - context for the function
2469: Calling sequence of interphook:
2470: + coarse - the coarse `DM`
2471: . interp - the interpolation `Mat` from coarse to fine
2472: . fine - the fine `DM`
2473: - ctx - context for the function
2475: Level: advanced
2477: Note:
2478: This function does nothing if the hook is not in the list.
2480: .seealso: [](ch_dmbase), `DM`, `DMRefineHookAdd()`, `DMCoarsenHookRemove()`, `DMInterpolate()`, `SNESFASGetInterpolation()`, `SNESFASGetInjection()`, `PetscObjectCompose()`, `PetscContainerCreate()`
2481: @*/
2482: PetscErrorCode DMRefineHookRemove(DM coarse, PetscErrorCode (*refinehook)(DM coarse, DM fine, PetscCtx ctx), PetscErrorCode (*interphook)(DM coarse, Mat interp, DM fine, PetscCtx ctx), PetscCtx ctx)
2483: {
2484: DMRefineHookLink link, *p;
2486: PetscFunctionBegin;
2488: for (p = &coarse->refinehook; *p; p = &(*p)->next) { /* Search the list of current hooks */
2489: if ((*p)->refinehook == refinehook && (*p)->interphook == interphook && (*p)->ctx == ctx) {
2490: link = *p;
2491: *p = link->next;
2492: PetscCall(PetscFree(link));
2493: break;
2494: }
2495: }
2496: PetscFunctionReturn(PETSC_SUCCESS);
2497: }
2499: /*@
2500: DMInterpolate - interpolates user-defined problem data attached to a `DM` to a finer `DM` by running hooks registered by `DMRefineHookAdd()`
2502: Collective if any hooks are
2504: Input Parameters:
2505: + coarse - coarser `DM` to use as a base
2506: . interp - interpolation matrix, apply using `MatInterpolate()`
2507: - fine - finer `DM` to update
2509: Level: developer
2511: Developer Note:
2512: This routine is called `DMInterpolate()` while the hook is called `DMRefineHookAdd()`. It would be better to have an
2513: an API with consistent terminology.
2515: .seealso: [](ch_dmbase), `DM`, `DMRefineHookAdd()`, `MatInterpolate()`
2516: @*/
2517: PetscErrorCode DMInterpolate(DM coarse, Mat interp, DM fine)
2518: {
2519: DMRefineHookLink link;
2521: PetscFunctionBegin;
2522: for (link = fine->refinehook; link; link = link->next) {
2523: if (link->interphook) PetscCall((*link->interphook)(coarse, interp, fine, link->ctx));
2524: }
2525: PetscFunctionReturn(PETSC_SUCCESS);
2526: }
2528: /*@
2529: DMInterpolateSolution - Interpolates a solution from a coarse mesh to a fine mesh.
2531: Collective
2533: Input Parameters:
2534: + coarse - coarse `DM`
2535: . fine - fine `DM`
2536: . interp - (optional) the matrix computed by `DMCreateInterpolation()`. Implementations may not need this, but if it
2537: is available it can avoid some recomputation. If it is provided, `MatInterpolate()` will be used if
2538: the coarse `DM` does not have a specialized implementation.
2539: - coarseSol - solution on the coarse mesh
2541: Output Parameter:
2542: . fineSol - the interpolation of coarseSol to the fine mesh
2544: Level: developer
2546: Note:
2547: This function exists because the interpolation of a solution vector between meshes is not always a linear
2548: map. For example, if a boundary value problem has an inhomogeneous Dirichlet boundary condition that is compressed
2549: out of the solution vector. Or if interpolation is inherently a nonlinear operation, such as a method using
2550: slope-limiting reconstruction.
2552: Developer Note:
2553: This doesn't just interpolate "solutions" so its API name is questionable.
2555: .seealso: [](ch_dmbase), `DM`, `DMInterpolate()`, `DMCreateInterpolation()`
2556: @*/
2557: PetscErrorCode DMInterpolateSolution(DM coarse, DM fine, Mat interp, Vec coarseSol, Vec fineSol)
2558: {
2559: PetscErrorCode (*interpsol)(DM, DM, Mat, Vec, Vec) = NULL;
2561: PetscFunctionBegin;
2567: PetscCall(PetscObjectQueryFunction((PetscObject)coarse, "DMInterpolateSolution_C", &interpsol));
2568: if (interpsol) {
2569: PetscCall((*interpsol)(coarse, fine, interp, coarseSol, fineSol));
2570: } else if (interp) {
2571: PetscCall(MatInterpolate(interp, coarseSol, fineSol));
2572: } else SETERRQ(PetscObjectComm((PetscObject)coarse), PETSC_ERR_SUP, "DM %s does not implement DMInterpolateSolution()", ((PetscObject)coarse)->type_name);
2573: PetscFunctionReturn(PETSC_SUCCESS);
2574: }
2576: /*@
2577: DMGetRefineLevel - Gets the number of refinements that have generated this `DM` from some initial `DM`.
2579: Not Collective
2581: Input Parameter:
2582: . dm - the `DM` object
2584: Output Parameter:
2585: . level - number of refinements
2587: Level: developer
2589: Note:
2590: This can be used, by example, to set the number of coarser levels associated with this `DM` for a multigrid solver.
2592: .seealso: [](ch_dmbase), `DM`, `DMRefine()`, `DMCoarsen()`, `DMGetCoarsenLevel()`, `DMDestroy()`, `DMView()`, `DMCreateGlobalVector()`, `DMCreateInterpolation()`
2593: @*/
2594: PetscErrorCode DMGetRefineLevel(DM dm, PetscInt *level)
2595: {
2596: PetscFunctionBegin;
2598: *level = dm->levelup;
2599: PetscFunctionReturn(PETSC_SUCCESS);
2600: }
2602: /*@
2603: DMSetRefineLevel - Sets the number of refinements that have generated this `DM`.
2605: Not Collective
2607: Input Parameters:
2608: + dm - the `DM` object
2609: - level - number of refinements
2611: Level: advanced
2613: Notes:
2614: This value is used by `PCMG` to determine how many multigrid levels to use
2616: The values are usually set automatically by the process that is causing the refinements of an initial `DM` by calling this routine.
2618: .seealso: [](ch_dmbase), `DM`, `DMGetRefineLevel()`, `DMCoarsen()`, `DMGetCoarsenLevel()`, `DMDestroy()`, `DMView()`, `DMCreateGlobalVector()`, `DMCreateInterpolation()`
2619: @*/
2620: PetscErrorCode DMSetRefineLevel(DM dm, PetscInt level)
2621: {
2622: PetscFunctionBegin;
2624: dm->levelup = level;
2625: PetscFunctionReturn(PETSC_SUCCESS);
2626: }
2628: /*@
2629: DMExtrude - Extrude a `DM` object from a surface
2631: Collective
2633: Input Parameters:
2634: + dm - the `DM` object
2635: - layers - the number of extruded cell layers
2637: Output Parameter:
2638: . dme - the extruded `DM`, or `NULL`
2640: Level: developer
2642: Note:
2643: If no extrusion was done, the return value is `NULL`
2645: .seealso: [](ch_dmbase), `DM`, `DMRefine()`, `DMCoarsen()`, `DMDestroy()`, `DMView()`, `DMCreateGlobalVector()`
2646: @*/
2647: PetscErrorCode DMExtrude(DM dm, PetscInt layers, DM *dme)
2648: {
2649: PetscFunctionBegin;
2651: PetscUseTypeMethod(dm, extrude, layers, dme);
2652: if (*dme) {
2653: (*dme)->ops->creatematrix = dm->ops->creatematrix;
2654: PetscCall(PetscObjectCopyFortranFunctionPointers((PetscObject)dm, (PetscObject)*dme));
2655: (*dme)->ctx = dm->ctx;
2656: PetscCall(DMSetMatType(*dme, dm->mattype));
2657: }
2658: PetscFunctionReturn(PETSC_SUCCESS);
2659: }
2661: PetscErrorCode DMGetBasisTransformDM_Internal(DM dm, DM *tdm)
2662: {
2663: PetscFunctionBegin;
2665: PetscAssertPointer(tdm, 2);
2666: *tdm = dm->transformDM;
2667: PetscFunctionReturn(PETSC_SUCCESS);
2668: }
2670: PetscErrorCode DMGetBasisTransformVec_Internal(DM dm, Vec *tv)
2671: {
2672: PetscFunctionBegin;
2674: PetscAssertPointer(tv, 2);
2675: *tv = dm->transform;
2676: PetscFunctionReturn(PETSC_SUCCESS);
2677: }
2679: /*@
2680: DMHasBasisTransform - Whether the `DM` employs a basis transformation from functions in global vectors to functions in local vectors
2682: Input Parameter:
2683: . dm - The `DM`
2685: Output Parameter:
2686: . flg - `PETSC_TRUE` if a basis transformation should be done
2688: Level: developer
2690: .seealso: [](ch_dmbase), `DM`, `DMPlexGlobalToLocalBasis()`, `DMPlexLocalToGlobalBasis()`, `DMPlexCreateBasisRotation()`
2691: @*/
2692: PetscErrorCode DMHasBasisTransform(DM dm, PetscBool *flg)
2693: {
2694: Vec tv;
2696: PetscFunctionBegin;
2698: PetscAssertPointer(flg, 2);
2699: PetscCall(DMGetBasisTransformVec_Internal(dm, &tv));
2700: *flg = tv ? PETSC_TRUE : PETSC_FALSE;
2701: PetscFunctionReturn(PETSC_SUCCESS);
2702: }
2704: PetscErrorCode DMConstructBasisTransform_Internal(DM dm)
2705: {
2706: PetscSection s, ts;
2707: PetscScalar *ta;
2708: PetscInt cdim, pStart, pEnd, p, Nf, f, Nc, dof;
2710: PetscFunctionBegin;
2711: PetscCall(DMGetCoordinateDim(dm, &cdim));
2712: PetscCall(DMGetLocalSection(dm, &s));
2713: PetscCall(PetscSectionGetChart(s, &pStart, &pEnd));
2714: PetscCall(PetscSectionGetNumFields(s, &Nf));
2715: PetscCall(DMClone(dm, &dm->transformDM));
2716: PetscCall(DMGetLocalSection(dm->transformDM, &ts));
2717: PetscCall(PetscSectionSetNumFields(ts, Nf));
2718: PetscCall(PetscSectionSetChart(ts, pStart, pEnd));
2719: for (f = 0; f < Nf; ++f) {
2720: PetscCall(PetscSectionGetFieldComponents(s, f, &Nc));
2721: /* We could start to label fields by their transformation properties */
2722: if (Nc != cdim) continue;
2723: for (p = pStart; p < pEnd; ++p) {
2724: PetscCall(PetscSectionGetFieldDof(s, p, f, &dof));
2725: if (!dof) continue;
2726: PetscCall(PetscSectionSetFieldDof(ts, p, f, PetscSqr(cdim)));
2727: PetscCall(PetscSectionAddDof(ts, p, PetscSqr(cdim)));
2728: }
2729: }
2730: PetscCall(PetscSectionSetUp(ts));
2731: PetscCall(DMCreateLocalVector(dm->transformDM, &dm->transform));
2732: PetscCall(VecGetArray(dm->transform, &ta));
2733: for (p = pStart; p < pEnd; ++p) {
2734: for (f = 0; f < Nf; ++f) {
2735: PetscCall(PetscSectionGetFieldDof(ts, p, f, &dof));
2736: if (dof) {
2737: PetscReal x[3] = {0.0, 0.0, 0.0};
2738: PetscScalar *tva;
2739: const PetscScalar *A;
2741: /* TODO Get quadrature point for this dual basis vector for coordinate */
2742: PetscCall((*dm->transformGetMatrix)(dm, x, PETSC_TRUE, &A, dm->transformCtx));
2743: PetscCall(DMPlexPointLocalFieldRef(dm->transformDM, p, f, ta, (void *)&tva));
2744: PetscCall(PetscArraycpy(tva, A, PetscSqr(cdim)));
2745: }
2746: }
2747: }
2748: PetscCall(VecRestoreArray(dm->transform, &ta));
2749: PetscFunctionReturn(PETSC_SUCCESS);
2750: }
2752: /*@
2753: DMCopyTransform - Copy the basis transform context and callbacks from `dm` to `newdm`
2755: Not Collective
2757: Input Parameter:
2758: . dm - the source `DM`
2760: Output Parameter:
2761: . newdm - the destination `DM`
2763: Level: developer
2765: Note:
2766: If the transform requires setup, `DMConstructBasisTransform_Internal()` is invoked on `newdm`.
2768: .seealso: [](ch_dmbase), `DM`, `DMCopyDS()`, `DMCopyDisc()`
2769: @*/
2770: PetscErrorCode DMCopyTransform(DM dm, DM newdm)
2771: {
2772: PetscFunctionBegin;
2775: newdm->transformCtx = dm->transformCtx;
2776: newdm->transformSetUp = dm->transformSetUp;
2777: newdm->transformDestroy = NULL;
2778: newdm->transformGetMatrix = dm->transformGetMatrix;
2779: if (newdm->transformSetUp) PetscCall(DMConstructBasisTransform_Internal(newdm));
2780: PetscFunctionReturn(PETSC_SUCCESS);
2781: }
2783: /*@C
2784: DMGlobalToLocalHookAdd - adds a callback to be run when `DMGlobalToLocal()` is called
2786: Logically Collective
2788: Input Parameters:
2789: + dm - the `DM`
2790: . beginhook - function to run at the beginning of `DMGlobalToLocalBegin()`
2791: . endhook - function to run after `DMGlobalToLocalEnd()` has completed
2792: - ctx - [optional] context for provide data for the hooks (may be `NULL`)
2794: Calling sequence of `beginhook`:
2795: + dm - global `DM`
2796: . g - global vector
2797: . mode - mode
2798: . l - local vector
2799: - ctx - optional function context
2801: Calling sequence of `endhook`:
2802: + dm - global `DM`
2803: . g - global vector
2804: . mode - mode
2805: . l - local vector
2806: - ctx - optional function context
2808: Level: advanced
2810: Note:
2811: 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.
2813: .seealso: [](ch_dmbase), `DM`, `DMGlobalToLocal()`, `DMRefineHookAdd()`, `SNESFASGetInterpolation()`, `SNESFASGetInjection()`, `PetscObjectCompose()`, `PetscContainerCreate()`
2814: @*/
2815: 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)
2816: {
2817: DMGlobalToLocalHookLink link, *p;
2819: PetscFunctionBegin;
2821: for (p = &dm->gtolhook; *p; p = &(*p)->next) { } /* Scan to the end of the current list of hooks */
2822: PetscCall(PetscNew(&link));
2823: link->beginhook = beginhook;
2824: link->endhook = endhook;
2825: link->ctx = ctx;
2826: link->next = NULL;
2827: *p = link;
2828: PetscFunctionReturn(PETSC_SUCCESS);
2829: }
2831: static PetscErrorCode DMGlobalToLocalHook_Constraints(DM dm, Vec g, InsertMode mode, Vec l, PetscCtx ctx)
2832: {
2833: Mat cMat;
2834: Vec cVec, cBias;
2835: PetscSection section, cSec;
2836: PetscInt pStart, pEnd, p, dof;
2838: PetscFunctionBegin;
2839: (void)g;
2840: (void)ctx;
2842: PetscCall(DMGetDefaultConstraints(dm, &cSec, &cMat, &cBias));
2843: if (cMat && (mode == INSERT_VALUES || mode == INSERT_ALL_VALUES || mode == INSERT_BC_VALUES)) {
2844: PetscInt nRows;
2846: PetscCall(MatGetSize(cMat, &nRows, NULL));
2847: if (nRows <= 0) PetscFunctionReturn(PETSC_SUCCESS);
2848: PetscCall(DMGetLocalSection(dm, §ion));
2849: PetscCall(MatCreateVecs(cMat, NULL, &cVec));
2850: PetscCall(MatMult(cMat, l, cVec));
2851: if (cBias) PetscCall(VecAXPY(cVec, 1., cBias));
2852: PetscCall(PetscSectionGetChart(cSec, &pStart, &pEnd));
2853: for (p = pStart; p < pEnd; p++) {
2854: PetscCall(PetscSectionGetDof(cSec, p, &dof));
2855: if (dof) {
2856: PetscScalar *vals;
2857: PetscCall(VecGetValuesSection(cVec, cSec, p, &vals));
2858: PetscCall(VecSetValuesSection(l, section, p, vals, INSERT_ALL_VALUES));
2859: }
2860: }
2861: PetscCall(VecDestroy(&cVec));
2862: }
2863: PetscFunctionReturn(PETSC_SUCCESS);
2864: }
2866: /*@
2867: DMGlobalToLocal - update local vectors from global vector
2869: Neighbor-wise Collective
2871: Input Parameters:
2872: + dm - the `DM` object
2873: . g - the global vector
2874: . mode - `INSERT_VALUES` or `ADD_VALUES`
2875: - l - the local vector
2877: Level: beginner
2879: Notes:
2880: The communication involved in this update can be overlapped with computation by instead using
2881: `DMGlobalToLocalBegin()` and `DMGlobalToLocalEnd()`.
2883: `DMGlobalToLocalHookAdd()` may be used to provide additional operations that are performed during the update process.
2885: .seealso: [](ch_dmbase), `DM`, `DMGlobalToLocalHookAdd()`, `DMCoarsen()`, `DMDestroy()`, `DMView()`, `DMCreateGlobalVector()`, `DMCreateInterpolation()`,
2886: `DMLocalToGlobalBegin()`, `DMLocalToGlobal()`, `DMLocalToGlobalEnd()`,
2887: `DMGlobalToLocalBegin()`, `DMGlobalToLocalEnd()`
2888: @*/
2889: PetscErrorCode DMGlobalToLocal(DM dm, Vec g, InsertMode mode, Vec l)
2890: {
2891: PetscFunctionBegin;
2892: PetscCall(DMGlobalToLocalBegin(dm, g, mode, l));
2893: PetscCall(DMGlobalToLocalEnd(dm, g, mode, l));
2894: PetscFunctionReturn(PETSC_SUCCESS);
2895: }
2897: /*@
2898: DMGlobalToLocalBegin - Begins updating local vectors from global vector
2900: Neighbor-wise Collective
2902: Input Parameters:
2903: + dm - the `DM` object
2904: . g - the global vector
2905: . mode - `INSERT_VALUES` or `ADD_VALUES`
2906: - l - the local vector
2908: Level: intermediate
2910: Notes:
2911: The operation is completed with `DMGlobalToLocalEnd()`
2913: One can perform local computations between the `DMGlobalToLocalBegin()` and `DMGlobalToLocalEnd()` to overlap communication and computation
2915: `DMGlobalToLocal()` is a short form of `DMGlobalToLocalBegin()` and `DMGlobalToLocalEnd()`
2917: `DMGlobalToLocalHookAdd()` may be used to provide additional operations that are performed during the update process.
2919: .seealso: [](ch_dmbase), `DM`, `DMCoarsen()`, `DMDestroy()`, `DMView()`, `DMCreateGlobalVector()`, `DMCreateInterpolation()`, `DMGlobalToLocal()`, `DMGlobalToLocalEnd()`, `DMLocalToGlobalBegin()`, `DMLocalToGlobal()`, `DMLocalToGlobalEnd()`
2920: @*/
2921: PetscErrorCode DMGlobalToLocalBegin(DM dm, Vec g, InsertMode mode, Vec l)
2922: {
2923: PetscSF sf;
2924: DMGlobalToLocalHookLink link;
2926: PetscFunctionBegin;
2928: for (link = dm->gtolhook; link; link = link->next) {
2929: if (link->beginhook) PetscCall((*link->beginhook)(dm, g, mode, l, link->ctx));
2930: }
2931: PetscCall(DMGetSectionSF(dm, &sf));
2932: if (sf) {
2933: const PetscScalar *gArray;
2934: PetscScalar *lArray;
2935: PetscMemType lmtype, gmtype;
2937: PetscCheck(mode != ADD_VALUES, PetscObjectComm((PetscObject)dm), PETSC_ERR_ARG_OUTOFRANGE, "Invalid insertion mode %d", (int)mode);
2938: PetscCall(VecGetArrayAndMemType(l, &lArray, &lmtype));
2939: PetscCall(VecGetArrayReadAndMemType(g, &gArray, &gmtype));
2940: PetscCall(PetscSFBcastWithMemTypeBegin(sf, MPIU_SCALAR, gmtype, gArray, lmtype, lArray, MPI_REPLACE));
2941: PetscCall(VecRestoreArrayAndMemType(l, &lArray));
2942: PetscCall(VecRestoreArrayReadAndMemType(g, &gArray));
2943: } else {
2944: PetscUseTypeMethod(dm, globaltolocalbegin, g, mode == INSERT_ALL_VALUES ? INSERT_VALUES : (mode == ADD_ALL_VALUES ? ADD_VALUES : mode), l);
2945: }
2946: PetscFunctionReturn(PETSC_SUCCESS);
2947: }
2949: /*@
2950: DMGlobalToLocalEnd - Ends updating local vectors from global vector
2952: Neighbor-wise Collective
2954: Input Parameters:
2955: + dm - the `DM` object
2956: . g - the global vector
2957: . mode - `INSERT_VALUES` or `ADD_VALUES`
2958: - l - the local vector
2960: Level: intermediate
2962: Note:
2963: See `DMGlobalToLocalBegin()` for details.
2965: .seealso: [](ch_dmbase), `DM`, `DMCoarsen()`, `DMDestroy()`, `DMView()`, `DMCreateGlobalVector()`, `DMCreateInterpolation()`, `DMGlobalToLocal()`, `DMLocalToGlobalBegin()`, `DMLocalToGlobal()`, `DMLocalToGlobalEnd()`
2966: @*/
2967: PetscErrorCode DMGlobalToLocalEnd(DM dm, Vec g, InsertMode mode, Vec l)
2968: {
2969: PetscSF sf;
2970: const PetscScalar *gArray;
2971: PetscScalar *lArray;
2972: PetscBool transform;
2973: DMGlobalToLocalHookLink link;
2974: PetscMemType lmtype, gmtype;
2976: PetscFunctionBegin;
2978: PetscCall(DMGetSectionSF(dm, &sf));
2979: PetscCall(DMHasBasisTransform(dm, &transform));
2980: if (sf) {
2981: PetscCheck(mode != ADD_VALUES, PetscObjectComm((PetscObject)dm), PETSC_ERR_ARG_OUTOFRANGE, "Invalid insertion mode %d", (int)mode);
2983: PetscCall(VecGetArrayAndMemType(l, &lArray, &lmtype));
2984: PetscCall(VecGetArrayReadAndMemType(g, &gArray, &gmtype));
2985: PetscCall(PetscSFBcastEnd(sf, MPIU_SCALAR, gArray, lArray, MPI_REPLACE));
2986: PetscCall(VecRestoreArrayAndMemType(l, &lArray));
2987: PetscCall(VecRestoreArrayReadAndMemType(g, &gArray));
2988: if (transform) PetscCall(DMPlexGlobalToLocalBasis(dm, l));
2989: } else {
2990: PetscUseTypeMethod(dm, globaltolocalend, g, mode == INSERT_ALL_VALUES ? INSERT_VALUES : (mode == ADD_ALL_VALUES ? ADD_VALUES : mode), l);
2991: }
2992: PetscCall(DMGlobalToLocalHook_Constraints(dm, g, mode, l, NULL));
2993: for (link = dm->gtolhook; link; link = link->next) {
2994: if (link->endhook) PetscCall((*link->endhook)(dm, g, mode, l, link->ctx));
2995: }
2996: PetscFunctionReturn(PETSC_SUCCESS);
2997: }
2999: /*@C
3000: DMLocalToGlobalHookAdd - adds a callback to be run when a local to global is called
3002: Logically Collective
3004: Input Parameters:
3005: + dm - the `DM`
3006: . beginhook - function to run at the beginning of `DMLocalToGlobalBegin()`
3007: . endhook - function to run after `DMLocalToGlobalEnd()` has completed
3008: - ctx - [optional] context for provide data for the hooks (may be `NULL`)
3010: Calling sequence of `beginhook`:
3011: + global - global `DM`
3012: . l - local vector
3013: . mode - mode
3014: . g - global vector
3015: - ctx - optional function context
3017: Calling sequence of `endhook`:
3018: + global - global `DM`
3019: . l - local vector
3020: . mode - mode
3021: . g - global vector
3022: - ctx - optional function context
3024: Level: advanced
3026: .seealso: [](ch_dmbase), `DM`, `DMLocalToGlobal()`, `DMRefineHookAdd()`, `DMGlobalToLocalHookAdd()`, `SNESFASGetInterpolation()`, `SNESFASGetInjection()`, `PetscObjectCompose()`, `PetscContainerCreate()`
3027: @*/
3028: 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)
3029: {
3030: DMLocalToGlobalHookLink link, *p;
3032: PetscFunctionBegin;
3034: for (p = &dm->ltoghook; *p; p = &(*p)->next) { } /* Scan to the end of the current list of hooks */
3035: PetscCall(PetscNew(&link));
3036: link->beginhook = beginhook;
3037: link->endhook = endhook;
3038: link->ctx = ctx;
3039: link->next = NULL;
3040: *p = link;
3041: PetscFunctionReturn(PETSC_SUCCESS);
3042: }
3044: static PetscErrorCode DMLocalToGlobalHook_Constraints(DM dm, Vec l, InsertMode mode, Vec g, PetscCtx ctx)
3045: {
3046: PetscFunctionBegin;
3047: (void)g;
3048: (void)ctx;
3050: if (mode == ADD_VALUES || mode == ADD_ALL_VALUES || mode == ADD_BC_VALUES) {
3051: Mat cMat;
3052: Vec cVec;
3053: PetscInt nRows;
3054: PetscSection section, cSec;
3055: PetscInt pStart, pEnd, p, dof;
3057: PetscCall(DMGetDefaultConstraints(dm, &cSec, &cMat, NULL));
3058: if (!cMat) PetscFunctionReturn(PETSC_SUCCESS);
3060: PetscCall(MatGetSize(cMat, &nRows, NULL));
3061: if (nRows <= 0) PetscFunctionReturn(PETSC_SUCCESS);
3062: PetscCall(DMGetLocalSection(dm, §ion));
3063: PetscCall(MatCreateVecs(cMat, NULL, &cVec));
3064: PetscCall(PetscSectionGetChart(cSec, &pStart, &pEnd));
3065: for (p = pStart; p < pEnd; p++) {
3066: PetscCall(PetscSectionGetDof(cSec, p, &dof));
3067: if (dof) {
3068: PetscInt d;
3069: PetscScalar *vals;
3070: PetscCall(VecGetValuesSection(l, section, p, &vals));
3071: PetscCall(VecSetValuesSection(cVec, cSec, p, vals, mode));
3072: /* for this to be the true transpose, we have to zero the values that
3073: * we just extracted */
3074: for (d = 0; d < dof; d++) vals[d] = 0.;
3075: }
3076: }
3077: PetscCall(MatMultTransposeAdd(cMat, cVec, l, l));
3078: PetscCall(VecDestroy(&cVec));
3079: }
3080: PetscFunctionReturn(PETSC_SUCCESS);
3081: }
3082: /*@
3083: DMLocalToGlobal - updates global vectors from local vectors
3085: Neighbor-wise Collective
3087: Input Parameters:
3088: + dm - the `DM` object
3089: . l - the local vector
3090: . 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.
3091: - g - the global vector
3093: Level: beginner
3095: Notes:
3096: The communication involved in this update can be overlapped with computation by using
3097: `DMLocalToGlobalBegin()` and `DMLocalToGlobalEnd()`.
3099: In the `ADD_VALUES` case you normally would zero the receiving vector before beginning this operation.
3101: `INSERT_VALUES` is not supported for `DMDA`; in that case simply compute the values directly into a global vector instead of a local one.
3103: Use `DMLocalToGlobalHookAdd()` to add additional operations that are performed on the data during the update process
3105: .seealso: [](ch_dmbase), `DM`, `DMLocalToGlobalBegin()`, `DMLocalToGlobalEnd()`, `DMCoarsen()`, `DMDestroy()`, `DMView()`, `DMCreateGlobalVector()`, `DMCreateInterpolation()`, `DMGlobalToLocal()`, `DMGlobalToLocalEnd()`, `DMGlobalToLocalBegin()`, `DMLocalToGlobalHookAdd()`, `DMGlobaToLocallHookAdd()`
3106: @*/
3107: PetscErrorCode DMLocalToGlobal(DM dm, Vec l, InsertMode mode, Vec g)
3108: {
3109: PetscFunctionBegin;
3110: PetscCall(DMLocalToGlobalBegin(dm, l, mode, g));
3111: PetscCall(DMLocalToGlobalEnd(dm, l, mode, g));
3112: PetscFunctionReturn(PETSC_SUCCESS);
3113: }
3115: /*@
3116: DMLocalToGlobalBegin - begins updating global vectors from local vectors
3118: Neighbor-wise Collective
3120: Input Parameters:
3121: + dm - the `DM` object
3122: . l - the local vector
3123: . 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.
3124: - g - the global vector
3126: Level: intermediate
3128: Notes:
3129: In the `ADD_VALUES` case you normally would zero the receiving vector before beginning this operation.
3131: `INSERT_VALUES is` not supported for `DMDA`, in that case simply compute the values directly into a global vector instead of a local one.
3133: Use `DMLocalToGlobalEnd()` to complete the communication process.
3135: `DMLocalToGlobal()` is a short form of `DMLocalToGlobalBegin()` and `DMLocalToGlobalEnd()`
3137: `DMLocalToGlobalHookAdd()` may be used to provide additional operations that are performed during the update process.
3139: .seealso: [](ch_dmbase), `DM`, `DMLocalToGlobal()`, `DMLocalToGlobalEnd()`, `DMCoarsen()`, `DMDestroy()`, `DMView()`, `DMCreateGlobalVector()`, `DMCreateInterpolation()`, `DMGlobalToLocal()`, `DMGlobalToLocalEnd()`, `DMGlobalToLocalBegin()`
3140: @*/
3141: PetscErrorCode DMLocalToGlobalBegin(DM dm, Vec l, InsertMode mode, Vec g)
3142: {
3143: PetscSF sf;
3144: PetscSection s, gs;
3145: DMLocalToGlobalHookLink link;
3146: Vec tmpl;
3147: const PetscScalar *lArray;
3148: PetscScalar *gArray;
3149: PetscBool isInsert, transform, l_inplace = PETSC_FALSE, g_inplace = PETSC_FALSE;
3150: PetscMemType lmtype = PETSC_MEMTYPE_HOST, gmtype = PETSC_MEMTYPE_HOST;
3152: PetscFunctionBegin;
3154: for (link = dm->ltoghook; link; link = link->next) {
3155: if (link->beginhook) PetscCall((*link->beginhook)(dm, l, mode, g, link->ctx));
3156: }
3157: PetscCall(DMLocalToGlobalHook_Constraints(dm, l, mode, g, NULL));
3158: PetscCall(DMGetSectionSF(dm, &sf));
3159: PetscCall(DMGetLocalSection(dm, &s));
3160: switch (mode) {
3161: case INSERT_VALUES:
3162: case INSERT_ALL_VALUES:
3163: case INSERT_BC_VALUES:
3164: isInsert = PETSC_TRUE;
3165: break;
3166: case ADD_VALUES:
3167: case ADD_ALL_VALUES:
3168: case ADD_BC_VALUES:
3169: isInsert = PETSC_FALSE;
3170: break;
3171: default:
3172: SETERRQ(PetscObjectComm((PetscObject)dm), PETSC_ERR_ARG_OUTOFRANGE, "Invalid insertion mode %d", mode);
3173: }
3174: if ((sf && !isInsert) || (s && isInsert)) {
3175: PetscCall(DMHasBasisTransform(dm, &transform));
3176: if (transform) {
3177: PetscCall(DMGetNamedLocalVector(dm, "__petsc_dm_transform_local_copy", &tmpl));
3178: PetscCall(VecCopy(l, tmpl));
3179: PetscCall(DMPlexLocalToGlobalBasis(dm, tmpl));
3180: PetscCall(VecGetArrayRead(tmpl, &lArray));
3181: } else if (isInsert) {
3182: PetscCall(VecGetArrayRead(l, &lArray));
3183: } else {
3184: PetscCall(VecGetArrayReadAndMemType(l, &lArray, &lmtype));
3185: l_inplace = PETSC_TRUE;
3186: }
3187: if (s && isInsert) {
3188: PetscCall(VecGetArray(g, &gArray));
3189: } else {
3190: PetscCall(VecGetArrayAndMemType(g, &gArray, &gmtype));
3191: g_inplace = PETSC_TRUE;
3192: }
3193: if (sf && !isInsert) {
3194: PetscCall(PetscSFReduceWithMemTypeBegin(sf, MPIU_SCALAR, lmtype, lArray, gmtype, gArray, MPIU_SUM));
3195: } else if (s && isInsert) {
3196: PetscInt gStart, pStart, pEnd, p;
3198: PetscCall(DMGetGlobalSection(dm, &gs));
3199: PetscCall(PetscSectionGetChart(s, &pStart, &pEnd));
3200: PetscCall(VecGetOwnershipRange(g, &gStart, NULL));
3201: for (p = pStart; p < pEnd; ++p) {
3202: PetscInt dof, gdof, cdof, gcdof, off, goff, d, e;
3204: PetscCall(PetscSectionGetDof(s, p, &dof));
3205: PetscCall(PetscSectionGetDof(gs, p, &gdof));
3206: PetscCall(PetscSectionGetConstraintDof(s, p, &cdof));
3207: PetscCall(PetscSectionGetConstraintDof(gs, p, &gcdof));
3208: PetscCall(PetscSectionGetOffset(s, p, &off));
3209: PetscCall(PetscSectionGetOffset(gs, p, &goff));
3210: /* Ignore off-process data and points with no global data */
3211: if (!gdof || goff < 0) continue;
3212: 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);
3213: /* If no constraints are enforced in the global vector */
3214: if (!gcdof) {
3215: for (d = 0; d < dof; ++d) gArray[goff - gStart + d] = lArray[off + d];
3216: /* If constraints are enforced in the global vector */
3217: } else if (cdof == gcdof) {
3218: const PetscInt *cdofs;
3219: PetscInt cind = 0;
3221: PetscCall(PetscSectionGetConstraintIndices(s, p, &cdofs));
3222: for (d = 0, e = 0; d < dof; ++d) {
3223: if ((cind < cdof) && (d == cdofs[cind])) {
3224: ++cind;
3225: continue;
3226: }
3227: gArray[goff - gStart + e++] = lArray[off + d];
3228: }
3229: } 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);
3230: }
3231: }
3232: if (g_inplace) {
3233: PetscCall(VecRestoreArrayAndMemType(g, &gArray));
3234: } else {
3235: PetscCall(VecRestoreArray(g, &gArray));
3236: }
3237: if (transform) {
3238: PetscCall(VecRestoreArrayRead(tmpl, &lArray));
3239: PetscCall(DMRestoreNamedLocalVector(dm, "__petsc_dm_transform_local_copy", &tmpl));
3240: } else if (l_inplace) {
3241: PetscCall(VecRestoreArrayReadAndMemType(l, &lArray));
3242: } else {
3243: PetscCall(VecRestoreArrayRead(l, &lArray));
3244: }
3245: } else {
3246: PetscUseTypeMethod(dm, localtoglobalbegin, l, mode == INSERT_ALL_VALUES ? INSERT_VALUES : (mode == ADD_ALL_VALUES ? ADD_VALUES : mode), g);
3247: }
3248: PetscFunctionReturn(PETSC_SUCCESS);
3249: }
3251: /*@
3252: DMLocalToGlobalEnd - updates global vectors from local vectors
3254: Neighbor-wise Collective
3256: Input Parameters:
3257: + dm - the `DM` object
3258: . l - the local vector
3259: . mode - `INSERT_VALUES` or `ADD_VALUES`
3260: - g - the global vector
3262: Level: intermediate
3264: Note:
3265: See `DMLocalToGlobalBegin()` for full details
3267: .seealso: [](ch_dmbase), `DM`, `DMLocalToGlobalBegin()`, `DMCoarsen()`, `DMDestroy()`, `DMView()`, `DMCreateGlobalVector()`, `DMCreateInterpolation()`, `DMGlobalToLocalEnd()`
3268: @*/
3269: PetscErrorCode DMLocalToGlobalEnd(DM dm, Vec l, InsertMode mode, Vec g)
3270: {
3271: PetscSF sf;
3272: PetscSection s;
3273: DMLocalToGlobalHookLink link;
3274: PetscBool isInsert, transform;
3276: PetscFunctionBegin;
3278: PetscCall(DMGetSectionSF(dm, &sf));
3279: PetscCall(DMGetLocalSection(dm, &s));
3280: switch (mode) {
3281: case INSERT_VALUES:
3282: case INSERT_ALL_VALUES:
3283: isInsert = PETSC_TRUE;
3284: break;
3285: case ADD_VALUES:
3286: case ADD_ALL_VALUES:
3287: isInsert = PETSC_FALSE;
3288: break;
3289: default:
3290: SETERRQ(PetscObjectComm((PetscObject)dm), PETSC_ERR_ARG_OUTOFRANGE, "Invalid insertion mode %d", mode);
3291: }
3292: if (sf && !isInsert) {
3293: const PetscScalar *lArray;
3294: PetscScalar *gArray;
3295: Vec tmpl;
3297: PetscCall(DMHasBasisTransform(dm, &transform));
3298: if (transform) {
3299: PetscCall(DMGetNamedLocalVector(dm, "__petsc_dm_transform_local_copy", &tmpl));
3300: PetscCall(VecGetArrayRead(tmpl, &lArray));
3301: } else {
3302: PetscCall(VecGetArrayReadAndMemType(l, &lArray, NULL));
3303: }
3304: PetscCall(VecGetArrayAndMemType(g, &gArray, NULL));
3305: PetscCall(PetscSFReduceEnd(sf, MPIU_SCALAR, lArray, gArray, MPIU_SUM));
3306: if (transform) {
3307: PetscCall(VecRestoreArrayRead(tmpl, &lArray));
3308: PetscCall(DMRestoreNamedLocalVector(dm, "__petsc_dm_transform_local_copy", &tmpl));
3309: } else {
3310: PetscCall(VecRestoreArrayReadAndMemType(l, &lArray));
3311: }
3312: PetscCall(VecRestoreArrayAndMemType(g, &gArray));
3313: } else if (s && isInsert) {
3314: } else {
3315: PetscUseTypeMethod(dm, localtoglobalend, l, mode == INSERT_ALL_VALUES ? INSERT_VALUES : (mode == ADD_ALL_VALUES ? ADD_VALUES : mode), g);
3316: }
3317: for (link = dm->ltoghook; link; link = link->next) {
3318: if (link->endhook) PetscCall((*link->endhook)(dm, g, mode, l, link->ctx));
3319: }
3320: PetscFunctionReturn(PETSC_SUCCESS);
3321: }
3323: /*@
3324: DMLocalToLocalBegin - Begins the process of mapping values from a local vector (that include
3325: ghost points that contain irrelevant values) to another local vector where the ghost points
3326: in the second are set correctly from values on other MPI ranks.
3328: Neighbor-wise Collective
3330: Input Parameters:
3331: + dm - the `DM` object
3332: . g - the original local vector
3333: - mode - one of `INSERT_VALUES` or `ADD_VALUES`
3335: Output Parameter:
3336: . l - the local vector with correct ghost values
3338: Level: intermediate
3340: Note:
3341: Must be followed by `DMLocalToLocalEnd()`.
3343: .seealso: [](ch_dmbase), `DM`, `DMLocalToLocalEnd()`, `DMCoarsen()`, `DMDestroy()`, `DMView()`, `DMCreateLocalVector()`, `DMCreateGlobalVector()`, `DMCreateInterpolation()`, `DMGlobalToLocalEnd()`, `DMLocalToGlobalBegin()`
3344: @*/
3345: PetscErrorCode DMLocalToLocalBegin(DM dm, Vec g, InsertMode mode, Vec l)
3346: {
3347: PetscFunctionBegin;
3351: PetscUseTypeMethod(dm, localtolocalbegin, g, mode == INSERT_ALL_VALUES ? INSERT_VALUES : (mode == ADD_ALL_VALUES ? ADD_VALUES : mode), l);
3352: PetscFunctionReturn(PETSC_SUCCESS);
3353: }
3355: /*@
3356: DMLocalToLocalEnd - Maps from a local vector to another local vector where the ghost
3357: points in the second are set correctly. Must be preceded by `DMLocalToLocalBegin()`.
3359: Neighbor-wise Collective
3361: Input Parameters:
3362: + dm - the `DM` object
3363: . g - the original local vector
3364: - mode - one of `INSERT_VALUES` or `ADD_VALUES`
3366: Output Parameter:
3367: . l - the local vector with correct ghost values
3369: Level: intermediate
3371: .seealso: [](ch_dmbase), `DM`, `DMLocalToLocalBegin()`, `DMCoarsen()`, `DMDestroy()`, `DMView()`, `DMCreateLocalVector()`, `DMCreateGlobalVector()`, `DMCreateInterpolation()`, `DMGlobalToLocalEnd()`, `DMLocalToGlobalBegin()`
3372: @*/
3373: PetscErrorCode DMLocalToLocalEnd(DM dm, Vec g, InsertMode mode, Vec l)
3374: {
3375: PetscFunctionBegin;
3379: PetscUseTypeMethod(dm, localtolocalend, g, mode == INSERT_ALL_VALUES ? INSERT_VALUES : (mode == ADD_ALL_VALUES ? ADD_VALUES : mode), l);
3380: PetscFunctionReturn(PETSC_SUCCESS);
3381: }
3383: /*@
3384: DMCoarsen - Coarsens a `DM` object using a standard, non-adaptive coarsening of the underlying mesh
3386: Collective
3388: Input Parameters:
3389: + dm - the `DM` object
3390: - comm - the communicator to contain the new `DM` object (or `MPI_COMM_NULL`)
3392: Output Parameter:
3393: . dmc - the coarsened `DM`
3395: Level: developer
3397: .seealso: [](ch_dmbase), `DM`, `DMRefine()`, `DMDestroy()`, `DMView()`, `DMCreateGlobalVector()`, `DMCreateInterpolation()`, `DMCreateDomainDecomposition()`,
3398: `DMCoarsenHookAdd()`, `DMCoarsenHookRemove()`
3399: @*/
3400: PetscErrorCode DMCoarsen(DM dm, MPI_Comm comm, DM *dmc)
3401: {
3402: DMCoarsenHookLink link;
3404: PetscFunctionBegin;
3406: PetscCall(PetscLogEventBegin(DM_Coarsen, dm, 0, 0, 0));
3407: PetscUseTypeMethod(dm, coarsen, comm, dmc);
3408: if (*dmc) {
3409: (*dmc)->bind_below = dm->bind_below; /* Propagate this from parent DM; otherwise -dm_bind_below will be useless for multigrid cases. */
3410: PetscCall(DMSetCoarseDM(dm, *dmc));
3411: (*dmc)->ops->creatematrix = dm->ops->creatematrix;
3412: PetscCall(PetscObjectCopyFortranFunctionPointers((PetscObject)dm, (PetscObject)*dmc));
3413: (*dmc)->ctx = dm->ctx;
3414: (*dmc)->levelup = dm->levelup;
3415: (*dmc)->leveldown = dm->leveldown + 1;
3416: PetscCall(DMSetMatType(*dmc, dm->mattype));
3417: for (link = dm->coarsenhook; link; link = link->next) {
3418: if (link->coarsenhook) PetscCall((*link->coarsenhook)(dm, *dmc, link->ctx));
3419: }
3420: }
3421: PetscCall(PetscLogEventEnd(DM_Coarsen, dm, 0, 0, 0));
3422: PetscCheck(*dmc, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "NULL coarse mesh produced");
3423: PetscFunctionReturn(PETSC_SUCCESS);
3424: }
3426: /*@C
3427: DMCoarsenHookAdd - adds a callback to be run when restricting a nonlinear problem to the coarse grid
3429: Logically Collective; No Fortran Support
3431: Input Parameters:
3432: + fine - `DM` on which to run a hook when restricting to a coarser level
3433: . coarsenhook - function to run when setting up a coarser level
3434: . restricthook - function to run to update data on coarser levels (called once per `SNESSolve()`)
3435: - ctx - [optional] application context for provide data for the hooks (may be `NULL`)
3437: Calling sequence of `coarsenhook`:
3438: + fine - fine level `DM`
3439: . coarse - coarse level `DM` to restrict problem to
3440: - ctx - optional application function context
3442: Calling sequence of `restricthook`:
3443: + fine - fine level `DM`
3444: . mrestrict - matrix restricting a fine-level solution to the coarse grid, usually the transpose of the interpolation
3445: . rscale - scaling vector for restriction
3446: . inject - matrix restricting by injection
3447: . coarse - coarse level DM to update
3448: - ctx - optional application function context
3450: Level: advanced
3452: Notes:
3453: 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`.
3455: If this function is called multiple times, the hooks will be run in the order they are added.
3457: In order to compose with nonlinear preconditioning without duplicating storage, the hook should be implemented to
3458: extract the finest level information from its context (instead of from the `SNES`).
3460: The hooks are automatically called by `DMRestrict()`
3462: .seealso: [](ch_dmbase), `DM`, `DMCoarsenHookRemove()`, `DMRefineHookAdd()`, `SNESFASGetInterpolation()`, `SNESFASGetInjection()`, `PetscObjectCompose()`, `PetscContainerCreate()`
3463: @*/
3464: 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)
3465: {
3466: DMCoarsenHookLink link, *p;
3468: PetscFunctionBegin;
3470: for (p = &fine->coarsenhook; *p; p = &(*p)->next) { /* Scan to the end of the current list of hooks */
3471: if ((*p)->coarsenhook == coarsenhook && (*p)->restricthook == restricthook && (*p)->ctx == ctx) PetscFunctionReturn(PETSC_SUCCESS);
3472: }
3473: PetscCall(PetscNew(&link));
3474: link->coarsenhook = coarsenhook;
3475: link->restricthook = restricthook;
3476: link->ctx = ctx;
3477: link->next = NULL;
3478: *p = link;
3479: PetscFunctionReturn(PETSC_SUCCESS);
3480: }
3482: /*@C
3483: DMCoarsenHookRemove - remove a callback set with `DMCoarsenHookAdd()`
3485: Logically Collective; No Fortran Support
3487: Input Parameters:
3488: + fine - `DM` on which to run a hook when restricting to a coarser level
3489: . coarsenhook - function to run when setting up a coarser level
3490: . restricthook - function to run to update data on coarser levels
3491: - ctx - [optional] application context for provide data for the hooks (may be `NULL`)
3493: Calling sequence of `coarsenhook`:
3494: + fine - fine level `DM`
3495: . coarse - coarse level `DM` to restrict problem to
3496: - ctx - optional application function context
3498: Calling sequence of `restricthook`:
3499: + fine - fine level `DM`
3500: . rstrict - matrix restricting a fine-level solution to the coarse grid, usually the transpose of the interpolation
3501: . rscale - scaling vector for restriction
3502: . inject - matrix restricting by injection
3503: . coarse - coarse level DM to update
3504: - ctx - optional application function context
3506: Level: advanced
3508: Notes:
3509: This function does nothing if the `coarsenhook` is not in the list.
3511: See `DMCoarsenHookAdd()` for the calling sequence of `coarsenhook` and `restricthook`
3513: .seealso: [](ch_dmbase), `DM`, `DMCoarsenHookAdd()`, `DMRefineHookAdd()`, `SNESFASGetInterpolation()`, `SNESFASGetInjection()`, `PetscObjectCompose()`, `PetscContainerCreate()`
3514: @*/
3515: 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)
3516: {
3517: DMCoarsenHookLink link, *p;
3519: PetscFunctionBegin;
3521: for (p = &fine->coarsenhook; *p; p = &(*p)->next) { /* Search the list of current hooks */
3522: if ((*p)->coarsenhook == coarsenhook && (*p)->restricthook == restricthook && (*p)->ctx == ctx) {
3523: link = *p;
3524: *p = link->next;
3525: PetscCall(PetscFree(link));
3526: break;
3527: }
3528: }
3529: PetscFunctionReturn(PETSC_SUCCESS);
3530: }
3532: /*@
3533: DMRestrict - restricts user-defined problem data to a coarser `DM` by running hooks registered by `DMCoarsenHookAdd()`
3535: Collective if any hooks are
3537: Input Parameters:
3538: + fine - finer `DM` from which the data is obtained
3539: . restrct - restriction matrix, apply using `MatRestrict()`, usually the transpose of the interpolation
3540: . rscale - scaling vector for restriction
3541: . inject - injection matrix, also use `MatRestrict()`
3542: - coarse - coarser `DM` to update
3544: Level: developer
3546: Developer Note:
3547: Though this routine is called `DMRestrict()` the hooks are added with `DMCoarsenHookAdd()`, a consistent terminology would be better
3549: .seealso: [](ch_dmbase), `DM`, `DMCoarsenHookAdd()`, `MatRestrict()`, `DMInterpolate()`, `DMRefineHookAdd()`
3550: @*/
3551: PetscErrorCode DMRestrict(DM fine, Mat restrct, Vec rscale, Mat inject, DM coarse)
3552: {
3553: DMCoarsenHookLink link;
3555: PetscFunctionBegin;
3556: for (link = fine->coarsenhook; link; link = link->next) {
3557: if (link->restricthook) PetscCall((*link->restricthook)(fine, restrct, rscale, inject, coarse, link->ctx));
3558: }
3559: PetscFunctionReturn(PETSC_SUCCESS);
3560: }
3562: /*@C
3563: DMSubDomainHookAdd - adds a callback to be run when restricting a problem to subdomain `DM`s with `DMCreateDomainDecomposition()`
3565: Logically Collective; No Fortran Support
3567: Input Parameters:
3568: + global - global `DM`
3569: . ddhook - function to run to pass data to the decomposition `DM` upon its creation
3570: . restricthook - function to run to update data on block solve (at the beginning of the block solve)
3571: - ctx - [optional] application context for provide data for the hooks (may be `NULL`)
3573: Calling sequence of `ddhook`:
3574: + global - global `DM`
3575: . block - subdomain `DM`
3576: - ctx - optional application function context
3578: Calling sequence of `restricthook`:
3579: + global - global `DM`
3580: . out - scatter to the outer (with ghost and overlap points) sub vector
3581: . in - scatter to sub vector values only owned locally
3582: . block - subdomain `DM`
3583: - ctx - optional application function context
3585: Level: advanced
3587: Notes:
3588: This function can be used if auxiliary data needs to be set up on subdomain `DM`s.
3590: If this function is called multiple times, the hooks will be run in the order they are added.
3592: In order to compose with nonlinear preconditioning without duplicating storage, the hook should be implemented to
3593: extract the global information from its context (instead of from the `SNES`).
3595: Developer Note:
3596: It is unclear what "block solve" means within the definition of `restricthook`
3598: .seealso: [](ch_dmbase), `DM`, `DMSubDomainHookRemove()`, `DMRefineHookAdd()`, `SNESFASGetInterpolation()`, `SNESFASGetInjection()`, `PetscObjectCompose()`, `PetscContainerCreate()`, `DMCreateDomainDecomposition()`
3599: @*/
3600: 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)
3601: {
3602: DMSubDomainHookLink link, *p;
3604: PetscFunctionBegin;
3606: for (p = &global->subdomainhook; *p; p = &(*p)->next) { /* Scan to the end of the current list of hooks */
3607: if ((*p)->ddhook == ddhook && (*p)->restricthook == restricthook && (*p)->ctx == ctx) PetscFunctionReturn(PETSC_SUCCESS);
3608: }
3609: PetscCall(PetscNew(&link));
3610: link->restricthook = restricthook;
3611: link->ddhook = ddhook;
3612: link->ctx = ctx;
3613: link->next = NULL;
3614: *p = link;
3615: PetscFunctionReturn(PETSC_SUCCESS);
3616: }
3618: /*@C
3619: DMSubDomainHookRemove - remove a callback from the list to be run when restricting a problem to subdomain `DM`s with `DMCreateDomainDecomposition()`
3621: Logically Collective; No Fortran Support
3623: Input Parameters:
3624: + global - global `DM`
3625: . ddhook - function to run to pass data to the decomposition `DM` upon its creation
3626: . restricthook - function to run to update data on block solve (at the beginning of the block solve)
3627: - ctx - [optional] application context for provide data for the hooks (may be `NULL`)
3629: Calling sequence of `ddhook`:
3630: + dm - global `DM`
3631: . block - subdomain `DM`
3632: - ctx - optional application function context
3634: Calling sequence of `restricthook`:
3635: + dm - global `DM`
3636: . oscatter - scatter to the outer (with ghost and overlap points) sub vector
3637: . gscatter - scatter to sub vector values only owned locally
3638: . block - subdomain `DM`
3639: - ctx - optional application function context
3641: Level: advanced
3643: .seealso: [](ch_dmbase), `DM`, `DMSubDomainHookAdd()`, `SNESFASGetInterpolation()`, `SNESFASGetInjection()`, `PetscObjectCompose()`, `PetscContainerCreate()`,
3644: `DMCreateDomainDecomposition()`
3645: @*/
3646: 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)
3647: {
3648: DMSubDomainHookLink link, *p;
3650: PetscFunctionBegin;
3652: for (p = &global->subdomainhook; *p; p = &(*p)->next) { /* Search the list of current hooks */
3653: if ((*p)->ddhook == ddhook && (*p)->restricthook == restricthook && (*p)->ctx == ctx) {
3654: link = *p;
3655: *p = link->next;
3656: PetscCall(PetscFree(link));
3657: break;
3658: }
3659: }
3660: PetscFunctionReturn(PETSC_SUCCESS);
3661: }
3663: /*@
3664: DMSubDomainRestrict - restricts user-defined problem data to a subdomain `DM` by running hooks registered by `DMSubDomainHookAdd()`
3666: Collective if any hooks are
3668: Input Parameters:
3669: + global - The global `DM` to use as a base
3670: . oscatter - The scatter from domain global vector filling subdomain global vector with overlap
3671: . gscatter - The scatter from domain global vector filling subdomain local vector with ghosts
3672: - subdm - The subdomain `DM` to update
3674: Level: developer
3676: .seealso: [](ch_dmbase), `DM`, `DMCoarsenHookAdd()`, `MatRestrict()`, `DMCreateDomainDecomposition()`
3677: @*/
3678: PetscErrorCode DMSubDomainRestrict(DM global, VecScatter oscatter, VecScatter gscatter, DM subdm)
3679: {
3680: DMSubDomainHookLink link;
3682: PetscFunctionBegin;
3683: for (link = global->subdomainhook; link; link = link->next) {
3684: if (link->restricthook) PetscCall((*link->restricthook)(global, oscatter, gscatter, subdm, link->ctx));
3685: }
3686: PetscFunctionReturn(PETSC_SUCCESS);
3687: }
3689: /*@
3690: DMGetCoarsenLevel - Gets the number of coarsenings that have generated this `DM`.
3692: Not Collective
3694: Input Parameter:
3695: . dm - the `DM` object
3697: Output Parameter:
3698: . level - number of coarsenings
3700: Level: developer
3702: .seealso: [](ch_dmbase), `DM`, `DMCoarsen()`, `DMSetCoarsenLevel()`, `DMGetRefineLevel()`, `DMDestroy()`, `DMView()`, `DMCreateGlobalVector()`, `DMCreateInterpolation()`
3703: @*/
3704: PetscErrorCode DMGetCoarsenLevel(DM dm, PetscInt *level)
3705: {
3706: PetscFunctionBegin;
3708: PetscAssertPointer(level, 2);
3709: *level = dm->leveldown;
3710: PetscFunctionReturn(PETSC_SUCCESS);
3711: }
3713: /*@
3714: DMSetCoarsenLevel - Sets the number of coarsenings that have generated this `DM`.
3716: Collective
3718: Input Parameters:
3719: + dm - the `DM` object
3720: - level - number of coarsenings
3722: Level: developer
3724: Note:
3725: This is rarely used directly, the information is automatically set when a `DM` is created with `DMCoarsen()`
3727: .seealso: [](ch_dmbase), `DM`, `DMCoarsen()`, `DMGetCoarsenLevel()`, `DMGetRefineLevel()`, `DMDestroy()`, `DMView()`, `DMCreateGlobalVector()`, `DMCreateInterpolation()`
3728: @*/
3729: PetscErrorCode DMSetCoarsenLevel(DM dm, PetscInt level)
3730: {
3731: PetscFunctionBegin;
3733: dm->leveldown = level;
3734: PetscFunctionReturn(PETSC_SUCCESS);
3735: }
3737: /*@
3738: DMRefineHierarchy - Refines a `DM` object, all levels at once
3740: Collective
3742: Input Parameters:
3743: + dm - the `DM` object
3744: - nlevels - the number of levels of refinement
3746: Output Parameter:
3747: . dmf - the refined `DM` hierarchy
3749: Level: developer
3751: .seealso: [](ch_dmbase), `DM`, `DMCoarsen()`, `DMCoarsenHierarchy()`, `DMDestroy()`, `DMView()`, `DMCreateGlobalVector()`, `DMCreateInterpolation()`
3752: @*/
3753: PetscErrorCode DMRefineHierarchy(DM dm, PetscInt nlevels, DM dmf[])
3754: {
3755: PetscFunctionBegin;
3757: PetscCheck(nlevels >= 0, PetscObjectComm((PetscObject)dm), PETSC_ERR_ARG_OUTOFRANGE, "nlevels cannot be negative");
3758: if (nlevels == 0) PetscFunctionReturn(PETSC_SUCCESS);
3759: PetscAssertPointer(dmf, 3);
3760: if (dm->ops->refine && !dm->ops->refinehierarchy) {
3761: PetscInt i;
3763: PetscCall(DMRefine(dm, PetscObjectComm((PetscObject)dm), &dmf[0]));
3764: for (i = 1; i < nlevels; i++) PetscCall(DMRefine(dmf[i - 1], PetscObjectComm((PetscObject)dm), &dmf[i]));
3765: } else PetscUseTypeMethod(dm, refinehierarchy, nlevels, dmf);
3766: PetscFunctionReturn(PETSC_SUCCESS);
3767: }
3769: /*@
3770: DMCoarsenHierarchy - Coarsens a `DM` object, all levels at once
3772: Collective
3774: Input Parameters:
3775: + dm - the `DM` object
3776: - nlevels - the number of levels of coarsening
3778: Output Parameter:
3779: . dmc - the coarsened `DM` hierarchy
3781: Level: developer
3783: .seealso: [](ch_dmbase), `DM`, `DMCoarsen()`, `DMRefineHierarchy()`, `DMDestroy()`, `DMView()`, `DMCreateGlobalVector()`, `DMCreateInterpolation()`
3784: @*/
3785: PetscErrorCode DMCoarsenHierarchy(DM dm, PetscInt nlevels, DM dmc[])
3786: {
3787: PetscFunctionBegin;
3789: PetscCheck(nlevels >= 0, PetscObjectComm((PetscObject)dm), PETSC_ERR_ARG_OUTOFRANGE, "nlevels cannot be negative");
3790: if (nlevels == 0) PetscFunctionReturn(PETSC_SUCCESS);
3791: PetscAssertPointer(dmc, 3);
3792: if (dm->ops->coarsen && !dm->ops->coarsenhierarchy) {
3793: PetscInt i;
3795: PetscCall(DMCoarsen(dm, PetscObjectComm((PetscObject)dm), &dmc[0]));
3796: for (i = 1; i < nlevels; i++) PetscCall(DMCoarsen(dmc[i - 1], PetscObjectComm((PetscObject)dm), &dmc[i]));
3797: } else PetscUseTypeMethod(dm, coarsenhierarchy, nlevels, dmc);
3798: PetscFunctionReturn(PETSC_SUCCESS);
3799: }
3801: /*@C
3802: DMSetApplicationContextDestroy - Sets a user function that will be called to destroy the application context when the `DM` is destroyed
3804: Logically Collective if the function is collective
3806: Input Parameters:
3807: + dm - the `DM` object
3808: - destroy - the destroy function, see `PetscCtxDestroyFn` for the calling sequence
3810: Level: intermediate
3812: .seealso: [](ch_dmbase), `DM`, `DMSetApplicationContext()`, `DMView()`, `DMCreateGlobalVector()`, `DMCreateInterpolation()`, `DMCreateColoring()`, `DMCreateMatrix()`, `DMCreateMassMatrix()`,
3813: `DMGetApplicationContext()`, `PetscCtxDestroyFn`
3814: @*/
3815: PetscErrorCode DMSetApplicationContextDestroy(DM dm, PetscCtxDestroyFn *destroy)
3816: {
3817: PetscFunctionBegin;
3819: dm->ctxdestroy = destroy;
3820: PetscFunctionReturn(PETSC_SUCCESS);
3821: }
3823: /*@
3824: DMSetApplicationContext - Set an application context into a `DM` object
3826: Not Collective
3828: Input Parameters:
3829: + dm - the `DM` object
3830: - ctx - the application context
3832: Level: intermediate
3834: Note:
3835: An application context is a way to pass problem specific information that is accessible whenever the `DM` is available
3836: In a multilevel solver, the application context is shared by all the `DM` in the hierarchy; it is thus not advisable
3837: to store objects that represent discretized quantities inside the context.
3839: Fortran Notes:
3840: This only works when the context is a Fortran derived type or a `PetscObject`. Declare `ctx` with
3841: .vb
3842: type(tUsertype), pointer :: ctx
3843: .ve
3845: .seealso: [](ch_dmbase), `DM`, `DMGetApplicationContext()`, `DMView()`, `DMCreateGlobalVector()`, `DMCreateInterpolation()`, `DMCreateColoring()`, `DMCreateMatrix()`, `DMCreateMassMatrix()`
3846: @*/
3847: PetscErrorCode DMSetApplicationContext(DM dm, PetscCtx ctx)
3848: {
3849: PetscFunctionBegin;
3851: dm->ctx = ctx;
3852: PetscFunctionReturn(PETSC_SUCCESS);
3853: }
3855: /*@
3856: DMGetApplicationContext - Gets an application context from a `DM` object provided with `DMSetApplicationContext()`
3858: Not Collective
3860: Input Parameter:
3861: . dm - the `DM` object
3863: Output Parameter:
3864: . ctx - a pointer to the application context
3866: Level: intermediate
3868: Note:
3869: An application context is a way to pass problem specific information that is accessible whenever the `DM` is available
3871: Fortran Notes:
3872: 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
3873: function that tells the Fortran compiler the derived data type that is returned as the `ctx` argument. For example,
3874: .vb
3875: Interface DMGetApplicationContext
3876: Subroutine DMGetApplicationContext(dm,ctx,ierr)
3877: #include <petsc/finclude/petscdm.h>
3878: use petscdm
3879: DM dm
3880: type(tUsertype), pointer :: ctx
3881: PetscErrorCode ierr
3882: End Subroutine
3883: End Interface DMGetApplicationContext
3884: .ve
3886: The prototype for `ctx` must be
3887: .vb
3888: type(tUsertype), pointer :: ctx
3889: .ve
3891: .seealso: [](ch_dmbase), `DM`, `DMView()`, `DMCreateGlobalVector()`, `DMCreateInterpolation()`, `DMCreateColoring()`, `DMCreateMatrix()`, `DMCreateMassMatrix()`
3892: @*/
3893: PetscErrorCode DMGetApplicationContext(DM dm, PetscCtxRt ctx)
3894: {
3895: PetscFunctionBegin;
3897: *(void **)ctx = dm->ctx;
3898: PetscFunctionReturn(PETSC_SUCCESS);
3899: }
3901: /*@C
3902: DMSetVariableBounds - sets a function to compute the lower and upper bound vectors for `SNESVI`.
3904: Logically Collective
3906: Input Parameters:
3907: + dm - the `DM` object
3908: - f - the function that computes variable bounds used by `SNESVI` (use `NULL` to cancel a previous function that was set)
3910: Calling sequence of f:
3911: + dm - the `DM`
3912: . lower - the vector to hold the lower bounds
3913: - upper - the vector to hold the upper bounds
3915: Level: intermediate
3917: Developer Note:
3918: Should be called `DMSetComputeVIBounds()` or something similar
3920: .seealso: [](ch_dmbase), `DM`, `DMComputeVariableBounds()`, `DMHasVariableBounds()`, `DMView()`, `DMCreateGlobalVector()`, `DMCreateInterpolation()`, `DMCreateColoring()`, `DMCreateMatrix()`, `DMCreateMassMatrix()`, `DMGetApplicationContext()`,
3921: `DMSetJacobian()`
3922: @*/
3923: PetscErrorCode DMSetVariableBounds(DM dm, PetscErrorCode (*f)(DM dm, Vec lower, Vec upper))
3924: {
3925: PetscFunctionBegin;
3927: dm->ops->computevariablebounds = f;
3928: PetscFunctionReturn(PETSC_SUCCESS);
3929: }
3931: /*@
3932: DMHasVariableBounds - does the `DM` object have a variable bounds function?
3934: Not Collective
3936: Input Parameter:
3937: . dm - the `DM` object to destroy
3939: Output Parameter:
3940: . flg - `PETSC_TRUE` if the variable bounds function exists
3942: Level: developer
3944: .seealso: [](ch_dmbase), `DM`, `DMComputeVariableBounds()`, `DMView()`, `DMCreateGlobalVector()`, `DMCreateInterpolation()`, `DMCreateColoring()`, `DMCreateMatrix()`, `DMCreateMassMatrix()`, `DMGetApplicationContext()`
3945: @*/
3946: PetscErrorCode DMHasVariableBounds(DM dm, PetscBool *flg)
3947: {
3948: PetscFunctionBegin;
3950: PetscAssertPointer(flg, 2);
3951: *flg = (dm->ops->computevariablebounds) ? PETSC_TRUE : PETSC_FALSE;
3952: PetscFunctionReturn(PETSC_SUCCESS);
3953: }
3955: /*@
3956: DMComputeVariableBounds - compute variable bounds used by `SNESVI`.
3958: Logically Collective
3960: Input Parameter:
3961: . dm - the `DM` object
3963: Output Parameters:
3964: + xl - lower bound
3965: - xu - upper bound
3967: Level: advanced
3969: Note:
3970: This is generally not called by users. It calls the function provided by the user with DMSetVariableBounds()
3972: .seealso: [](ch_dmbase), `DM`, `DMHasVariableBounds()`, `DMView()`, `DMCreateGlobalVector()`, `DMCreateInterpolation()`, `DMCreateColoring()`, `DMCreateMatrix()`, `DMCreateMassMatrix()`, `DMGetApplicationContext()`
3973: @*/
3974: PetscErrorCode DMComputeVariableBounds(DM dm, Vec xl, Vec xu)
3975: {
3976: PetscFunctionBegin;
3980: PetscUseTypeMethod(dm, computevariablebounds, xl, xu);
3981: PetscFunctionReturn(PETSC_SUCCESS);
3982: }
3984: /*@
3985: DMHasColoring - does the `DM` object have a method of providing a coloring?
3987: Not Collective
3989: Input Parameter:
3990: . dm - the DM object
3992: Output Parameter:
3993: . flg - `PETSC_TRUE` if the `DM` has facilities for `DMCreateColoring()`.
3995: Level: developer
3997: .seealso: [](ch_dmbase), `DM`, `DMCreateColoring()`
3998: @*/
3999: PetscErrorCode DMHasColoring(DM dm, PetscBool *flg)
4000: {
4001: PetscFunctionBegin;
4003: PetscAssertPointer(flg, 2);
4004: *flg = (dm->ops->getcoloring) ? PETSC_TRUE : PETSC_FALSE;
4005: PetscFunctionReturn(PETSC_SUCCESS);
4006: }
4008: /*@
4009: DMHasCreateRestriction - does the `DM` object have a method of providing a restriction?
4011: Not Collective
4013: Input Parameter:
4014: . dm - the `DM` object
4016: Output Parameter:
4017: . flg - `PETSC_TRUE` if the `DM` has facilities for `DMCreateRestriction()`.
4019: Level: developer
4021: .seealso: [](ch_dmbase), `DM`, `DMCreateRestriction()`, `DMHasCreateInterpolation()`, `DMHasCreateInjection()`
4022: @*/
4023: PetscErrorCode DMHasCreateRestriction(DM dm, PetscBool *flg)
4024: {
4025: PetscFunctionBegin;
4027: PetscAssertPointer(flg, 2);
4028: *flg = (dm->ops->createrestriction) ? PETSC_TRUE : PETSC_FALSE;
4029: PetscFunctionReturn(PETSC_SUCCESS);
4030: }
4032: /*@
4033: DMHasCreateInjection - does the `DM` object have a method of providing an injection?
4035: Not Collective
4037: Input Parameter:
4038: . dm - the `DM` object
4040: Output Parameter:
4041: . flg - `PETSC_TRUE` if the `DM` has facilities for `DMCreateInjection()`.
4043: Level: developer
4045: .seealso: [](ch_dmbase), `DM`, `DMCreateInjection()`, `DMHasCreateRestriction()`, `DMHasCreateInterpolation()`
4046: @*/
4047: PetscErrorCode DMHasCreateInjection(DM dm, PetscBool *flg)
4048: {
4049: PetscFunctionBegin;
4051: PetscAssertPointer(flg, 2);
4052: if (dm->ops->hascreateinjection) PetscUseTypeMethod(dm, hascreateinjection, flg);
4053: else *flg = (dm->ops->createinjection) ? PETSC_TRUE : PETSC_FALSE;
4054: PetscFunctionReturn(PETSC_SUCCESS);
4055: }
4057: PetscFunctionList DMList = NULL;
4058: PetscBool DMRegisterAllCalled = PETSC_FALSE;
4060: /*@
4061: DMSetType - Builds a `DM`, for a particular `DM` implementation.
4063: Collective
4065: Input Parameters:
4066: + dm - The `DM` object
4067: - method - The name of the `DMType`, for example `DMDA`, `DMPLEX`
4069: Options Database Key:
4070: . -dm_type type - Sets the `DM` type; use -help for a list of available types
4072: Level: intermediate
4074: Note:
4075: Of the `DM` is constructed by directly calling a function to construct a particular `DM`, for example, `DMDACreate2d()` or `DMPlexCreateBoxMesh()`
4077: .seealso: [](ch_dmbase), `DM`, `DMType`, `DMDA`, `DMPLEX`, `DMGetType()`, `DMCreate()`, `DMDACreate2d()`
4078: @*/
4079: PetscErrorCode DMSetType(DM dm, DMType method)
4080: {
4081: PetscErrorCode (*r)(DM);
4082: PetscBool match;
4084: PetscFunctionBegin;
4086: PetscCall(PetscObjectTypeCompare((PetscObject)dm, method, &match));
4087: if (match) PetscFunctionReturn(PETSC_SUCCESS);
4089: PetscCall(DMRegisterAll());
4090: PetscCall(PetscFunctionListFind(DMList, method, &r));
4091: PetscCheck(r, PetscObjectComm((PetscObject)dm), PETSC_ERR_ARG_UNKNOWN_TYPE, "Unknown DM type: %s", method);
4093: PetscTryTypeMethod(dm, destroy);
4094: PetscCall(PetscMemzero(dm->ops, sizeof(*dm->ops)));
4095: PetscCall(PetscObjectChangeTypeName((PetscObject)dm, method));
4096: PetscCall((*r)(dm));
4097: PetscFunctionReturn(PETSC_SUCCESS);
4098: }
4100: /*@
4101: DMGetType - Gets the `DM` type name (as a string) from the `DM`.
4103: Not Collective
4105: Input Parameter:
4106: . dm - The `DM`
4108: Output Parameter:
4109: . type - The `DMType` name
4111: Level: intermediate
4113: Note:
4114: `type` should not be retained for later use as it will be an invalid pointer if the `DMType` of `dm` is changed.
4116: .seealso: [](ch_dmbase), `DM`, `DMType`, `DMDA`, `DMPLEX`, `DMSetType()`, `DMCreate()`, `PetscObjectTypeCompare()`, `PetscObjectTypeCompareAny()`
4117: @*/
4118: PetscErrorCode DMGetType(DM dm, DMType *type)
4119: {
4120: PetscFunctionBegin;
4122: PetscAssertPointer(type, 2);
4123: PetscCall(DMRegisterAll());
4124: *type = ((PetscObject)dm)->type_name;
4125: PetscFunctionReturn(PETSC_SUCCESS);
4126: }
4128: /*@
4129: DMConvert - Converts a `DM` to another `DM`, either of the same or different type.
4131: Collective
4133: Input Parameters:
4134: + dm - the `DM`
4135: - newtype - new `DM` type (use "same" for the same type)
4137: Output Parameter:
4138: . M - pointer to new `DM`
4140: Level: intermediate
4142: Note:
4143: Cannot be used to convert a sequential `DM` to a parallel or a parallel to sequential,
4144: the MPI communicator of the generated `DM` is always the same as the communicator
4145: of the input `DM`.
4147: .seealso: [](ch_dmbase), `DM`, `DMSetType()`, `DMCreate()`, `DMClone()`
4148: @*/
4149: PetscErrorCode DMConvert(DM dm, DMType newtype, DM *M)
4150: {
4151: DM B;
4152: char convname[256];
4153: PetscBool sametype /*, issame */;
4155: PetscFunctionBegin;
4158: PetscAssertPointer(M, 3);
4159: PetscCall(PetscObjectTypeCompare((PetscObject)dm, newtype, &sametype));
4160: /* PetscCall(PetscStrcmp(newtype, "same", &issame)); */
4161: if (sametype) {
4162: *M = dm;
4163: PetscCall(PetscObjectReference((PetscObject)dm));
4164: PetscFunctionReturn(PETSC_SUCCESS);
4165: } else {
4166: PetscErrorCode (*conv)(DM, DMType, DM *) = NULL;
4168: /*
4169: Order of precedence:
4170: 1) See if a specialized converter is known to the current DM.
4171: 2) See if a specialized converter is known to the desired DM class.
4172: 3) See if a good general converter is registered for the desired class
4173: 4) See if a good general converter is known for the current matrix.
4174: 5) Use a really basic converter.
4175: */
4177: /* 1) See if a specialized converter is known to the current DM and the desired class */
4178: PetscCall(PetscStrncpy(convname, "DMConvert_", sizeof(convname)));
4179: PetscCall(PetscStrlcat(convname, ((PetscObject)dm)->type_name, sizeof(convname)));
4180: PetscCall(PetscStrlcat(convname, "_", sizeof(convname)));
4181: PetscCall(PetscStrlcat(convname, newtype, sizeof(convname)));
4182: PetscCall(PetscStrlcat(convname, "_C", sizeof(convname)));
4183: PetscCall(PetscObjectQueryFunction((PetscObject)dm, convname, &conv));
4184: if (conv) goto foundconv;
4186: /* 2) See if a specialized converter is known to the desired DM class. */
4187: PetscCall(DMCreate(PetscObjectComm((PetscObject)dm), &B));
4188: PetscCall(DMSetType(B, newtype));
4189: PetscCall(PetscStrncpy(convname, "DMConvert_", sizeof(convname)));
4190: PetscCall(PetscStrlcat(convname, ((PetscObject)dm)->type_name, sizeof(convname)));
4191: PetscCall(PetscStrlcat(convname, "_", sizeof(convname)));
4192: PetscCall(PetscStrlcat(convname, newtype, sizeof(convname)));
4193: PetscCall(PetscStrlcat(convname, "_C", sizeof(convname)));
4194: PetscCall(PetscObjectQueryFunction((PetscObject)B, convname, &conv));
4195: if (conv) {
4196: PetscCall(DMDestroy(&B));
4197: goto foundconv;
4198: }
4200: #if 0
4201: /* 3) See if a good general converter is registered for the desired class */
4202: conv = B->ops->convertfrom;
4203: PetscCall(DMDestroy(&B));
4204: if (conv) goto foundconv;
4206: /* 4) See if a good general converter is known for the current matrix */
4207: if (dm->ops->convert) conv = dm->ops->convert;
4208: if (conv) goto foundconv;
4209: #endif
4211: /* 5) Use a really basic converter. */
4212: SETERRQ(PetscObjectComm((PetscObject)dm), PETSC_ERR_SUP, "No conversion possible between DM types %s and %s", ((PetscObject)dm)->type_name, newtype);
4214: foundconv:
4215: PetscCall(PetscLogEventBegin(DM_Convert, dm, 0, 0, 0));
4216: PetscCall((*conv)(dm, newtype, M));
4217: /* Things that are independent of DM type: We should consult DMClone() here */
4218: {
4219: const PetscReal *maxCell, *Lstart, *L;
4221: PetscCall(DMGetPeriodicity(dm, &maxCell, &Lstart, &L));
4222: PetscCall(DMSetPeriodicity(*M, maxCell, Lstart, L));
4223: (*M)->prealloc_only = dm->prealloc_only;
4224: PetscCall(PetscFree((*M)->vectype));
4225: PetscCall(PetscStrallocpy(dm->vectype, (char **)&(*M)->vectype));
4226: PetscCall(PetscFree((*M)->mattype));
4227: PetscCall(PetscStrallocpy(dm->mattype, (char **)&(*M)->mattype));
4228: }
4229: PetscCall(PetscLogEventEnd(DM_Convert, dm, 0, 0, 0));
4230: }
4231: PetscCall(PetscObjectStateIncrease((PetscObject)*M));
4232: PetscFunctionReturn(PETSC_SUCCESS);
4233: }
4235: /*@C
4236: DMRegister - Adds a new `DM` type implementation
4238: Not Collective, No Fortran Support
4240: Input Parameters:
4241: + sname - The name of a new user-defined creation routine
4242: - function - The creation routine itself
4244: Calling sequence of function:
4245: . dm - the new `DM` that is being created
4247: Level: advanced
4249: Note:
4250: `DMRegister()` may be called multiple times to add several user-defined `DM`s
4252: Example Usage:
4253: .vb
4254: DMRegister("my_da", MyDMCreate);
4255: .ve
4257: Then, your `DM` type can be chosen with the procedural interface via
4258: .vb
4259: DMCreate(MPI_Comm, DM *);
4260: DMSetType(DM,"my_da");
4261: .ve
4262: or at runtime via the option
4263: .vb
4264: -da_type my_da
4265: .ve
4267: .seealso: [](ch_dmbase), `DM`, `DMType`, `DMSetType()`, `DMRegisterAll()`, `DMRegisterDestroy()`
4268: @*/
4269: PetscErrorCode DMRegister(const char sname[], PetscErrorCode (*function)(DM dm))
4270: {
4271: PetscFunctionBegin;
4272: PetscCall(DMInitializePackage());
4273: PetscCall(PetscFunctionListAdd(&DMList, sname, function));
4274: PetscFunctionReturn(PETSC_SUCCESS);
4275: }
4277: /*@
4278: DMLoad - Loads a DM that has been stored in binary with `DMView()`.
4280: Collective
4282: Input Parameters:
4283: + newdm - the newly loaded `DM`, this needs to have been created with `DMCreate()` or
4284: some related function before a call to `DMLoad()`.
4285: - viewer - binary file viewer, obtained from `PetscViewerBinaryOpen()` or
4286: `PETSCVIEWERHDF5` file viewer, obtained from `PetscViewerHDF5Open()`
4288: Level: intermediate
4290: Notes:
4291: The type is determined by the data in the file, any type set into the DM before this call is ignored.
4293: Using `PETSCVIEWERHDF5` type with `PETSC_VIEWER_HDF5_PETSC` format, one can save multiple `DMPLEX`
4294: meshes in a single HDF5 file. This in turn requires one to name the `DMPLEX` object with `PetscObjectSetName()`
4295: before saving it with `DMView()` and before loading it with `DMLoad()` for identification of the mesh object.
4297: .seealso: [](ch_dmbase), `DM`, `PetscViewerBinaryOpen()`, `DMView()`, `MatLoad()`, `VecLoad()`
4298: @*/
4299: PetscErrorCode DMLoad(DM newdm, PetscViewer viewer)
4300: {
4301: PetscBool isbinary, ishdf5;
4303: PetscFunctionBegin;
4306: PetscCall(PetscViewerCheckReadable(viewer));
4307: PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERBINARY, &isbinary));
4308: PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERHDF5, &ishdf5));
4309: PetscCall(PetscLogEventBegin(DM_Load, viewer, 0, 0, 0));
4310: if (isbinary) {
4311: PetscInt classid;
4312: char type[256];
4314: PetscCall(PetscViewerBinaryRead(viewer, &classid, 1, NULL, PETSC_INT));
4315: PetscCheck(classid == DM_FILE_CLASSID, PetscObjectComm((PetscObject)newdm), PETSC_ERR_ARG_WRONG, "Not DM next in file, classid found %" PetscInt_FMT, classid);
4316: PetscCall(PetscViewerBinaryRead(viewer, type, 256, NULL, PETSC_CHAR));
4317: PetscCall(DMSetType(newdm, type));
4318: PetscTryTypeMethod(newdm, load, viewer);
4319: } else if (ishdf5) {
4320: PetscTryTypeMethod(newdm, load, viewer);
4321: } else SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Invalid viewer; open viewer with PetscViewerBinaryOpen() or PetscViewerHDF5Open()");
4322: PetscCall(PetscLogEventEnd(DM_Load, viewer, 0, 0, 0));
4323: PetscFunctionReturn(PETSC_SUCCESS);
4324: }
4326: /* FEM Support */
4328: /*@
4329: DMPrintCellIndices - Print an integer array of per-cell indices to `PETSC_COMM_SELF`
4331: Not Collective
4333: Input Parameters:
4334: + c - the cell number
4335: . name - the label to print with the cell (typically the element or field name)
4336: . len - the length of `x`
4337: - x - the array of integer indices
4339: Level: developer
4341: .seealso: [](ch_dmbase), `DM`, `DMPrintCellVector()`, `DMPrintCellVectorReal()`, `DMPrintCellMatrix()`, `DMPrintLocalVec()`
4342: @*/
4343: PetscErrorCode DMPrintCellIndices(PetscInt c, const char name[], PetscInt len, const PetscInt x[])
4344: {
4345: PetscInt f;
4347: PetscFunctionBegin;
4348: PetscCall(PetscPrintf(PETSC_COMM_SELF, "Cell %" PetscInt_FMT " Element %s\n", c, name));
4349: for (f = 0; f < len; ++f) PetscCall(PetscPrintf(PETSC_COMM_SELF, " | %" PetscInt_FMT " |\n", x[f]));
4350: PetscFunctionReturn(PETSC_SUCCESS);
4351: }
4353: /*@
4354: DMPrintCellVector - Print a scalar array representing a per-cell vector to `PETSC_COMM_SELF`
4356: Not Collective
4358: Input Parameters:
4359: + c - the cell number
4360: . name - the label to print with the cell (typically the element or field name)
4361: . len - the length of `x`
4362: - x - the array of `PetscScalar` values
4364: Level: developer
4366: Note:
4367: Only the real part of each entry is printed.
4369: .seealso: [](ch_dmbase), `DM`, `DMPrintCellIndices()`, `DMPrintCellVectorReal()`, `DMPrintCellMatrix()`, `DMPrintLocalVec()`
4370: @*/
4371: PetscErrorCode DMPrintCellVector(PetscInt c, const char name[], PetscInt len, const PetscScalar x[])
4372: {
4373: PetscInt f;
4375: PetscFunctionBegin;
4376: PetscCall(PetscPrintf(PETSC_COMM_SELF, "Cell %" PetscInt_FMT " Element %s\n", c, name));
4377: for (f = 0; f < len; ++f) PetscCall(PetscPrintf(PETSC_COMM_SELF, " | %g |\n", (double)PetscRealPart(x[f])));
4378: PetscFunctionReturn(PETSC_SUCCESS);
4379: }
4381: /*@
4382: DMPrintCellVectorReal - Print a real array representing a per-cell vector to `PETSC_COMM_SELF`
4384: Not Collective
4386: Input Parameters:
4387: + c - the cell number
4388: . name - the label to print with the cell (typically the element or field name)
4389: . len - the length of `x`
4390: - x - the array of `PetscReal` values
4392: Level: developer
4394: .seealso: [](ch_dmbase), `DM`, `DMPrintCellIndices()`, `DMPrintCellVector()`, `DMPrintCellMatrix()`, `DMPrintLocalVec()`
4395: @*/
4396: PetscErrorCode DMPrintCellVectorReal(PetscInt c, const char name[], PetscInt len, const PetscReal x[])
4397: {
4398: PetscInt f;
4400: PetscFunctionBegin;
4401: PetscCall(PetscPrintf(PETSC_COMM_SELF, "Cell %" PetscInt_FMT " Element %s\n", c, name));
4402: for (f = 0; f < len; ++f) PetscCall(PetscPrintf(PETSC_COMM_SELF, " | %g |\n", (double)x[f]));
4403: PetscFunctionReturn(PETSC_SUCCESS);
4404: }
4406: /*@
4407: DMPrintCellMatrix - Print a scalar array representing a per-cell matrix to `PETSC_COMM_SELF`
4409: Not Collective
4411: Input Parameters:
4412: + c - the cell number
4413: . name - the label to print with the cell (typically the element or field name)
4414: . rows - number of rows in the matrix
4415: . cols - number of columns in the matrix
4416: - A - the row-major array of `PetscScalar` matrix entries
4418: Level: developer
4420: Note:
4421: Only the real part of each entry is printed.
4423: .seealso: [](ch_dmbase), `DM`, `DMPrintCellIndices()`, `DMPrintCellVector()`, `DMPrintCellVectorReal()`, `DMPrintLocalVec()`
4424: @*/
4425: PetscErrorCode DMPrintCellMatrix(PetscInt c, const char name[], PetscInt rows, PetscInt cols, const PetscScalar A[])
4426: {
4427: PetscInt f, g;
4429: PetscFunctionBegin;
4430: PetscCall(PetscPrintf(PETSC_COMM_SELF, "Cell %" PetscInt_FMT " Element %s\n", c, name));
4431: for (f = 0; f < rows; ++f) {
4432: PetscCall(PetscPrintf(PETSC_COMM_SELF, " |"));
4433: for (g = 0; g < cols; ++g) PetscCall(PetscPrintf(PETSC_COMM_SELF, " % 9.5g", (double)PetscRealPart(A[f * cols + g])));
4434: PetscCall(PetscPrintf(PETSC_COMM_SELF, " |\n"));
4435: }
4436: PetscFunctionReturn(PETSC_SUCCESS);
4437: }
4439: /*@
4440: DMPrintLocalVec - Print a `Vec` associated with a `DM`, filtering out very small entries
4442: Collective
4444: Input Parameters:
4445: + dm - the `DM` providing the communicator
4446: . name - a label printed before the vector values
4447: . tol - tolerance below which entries are filtered to zero using `VecFilter()`
4448: - X - the `Vec` to print
4450: Level: developer
4452: Note:
4453: Runs in parallel by wrapping the local portion of the vector in an MPI vector for viewing.
4455: .seealso: [](ch_dmbase), `DM`, `DMPrintCellIndices()`, `DMPrintCellVector()`, `DMPrintCellVectorReal()`, `DMPrintCellMatrix()`, `VecFilter()`
4456: @*/
4457: PetscErrorCode DMPrintLocalVec(DM dm, const char name[], PetscReal tol, Vec X)
4458: {
4459: PetscInt localSize, bs;
4460: PetscMPIInt size;
4461: Vec x, xglob;
4462: const PetscScalar *xarray;
4464: PetscFunctionBegin;
4465: PetscCallMPI(MPI_Comm_size(PetscObjectComm((PetscObject)dm), &size));
4466: PetscCall(VecDuplicate(X, &x));
4467: PetscCall(VecCopy(X, x));
4468: PetscCall(VecFilter(x, tol));
4469: PetscCall(PetscPrintf(PetscObjectComm((PetscObject)dm), "%s:\n", name));
4470: if (size > 1) {
4471: PetscCall(VecGetLocalSize(x, &localSize));
4472: PetscCall(VecGetArrayRead(x, &xarray));
4473: PetscCall(VecGetBlockSize(x, &bs));
4474: PetscCall(VecCreateMPIWithArray(PetscObjectComm((PetscObject)dm), bs, localSize, PETSC_DETERMINE, xarray, &xglob));
4475: } else {
4476: xglob = x;
4477: }
4478: PetscCall(VecView(xglob, PETSC_VIEWER_STDOUT_(PetscObjectComm((PetscObject)dm))));
4479: if (size > 1) {
4480: PetscCall(VecDestroy(&xglob));
4481: PetscCall(VecRestoreArrayRead(x, &xarray));
4482: }
4483: PetscCall(VecDestroy(&x));
4484: PetscFunctionReturn(PETSC_SUCCESS);
4485: }
4487: /*@
4488: DMGetLocalSection - Get the `PetscSection` encoding the local data layout for the `DM`.
4490: Input Parameter:
4491: . dm - The `DM`
4493: Output Parameter:
4494: . section - The `PetscSection`
4496: Options Database Key:
4497: . -dm_petscsection_view - View the section created by the `DM`
4499: Level: intermediate
4501: Note:
4502: This gets a borrowed reference, so the user should not destroy this `PetscSection`.
4504: .seealso: [](ch_dmbase), `DM`, `DMSetLocalSection()`, `DMGetGlobalSection()`
4505: @*/
4506: PetscErrorCode DMGetLocalSection(DM dm, PetscSection *section)
4507: {
4508: PetscFunctionBegin;
4510: PetscAssertPointer(section, 2);
4511: if (!dm->localSection && dm->ops->createlocalsection) {
4512: PetscInt d;
4514: if (dm->setfromoptionscalled) {
4515: PetscObject obj = (PetscObject)dm;
4516: PetscViewer viewer;
4517: PetscViewerFormat format;
4518: PetscBool flg;
4520: PetscCall(PetscOptionsCreateViewer(PetscObjectComm(obj), obj->options, obj->prefix, "-dm_petscds_view", &viewer, &format, &flg));
4521: if (flg) PetscCall(PetscViewerPushFormat(viewer, format));
4522: for (d = 0; d < dm->Nds; ++d) {
4523: PetscCall(PetscDSSetFromOptions(dm->probs[d].ds));
4524: if (flg) PetscCall(PetscDSView(dm->probs[d].ds, viewer));
4525: }
4526: if (flg) {
4527: PetscCall(PetscViewerFlush(viewer));
4528: PetscCall(PetscViewerPopFormat(viewer));
4529: PetscCall(PetscViewerDestroy(&viewer));
4530: }
4531: }
4532: PetscUseTypeMethod(dm, createlocalsection);
4533: if (dm->localSection) PetscCall(PetscObjectViewFromOptions((PetscObject)dm->localSection, NULL, "-dm_petscsection_view"));
4534: }
4535: *section = dm->localSection;
4536: PetscFunctionReturn(PETSC_SUCCESS);
4537: }
4539: /*@
4540: DMSetLocalSection - Set the `PetscSection` encoding the local data layout for the `DM`.
4542: Input Parameters:
4543: + dm - The `DM`
4544: - section - The `PetscSection`
4546: Level: intermediate
4548: Note:
4549: Any existing Section will be destroyed
4551: .seealso: [](ch_dmbase), `DM`, `PetscSection`, `DMGetLocalSection()`, `DMSetGlobalSection()`
4552: @*/
4553: PetscErrorCode DMSetLocalSection(DM dm, PetscSection section)
4554: {
4555: PetscInt numFields = 0;
4556: PetscInt f;
4558: PetscFunctionBegin;
4561: PetscCall(PetscObjectReference((PetscObject)section));
4562: PetscCall(PetscSectionDestroy(&dm->localSection));
4563: dm->localSection = section;
4564: if (section) PetscCall(PetscSectionGetNumFields(dm->localSection, &numFields));
4565: if (numFields) {
4566: PetscCall(DMSetNumFields(dm, numFields));
4567: for (f = 0; f < numFields; ++f) {
4568: PetscObject disc;
4569: const char *name;
4571: PetscCall(PetscSectionGetFieldName(dm->localSection, f, &name));
4572: PetscCall(DMGetField(dm, f, NULL, &disc));
4573: PetscCall(PetscObjectSetName(disc, name));
4574: }
4575: }
4576: /* The global section and the SectionSF will be rebuilt
4577: in the next call to DMGetGlobalSection() and DMGetSectionSF(). */
4578: PetscCall(PetscSectionDestroy(&dm->globalSection));
4579: PetscCall(PetscSFDestroy(&dm->sectionSF));
4580: PetscCall(PetscSFCreate(PetscObjectComm((PetscObject)dm), &dm->sectionSF));
4582: /* Clear scratch vectors */
4583: PetscCall(DMClearGlobalVectors(dm));
4584: PetscCall(DMClearLocalVectors(dm));
4585: PetscCall(DMClearNamedGlobalVectors(dm));
4586: PetscCall(DMClearNamedLocalVectors(dm));
4587: PetscFunctionReturn(PETSC_SUCCESS);
4588: }
4590: /*@C
4591: DMCreateSectionPermutation - Create a permutation of the `PetscSection` chart and optionally a block structure.
4593: Input Parameter:
4594: . dm - The `DM`
4596: Output Parameters:
4597: + perm - A permutation of the mesh points in the chart
4598: - blockStarts - A high bit is set for the point that begins every block, or `NULL` for default blocking
4600: Level: developer
4602: .seealso: [](ch_dmbase), `DM`, `PetscSection`, `DMGetLocalSection()`, `DMGetGlobalSection()`
4603: @*/
4604: PetscErrorCode DMCreateSectionPermutation(DM dm, IS *perm, PetscBT *blockStarts)
4605: {
4606: PetscFunctionBegin;
4607: *perm = NULL;
4608: *blockStarts = NULL;
4609: PetscTryTypeMethod(dm, createsectionpermutation, perm, blockStarts);
4610: PetscFunctionReturn(PETSC_SUCCESS);
4611: }
4613: /*@
4614: DMGetDefaultConstraints - Get the `PetscSection` and `Mat` that specify the local constraint interpolation. See `DMSetDefaultConstraints()` for a description of the purpose of constraint interpolation.
4616: not Collective
4618: Input Parameter:
4619: . dm - The `DM`
4621: Output Parameters:
4622: + 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.
4623: . 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.
4624: - bias - Vector containing bias to be added to constrained dofs
4626: Level: advanced
4628: Note:
4629: This gets borrowed references, so the user should not destroy the `PetscSection`, `Mat`, or `Vec`.
4631: .seealso: [](ch_dmbase), `DM`, `DMSetDefaultConstraints()`
4632: @*/
4633: PetscErrorCode DMGetDefaultConstraints(DM dm, PetscSection *section, Mat *mat, Vec *bias)
4634: {
4635: PetscFunctionBegin;
4637: if (!dm->defaultConstraint.section && !dm->defaultConstraint.mat && dm->ops->createdefaultconstraints) PetscUseTypeMethod(dm, createdefaultconstraints);
4638: if (section) *section = dm->defaultConstraint.section;
4639: if (mat) *mat = dm->defaultConstraint.mat;
4640: if (bias) *bias = dm->defaultConstraint.bias;
4641: PetscFunctionReturn(PETSC_SUCCESS);
4642: }
4644: /*@
4645: DMSetDefaultConstraints - Set the `PetscSection` and `Mat` that specify the local constraint interpolation.
4647: Collective
4649: Input Parameters:
4650: + dm - The `DM`
4651: . 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).
4652: . 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).
4653: - 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).
4655: Level: advanced
4657: Notes:
4658: 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()`.
4660: 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.
4662: This increments the references of the `PetscSection`, `Mat`, and `Vec`, so they user can destroy them.
4664: .seealso: [](ch_dmbase), `DM`, `DMGetDefaultConstraints()`
4665: @*/
4666: PetscErrorCode DMSetDefaultConstraints(DM dm, PetscSection section, Mat mat, Vec bias)
4667: {
4668: PetscMPIInt result;
4670: PetscFunctionBegin;
4672: if (section) {
4674: PetscCallMPI(MPI_Comm_compare(PETSC_COMM_SELF, PetscObjectComm((PetscObject)section), &result));
4675: PetscCheck(result == MPI_CONGRUENT || result == MPI_IDENT, PETSC_COMM_SELF, PETSC_ERR_ARG_NOTSAMECOMM, "constraint section must have local communicator");
4676: }
4677: if (mat) {
4679: PetscCallMPI(MPI_Comm_compare(PETSC_COMM_SELF, PetscObjectComm((PetscObject)mat), &result));
4680: PetscCheck(result == MPI_CONGRUENT || result == MPI_IDENT, PETSC_COMM_SELF, PETSC_ERR_ARG_NOTSAMECOMM, "constraint matrix must have local communicator");
4681: }
4682: if (bias) {
4684: PetscCallMPI(MPI_Comm_compare(PETSC_COMM_SELF, PetscObjectComm((PetscObject)bias), &result));
4685: PetscCheck(result == MPI_CONGRUENT || result == MPI_IDENT, PETSC_COMM_SELF, PETSC_ERR_ARG_NOTSAMECOMM, "constraint bias must have local communicator");
4686: }
4687: PetscCall(PetscObjectReference((PetscObject)section));
4688: PetscCall(PetscSectionDestroy(&dm->defaultConstraint.section));
4689: dm->defaultConstraint.section = section;
4690: PetscCall(PetscObjectReference((PetscObject)mat));
4691: PetscCall(MatDestroy(&dm->defaultConstraint.mat));
4692: dm->defaultConstraint.mat = mat;
4693: PetscCall(PetscObjectReference((PetscObject)bias));
4694: PetscCall(VecDestroy(&dm->defaultConstraint.bias));
4695: dm->defaultConstraint.bias = bias;
4696: PetscFunctionReturn(PETSC_SUCCESS);
4697: }
4699: #if defined(PETSC_USE_DEBUG)
4700: /*
4701: DMDefaultSectionCheckConsistency - Check the consistentcy of the global and local sections. Generates and error if they are not consistent.
4703: Input Parameters:
4704: + dm - The `DM`
4705: . localSection - `PetscSection` describing the local data layout
4706: - globalSection - `PetscSection` describing the global data layout
4708: Level: intermediate
4710: .seealso: [](ch_dmbase), `DM`, `DMGetSectionSF()`, `DMSetSectionSF()`
4711: */
4712: static PetscErrorCode DMDefaultSectionCheckConsistency_Internal(DM dm, PetscSection localSection, PetscSection globalSection)
4713: {
4714: MPI_Comm comm;
4715: PetscLayout layout;
4716: const PetscInt *ranges;
4717: PetscInt pStart, pEnd, p, nroots;
4718: PetscMPIInt size, rank;
4719: PetscBool valid = PETSC_TRUE, gvalid;
4721: PetscFunctionBegin;
4722: PetscCall(PetscObjectGetComm((PetscObject)dm, &comm));
4724: PetscCallMPI(MPI_Comm_size(comm, &size));
4725: PetscCallMPI(MPI_Comm_rank(comm, &rank));
4726: PetscCall(PetscSectionGetChart(globalSection, &pStart, &pEnd));
4727: PetscCall(PetscSectionGetConstrainedStorageSize(globalSection, &nroots));
4728: PetscCall(PetscLayoutCreate(comm, &layout));
4729: PetscCall(PetscLayoutSetBlockSize(layout, 1));
4730: PetscCall(PetscLayoutSetLocalSize(layout, nroots));
4731: PetscCall(PetscLayoutSetUp(layout));
4732: PetscCall(PetscLayoutGetRanges(layout, &ranges));
4733: for (p = pStart; p < pEnd; ++p) {
4734: PetscInt dof, cdof, off, gdof, gcdof, goff, gsize, d;
4736: PetscCall(PetscSectionGetDof(localSection, p, &dof));
4737: PetscCall(PetscSectionGetOffset(localSection, p, &off));
4738: PetscCall(PetscSectionGetConstraintDof(localSection, p, &cdof));
4739: PetscCall(PetscSectionGetDof(globalSection, p, &gdof));
4740: PetscCall(PetscSectionGetConstraintDof(globalSection, p, &gcdof));
4741: PetscCall(PetscSectionGetOffset(globalSection, p, &goff));
4742: if (!gdof) continue; /* Censored point */
4743: if ((gdof < 0 ? -(gdof + 1) : gdof) != dof) {
4744: PetscCall(PetscSynchronizedPrintf(comm, "[%d]Global dof %" PetscInt_FMT " for point %" PetscInt_FMT " not equal to local dof %" PetscInt_FMT "\n", rank, gdof, p, dof));
4745: valid = PETSC_FALSE;
4746: }
4747: if (gcdof && (gcdof != cdof)) {
4748: PetscCall(PetscSynchronizedPrintf(comm, "[%d]Global constraints %" PetscInt_FMT " for point %" PetscInt_FMT " not equal to local constraints %" PetscInt_FMT "\n", rank, gcdof, p, cdof));
4749: valid = PETSC_FALSE;
4750: }
4751: if (gdof < 0) {
4752: gsize = gdof < 0 ? -(gdof + 1) - gcdof : gdof - gcdof;
4753: for (d = 0; d < gsize; ++d) {
4754: PetscInt offset = -(goff + 1) + d, r;
4756: PetscCall(PetscFindInt(offset, size + 1, ranges, &r));
4757: if (r < 0) r = -(r + 2);
4758: if ((r < 0) || (r >= size)) {
4759: PetscCall(PetscSynchronizedPrintf(comm, "[%d]Point %" PetscInt_FMT " mapped to invalid process %" PetscInt_FMT " (%" PetscInt_FMT ", %" PetscInt_FMT ")\n", rank, p, r, gdof, goff));
4760: valid = PETSC_FALSE;
4761: break;
4762: }
4763: }
4764: }
4765: }
4766: PetscCall(PetscLayoutDestroy(&layout));
4767: PetscCall(PetscSynchronizedFlush(comm, NULL));
4768: PetscCallMPI(MPIU_Allreduce(&valid, &gvalid, 1, MPI_C_BOOL, MPI_LAND, comm));
4769: if (!gvalid) {
4770: PetscCall(DMView(dm, NULL));
4771: SETERRQ(comm, PETSC_ERR_ARG_WRONG, "Inconsistent local and global sections");
4772: }
4773: PetscFunctionReturn(PETSC_SUCCESS);
4774: }
4775: #endif
4777: PetscErrorCode DMGetIsoperiodicPointSF_Internal(DM dm, PetscSF *sf)
4778: {
4779: PetscErrorCode (*f)(DM, PetscSF *);
4781: PetscFunctionBegin;
4783: PetscAssertPointer(sf, 2);
4784: PetscCall(PetscObjectQueryFunction((PetscObject)dm, "DMGetIsoperiodicPointSF_C", &f));
4785: if (f) PetscCall(f(dm, sf));
4786: else *sf = dm->sf;
4787: PetscFunctionReturn(PETSC_SUCCESS);
4788: }
4790: /*@
4791: DMGetGlobalSection - Get the `PetscSection` encoding the global data layout for the `DM`.
4793: Collective
4795: Input Parameter:
4796: . dm - The `DM`
4798: Output Parameter:
4799: . section - The `PetscSection`
4801: Level: intermediate
4803: Note:
4804: This gets a borrowed reference, so the user should not destroy this `PetscSection`.
4806: .seealso: [](ch_dmbase), `DM`, `DMSetLocalSection()`, `DMGetLocalSection()`
4807: @*/
4808: PetscErrorCode DMGetGlobalSection(DM dm, PetscSection *section)
4809: {
4810: PetscFunctionBegin;
4812: PetscAssertPointer(section, 2);
4813: if (!dm->globalSection) {
4814: PetscSection s;
4815: PetscSF sf;
4817: PetscCall(DMGetLocalSection(dm, &s));
4818: PetscCheck(s, PetscObjectComm((PetscObject)dm), PETSC_ERR_ARG_WRONGSTATE, "DM must have a default PetscSection in order to create a global PetscSection");
4819: PetscCheck(dm->sf, PetscObjectComm((PetscObject)dm), PETSC_ERR_ARG_WRONGSTATE, "DM must have a point PetscSF in order to create a global PetscSection");
4820: PetscCall(DMGetIsoperiodicPointSF_Internal(dm, &sf));
4821: PetscCall(PetscSectionCreateGlobalSection(s, sf, PETSC_TRUE, PETSC_FALSE, PETSC_FALSE, &dm->globalSection));
4822: PetscCall(PetscLayoutDestroy(&dm->map));
4823: PetscCall(PetscSectionGetValueLayout(PetscObjectComm((PetscObject)dm), dm->globalSection, &dm->map));
4824: PetscCall(PetscSectionViewFromOptions(dm->globalSection, NULL, "-global_section_view"));
4825: }
4826: *section = dm->globalSection;
4827: PetscFunctionReturn(PETSC_SUCCESS);
4828: }
4830: /*@
4831: DMSetGlobalSection - Set the `PetscSection` encoding the global data layout for the `DM`.
4833: Input Parameters:
4834: + dm - The `DM`
4835: - section - The PetscSection, or `NULL`
4837: Level: intermediate
4839: Note:
4840: Any existing `PetscSection` will be destroyed
4842: .seealso: [](ch_dmbase), `DM`, `DMGetGlobalSection()`, `DMSetLocalSection()`
4843: @*/
4844: PetscErrorCode DMSetGlobalSection(DM dm, PetscSection section)
4845: {
4846: PetscFunctionBegin;
4849: PetscCall(PetscObjectReference((PetscObject)section));
4850: PetscCall(PetscSectionDestroy(&dm->globalSection));
4851: dm->globalSection = section;
4852: #if defined(PETSC_USE_DEBUG)
4853: if (section) PetscCall(DMDefaultSectionCheckConsistency_Internal(dm, dm->localSection, section));
4854: #endif
4855: /* Clear global scratch vectors and sectionSF */
4856: PetscCall(PetscSFDestroy(&dm->sectionSF));
4857: PetscCall(PetscSFCreate(PetscObjectComm((PetscObject)dm), &dm->sectionSF));
4858: PetscCall(DMClearGlobalVectors(dm));
4859: PetscCall(DMClearNamedGlobalVectors(dm));
4860: PetscFunctionReturn(PETSC_SUCCESS);
4861: }
4863: /*@
4864: DMGetSectionSF - Get the `PetscSF` encoding the parallel dof overlap for the `DM`. If it has not been set,
4865: it is created from the default `PetscSection` layouts in the `DM`.
4867: Input Parameter:
4868: . dm - The `DM`
4870: Output Parameter:
4871: . sf - The `PetscSF`
4873: Level: intermediate
4875: Note:
4876: This gets a borrowed reference, so the user should not destroy this `PetscSF`.
4878: .seealso: [](ch_dmbase), `DM`, `DMSetSectionSF()`, `DMCreateSectionSF()`
4879: @*/
4880: PetscErrorCode DMGetSectionSF(DM dm, PetscSF *sf)
4881: {
4882: PetscInt nroots;
4884: PetscFunctionBegin;
4886: PetscAssertPointer(sf, 2);
4887: if (!dm->sectionSF) PetscCall(PetscSFCreate(PetscObjectComm((PetscObject)dm), &dm->sectionSF));
4888: PetscCall(PetscSFGetGraph(dm->sectionSF, &nroots, NULL, NULL, NULL));
4889: if (nroots < 0) {
4890: PetscSection section, gSection;
4892: PetscCall(DMGetLocalSection(dm, §ion));
4893: if (section) {
4894: PetscCall(DMGetGlobalSection(dm, &gSection));
4895: PetscCall(DMCreateSectionSF(dm, section, gSection));
4896: } else {
4897: *sf = NULL;
4898: PetscFunctionReturn(PETSC_SUCCESS);
4899: }
4900: }
4901: *sf = dm->sectionSF;
4902: PetscFunctionReturn(PETSC_SUCCESS);
4903: }
4905: /*@
4906: DMSetSectionSF - Set the `PetscSF` encoding the parallel dof overlap for the `DM`
4908: Input Parameters:
4909: + dm - The `DM`
4910: - sf - The `PetscSF`
4912: Level: intermediate
4914: Note:
4915: Any previous `PetscSF` is destroyed
4917: .seealso: [](ch_dmbase), `DM`, `DMGetSectionSF()`, `DMCreateSectionSF()`
4918: @*/
4919: PetscErrorCode DMSetSectionSF(DM dm, PetscSF sf)
4920: {
4921: PetscFunctionBegin;
4924: PetscCall(PetscObjectReference((PetscObject)sf));
4925: PetscCall(PetscSFDestroy(&dm->sectionSF));
4926: dm->sectionSF = sf;
4927: PetscFunctionReturn(PETSC_SUCCESS);
4928: }
4930: /*@
4931: DMCreateSectionSF - Create the `PetscSF` encoding the parallel dof overlap for the `DM` based upon the `PetscSection`s
4932: describing the data layout.
4934: Input Parameters:
4935: + dm - The `DM`
4936: . localSection - `PetscSection` describing the local data layout
4937: - globalSection - `PetscSection` describing the global data layout
4939: Level: developer
4941: Note:
4942: One usually uses `DMGetSectionSF()` to obtain the `PetscSF`
4944: Developer Note:
4945: Since this routine has for arguments the two sections from the `DM` and puts the resulting `PetscSF`
4946: directly into the `DM`, perhaps this function should not take the local and global sections as
4947: input and should just obtain them from the `DM`? Plus PETSc creation functions return the thing
4948: they create, this returns nothing
4950: .seealso: [](ch_dmbase), `DM`, `DMGetSectionSF()`, `DMSetSectionSF()`, `DMGetLocalSection()`, `DMGetGlobalSection()`
4951: @*/
4952: PetscErrorCode DMCreateSectionSF(DM dm, PetscSection localSection, PetscSection globalSection)
4953: {
4954: PetscFunctionBegin;
4956: PetscCall(PetscSFSetGraphSection(dm->sectionSF, localSection, globalSection));
4957: PetscFunctionReturn(PETSC_SUCCESS);
4958: }
4960: /*@
4961: DMGetPointSF - Get the `PetscSF` encoding the parallel section point overlap for the `DM`.
4963: Not collective but the resulting `PetscSF` is collective
4965: Input Parameter:
4966: . dm - The `DM`
4968: Output Parameter:
4969: . sf - The `PetscSF`
4971: Level: intermediate
4973: Note:
4974: This gets a borrowed reference, so the user should not destroy this `PetscSF`.
4976: .seealso: [](ch_dmbase), `DM`, `DMSetPointSF()`, `DMGetSectionSF()`, `DMSetSectionSF()`, `DMCreateSectionSF()`
4977: @*/
4978: PetscErrorCode DMGetPointSF(DM dm, PetscSF *sf)
4979: {
4980: PetscFunctionBegin;
4982: PetscAssertPointer(sf, 2);
4983: *sf = dm->sf;
4984: PetscFunctionReturn(PETSC_SUCCESS);
4985: }
4987: /*@
4988: DMSetPointSF - Set the `PetscSF` encoding the parallel section point overlap for the `DM`.
4990: Collective
4992: Input Parameters:
4993: + dm - The `DM`
4994: - sf - The `PetscSF`
4996: Level: intermediate
4998: .seealso: [](ch_dmbase), `DM`, `DMGetPointSF()`, `DMGetSectionSF()`, `DMSetSectionSF()`, `DMCreateSectionSF()`
4999: @*/
5000: PetscErrorCode DMSetPointSF(DM dm, PetscSF sf)
5001: {
5002: PetscFunctionBegin;
5005: PetscCall(PetscObjectReference((PetscObject)sf));
5006: PetscCall(PetscSFDestroy(&dm->sf));
5007: dm->sf = sf;
5008: PetscFunctionReturn(PETSC_SUCCESS);
5009: }
5011: /*@
5012: DMGetNaturalSF - Get the `PetscSF` encoding the map back to the original mesh ordering
5014: Input Parameter:
5015: . dm - The `DM`
5017: Output Parameter:
5018: . sf - The `PetscSF`
5020: Level: intermediate
5022: Note:
5023: This gets a borrowed reference, so the user should not destroy this `PetscSF`.
5025: .seealso: [](ch_dmbase), `DM`, `DMSetNaturalSF()`, `DMSetUseNatural()`, `DMGetUseNatural()`, `DMPlexCreateGlobalToNaturalSF()`, `DMPlexDistribute()`
5026: @*/
5027: PetscErrorCode DMGetNaturalSF(DM dm, PetscSF *sf)
5028: {
5029: PetscFunctionBegin;
5031: PetscAssertPointer(sf, 2);
5032: *sf = dm->sfNatural;
5033: PetscFunctionReturn(PETSC_SUCCESS);
5034: }
5036: /*@
5037: DMSetNaturalSF - Set the PetscSF encoding the map back to the original mesh ordering
5039: Input Parameters:
5040: + dm - The DM
5041: - sf - The PetscSF
5043: Level: intermediate
5045: .seealso: [](ch_dmbase), `DM`, `DMGetNaturalSF()`, `DMSetUseNatural()`, `DMGetUseNatural()`, `DMPlexCreateGlobalToNaturalSF()`, `DMPlexDistribute()`
5046: @*/
5047: PetscErrorCode DMSetNaturalSF(DM dm, PetscSF sf)
5048: {
5049: PetscFunctionBegin;
5052: PetscCall(PetscObjectReference((PetscObject)sf));
5053: PetscCall(PetscSFDestroy(&dm->sfNatural));
5054: dm->sfNatural = sf;
5055: PetscFunctionReturn(PETSC_SUCCESS);
5056: }
5058: static PetscErrorCode DMSetDefaultAdjacency_Private(DM dm, PetscInt f, PetscObject disc)
5059: {
5060: PetscClassId id;
5062: PetscFunctionBegin;
5063: PetscCall(PetscObjectGetClassId(disc, &id));
5064: if (id == PETSCFE_CLASSID) PetscCall(DMSetAdjacency(dm, f, PETSC_FALSE, PETSC_TRUE));
5065: else if (id == PETSCFV_CLASSID) PetscCall(DMSetAdjacency(dm, f, PETSC_TRUE, PETSC_FALSE));
5066: else PetscCall(DMSetAdjacency(dm, f, PETSC_FALSE, PETSC_TRUE));
5067: PetscFunctionReturn(PETSC_SUCCESS);
5068: }
5070: static PetscErrorCode DMFieldEnlarge_Static(DM dm, PetscInt NfNew)
5071: {
5072: RegionField *tmpr;
5073: PetscInt Nf = dm->Nf, f;
5075: PetscFunctionBegin;
5076: if (Nf >= NfNew) PetscFunctionReturn(PETSC_SUCCESS);
5077: PetscCall(PetscMalloc1(NfNew, &tmpr));
5078: for (f = 0; f < Nf; ++f) tmpr[f] = dm->fields[f];
5079: for (f = Nf; f < NfNew; ++f) {
5080: tmpr[f].disc = NULL;
5081: tmpr[f].label = NULL;
5082: tmpr[f].avoidTensor = PETSC_FALSE;
5083: }
5084: PetscCall(PetscFree(dm->fields));
5085: dm->Nf = NfNew;
5086: dm->fields = tmpr;
5087: PetscFunctionReturn(PETSC_SUCCESS);
5088: }
5090: /*@
5091: DMClearFields - Remove all fields from the `DM`
5093: Logically Collective
5095: Input Parameter:
5096: . dm - The `DM`
5098: Level: intermediate
5100: .seealso: [](ch_dmbase), `DM`, `DMGetNumFields()`, `DMSetNumFields()`, `DMSetField()`
5101: @*/
5102: PetscErrorCode DMClearFields(DM dm)
5103: {
5104: PetscInt f;
5106: PetscFunctionBegin;
5108: if (!dm->fields) PetscFunctionReturn(PETSC_SUCCESS); // DMDA does not use fields field in DM
5109: for (f = 0; f < dm->Nf; ++f) {
5110: PetscCall(PetscObjectDestroy(&dm->fields[f].disc));
5111: PetscCall(DMLabelDestroy(&dm->fields[f].label));
5112: }
5113: PetscCall(PetscFree(dm->fields));
5114: dm->fields = NULL;
5115: dm->Nf = 0;
5116: PetscFunctionReturn(PETSC_SUCCESS);
5117: }
5119: /*@
5120: DMGetNumFields - Get the number of fields in the `DM`
5122: Not Collective
5124: Input Parameter:
5125: . dm - The `DM`
5127: Output Parameter:
5128: . numFields - The number of fields
5130: Level: intermediate
5132: .seealso: [](ch_dmbase), `DM`, `DMSetNumFields()`, `DMSetField()`
5133: @*/
5134: PetscErrorCode DMGetNumFields(DM dm, PetscInt *numFields)
5135: {
5136: PetscFunctionBegin;
5138: PetscAssertPointer(numFields, 2);
5139: *numFields = dm->Nf;
5140: PetscFunctionReturn(PETSC_SUCCESS);
5141: }
5143: /*@
5144: DMSetNumFields - Set the number of fields in the `DM`
5146: Logically Collective
5148: Input Parameters:
5149: + dm - The `DM`
5150: - numFields - The number of fields
5152: Level: intermediate
5154: .seealso: [](ch_dmbase), `DM`, `DMGetNumFields()`, `DMSetField()`
5155: @*/
5156: PetscErrorCode DMSetNumFields(DM dm, PetscInt numFields)
5157: {
5158: PetscInt Nf, f;
5160: PetscFunctionBegin;
5162: PetscCall(DMGetNumFields(dm, &Nf));
5163: for (f = Nf; f < numFields; ++f) {
5164: PetscContainer obj;
5166: PetscCall(PetscContainerCreate(PetscObjectComm((PetscObject)dm), &obj));
5167: PetscCall(DMAddField(dm, NULL, (PetscObject)obj));
5168: PetscCall(PetscContainerDestroy(&obj));
5169: }
5170: PetscFunctionReturn(PETSC_SUCCESS);
5171: }
5173: /*@
5174: DMGetField - Return the `DMLabel` and discretization object for a given `DM` field
5176: Not Collective
5178: Input Parameters:
5179: + dm - The `DM`
5180: - f - The field number
5182: Output Parameters:
5183: + label - The label indicating the support of the field, or `NULL` for the entire mesh (pass in `NULL` if not needed)
5184: - disc - The discretization object (pass in `NULL` if not needed)
5186: Level: intermediate
5188: .seealso: [](ch_dmbase), `DM`, `DMAddField()`, `DMSetField()`
5189: @*/
5190: PetscErrorCode DMGetField(DM dm, PetscInt f, DMLabel *label, PetscObject *disc)
5191: {
5192: PetscFunctionBegin;
5194: PetscAssertPointer(disc, 4);
5195: 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);
5196: if (!dm->fields) {
5197: if (label) *label = NULL;
5198: if (disc) *disc = NULL;
5199: } else { // some DM such as DMDA do not have dm->fields
5200: if (label) *label = dm->fields[f].label;
5201: if (disc) *disc = dm->fields[f].disc;
5202: }
5203: PetscFunctionReturn(PETSC_SUCCESS);
5204: }
5206: /* Does not clear the DS */
5207: PetscErrorCode DMSetField_Internal(DM dm, PetscInt f, DMLabel label, PetscObject disc)
5208: {
5209: PetscFunctionBegin;
5210: PetscCall(DMFieldEnlarge_Static(dm, f + 1));
5211: PetscCall(DMLabelDestroy(&dm->fields[f].label));
5212: PetscCall(PetscObjectDestroy(&dm->fields[f].disc));
5213: dm->fields[f].label = label;
5214: dm->fields[f].disc = disc;
5215: PetscCall(PetscObjectReference((PetscObject)label));
5216: PetscCall(PetscObjectReference(disc));
5217: PetscFunctionReturn(PETSC_SUCCESS);
5218: }
5220: /*@
5221: DMSetField - Set the discretization object for a given `DM` field. Usually one would call `DMAddField()` which automatically handles
5222: the field numbering.
5224: Logically Collective
5226: Input Parameters:
5227: + dm - The `DM`
5228: . f - The field number
5229: . label - The label indicating the support of the field, or `NULL` for the entire mesh
5230: - disc - The discretization object
5232: Level: intermediate
5234: .seealso: [](ch_dmbase), `DM`, `DMAddField()`, `DMGetField()`
5235: @*/
5236: PetscErrorCode DMSetField(DM dm, PetscInt f, DMLabel label, PetscObject disc)
5237: {
5238: PetscFunctionBegin;
5242: PetscCheck(f >= 0, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Field number %" PetscInt_FMT " must be non-negative", f);
5243: PetscCall(DMSetField_Internal(dm, f, label, disc));
5244: PetscCall(DMSetDefaultAdjacency_Private(dm, f, disc));
5245: PetscCall(DMClearDS(dm));
5246: PetscFunctionReturn(PETSC_SUCCESS);
5247: }
5249: /*@
5250: DMAddField - Add a field to a `DM` object. A field is a function space defined by of a set of discretization points (geometric entities)
5251: and a discretization object that defines the function space associated with those points.
5253: Logically Collective
5255: Input Parameters:
5256: + dm - The `DM`
5257: . label - The label indicating the support of the field, or `NULL` for the entire mesh
5258: - disc - The discretization object
5260: Level: intermediate
5262: Notes:
5263: The label already exists or will be added to the `DM` with `DMSetLabel()`.
5265: For example, a piecewise continuous pressure field can be defined by coefficients at the cell centers of a mesh and piecewise constant functions
5266: 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
5267: geometry entities, a `DMLabel` indicating a subset of those geometric entities, and a discretization object, such as a `PetscFE`.
5269: Fortran Note:
5270: Use the argument `PetscObjectCast(disc)` as the second argument
5272: .seealso: [](ch_dmbase), `DM`, `DMSetLabel()`, `DMSetField()`, `DMGetField()`, `PetscFE`
5273: @*/
5274: PetscErrorCode DMAddField(DM dm, DMLabel label, PetscObject disc)
5275: {
5276: PetscInt Nf = dm->Nf;
5278: PetscFunctionBegin;
5282: PetscCall(DMFieldEnlarge_Static(dm, Nf + 1));
5283: dm->fields[Nf].label = label;
5284: dm->fields[Nf].disc = disc;
5285: PetscCall(PetscObjectReference((PetscObject)label));
5286: PetscCall(PetscObjectReference(disc));
5287: PetscCall(DMSetDefaultAdjacency_Private(dm, Nf, disc));
5288: PetscCall(DMClearDS(dm));
5289: PetscFunctionReturn(PETSC_SUCCESS);
5290: }
5292: /*@
5293: DMSetFieldAvoidTensor - Set flag to avoid defining the field on tensor cells
5295: Logically Collective
5297: Input Parameters:
5298: + dm - The `DM`
5299: . f - The field index
5300: - avoidTensor - `PETSC_TRUE` to skip defining the field on tensor cells
5302: Level: intermediate
5304: .seealso: [](ch_dmbase), `DM`, `DMGetFieldAvoidTensor()`, `DMSetField()`, `DMGetField()`
5305: @*/
5306: PetscErrorCode DMSetFieldAvoidTensor(DM dm, PetscInt f, PetscBool avoidTensor)
5307: {
5308: PetscFunctionBegin;
5309: 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);
5310: dm->fields[f].avoidTensor = avoidTensor;
5311: PetscFunctionReturn(PETSC_SUCCESS);
5312: }
5314: /*@
5315: DMGetFieldAvoidTensor - Get flag to avoid defining the field on tensor cells
5317: Not Collective
5319: Input Parameters:
5320: + dm - The `DM`
5321: - f - The field index
5323: Output Parameter:
5324: . avoidTensor - The flag to avoid defining the field on tensor cells
5326: Level: intermediate
5328: .seealso: [](ch_dmbase), `DM`, `DMAddField()`, `DMSetField()`, `DMGetField()`, `DMSetFieldAvoidTensor()`
5329: @*/
5330: PetscErrorCode DMGetFieldAvoidTensor(DM dm, PetscInt f, PetscBool *avoidTensor)
5331: {
5332: PetscFunctionBegin;
5333: 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);
5334: *avoidTensor = dm->fields[f].avoidTensor;
5335: PetscFunctionReturn(PETSC_SUCCESS);
5336: }
5338: /*@
5339: DMCopyFields - Copy the discretizations for the `DM` into another `DM`
5341: Collective
5343: Input Parameters:
5344: + dm - The `DM`
5345: . minDegree - Minimum degree for a discretization, or `PETSC_DETERMINE` for no limit
5346: - maxDegree - Maximum degree for a discretization, or `PETSC_DETERMINE` for no limit
5348: Output Parameter:
5349: . newdm - The `DM`
5351: Level: advanced
5353: .seealso: [](ch_dmbase), `DM`, `DMGetField()`, `DMSetField()`, `DMAddField()`, `DMCopyDS()`, `DMGetDS()`, `DMGetCellDS()`
5354: @*/
5355: PetscErrorCode DMCopyFields(DM dm, PetscInt minDegree, PetscInt maxDegree, DM newdm)
5356: {
5357: PetscInt Nf, f;
5359: PetscFunctionBegin;
5360: if (dm == newdm) PetscFunctionReturn(PETSC_SUCCESS);
5361: PetscCall(DMGetNumFields(dm, &Nf));
5362: PetscCall(DMClearFields(newdm));
5363: for (f = 0; f < Nf; ++f) {
5364: DMLabel label;
5365: PetscObject field;
5366: PetscClassId id;
5367: PetscBool useCone, useClosure;
5369: PetscCall(DMGetField(dm, f, &label, &field));
5370: PetscCall(PetscObjectGetClassId(field, &id));
5371: if (id == PETSCFE_CLASSID) {
5372: PetscFE newfe;
5374: PetscCall(PetscFELimitDegree((PetscFE)field, minDegree, maxDegree, &newfe));
5375: PetscCall(DMSetField(newdm, f, label, (PetscObject)newfe));
5376: PetscCall(PetscFEDestroy(&newfe));
5377: } else {
5378: PetscCall(DMSetField(newdm, f, label, field));
5379: }
5380: PetscCall(DMGetAdjacency(dm, f, &useCone, &useClosure));
5381: PetscCall(DMSetAdjacency(newdm, f, useCone, useClosure));
5382: }
5383: // Create nullspace constructor slots
5384: if (dm->nullspaceConstructors) {
5385: PetscCall(PetscFree2(newdm->nullspaceConstructors, newdm->nearnullspaceConstructors));
5386: PetscCall(PetscCalloc2(Nf, &newdm->nullspaceConstructors, Nf, &newdm->nearnullspaceConstructors));
5387: }
5388: PetscFunctionReturn(PETSC_SUCCESS);
5389: }
5391: /*@
5392: DMGetAdjacency - Returns the flags for determining variable influence
5394: Not Collective
5396: Input Parameters:
5397: + dm - The `DM` object
5398: - f - The field number, or `PETSC_DEFAULT` for the default adjacency
5400: Output Parameters:
5401: + useCone - Flag for variable influence starting with the cone operation
5402: - useClosure - Flag for variable influence using transitive closure
5404: Level: developer
5406: Notes:
5407: .vb
5408: FEM: Two points p and q are adjacent if q \in closure(star(p)), useCone = PETSC_FALSE, useClosure = PETSC_TRUE
5409: FVM: Two points p and q are adjacent if q \in support(p+cone(p)), useCone = PETSC_TRUE, useClosure = PETSC_FALSE
5410: FVM++: Two points p and q are adjacent if q \in star(closure(p)), useCone = PETSC_TRUE, useClosure = PETSC_TRUE
5411: .ve
5412: Further explanation can be found in the User's Manual Section on the Influence of Variables on One Another.
5414: .seealso: [](ch_dmbase), `DM`, `DMSetAdjacency()`, `DMGetField()`, `DMSetField()`
5415: @*/
5416: PetscErrorCode DMGetAdjacency(DM dm, PetscInt f, PetscBool *useCone, PetscBool *useClosure)
5417: {
5418: PetscFunctionBegin;
5420: if (useCone) PetscAssertPointer(useCone, 3);
5421: if (useClosure) PetscAssertPointer(useClosure, 4);
5422: if (f < 0) {
5423: if (useCone) *useCone = dm->adjacency[0];
5424: if (useClosure) *useClosure = dm->adjacency[1];
5425: } else {
5426: PetscInt Nf;
5428: PetscCall(DMGetNumFields(dm, &Nf));
5429: PetscCheck(f < Nf, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Field number %" PetscInt_FMT " must be in [0, %" PetscInt_FMT ")", f, Nf);
5430: if (useCone) *useCone = dm->fields[f].adjacency[0];
5431: if (useClosure) *useClosure = dm->fields[f].adjacency[1];
5432: }
5433: PetscFunctionReturn(PETSC_SUCCESS);
5434: }
5436: /*@
5437: DMSetAdjacency - Set the flags for determining variable influence
5439: Not Collective
5441: Input Parameters:
5442: + dm - The `DM` object
5443: . f - The field number
5444: . useCone - Flag for variable influence starting with the cone operation
5445: - useClosure - Flag for variable influence using transitive closure
5447: Level: developer
5449: Notes:
5450: .vb
5451: FEM: Two points p and q are adjacent if q \in closure(star(p)), useCone = PETSC_FALSE, useClosure = PETSC_TRUE
5452: FVM: Two points p and q are adjacent if q \in support(p+cone(p)), useCone = PETSC_TRUE, useClosure = PETSC_FALSE
5453: FVM++: Two points p and q are adjacent if q \in star(closure(p)), useCone = PETSC_TRUE, useClosure = PETSC_TRUE
5454: .ve
5455: Further explanation can be found in the User's Manual Section on the Influence of Variables on One Another.
5457: .seealso: [](ch_dmbase), `DM`, `DMGetAdjacency()`, `DMGetField()`, `DMSetField()`
5458: @*/
5459: PetscErrorCode DMSetAdjacency(DM dm, PetscInt f, PetscBool useCone, PetscBool useClosure)
5460: {
5461: PetscFunctionBegin;
5463: if (f < 0) {
5464: dm->adjacency[0] = useCone;
5465: dm->adjacency[1] = useClosure;
5466: } else {
5467: PetscInt Nf;
5469: PetscCall(DMGetNumFields(dm, &Nf));
5470: PetscCheck(f < Nf, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Field number %" PetscInt_FMT " must be in [0, %" PetscInt_FMT ")", f, Nf);
5471: dm->fields[f].adjacency[0] = useCone;
5472: dm->fields[f].adjacency[1] = useClosure;
5473: }
5474: PetscFunctionReturn(PETSC_SUCCESS);
5475: }
5477: /*@
5478: DMGetBasicAdjacency - Returns the flags for determining variable influence, using either the default or field 0 if it is defined
5480: Not collective
5482: Input Parameter:
5483: . dm - The `DM` object
5485: Output Parameters:
5486: + useCone - Flag for variable influence starting with the cone operation
5487: - useClosure - Flag for variable influence using transitive closure
5489: Level: developer
5491: Notes:
5492: .vb
5493: FEM: Two points p and q are adjacent if q \in closure(star(p)), useCone = PETSC_FALSE, useClosure = PETSC_TRUE
5494: FVM: Two points p and q are adjacent if q \in support(p+cone(p)), useCone = PETSC_TRUE, useClosure = PETSC_FALSE
5495: FVM++: Two points p and q are adjacent if q \in star(closure(p)), useCone = PETSC_TRUE, useClosure = PETSC_TRUE
5496: .ve
5498: .seealso: [](ch_dmbase), `DM`, `DMSetBasicAdjacency()`, `DMGetField()`, `DMSetField()`
5499: @*/
5500: PetscErrorCode DMGetBasicAdjacency(DM dm, PetscBool *useCone, PetscBool *useClosure)
5501: {
5502: PetscInt Nf;
5504: PetscFunctionBegin;
5506: if (useCone) PetscAssertPointer(useCone, 2);
5507: if (useClosure) PetscAssertPointer(useClosure, 3);
5508: PetscCall(DMGetNumFields(dm, &Nf));
5509: if (!Nf) {
5510: PetscCall(DMGetAdjacency(dm, PETSC_DEFAULT, useCone, useClosure));
5511: } else {
5512: PetscCall(DMGetAdjacency(dm, 0, useCone, useClosure));
5513: }
5514: PetscFunctionReturn(PETSC_SUCCESS);
5515: }
5517: /*@
5518: DMSetBasicAdjacency - Set the flags for determining variable influence, using either the default or field 0 if it is defined
5520: Not Collective
5522: Input Parameters:
5523: + dm - The `DM` object
5524: . useCone - Flag for variable influence starting with the cone operation
5525: - useClosure - Flag for variable influence using transitive closure
5527: Level: developer
5529: Notes:
5530: .vb
5531: FEM: Two points p and q are adjacent if q \in closure(star(p)), useCone = PETSC_FALSE, useClosure = PETSC_TRUE
5532: FVM: Two points p and q are adjacent if q \in support(p+cone(p)), useCone = PETSC_TRUE, useClosure = PETSC_FALSE
5533: FVM++: Two points p and q are adjacent if q \in star(closure(p)), useCone = PETSC_TRUE, useClosure = PETSC_TRUE
5534: .ve
5536: .seealso: [](ch_dmbase), `DM`, `DMGetBasicAdjacency()`, `DMGetField()`, `DMSetField()`
5537: @*/
5538: PetscErrorCode DMSetBasicAdjacency(DM dm, PetscBool useCone, PetscBool useClosure)
5539: {
5540: PetscInt Nf;
5542: PetscFunctionBegin;
5544: PetscCall(DMGetNumFields(dm, &Nf));
5545: if (!Nf) {
5546: PetscCall(DMSetAdjacency(dm, PETSC_DEFAULT, useCone, useClosure));
5547: } else {
5548: PetscCall(DMSetAdjacency(dm, 0, useCone, useClosure));
5549: }
5550: PetscFunctionReturn(PETSC_SUCCESS);
5551: }
5553: PetscErrorCode DMCompleteBCLabels_Internal(DM dm)
5554: {
5555: DM plex;
5556: DMLabel *labels, *glabels;
5557: const char **names;
5558: char *sendNames, *recvNames;
5559: PetscInt Nds, s, maxLabels = 0, maxLen = 0, gmaxLen, Nl = 0, gNl, l, gl, m;
5560: size_t len;
5561: MPI_Comm comm;
5562: PetscMPIInt rank, size, p, *counts, *displs;
5564: PetscFunctionBegin;
5565: PetscCall(PetscObjectGetComm((PetscObject)dm, &comm));
5566: PetscCallMPI(MPI_Comm_size(comm, &size));
5567: PetscCallMPI(MPI_Comm_rank(comm, &rank));
5568: PetscCall(DMGetNumDS(dm, &Nds));
5569: for (s = 0; s < Nds; ++s) {
5570: PetscDS dsBC;
5571: PetscInt numBd;
5573: PetscCall(DMGetRegionNumDS(dm, s, NULL, NULL, &dsBC, NULL));
5574: PetscCall(PetscDSGetNumBoundary(dsBC, &numBd));
5575: maxLabels += numBd;
5576: }
5577: PetscCall(PetscCalloc1(maxLabels, &labels));
5578: /* Get list of labels to be completed */
5579: for (s = 0; s < Nds; ++s) {
5580: PetscDS dsBC;
5581: PetscInt numBd, bd;
5583: PetscCall(DMGetRegionNumDS(dm, s, NULL, NULL, &dsBC, NULL));
5584: PetscCall(PetscDSGetNumBoundary(dsBC, &numBd));
5585: for (bd = 0; bd < numBd; ++bd) {
5586: DMLabel label;
5587: PetscInt field;
5588: PetscObject obj;
5589: PetscClassId id;
5591: PetscCall(PetscDSGetBoundary(dsBC, bd, NULL, NULL, NULL, &label, NULL, NULL, &field, NULL, NULL, NULL, NULL, NULL));
5592: PetscCall(DMGetField(dm, field, NULL, &obj));
5593: PetscCall(PetscObjectGetClassId(obj, &id));
5594: if (id != PETSCFE_CLASSID || !label) continue;
5595: for (l = 0; l < Nl; ++l)
5596: if (labels[l] == label) break;
5597: if (l == Nl) labels[Nl++] = label;
5598: }
5599: }
5600: /* Get label names */
5601: PetscCall(PetscMalloc1(Nl, &names));
5602: for (l = 0; l < Nl; ++l) PetscCall(PetscObjectGetName((PetscObject)labels[l], &names[l]));
5603: for (l = 0; l < Nl; ++l) {
5604: PetscCall(PetscStrlen(names[l], &len));
5605: maxLen = PetscMax(maxLen, (PetscInt)len + 2);
5606: }
5607: PetscCall(PetscFree(labels));
5608: PetscCallMPI(MPIU_Allreduce(&maxLen, &gmaxLen, 1, MPIU_INT, MPI_MAX, comm));
5609: PetscCall(PetscCalloc1(Nl * gmaxLen, &sendNames));
5610: for (l = 0; l < Nl; ++l) PetscCall(PetscStrncpy(&sendNames[gmaxLen * l], names[l], gmaxLen));
5611: PetscCall(PetscFree(names));
5612: /* Put all names on all processes */
5613: PetscCall(PetscCalloc2(size, &counts, size + 1, &displs));
5614: PetscCallMPI(MPI_Allgather(&Nl, 1, MPI_INT, counts, 1, MPI_INT, comm));
5615: for (p = 0; p < size; ++p) displs[p + 1] = displs[p] + counts[p];
5616: gNl = displs[size];
5617: for (p = 0; p < size; ++p) {
5618: counts[p] *= gmaxLen;
5619: displs[p] *= gmaxLen;
5620: }
5621: PetscCall(PetscCalloc2(gNl * gmaxLen, &recvNames, gNl, &glabels));
5622: PetscCallMPI(MPI_Allgatherv(sendNames, counts[rank], MPI_CHAR, recvNames, counts, displs, MPI_CHAR, comm));
5623: PetscCall(PetscFree2(counts, displs));
5624: PetscCall(PetscFree(sendNames));
5625: for (l = 0, gl = 0; l < gNl; ++l) {
5626: PetscCall(DMGetLabel(dm, &recvNames[l * gmaxLen], &glabels[gl]));
5627: PetscCheck(glabels[gl], PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Label %s missing on rank %d", &recvNames[l * gmaxLen], rank);
5628: for (m = 0; m < gl; ++m)
5629: if (glabels[m] == glabels[gl]) goto next_label;
5630: PetscCall(DMConvert(dm, DMPLEX, &plex));
5631: PetscCall(DMPlexLabelComplete(plex, glabels[gl]));
5632: PetscCall(DMDestroy(&plex));
5633: ++gl;
5634: next_label:
5635: continue;
5636: }
5637: PetscCall(PetscFree2(recvNames, glabels));
5638: PetscFunctionReturn(PETSC_SUCCESS);
5639: }
5641: static PetscErrorCode DMDSEnlarge_Static(DM dm, PetscInt NdsNew)
5642: {
5643: DMSpace *tmpd;
5644: PetscInt Nds = dm->Nds, s;
5646: PetscFunctionBegin;
5647: if (Nds >= NdsNew) PetscFunctionReturn(PETSC_SUCCESS);
5648: PetscCall(PetscMalloc1(NdsNew, &tmpd));
5649: for (s = 0; s < Nds; ++s) tmpd[s] = dm->probs[s];
5650: for (s = Nds; s < NdsNew; ++s) {
5651: tmpd[s].ds = NULL;
5652: tmpd[s].label = NULL;
5653: tmpd[s].fields = NULL;
5654: }
5655: PetscCall(PetscFree(dm->probs));
5656: dm->Nds = NdsNew;
5657: dm->probs = tmpd;
5658: PetscFunctionReturn(PETSC_SUCCESS);
5659: }
5661: /*@
5662: DMGetNumDS - Get the number of discrete systems in the `DM`
5664: Not Collective
5666: Input Parameter:
5667: . dm - The `DM`
5669: Output Parameter:
5670: . Nds - The number of `PetscDS` objects
5672: Level: intermediate
5674: .seealso: [](ch_dmbase), `DM`, `DMGetDS()`, `DMGetCellDS()`
5675: @*/
5676: PetscErrorCode DMGetNumDS(DM dm, PetscInt *Nds)
5677: {
5678: PetscFunctionBegin;
5680: PetscAssertPointer(Nds, 2);
5681: *Nds = dm->Nds;
5682: PetscFunctionReturn(PETSC_SUCCESS);
5683: }
5685: /*@
5686: DMClearDS - Remove all discrete systems from the `DM`
5688: Logically Collective
5690: Input Parameter:
5691: . dm - The `DM`
5693: Level: intermediate
5695: .seealso: [](ch_dmbase), `DM`, `DMGetNumDS()`, `DMGetDS()`, `DMSetField()`
5696: @*/
5697: PetscErrorCode DMClearDS(DM dm)
5698: {
5699: PetscInt s;
5701: PetscFunctionBegin;
5703: for (s = 0; s < dm->Nds; ++s) {
5704: PetscCall(PetscDSDestroy(&dm->probs[s].ds));
5705: PetscCall(PetscDSDestroy(&dm->probs[s].dsIn));
5706: PetscCall(DMLabelDestroy(&dm->probs[s].label));
5707: PetscCall(ISDestroy(&dm->probs[s].fields));
5708: }
5709: PetscCall(PetscFree(dm->probs));
5710: dm->probs = NULL;
5711: dm->Nds = 0;
5712: PetscFunctionReturn(PETSC_SUCCESS);
5713: }
5715: /*@
5716: DMGetDS - Get the default `PetscDS`
5718: Not Collective
5720: Input Parameter:
5721: . dm - The `DM`
5723: Output Parameter:
5724: . ds - The default `PetscDS`
5726: Level: intermediate
5728: Note:
5729: The `ds` is owned by the `dm` and should not be destroyed directly.
5731: .seealso: [](ch_dmbase), `DM`, `DMGetCellDS()`, `DMGetRegionDS()`
5732: @*/
5733: PetscErrorCode DMGetDS(DM dm, PetscDS *ds)
5734: {
5735: PetscFunctionBeginHot;
5737: PetscAssertPointer(ds, 2);
5738: PetscCheck(dm->Nds > 0, PetscObjectComm((PetscObject)dm), PETSC_ERR_ARG_WRONGSTATE, "Need to call DMCreateDS() before calling DMGetDS()");
5739: *ds = dm->probs[0].ds;
5740: PetscFunctionReturn(PETSC_SUCCESS);
5741: }
5743: /*@
5744: DMGetCellDS - Get the `PetscDS` defined on a given cell
5746: Not Collective
5748: Input Parameters:
5749: + dm - The `DM`
5750: - point - Cell for the `PetscDS`
5752: Output Parameters:
5753: + ds - The `PetscDS` defined on the given cell
5754: - dsIn - The `PetscDS` for input on the given cell, or `NULL` if the same ds
5756: Level: developer
5758: .seealso: [](ch_dmbase), `DM`, `DMGetDS()`, `DMSetRegionDS()`
5759: @*/
5760: PetscErrorCode DMGetCellDS(DM dm, PetscInt point, PetscDS *ds, PetscDS *dsIn)
5761: {
5762: PetscDS dsDef = NULL;
5763: PetscInt s;
5765: PetscFunctionBeginHot;
5767: if (ds) PetscAssertPointer(ds, 3);
5768: if (dsIn) PetscAssertPointer(dsIn, 4);
5769: PetscCheck(point >= 0, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Mesh point cannot be negative: %" PetscInt_FMT, point);
5770: if (ds) *ds = NULL;
5771: if (dsIn) *dsIn = NULL;
5772: for (s = 0; s < dm->Nds; ++s) {
5773: PetscInt val;
5775: if (!dm->probs[s].label) {
5776: dsDef = dm->probs[s].ds;
5777: } else {
5778: PetscCall(DMLabelGetValue(dm->probs[s].label, point, &val));
5779: if (val >= 0) {
5780: if (ds) *ds = dm->probs[s].ds;
5781: if (dsIn) *dsIn = dm->probs[s].dsIn;
5782: break;
5783: }
5784: }
5785: }
5786: if (ds && !*ds) *ds = dsDef;
5787: PetscFunctionReturn(PETSC_SUCCESS);
5788: }
5790: /*@
5791: DMGetRegionDS - Get the `PetscDS` for a given mesh region, defined by a `DMLabel`
5793: Not Collective
5795: Input Parameters:
5796: + dm - The `DM`
5797: - label - The `DMLabel` defining the mesh region, or `NULL` for the entire mesh
5799: Output Parameters:
5800: + fields - The `IS` containing the `DM` field numbers for the fields in this `PetscDS`, or `NULL`
5801: . ds - The `PetscDS` defined on the given region, or `NULL`
5802: - dsIn - The `PetscDS` for input in the given region, or `NULL`
5804: Level: advanced
5806: Note:
5807: If a non-`NULL` label is given, but there is no `PetscDS` on that specific label,
5808: the `PetscDS` for the full domain (if present) is returned. Returns with
5809: fields = `NULL` and ds = `NULL` if there is no `PetscDS` for the full domain.
5811: .seealso: [](ch_dmbase), `DM`, `DMGetRegionNumDS()`, `DMSetRegionDS()`, `DMGetDS()`, `DMGetCellDS()`
5812: @*/
5813: PetscErrorCode DMGetRegionDS(DM dm, DMLabel label, IS *fields, PetscDS *ds, PetscDS *dsIn)
5814: {
5815: PetscInt Nds = dm->Nds, s;
5817: PetscFunctionBegin;
5820: if (fields) {
5821: PetscAssertPointer(fields, 3);
5822: *fields = NULL;
5823: }
5824: if (ds) {
5825: PetscAssertPointer(ds, 4);
5826: *ds = NULL;
5827: }
5828: if (dsIn) {
5829: PetscAssertPointer(dsIn, 5);
5830: *dsIn = NULL;
5831: }
5832: for (s = 0; s < Nds; ++s) {
5833: if (dm->probs[s].label == label || !dm->probs[s].label) {
5834: if (fields) *fields = dm->probs[s].fields;
5835: if (ds) *ds = dm->probs[s].ds;
5836: if (dsIn) *dsIn = dm->probs[s].dsIn;
5837: if (dm->probs[s].label) PetscFunctionReturn(PETSC_SUCCESS);
5838: }
5839: }
5840: PetscFunctionReturn(PETSC_SUCCESS);
5841: }
5843: /*@
5844: DMSetRegionDS - Set the `PetscDS` for a given mesh region, defined by a `DMLabel`
5846: Collective
5848: Input Parameters:
5849: + dm - The `DM`
5850: . label - The `DMLabel` defining the mesh region, or `NULL` for the entire mesh
5851: . fields - The `IS` containing the `DM` field numbers for the fields in this `PetscDS`, or `NULL` for all fields
5852: . ds - The `PetscDS` defined on the given region
5853: - dsIn - The `PetscDS` for input on the given cell, or `NULL` if it is the same `PetscDS`
5855: Level: advanced
5857: Note:
5858: If the label has a `PetscDS` defined, it will be replaced. Otherwise, it will be added to the `DM`. If the `PetscDS` is replaced,
5859: the fields argument is ignored.
5861: .seealso: [](ch_dmbase), `DM`, `DMGetRegionDS()`, `DMSetRegionNumDS()`, `DMGetDS()`, `DMGetCellDS()`
5862: @*/
5863: PetscErrorCode DMSetRegionDS(DM dm, DMLabel label, IS fields, PetscDS ds, PetscDS dsIn)
5864: {
5865: PetscInt Nds = dm->Nds, s;
5867: PetscFunctionBegin;
5873: for (s = 0; s < Nds; ++s) {
5874: if (dm->probs[s].label == label) {
5875: PetscCall(PetscDSDestroy(&dm->probs[s].ds));
5876: PetscCall(PetscDSDestroy(&dm->probs[s].dsIn));
5877: dm->probs[s].ds = ds;
5878: dm->probs[s].dsIn = dsIn;
5879: PetscFunctionReturn(PETSC_SUCCESS);
5880: }
5881: }
5882: PetscCall(DMDSEnlarge_Static(dm, Nds + 1));
5883: PetscCall(PetscObjectReference((PetscObject)label));
5884: PetscCall(PetscObjectReference((PetscObject)fields));
5885: PetscCall(PetscObjectReference((PetscObject)ds));
5886: PetscCall(PetscObjectReference((PetscObject)dsIn));
5887: if (!label) {
5888: /* Put the NULL label at the front, so it is returned as the default */
5889: for (s = Nds - 1; s >= 0; --s) dm->probs[s + 1] = dm->probs[s];
5890: Nds = 0;
5891: }
5892: dm->probs[Nds].label = label;
5893: dm->probs[Nds].fields = fields;
5894: dm->probs[Nds].ds = ds;
5895: dm->probs[Nds].dsIn = dsIn;
5896: PetscFunctionReturn(PETSC_SUCCESS);
5897: }
5899: /*@
5900: DMGetRegionNumDS - Get the `PetscDS` for a given mesh region, defined by the region number
5902: Not Collective
5904: Input Parameters:
5905: + dm - The `DM`
5906: - num - The region number, in [0, Nds)
5908: Output Parameters:
5909: + label - The region label, or `NULL`
5910: . fields - The `IS` containing the `DM` field numbers for the fields in this `PetscDS`, or `NULL`
5911: . ds - The `PetscDS` defined on the given region, or `NULL`
5912: - dsIn - The `PetscDS` for input in the given region, or `NULL`
5914: Level: advanced
5916: .seealso: [](ch_dmbase), `DM`, `DMGetRegionDS()`, `DMSetRegionDS()`, `DMGetDS()`, `DMGetCellDS()`
5917: @*/
5918: PetscErrorCode DMGetRegionNumDS(DM dm, PetscInt num, DMLabel *label, IS *fields, PetscDS *ds, PetscDS *dsIn)
5919: {
5920: PetscInt Nds;
5922: PetscFunctionBegin;
5924: PetscCall(DMGetNumDS(dm, &Nds));
5925: PetscCheck((num >= 0) && (num < Nds), PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Region number %" PetscInt_FMT " is not in [0, %" PetscInt_FMT ")", num, Nds);
5926: if (label) {
5927: PetscAssertPointer(label, 3);
5928: *label = dm->probs[num].label;
5929: }
5930: if (fields) {
5931: PetscAssertPointer(fields, 4);
5932: *fields = dm->probs[num].fields;
5933: }
5934: if (ds) {
5935: PetscAssertPointer(ds, 5);
5936: *ds = dm->probs[num].ds;
5937: }
5938: if (dsIn) {
5939: PetscAssertPointer(dsIn, 6);
5940: *dsIn = dm->probs[num].dsIn;
5941: }
5942: PetscFunctionReturn(PETSC_SUCCESS);
5943: }
5945: /*@
5946: DMSetRegionNumDS - Set the `PetscDS` for a given mesh region, defined by the region number
5948: Not Collective
5950: Input Parameters:
5951: + dm - The `DM`
5952: . num - The region number, in [0, Nds)
5953: . label - The region label, or `NULL`
5954: . fields - The `IS` containing the `DM` field numbers for the fields in this `PetscDS`, or `NULL` to prevent setting
5955: . ds - The `PetscDS` defined on the given region, or `NULL` to prevent setting
5956: - dsIn - The `PetscDS` for input on the given cell, or `NULL` if it is the same `PetscDS`
5958: Level: advanced
5960: .seealso: [](ch_dmbase), `DM`, `DMGetRegionDS()`, `DMSetRegionDS()`, `DMGetDS()`, `DMGetCellDS()`
5961: @*/
5962: PetscErrorCode DMSetRegionNumDS(DM dm, PetscInt num, DMLabel label, IS fields, PetscDS ds, PetscDS dsIn)
5963: {
5964: PetscInt Nds;
5966: PetscFunctionBegin;
5969: PetscCall(DMGetNumDS(dm, &Nds));
5970: PetscCheck((num >= 0) && (num < Nds), PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Region number %" PetscInt_FMT " is not in [0, %" PetscInt_FMT ")", num, Nds);
5971: PetscCall(PetscObjectReference((PetscObject)label));
5972: PetscCall(DMLabelDestroy(&dm->probs[num].label));
5973: dm->probs[num].label = label;
5974: if (fields) {
5976: PetscCall(PetscObjectReference((PetscObject)fields));
5977: PetscCall(ISDestroy(&dm->probs[num].fields));
5978: dm->probs[num].fields = fields;
5979: }
5980: if (ds) {
5982: PetscCall(PetscObjectReference((PetscObject)ds));
5983: PetscCall(PetscDSDestroy(&dm->probs[num].ds));
5984: dm->probs[num].ds = ds;
5985: }
5986: if (dsIn) {
5988: PetscCall(PetscObjectReference((PetscObject)dsIn));
5989: PetscCall(PetscDSDestroy(&dm->probs[num].dsIn));
5990: dm->probs[num].dsIn = dsIn;
5991: }
5992: PetscFunctionReturn(PETSC_SUCCESS);
5993: }
5995: /*@
5996: DMFindRegionNum - Find the region number for a given `PetscDS`, or -1 if it is not found.
5998: Not Collective
6000: Input Parameters:
6001: + dm - The `DM`
6002: - ds - The `PetscDS` defined on the given region
6004: Output Parameter:
6005: . num - The region number, in [0, Nds), or -1 if not found
6007: Level: advanced
6009: .seealso: [](ch_dmbase), `DM`, `DMGetRegionNumDS()`, `DMGetRegionDS()`, `DMSetRegionDS()`, `DMGetDS()`, `DMGetCellDS()`
6010: @*/
6011: PetscErrorCode DMFindRegionNum(DM dm, PetscDS ds, PetscInt *num)
6012: {
6013: PetscInt Nds, n;
6015: PetscFunctionBegin;
6018: PetscAssertPointer(num, 3);
6019: PetscCall(DMGetNumDS(dm, &Nds));
6020: for (n = 0; n < Nds; ++n)
6021: if (ds == dm->probs[n].ds) break;
6022: if (n >= Nds) *num = -1;
6023: else *num = n;
6024: PetscFunctionReturn(PETSC_SUCCESS);
6025: }
6027: /*@
6028: DMCreateFEDefault - Create a `PetscFE` based on the celltype for the mesh
6030: Not Collective
6032: Input Parameters:
6033: + dm - The `DM`
6034: . Nc - The number of components for the field
6035: . prefix - The options prefix for the output `PetscFE`, or `NULL`
6036: - qorder - The quadrature order or `PETSC_DETERMINE` to use `PetscSpace` polynomial degree
6038: Output Parameter:
6039: . fem - The `PetscFE`
6041: Level: intermediate
6043: Note:
6044: This is a convenience method that just calls `PetscFECreateByCell()` underneath.
6046: .seealso: [](ch_dmbase), `DM`, `PetscFECreateByCell()`, `DMAddField()`, `DMCreateDS()`, `DMGetCellDS()`, `DMGetRegionDS()`
6047: @*/
6048: PetscErrorCode DMCreateFEDefault(DM dm, PetscInt Nc, const char prefix[], PetscInt qorder, PetscFE *fem)
6049: {
6050: DMPolytopeType ct;
6051: PetscInt dim, cStart;
6053: PetscFunctionBegin;
6056: if (prefix) PetscAssertPointer(prefix, 3);
6058: PetscAssertPointer(fem, 5);
6059: PetscCall(DMGetDimension(dm, &dim));
6060: PetscCall(DMPlexGetHeightStratum(dm, 0, &cStart, NULL));
6061: PetscCall(DMPlexGetCellType(dm, cStart, &ct));
6062: PetscCall(PetscFECreateByCell(PETSC_COMM_SELF, dim, Nc, ct, prefix, qorder, fem));
6063: PetscFunctionReturn(PETSC_SUCCESS);
6064: }
6066: /*@
6067: DMCreateDS - Create the discrete systems for the `DM` based upon the fields added to the `DM`
6069: Collective
6071: Input Parameter:
6072: . dm - The `DM`
6074: Options Database Key:
6075: . -dm_petscds_view - View all the `PetscDS` objects in this `DM`
6077: Level: intermediate
6079: Developer Note:
6080: The name of this function is wrong. Create functions always return the created object as one of the arguments.
6082: .seealso: [](ch_dmbase), `DM`, `DMSetField`, `DMAddField()`, `DMGetDS()`, `DMGetCellDS()`, `DMGetRegionDS()`, `DMSetRegionDS()`
6083: @*/
6084: PetscErrorCode DMCreateDS(DM dm)
6085: {
6086: MPI_Comm comm;
6087: PetscDS dsDef;
6088: DMLabel *labelSet;
6089: PetscInt dE, Nf = dm->Nf, f, s, Nl, l, Ndef, k;
6090: PetscBool doSetup = PETSC_TRUE, flg;
6092: PetscFunctionBegin;
6094: if (!dm->fields) PetscFunctionReturn(PETSC_SUCCESS);
6095: PetscCall(PetscObjectGetComm((PetscObject)dm, &comm));
6096: PetscCall(DMGetCoordinateDim(dm, &dE));
6097: // Create nullspace constructor slots
6098: PetscCall(PetscFree2(dm->nullspaceConstructors, dm->nearnullspaceConstructors));
6099: PetscCall(PetscCalloc2(Nf, &dm->nullspaceConstructors, Nf, &dm->nearnullspaceConstructors));
6100: /* Determine how many regions we have */
6101: PetscCall(PetscMalloc1(Nf, &labelSet));
6102: Nl = 0;
6103: Ndef = 0;
6104: for (f = 0; f < Nf; ++f) {
6105: DMLabel label = dm->fields[f].label;
6106: PetscInt l;
6108: #ifdef PETSC_HAVE_LIBCEED
6109: /* Move CEED context to discretizations */
6110: {
6111: PetscClassId id;
6113: PetscCall(PetscObjectGetClassId(dm->fields[f].disc, &id));
6114: if (id == PETSCFE_CLASSID) {
6115: Ceed ceed;
6117: PetscCall(DMGetCeed(dm, &ceed));
6118: PetscCall(PetscFESetCeed((PetscFE)dm->fields[f].disc, ceed));
6119: }
6120: }
6121: #endif
6122: if (!label) {
6123: ++Ndef;
6124: continue;
6125: }
6126: for (l = 0; l < Nl; ++l)
6127: if (label == labelSet[l]) break;
6128: if (l < Nl) continue;
6129: labelSet[Nl++] = label;
6130: }
6131: /* Create default DS if there are no labels to intersect with */
6132: PetscCall(DMGetRegionDS(dm, NULL, NULL, &dsDef, NULL));
6133: if (!dsDef && Ndef && !Nl) {
6134: IS fields;
6135: PetscInt *fld, nf;
6137: for (f = 0, nf = 0; f < Nf; ++f)
6138: if (!dm->fields[f].label) ++nf;
6139: PetscCheck(nf, comm, PETSC_ERR_PLIB, "All fields have labels, but we are trying to create a default DS");
6140: PetscCall(PetscMalloc1(nf, &fld));
6141: for (f = 0, nf = 0; f < Nf; ++f)
6142: if (!dm->fields[f].label) fld[nf++] = f;
6143: PetscCall(ISCreate(PETSC_COMM_SELF, &fields));
6144: PetscCall(PetscObjectSetOptionsPrefix((PetscObject)fields, "dm_fields_"));
6145: PetscCall(ISSetType(fields, ISGENERAL));
6146: PetscCall(ISGeneralSetIndices(fields, nf, fld, PETSC_OWN_POINTER));
6148: PetscCall(PetscDSCreate(PETSC_COMM_SELF, &dsDef));
6149: PetscCall(DMSetRegionDS(dm, NULL, fields, dsDef, NULL));
6150: PetscCall(PetscDSDestroy(&dsDef));
6151: PetscCall(ISDestroy(&fields));
6152: }
6153: PetscCall(DMGetRegionDS(dm, NULL, NULL, &dsDef, NULL));
6154: if (dsDef) PetscCall(PetscDSSetCoordinateDimension(dsDef, dE));
6155: /* Intersect labels with default fields */
6156: if (Ndef && Nl) {
6157: DM plex;
6158: DMLabel cellLabel;
6159: IS fieldIS, allcellIS, defcellIS = NULL;
6160: PetscInt *fields;
6161: const PetscInt *cells;
6162: PetscInt depth, nf = 0, n, c;
6164: PetscCall(DMConvert(dm, DMPLEX, &plex));
6165: PetscCall(DMPlexGetDepth(plex, &depth));
6166: PetscCall(DMGetStratumIS(plex, "dim", depth, &allcellIS));
6167: if (!allcellIS) PetscCall(DMGetStratumIS(plex, "depth", depth, &allcellIS));
6168: /* TODO This looks like it only works for one label */
6169: for (l = 0; l < Nl; ++l) {
6170: DMLabel label = labelSet[l];
6171: IS pointIS;
6173: PetscCall(ISDestroy(&defcellIS));
6174: PetscCall(DMLabelGetStratumIS(label, 1, &pointIS));
6175: PetscCall(ISDifference(allcellIS, pointIS, &defcellIS));
6176: PetscCall(ISDestroy(&pointIS));
6177: }
6178: PetscCall(ISDestroy(&allcellIS));
6180: PetscCall(DMLabelCreate(PETSC_COMM_SELF, "defaultCells", &cellLabel));
6181: PetscCall(ISGetLocalSize(defcellIS, &n));
6182: PetscCall(ISGetIndices(defcellIS, &cells));
6183: for (c = 0; c < n; ++c) PetscCall(DMLabelSetValue(cellLabel, cells[c], 1));
6184: PetscCall(ISRestoreIndices(defcellIS, &cells));
6185: PetscCall(ISDestroy(&defcellIS));
6186: PetscCall(DMPlexLabelComplete(plex, cellLabel));
6188: PetscCall(PetscMalloc1(Ndef, &fields));
6189: for (f = 0; f < Nf; ++f)
6190: if (!dm->fields[f].label) fields[nf++] = f;
6191: PetscCall(ISCreate(PETSC_COMM_SELF, &fieldIS));
6192: PetscCall(PetscObjectSetOptionsPrefix((PetscObject)fieldIS, "dm_fields_"));
6193: PetscCall(ISSetType(fieldIS, ISGENERAL));
6194: PetscCall(ISGeneralSetIndices(fieldIS, nf, fields, PETSC_OWN_POINTER));
6196: PetscCall(PetscDSCreate(PETSC_COMM_SELF, &dsDef));
6197: PetscCall(DMSetRegionDS(dm, cellLabel, fieldIS, dsDef, NULL));
6198: PetscCall(PetscDSSetCoordinateDimension(dsDef, dE));
6199: PetscCall(DMLabelDestroy(&cellLabel));
6200: PetscCall(PetscDSDestroy(&dsDef));
6201: PetscCall(ISDestroy(&fieldIS));
6202: PetscCall(DMDestroy(&plex));
6203: }
6204: /* Create label DSes
6205: - WE ONLY SUPPORT IDENTICAL OR DISJOINT LABELS
6206: */
6207: /* TODO Should check that labels are disjoint */
6208: for (l = 0; l < Nl; ++l) {
6209: DMLabel label = labelSet[l];
6210: PetscDS ds, dsIn = NULL;
6211: IS fields;
6212: PetscInt *fld, nf;
6214: PetscCall(PetscDSCreate(PETSC_COMM_SELF, &ds));
6215: for (f = 0, nf = 0; f < Nf; ++f)
6216: if (label == dm->fields[f].label || !dm->fields[f].label) ++nf;
6217: PetscCall(PetscMalloc1(nf, &fld));
6218: for (f = 0, nf = 0; f < Nf; ++f)
6219: if (label == dm->fields[f].label || !dm->fields[f].label) fld[nf++] = f;
6220: PetscCall(ISCreate(PETSC_COMM_SELF, &fields));
6221: PetscCall(PetscObjectSetOptionsPrefix((PetscObject)fields, "dm_fields_"));
6222: PetscCall(ISSetType(fields, ISGENERAL));
6223: PetscCall(ISGeneralSetIndices(fields, nf, fld, PETSC_OWN_POINTER));
6224: PetscCall(PetscDSSetCoordinateDimension(ds, dE));
6225: {
6226: DMPolytopeType ct;
6227: PetscInt lStart, lEnd;
6228: PetscBool isCohesiveLocal = PETSC_FALSE, isCohesive;
6230: PetscCall(DMLabelGetBounds(label, &lStart, &lEnd));
6231: if (lStart >= 0) {
6232: PetscCall(DMPlexGetCellType(dm, lStart, &ct));
6233: switch (ct) {
6234: case DM_POLYTOPE_POINT_PRISM_TENSOR:
6235: case DM_POLYTOPE_SEG_PRISM_TENSOR:
6236: case DM_POLYTOPE_TRI_PRISM_TENSOR:
6237: case DM_POLYTOPE_QUAD_PRISM_TENSOR:
6238: isCohesiveLocal = PETSC_TRUE;
6239: break;
6240: default:
6241: break;
6242: }
6243: }
6244: PetscCallMPI(MPIU_Allreduce(&isCohesiveLocal, &isCohesive, 1, MPI_C_BOOL, MPI_LOR, comm));
6245: if (isCohesive) {
6246: PetscCall(PetscDSCreate(PETSC_COMM_SELF, &dsIn));
6247: PetscCall(PetscDSSetCoordinateDimension(dsIn, dE));
6248: }
6249: for (f = 0, nf = 0; f < Nf; ++f) {
6250: if (label == dm->fields[f].label || !dm->fields[f].label) {
6251: if (label == dm->fields[f].label) {
6252: PetscCall(PetscDSSetDiscretization(ds, nf, NULL));
6253: PetscCall(PetscDSSetCohesive(ds, nf, isCohesive));
6254: if (dsIn) {
6255: PetscCall(PetscDSSetDiscretization(dsIn, nf, NULL));
6256: PetscCall(PetscDSSetCohesive(dsIn, nf, isCohesive));
6257: }
6258: }
6259: ++nf;
6260: }
6261: }
6262: }
6263: PetscCall(DMSetRegionDS(dm, label, fields, ds, dsIn));
6264: PetscCall(ISDestroy(&fields));
6265: PetscCall(PetscDSDestroy(&ds));
6266: PetscCall(PetscDSDestroy(&dsIn));
6267: }
6268: PetscCall(PetscFree(labelSet));
6269: /* Set fields in DSes */
6270: for (s = 0; s < dm->Nds; ++s) {
6271: PetscDS ds = dm->probs[s].ds;
6272: PetscDS dsIn = dm->probs[s].dsIn;
6273: IS fields = dm->probs[s].fields;
6274: const PetscInt *fld;
6275: PetscInt nf, dsnf;
6276: PetscBool isCohesive;
6278: PetscCall(PetscDSGetNumFields(ds, &dsnf));
6279: PetscCall(PetscDSIsCohesive(ds, &isCohesive));
6280: PetscCall(ISGetLocalSize(fields, &nf));
6281: PetscCall(ISGetIndices(fields, &fld));
6282: for (f = 0; f < nf; ++f) {
6283: PetscObject disc = dm->fields[fld[f]].disc;
6284: PetscBool isCohesiveField;
6285: PetscClassId id;
6287: /* Handle DS with no fields */
6288: if (dsnf) PetscCall(PetscDSGetCohesive(ds, f, &isCohesiveField));
6289: /* If this is a cohesive cell, then regular fields need the lower dimensional discretization */
6290: if (isCohesive) {
6291: if (!isCohesiveField) {
6292: PetscObject bdDisc;
6294: PetscCall(PetscFEGetHeightSubspace((PetscFE)disc, 1, (PetscFE *)&bdDisc));
6295: PetscCall(PetscDSSetDiscretization(ds, f, bdDisc));
6296: PetscCall(PetscDSSetDiscretization(dsIn, f, disc));
6297: } else {
6298: PetscCall(PetscDSSetDiscretization(ds, f, disc));
6299: PetscCall(PetscDSSetDiscretization(dsIn, f, disc));
6300: }
6301: } else {
6302: PetscCall(PetscDSSetDiscretization(ds, f, disc));
6303: }
6304: /* We allow people to have placeholder fields and construct the Section by hand */
6305: PetscCall(PetscObjectGetClassId(disc, &id));
6306: if ((id != PETSCFE_CLASSID) && (id != PETSCFV_CLASSID)) doSetup = PETSC_FALSE;
6307: }
6308: PetscCall(ISRestoreIndices(fields, &fld));
6309: }
6310: /* Allow k-jet tabulation */
6311: PetscCall(PetscOptionsGetInt(NULL, ((PetscObject)dm)->prefix, "-dm_ds_jet_degree", &k, &flg));
6312: if (flg) {
6313: for (s = 0; s < dm->Nds; ++s) {
6314: PetscDS ds = dm->probs[s].ds;
6315: PetscDS dsIn = dm->probs[s].dsIn;
6316: PetscInt Nf, f;
6318: PetscCall(PetscDSGetNumFields(ds, &Nf));
6319: for (f = 0; f < Nf; ++f) {
6320: PetscCall(PetscDSSetJetDegree(ds, f, k));
6321: if (dsIn) PetscCall(PetscDSSetJetDegree(dsIn, f, k));
6322: }
6323: }
6324: }
6325: /* Setup DSes */
6326: if (doSetup) {
6327: for (s = 0; s < dm->Nds; ++s) {
6328: if (dm->setfromoptionscalled) {
6329: PetscCall(PetscDSSetFromOptions(dm->probs[s].ds));
6330: if (dm->probs[s].dsIn) PetscCall(PetscDSSetFromOptions(dm->probs[s].dsIn));
6331: }
6332: PetscCall(PetscDSSetUp(dm->probs[s].ds));
6333: if (dm->probs[s].dsIn) PetscCall(PetscDSSetUp(dm->probs[s].dsIn));
6334: }
6335: }
6336: PetscFunctionReturn(PETSC_SUCCESS);
6337: }
6339: /*@
6340: DMUseTensorOrder - Use a tensor product closure ordering for the default section
6342: Input Parameters:
6343: + dm - The DM
6344: - tensor - Flag for tensor order
6346: Level: developer
6348: .seealso: `DMPlexSetClosurePermutationTensor()`, `PetscSectionResetClosurePermutation()`
6349: @*/
6350: PetscErrorCode DMUseTensorOrder(DM dm, PetscBool tensor)
6351: {
6352: PetscInt Nf;
6353: PetscBool reorder = PETSC_TRUE, isPlex;
6355: PetscFunctionBegin;
6356: PetscCall(PetscObjectTypeCompare((PetscObject)dm, DMPLEX, &isPlex));
6357: PetscCall(DMGetNumFields(dm, &Nf));
6358: for (PetscInt f = 0; f < Nf; ++f) {
6359: PetscObject obj;
6360: PetscClassId id;
6362: PetscCall(DMGetField(dm, f, NULL, &obj));
6363: PetscCall(PetscObjectGetClassId(obj, &id));
6364: if (id == PETSCFE_CLASSID) {
6365: PetscSpace sp;
6366: PetscBool tensor;
6368: PetscCall(PetscFEGetBasisSpace((PetscFE)obj, &sp));
6369: PetscCall(PetscSpacePolynomialGetTensor(sp, &tensor));
6370: reorder = reorder && tensor ? PETSC_TRUE : PETSC_FALSE;
6371: } else reorder = PETSC_FALSE;
6372: }
6373: if (tensor) {
6374: if (reorder && isPlex) PetscCall(DMPlexSetClosurePermutationTensor(dm, PETSC_DETERMINE, NULL));
6375: } else {
6376: PetscSection s;
6378: PetscCall(DMGetLocalSection(dm, &s));
6379: if (s) PetscCall(PetscSectionResetClosurePermutation(s));
6380: }
6381: PetscFunctionReturn(PETSC_SUCCESS);
6382: }
6384: /*@
6385: DMComputeExactSolution - Compute the exact solution for a given `DM`, using the `PetscDS` information.
6387: Collective
6389: Input Parameters:
6390: + dm - The `DM`
6391: - time - The time
6393: Output Parameters:
6394: + u - The vector will be filled with exact solution values, or `NULL`
6395: - u_t - The vector will be filled with the time derivative of exact solution values, or `NULL`
6397: Level: developer
6399: Note:
6400: The user must call `PetscDSSetExactSolution()` before using this routine
6402: .seealso: [](ch_dmbase), `DM`, `PetscDSSetExactSolution()`
6403: @*/
6404: PetscErrorCode DMComputeExactSolution(DM dm, PetscReal time, Vec u, Vec u_t)
6405: {
6406: PetscErrorCode (**exacts)(PetscInt, PetscReal, const PetscReal x[], PetscInt, PetscScalar *u, PetscCtx ctx);
6407: void **ectxs;
6408: Vec locu, locu_t;
6409: PetscInt Nf, Nds, s;
6411: PetscFunctionBegin;
6413: if (u) {
6415: PetscCall(DMGetLocalVector(dm, &locu));
6416: PetscCall(VecSet(locu, 0.));
6417: }
6418: if (u_t) {
6420: PetscCall(DMGetLocalVector(dm, &locu_t));
6421: PetscCall(VecSet(locu_t, 0.));
6422: }
6423: PetscCall(DMGetNumFields(dm, &Nf));
6424: PetscCall(PetscMalloc2(Nf, &exacts, Nf, &ectxs));
6425: PetscCall(DMGetNumDS(dm, &Nds));
6426: for (s = 0; s < Nds; ++s) {
6427: PetscDS ds;
6428: DMLabel label;
6429: IS fieldIS;
6430: const PetscInt *fields, id = 1;
6431: PetscInt dsNf, f;
6433: PetscCall(DMGetRegionNumDS(dm, s, &label, &fieldIS, &ds, NULL));
6434: PetscCall(PetscDSGetNumFields(ds, &dsNf));
6435: PetscCall(ISGetIndices(fieldIS, &fields));
6436: PetscCall(PetscArrayzero(exacts, Nf));
6437: PetscCall(PetscArrayzero(ectxs, Nf));
6438: if (u) {
6439: for (f = 0; f < dsNf; ++f) PetscCall(PetscDSGetExactSolution(ds, fields[f], &exacts[fields[f]], &ectxs[fields[f]]));
6440: if (label) PetscCall(DMProjectFunctionLabelLocal(dm, time, label, 1, &id, 0, NULL, exacts, ectxs, INSERT_ALL_VALUES, locu));
6441: else PetscCall(DMProjectFunctionLocal(dm, time, exacts, ectxs, INSERT_ALL_VALUES, locu));
6442: }
6443: if (u_t) {
6444: PetscCall(PetscArrayzero(exacts, Nf));
6445: PetscCall(PetscArrayzero(ectxs, Nf));
6446: for (f = 0; f < dsNf; ++f) PetscCall(PetscDSGetExactSolutionTimeDerivative(ds, fields[f], &exacts[fields[f]], &ectxs[fields[f]]));
6447: if (label) PetscCall(DMProjectFunctionLabelLocal(dm, time, label, 1, &id, 0, NULL, exacts, ectxs, INSERT_ALL_VALUES, locu_t));
6448: else PetscCall(DMProjectFunctionLocal(dm, time, exacts, ectxs, INSERT_ALL_VALUES, locu_t));
6449: }
6450: PetscCall(ISRestoreIndices(fieldIS, &fields));
6451: }
6452: if (u) {
6453: PetscCall(PetscObjectSetName((PetscObject)u, "Exact Solution"));
6454: PetscCall(PetscObjectSetOptionsPrefix((PetscObject)u, "exact_"));
6455: }
6456: if (u_t) {
6457: PetscCall(PetscObjectSetName((PetscObject)u, "Exact Solution Time Derivative"));
6458: PetscCall(PetscObjectSetOptionsPrefix((PetscObject)u_t, "exact_t_"));
6459: }
6460: PetscCall(PetscFree2(exacts, ectxs));
6461: if (u) {
6462: PetscCall(DMLocalToGlobalBegin(dm, locu, INSERT_ALL_VALUES, u));
6463: PetscCall(DMLocalToGlobalEnd(dm, locu, INSERT_ALL_VALUES, u));
6464: PetscCall(DMRestoreLocalVector(dm, &locu));
6465: }
6466: if (u_t) {
6467: PetscCall(DMLocalToGlobalBegin(dm, locu_t, INSERT_ALL_VALUES, u_t));
6468: PetscCall(DMLocalToGlobalEnd(dm, locu_t, INSERT_ALL_VALUES, u_t));
6469: PetscCall(DMRestoreLocalVector(dm, &locu_t));
6470: }
6471: PetscFunctionReturn(PETSC_SUCCESS);
6472: }
6474: static PetscErrorCode DMTransferDS_Internal(DM dm, DMLabel label, IS fields, PetscInt minDegree, PetscInt maxDegree, PetscDS ds, PetscDS dsIn)
6475: {
6476: PetscDS dsNew, dsInNew = NULL;
6478: PetscFunctionBegin;
6479: PetscCall(PetscDSCreate(PetscObjectComm((PetscObject)ds), &dsNew));
6480: PetscCall(PetscDSCopy(ds, minDegree, maxDegree, dm, dsNew));
6481: if (dsIn) {
6482: PetscCall(PetscDSCreate(PetscObjectComm((PetscObject)dsIn), &dsInNew));
6483: PetscCall(PetscDSCopy(dsIn, minDegree, maxDegree, dm, dsInNew));
6484: }
6485: PetscCall(DMSetRegionDS(dm, label, fields, dsNew, dsInNew));
6486: PetscCall(PetscDSDestroy(&dsNew));
6487: PetscCall(PetscDSDestroy(&dsInNew));
6488: PetscFunctionReturn(PETSC_SUCCESS);
6489: }
6491: /*@
6492: DMCopyDS - Copy the discrete systems for the `DM` into another `DM`
6494: Collective
6496: Input Parameters:
6497: + dm - The `DM`
6498: . minDegree - Minimum degree for a discretization, or `PETSC_DETERMINE` for no limit
6499: - maxDegree - Maximum degree for a discretization, or `PETSC_DETERMINE` for no limit
6501: Output Parameter:
6502: . newdm - The `DM`
6504: Level: advanced
6506: .seealso: [](ch_dmbase), `DM`, `DMCopyFields()`, `DMAddField()`, `DMGetDS()`, `DMGetCellDS()`, `DMGetRegionDS()`, `DMSetRegionDS()`
6507: @*/
6508: PetscErrorCode DMCopyDS(DM dm, PetscInt minDegree, PetscInt maxDegree, DM newdm)
6509: {
6510: PetscInt Nds, s;
6512: PetscFunctionBegin;
6513: if (dm == newdm) PetscFunctionReturn(PETSC_SUCCESS);
6514: PetscCall(DMGetNumDS(dm, &Nds));
6515: PetscCall(DMClearDS(newdm));
6516: for (s = 0; s < Nds; ++s) {
6517: DMLabel label;
6518: IS fields;
6519: PetscDS ds, dsIn, newds;
6520: PetscInt Nbd, bd;
6522: PetscCall(DMGetRegionNumDS(dm, s, &label, &fields, &ds, &dsIn));
6523: /* TODO: We need to change all keys from labels in the old DM to labels in the new DM */
6524: PetscCall(DMTransferDS_Internal(newdm, label, fields, minDegree, maxDegree, ds, dsIn));
6525: /* Complete new labels in the new DS */
6526: PetscCall(DMGetRegionDS(newdm, label, NULL, &newds, NULL));
6527: PetscCall(PetscDSGetNumBoundary(newds, &Nbd));
6528: for (bd = 0; bd < Nbd; ++bd) {
6529: PetscWeakForm wf;
6530: DMLabel label;
6531: PetscInt field;
6533: PetscCall(PetscDSGetBoundary(newds, bd, &wf, NULL, NULL, &label, NULL, NULL, &field, NULL, NULL, NULL, NULL, NULL));
6534: PetscCall(PetscWeakFormReplaceLabel(wf, label));
6535: }
6536: }
6537: PetscCall(DMCompleteBCLabels_Internal(newdm));
6538: PetscFunctionReturn(PETSC_SUCCESS);
6539: }
6541: /*@
6542: DMCopyDisc - Copy the fields and discrete systems for the `DM` into another `DM`
6544: Collective
6546: Input Parameter:
6547: . dm - The `DM`
6549: Output Parameter:
6550: . newdm - The `DM`
6552: Level: advanced
6554: Developer Note:
6555: Really ugly name, nothing in PETSc is called a `Disc` plus it is an ugly abbreviation
6557: .seealso: [](ch_dmbase), `DM`, `DMCopyFields()`, `DMCopyDS()`
6558: @*/
6559: PetscErrorCode DMCopyDisc(DM dm, DM newdm)
6560: {
6561: PetscFunctionBegin;
6562: PetscCall(DMCopyFields(dm, PETSC_DETERMINE, PETSC_DETERMINE, newdm));
6563: PetscCall(DMCopyDS(dm, PETSC_DETERMINE, PETSC_DETERMINE, newdm));
6564: PetscFunctionReturn(PETSC_SUCCESS);
6565: }
6567: /*@
6568: DMGetDimension - Return the topological dimension of the `DM`
6570: Not Collective
6572: Input Parameter:
6573: . dm - The `DM`
6575: Output Parameter:
6576: . dim - The topological dimension
6578: Level: beginner
6580: .seealso: [](ch_dmbase), `DM`, `DMSetDimension()`, `DMCreate()`
6581: @*/
6582: PetscErrorCode DMGetDimension(DM dm, PetscInt *dim)
6583: {
6584: PetscFunctionBegin;
6586: PetscAssertPointer(dim, 2);
6587: *dim = dm->dim;
6588: PetscFunctionReturn(PETSC_SUCCESS);
6589: }
6591: /*@
6592: DMSetDimension - Set the topological dimension of the `DM`
6594: Collective
6596: Input Parameters:
6597: + dm - The `DM`
6598: - dim - The topological dimension
6600: Level: beginner
6602: .seealso: [](ch_dmbase), `DM`, `DMGetDimension()`, `DMCreate()`
6603: @*/
6604: PetscErrorCode DMSetDimension(DM dm, PetscInt dim)
6605: {
6606: PetscDS ds;
6607: PetscInt Nds, n;
6609: PetscFunctionBegin;
6612: if (dm->dim != dim) PetscCall(DMSetPeriodicity(dm, NULL, NULL, NULL));
6613: dm->dim = dim;
6614: if (dm->dim >= 0) {
6615: PetscCall(DMGetNumDS(dm, &Nds));
6616: for (n = 0; n < Nds; ++n) {
6617: PetscCall(DMGetRegionNumDS(dm, n, NULL, NULL, &ds, NULL));
6618: if (ds->dimEmbed < 0) PetscCall(PetscDSSetCoordinateDimension(ds, dim));
6619: }
6620: }
6621: PetscFunctionReturn(PETSC_SUCCESS);
6622: }
6624: /*@
6625: DMGetDimPoints - Get the half-open interval for all points of a given dimension
6627: Collective
6629: Input Parameters:
6630: + dm - the `DM`
6631: - dim - the dimension
6633: Output Parameters:
6634: + pStart - The first point of the given dimension
6635: - pEnd - The first point following points of the given dimension
6637: Level: intermediate
6639: Note:
6640: The points are vertices in the Hasse diagram encoding the topology. This is explained in
6641: https://arxiv.org/abs/0908.4427. If no points exist of this dimension in the storage scheme,
6642: then the interval is empty.
6644: .seealso: [](ch_dmbase), `DM`, `DMPLEX`, `DMPlexGetDepthStratum()`, `DMPlexGetHeightStratum()`
6645: @*/
6646: PetscErrorCode DMGetDimPoints(DM dm, PetscInt dim, PetscInt *pStart, PetscInt *pEnd)
6647: {
6648: PetscInt d;
6650: PetscFunctionBegin;
6652: PetscCall(DMGetDimension(dm, &d));
6653: PetscCheck((dim >= 0) && (dim <= d), PetscObjectComm((PetscObject)dm), PETSC_ERR_ARG_OUTOFRANGE, "Invalid dimension %" PetscInt_FMT, dim);
6654: PetscUseTypeMethod(dm, getdimpoints, dim, pStart, pEnd);
6655: PetscFunctionReturn(PETSC_SUCCESS);
6656: }
6658: /*@
6659: DMGetOutputDM - Retrieve the `DM` associated with the layout for output
6661: Collective
6663: Input Parameter:
6664: . dm - The original `DM`
6666: Output Parameter:
6667: . odm - The `DM` which provides the layout for output
6669: Level: intermediate
6671: Note:
6672: In some situations the vector obtained with `DMCreateGlobalVector()` excludes points for degrees of freedom that are associated with fixed (Dirichelet) boundary
6673: conditions since the algebraic solver does not solve for those variables. The output `DM` includes these excluded points and its global vector contains the
6674: locations for those dof so that they can be output to a file or other viewer along with the unconstrained dof.
6676: .seealso: [](ch_dmbase), `DM`, `VecView()`, `DMGetGlobalSection()`, `DMCreateGlobalVector()`, `PetscSectionHasConstraints()`, `DMSetGlobalSection()`
6677: @*/
6678: PetscErrorCode DMGetOutputDM(DM dm, DM *odm)
6679: {
6680: PetscSection section;
6681: IS perm;
6682: PetscBool hasConstraints, newDM, gnewDM;
6683: PetscInt num_face_sfs = 0;
6685: PetscFunctionBegin;
6687: PetscAssertPointer(odm, 2);
6688: PetscCall(DMGetLocalSection(dm, §ion));
6689: PetscCall(PetscSectionHasConstraints(section, &hasConstraints));
6690: PetscCall(PetscSectionGetPermutation(section, &perm));
6691: PetscCall(DMPlexGetIsoperiodicFaceSF(dm, &num_face_sfs, NULL));
6692: newDM = hasConstraints || perm || (num_face_sfs > 0) ? PETSC_TRUE : PETSC_FALSE;
6693: PetscCallMPI(MPIU_Allreduce(&newDM, &gnewDM, 1, MPI_C_BOOL, MPI_LOR, PetscObjectComm((PetscObject)dm)));
6694: if (!gnewDM) {
6695: *odm = dm;
6696: PetscFunctionReturn(PETSC_SUCCESS);
6697: }
6698: if (!dm->dmBC) {
6699: PetscSection newSection, gsection;
6700: PetscSF sf, sfNatural;
6701: PetscBool usePerm = dm->ignorePermOutput ? PETSC_FALSE : PETSC_TRUE;
6703: PetscCall(DMClone(dm, &dm->dmBC));
6704: PetscCall(DMCopyDisc(dm, dm->dmBC));
6705: PetscCall(PetscSectionClone(section, &newSection));
6706: PetscCall(DMSetLocalSection(dm->dmBC, newSection));
6707: PetscCall(PetscSectionDestroy(&newSection));
6708: PetscCall(DMGetNaturalSF(dm, &sfNatural));
6709: PetscCall(DMSetNaturalSF(dm->dmBC, sfNatural));
6710: PetscCall(DMGetPointSF(dm->dmBC, &sf));
6711: PetscCall(PetscSectionCreateGlobalSection(section, sf, usePerm, PETSC_TRUE, PETSC_FALSE, &gsection));
6712: PetscCall(DMSetGlobalSection(dm->dmBC, gsection));
6713: PetscCall(PetscSectionDestroy(&gsection));
6714: }
6715: *odm = dm->dmBC;
6716: PetscFunctionReturn(PETSC_SUCCESS);
6717: }
6719: /*@
6720: DMGetOutputSequenceNumber - Retrieve the sequence number/value for output
6722: Input Parameter:
6723: . dm - The original `DM`
6725: Output Parameters:
6726: + num - The output sequence number
6727: - val - The output sequence value
6729: Level: intermediate
6731: Note:
6732: This is intended for output that should appear in sequence, for instance
6733: a set of timesteps in an `PETSCVIEWERHDF5` file, or a set of realizations of a stochastic system.
6735: Developer Note:
6736: The `DM` serves as a convenient place to store the current iteration value. The iteration is not
6737: not directly related to the `DM`.
6739: .seealso: [](ch_dmbase), `DM`, `VecView()`
6740: @*/
6741: PetscErrorCode DMGetOutputSequenceNumber(DM dm, PetscInt *num, PetscReal *val)
6742: {
6743: PetscFunctionBegin;
6745: if (num) {
6746: PetscAssertPointer(num, 2);
6747: *num = dm->outputSequenceNum;
6748: }
6749: if (val) {
6750: PetscAssertPointer(val, 3);
6751: *val = dm->outputSequenceVal;
6752: }
6753: PetscFunctionReturn(PETSC_SUCCESS);
6754: }
6756: /*@
6757: DMSetOutputSequenceNumber - Set the sequence number/value for output
6759: Input Parameters:
6760: + dm - The original `DM`
6761: . num - The output sequence number
6762: - val - The output sequence value
6764: Level: intermediate
6766: Note:
6767: This is intended for output that should appear in sequence, for instance
6768: a set of timesteps in an `PETSCVIEWERHDF5` file, or a set of realizations of a stochastic system.
6770: .seealso: [](ch_dmbase), `DM`, `VecView()`
6771: @*/
6772: PetscErrorCode DMSetOutputSequenceNumber(DM dm, PetscInt num, PetscReal val)
6773: {
6774: PetscFunctionBegin;
6776: dm->outputSequenceNum = num;
6777: dm->outputSequenceVal = val;
6778: PetscFunctionReturn(PETSC_SUCCESS);
6779: }
6781: /*@
6782: DMOutputSequenceLoad - Retrieve the sequence value from a `PetscViewer`
6784: Input Parameters:
6785: + dm - The original `DM`
6786: . viewer - The `PetscViewer` to get it from
6787: . name - The sequence name
6788: - num - The output sequence number
6790: Output Parameter:
6791: . val - The output sequence value
6793: Level: intermediate
6795: Note:
6796: This is intended for output that should appear in sequence, for instance
6797: a set of timesteps in an `PETSCVIEWERHDF5` file, or a set of realizations of a stochastic system.
6799: Developer Note:
6800: It is unclear at the user API level why a `DM` is needed as input
6802: .seealso: [](ch_dmbase), `DM`, `DMGetOutputSequenceNumber()`, `DMSetOutputSequenceNumber()`, `VecView()`
6803: @*/
6804: PetscErrorCode DMOutputSequenceLoad(DM dm, PetscViewer viewer, const char name[], PetscInt num, PetscReal *val)
6805: {
6806: PetscBool ishdf5;
6808: PetscFunctionBegin;
6811: PetscAssertPointer(name, 3);
6812: PetscAssertPointer(val, 5);
6813: PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERHDF5, &ishdf5));
6814: PetscCheck(ishdf5, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Invalid viewer; open viewer with PetscViewerHDF5Open()");
6815: #if defined(PETSC_HAVE_HDF5)
6816: PetscScalar value;
6818: PetscCall(DMSequenceLoad_HDF5_Internal(dm, name, num, &value, viewer));
6819: *val = PetscRealPart(value);
6820: #endif
6821: PetscFunctionReturn(PETSC_SUCCESS);
6822: }
6824: /*@
6825: DMGetOutputSequenceLength - Retrieve the number of sequence values from a `PetscViewer`
6827: Input Parameters:
6828: + dm - The original `DM`
6829: . viewer - The `PetscViewer` to get it from
6830: - name - The sequence name
6832: Output Parameter:
6833: . len - The length of the output sequence
6835: Level: intermediate
6837: Note:
6838: This is intended for output that should appear in sequence, for instance
6839: a set of timesteps in an `PETSCVIEWERHDF5` file, or a set of realizations of a stochastic system.
6841: Developer Note:
6842: It is unclear at the user API level why a `DM` is needed as input
6844: .seealso: [](ch_dmbase), `DM`, `DMGetOutputSequenceNumber()`, `DMSetOutputSequenceNumber()`, `VecView()`
6845: @*/
6846: PetscErrorCode DMGetOutputSequenceLength(DM dm, PetscViewer viewer, const char name[], PetscInt *len)
6847: {
6848: PetscBool ishdf5;
6850: PetscFunctionBegin;
6853: PetscAssertPointer(name, 3);
6854: PetscAssertPointer(len, 4);
6855: PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERHDF5, &ishdf5));
6856: PetscCheck(ishdf5, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Invalid viewer; open viewer with PetscViewerHDF5Open()");
6857: #if defined(PETSC_HAVE_HDF5)
6858: PetscCall(DMSequenceGetLength_HDF5_Internal(dm, name, len, viewer));
6859: #endif
6860: PetscFunctionReturn(PETSC_SUCCESS);
6861: }
6863: /*@
6864: DMGetUseNatural - Get the flag for creating a mapping to the natural order when a `DM` is (re)distributed in parallel
6866: Not Collective
6868: Input Parameter:
6869: . dm - The `DM`
6871: Output Parameter:
6872: . useNatural - `PETSC_TRUE` to build the mapping to a natural order during distribution
6874: Level: beginner
6876: .seealso: [](ch_dmbase), `DM`, `DMSetUseNatural()`, `DMCreate()`
6877: @*/
6878: PetscErrorCode DMGetUseNatural(DM dm, PetscBool *useNatural)
6879: {
6880: PetscFunctionBegin;
6882: PetscAssertPointer(useNatural, 2);
6883: *useNatural = dm->useNatural;
6884: PetscFunctionReturn(PETSC_SUCCESS);
6885: }
6887: /*@
6888: DMSetUseNatural - Set the flag for creating a mapping to the natural order when a `DM` is (re)distributed in parallel
6890: Collective
6892: Input Parameters:
6893: + dm - The `DM`
6894: - useNatural - `PETSC_TRUE` to build the mapping to a natural order during distribution
6896: Level: beginner
6898: Note:
6899: This also causes the map to be build after `DMCreateSubDM()` and `DMCreateSuperDM()`
6901: .seealso: [](ch_dmbase), `DM`, `DMGetUseNatural()`, `DMCreate()`, `DMPlexDistribute()`, `DMCreateSubDM()`, `DMCreateSuperDM()`
6902: @*/
6903: PetscErrorCode DMSetUseNatural(DM dm, PetscBool useNatural)
6904: {
6905: PetscFunctionBegin;
6908: dm->useNatural = useNatural;
6909: PetscFunctionReturn(PETSC_SUCCESS);
6910: }
6912: /*@
6913: DMCreateLabel - Create a label of the given name if it does not already exist in the `DM`
6915: Not Collective
6917: Input Parameters:
6918: + dm - The `DM` object
6919: - name - The label name
6921: Level: intermediate
6923: .seealso: [](ch_dmbase), `DM`, `DMLabelCreate()`, `DMHasLabel()`, `DMGetLabelValue()`, `DMSetLabelValue()`, `DMGetStratumIS()`
6924: @*/
6925: PetscErrorCode DMCreateLabel(DM dm, const char name[])
6926: {
6927: PetscBool flg;
6928: DMLabel label;
6930: PetscFunctionBegin;
6932: PetscAssertPointer(name, 2);
6933: PetscCall(DMHasLabel(dm, name, &flg));
6934: if (!flg) {
6935: PetscCall(DMLabelCreate(PETSC_COMM_SELF, name, &label));
6936: PetscCall(DMAddLabel(dm, label));
6937: PetscCall(DMLabelDestroy(&label));
6938: }
6939: PetscFunctionReturn(PETSC_SUCCESS);
6940: }
6942: /*@
6943: DMCreateLabelAtIndex - Create a label of the given name at the given index. If it already exists in the `DM`, move it to this index.
6945: Not Collective
6947: Input Parameters:
6948: + dm - The `DM` object
6949: . l - The index for the label
6950: - name - The label name
6952: Level: intermediate
6954: .seealso: [](ch_dmbase), `DM`, `DMCreateLabel()`, `DMLabelCreate()`, `DMHasLabel()`, `DMGetLabelValue()`, `DMSetLabelValue()`, `DMGetStratumIS()`
6955: @*/
6956: PetscErrorCode DMCreateLabelAtIndex(DM dm, PetscInt l, const char name[])
6957: {
6958: DMLabelLink orig, prev = NULL;
6959: DMLabel label;
6960: PetscInt Nl, m;
6961: PetscBool flg, match;
6962: const char *lname;
6964: PetscFunctionBegin;
6966: PetscAssertPointer(name, 3);
6967: PetscCall(DMHasLabel(dm, name, &flg));
6968: if (!flg) {
6969: PetscCall(DMLabelCreate(PETSC_COMM_SELF, name, &label));
6970: PetscCall(DMAddLabel(dm, label));
6971: PetscCall(DMLabelDestroy(&label));
6972: }
6973: PetscCall(DMGetNumLabels(dm, &Nl));
6974: PetscCheck(l < Nl, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Label index %" PetscInt_FMT " must be in [0, %" PetscInt_FMT ")", l, Nl);
6975: for (m = 0, orig = dm->labels; m < Nl; ++m, prev = orig, orig = orig->next) {
6976: PetscCall(PetscObjectGetName((PetscObject)orig->label, &lname));
6977: PetscCall(PetscStrcmp(name, lname, &match));
6978: if (match) break;
6979: }
6980: if (m == l) PetscFunctionReturn(PETSC_SUCCESS);
6981: if (!m) dm->labels = orig->next;
6982: else prev->next = orig->next;
6983: if (!l) {
6984: orig->next = dm->labels;
6985: dm->labels = orig;
6986: } else {
6987: for (m = 0, prev = dm->labels; m < l - 1; ++m, prev = prev->next);
6988: orig->next = prev->next;
6989: prev->next = orig;
6990: }
6991: PetscFunctionReturn(PETSC_SUCCESS);
6992: }
6994: /*@
6995: DMGetLabelValue - Get the value in a `DMLabel` for the given point, with -1 as the default
6997: Not Collective
6999: Input Parameters:
7000: + dm - The `DM` object
7001: . name - The label name
7002: - point - The mesh point
7004: Output Parameter:
7005: . value - The label value for this point, or -1 if the point is not in the label
7007: Level: beginner
7009: .seealso: [](ch_dmbase), `DM`, `DMLabelGetValue()`, `DMSetLabelValue()`, `DMGetStratumIS()`
7010: @*/
7011: PetscErrorCode DMGetLabelValue(DM dm, const char name[], PetscInt point, PetscInt *value)
7012: {
7013: DMLabel label;
7015: PetscFunctionBegin;
7017: PetscAssertPointer(name, 2);
7018: PetscCall(DMGetLabel(dm, name, &label));
7019: PetscCheck(label, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "No label named %s was found", name);
7020: PetscCall(DMLabelGetValue(label, point, value));
7021: PetscFunctionReturn(PETSC_SUCCESS);
7022: }
7024: /*@
7025: DMSetLabelValue - Add a point to a `DMLabel` with given value
7027: Not Collective
7029: Input Parameters:
7030: + dm - The `DM` object
7031: . name - The label name
7032: . point - The mesh point
7033: - value - The label value for this point
7035: Output Parameter:
7037: Level: beginner
7039: .seealso: [](ch_dmbase), `DM`, `DMLabelSetValue()`, `DMGetStratumIS()`, `DMClearLabelValue()`
7040: @*/
7041: PetscErrorCode DMSetLabelValue(DM dm, const char name[], PetscInt point, PetscInt value)
7042: {
7043: DMLabel label;
7045: PetscFunctionBegin;
7047: PetscAssertPointer(name, 2);
7048: PetscCall(DMGetLabel(dm, name, &label));
7049: if (!label) {
7050: PetscCall(DMCreateLabel(dm, name));
7051: PetscCall(DMGetLabel(dm, name, &label));
7052: }
7053: PetscCall(DMLabelSetValue(label, point, value));
7054: PetscFunctionReturn(PETSC_SUCCESS);
7055: }
7057: /*@
7058: DMClearLabelValue - Remove a point from a `DMLabel` with given value
7060: Not Collective
7062: Input Parameters:
7063: + dm - The `DM` object
7064: . name - The label name
7065: . point - The mesh point
7066: - value - The label value for this point
7068: Level: beginner
7070: .seealso: [](ch_dmbase), `DM`, `DMLabelClearValue()`, `DMSetLabelValue()`, `DMGetStratumIS()`
7071: @*/
7072: PetscErrorCode DMClearLabelValue(DM dm, const char name[], PetscInt point, PetscInt value)
7073: {
7074: DMLabel label;
7076: PetscFunctionBegin;
7078: PetscAssertPointer(name, 2);
7079: PetscCall(DMGetLabel(dm, name, &label));
7080: if (!label) PetscFunctionReturn(PETSC_SUCCESS);
7081: PetscCall(DMLabelClearValue(label, point, value));
7082: PetscFunctionReturn(PETSC_SUCCESS);
7083: }
7085: /*@
7086: DMGetLabelSize - Get the value of `DMLabelGetNumValues()` of a `DMLabel` in the `DM`
7088: Not Collective
7090: Input Parameters:
7091: + dm - The `DM` object
7092: - name - The label name
7094: Output Parameter:
7095: . size - The number of different integer ids, or 0 if the label does not exist
7097: Level: beginner
7099: Developer Note:
7100: This should be renamed to something like `DMGetLabelNumValues()` or removed.
7102: .seealso: [](ch_dmbase), `DM`, `DMLabelGetNumValues()`, `DMSetLabelValue()`, `DMGetLabel()`
7103: @*/
7104: PetscErrorCode DMGetLabelSize(DM dm, const char name[], PetscInt *size)
7105: {
7106: DMLabel label;
7108: PetscFunctionBegin;
7110: PetscAssertPointer(name, 2);
7111: PetscAssertPointer(size, 3);
7112: PetscCall(DMGetLabel(dm, name, &label));
7113: *size = 0;
7114: if (!label) PetscFunctionReturn(PETSC_SUCCESS);
7115: PetscCall(DMLabelGetNumValues(label, size));
7116: PetscFunctionReturn(PETSC_SUCCESS);
7117: }
7119: /*@
7120: DMGetLabelIdIS - Get the `DMLabelGetValueIS()` from a `DMLabel` in the `DM`
7122: Not Collective
7124: Input Parameters:
7125: + dm - The `DM` object
7126: - name - The label name
7128: Output Parameter:
7129: . ids - The integer ids, or `NULL` if the label does not exist
7131: Level: beginner
7133: .seealso: [](ch_dmbase), `DM`, `DMLabelGetValueIS()`, `DMGetLabelSize()`
7134: @*/
7135: PetscErrorCode DMGetLabelIdIS(DM dm, const char name[], IS *ids)
7136: {
7137: DMLabel label;
7139: PetscFunctionBegin;
7141: PetscAssertPointer(name, 2);
7142: PetscAssertPointer(ids, 3);
7143: PetscCall(DMGetLabel(dm, name, &label));
7144: *ids = NULL;
7145: if (label) PetscCall(DMLabelGetValueIS(label, ids));
7146: else {
7147: /* returning an empty IS */
7148: PetscCall(ISCreateGeneral(PETSC_COMM_SELF, 0, NULL, PETSC_USE_POINTER, ids));
7149: }
7150: PetscFunctionReturn(PETSC_SUCCESS);
7151: }
7153: /*@
7154: DMGetStratumSize - Get the number of points in a label stratum
7156: Not Collective
7158: Input Parameters:
7159: + dm - The `DM` object
7160: . name - The label name of the stratum
7161: - value - The stratum value
7163: Output Parameter:
7164: . size - The number of points, also called the stratum size
7166: Level: beginner
7168: .seealso: [](ch_dmbase), `DM`, `DMLabelGetStratumSize()`, `DMGetLabelSize()`, `DMGetLabelIds()`
7169: @*/
7170: PetscErrorCode DMGetStratumSize(DM dm, const char name[], PetscInt value, PetscInt *size)
7171: {
7172: DMLabel label;
7174: PetscFunctionBegin;
7176: PetscAssertPointer(name, 2);
7177: PetscAssertPointer(size, 4);
7178: PetscCall(DMGetLabel(dm, name, &label));
7179: *size = 0;
7180: if (!label) PetscFunctionReturn(PETSC_SUCCESS);
7181: PetscCall(DMLabelGetStratumSize(label, value, size));
7182: PetscFunctionReturn(PETSC_SUCCESS);
7183: }
7185: /*@
7186: DMGetStratumIS - Get the points in a label stratum
7188: Not Collective
7190: Input Parameters:
7191: + dm - The `DM` object
7192: . name - The label name
7193: - value - The stratum value
7195: Output Parameter:
7196: . points - The stratum points, or `NULL` if the label does not exist or does not have that value
7198: Level: beginner
7200: .seealso: [](ch_dmbase), `DM`, `DMLabelGetStratumIS()`, `DMGetStratumSize()`
7201: @*/
7202: PetscErrorCode DMGetStratumIS(DM dm, const char name[], PetscInt value, IS *points)
7203: {
7204: DMLabel label;
7206: PetscFunctionBegin;
7208: PetscAssertPointer(name, 2);
7209: PetscAssertPointer(points, 4);
7210: PetscCall(DMGetLabel(dm, name, &label));
7211: *points = NULL;
7212: if (!label) PetscFunctionReturn(PETSC_SUCCESS);
7213: PetscCall(DMLabelGetStratumIS(label, value, points));
7214: PetscFunctionReturn(PETSC_SUCCESS);
7215: }
7217: /*@
7218: DMSetStratumIS - Set the points in a label stratum
7220: Not Collective
7222: Input Parameters:
7223: + dm - The `DM` object
7224: . name - The label name
7225: . value - The stratum value
7226: - points - The stratum points
7228: Level: beginner
7230: .seealso: [](ch_dmbase), `DM`, `DMLabel`, `DMClearLabelStratum()`, `DMLabelClearStratum()`, `DMLabelSetStratumIS()`, `DMGetStratumSize()`
7231: @*/
7232: PetscErrorCode DMSetStratumIS(DM dm, const char name[], PetscInt value, IS points)
7233: {
7234: DMLabel label;
7236: PetscFunctionBegin;
7238: PetscAssertPointer(name, 2);
7240: PetscCall(DMGetLabel(dm, name, &label));
7241: if (!label) PetscFunctionReturn(PETSC_SUCCESS);
7242: PetscCall(DMLabelSetStratumIS(label, value, points));
7243: PetscFunctionReturn(PETSC_SUCCESS);
7244: }
7246: /*@
7247: DMClearLabelStratum - Remove all points from a stratum from a `DMLabel`
7249: Not Collective
7251: Input Parameters:
7252: + dm - The `DM` object
7253: . name - The label name
7254: - value - The label value for this point
7256: Output Parameter:
7258: Level: beginner
7260: .seealso: [](ch_dmbase), `DM`, `DMLabel`, `DMLabelClearStratum()`, `DMSetLabelValue()`, `DMGetStratumIS()`, `DMClearLabelValue()`
7261: @*/
7262: PetscErrorCode DMClearLabelStratum(DM dm, const char name[], PetscInt value)
7263: {
7264: DMLabel label;
7266: PetscFunctionBegin;
7268: PetscAssertPointer(name, 2);
7269: PetscCall(DMGetLabel(dm, name, &label));
7270: if (!label) PetscFunctionReturn(PETSC_SUCCESS);
7271: PetscCall(DMLabelClearStratum(label, value));
7272: PetscFunctionReturn(PETSC_SUCCESS);
7273: }
7275: /*@
7276: DMGetNumLabels - Return the number of labels defined by on the `DM`
7278: Not Collective
7280: Input Parameter:
7281: . dm - The `DM` object
7283: Output Parameter:
7284: . numLabels - the number of Labels
7286: Level: intermediate
7288: .seealso: [](ch_dmbase), `DM`, `DMLabel`, `DMGetLabelByNum()`, `DMGetLabelName()`, `DMGetLabelValue()`, `DMSetLabelValue()`, `DMGetStratumIS()`
7289: @*/
7290: PetscErrorCode DMGetNumLabels(DM dm, PetscInt *numLabels)
7291: {
7292: DMLabelLink next = dm->labels;
7293: PetscInt n = 0;
7295: PetscFunctionBegin;
7297: PetscAssertPointer(numLabels, 2);
7298: while (next) {
7299: ++n;
7300: next = next->next;
7301: }
7302: *numLabels = n;
7303: PetscFunctionReturn(PETSC_SUCCESS);
7304: }
7306: /*@
7307: DMGetLabelName - Return the name of nth label
7309: Not Collective
7311: Input Parameters:
7312: + dm - The `DM` object
7313: - n - the label number
7315: Output Parameter:
7316: . name - the label name
7318: Level: intermediate
7320: Developer Note:
7321: Some of the functions that appropriate on labels using their number have the suffix ByNum, others do not.
7323: .seealso: [](ch_dmbase), `DM`, `DMLabel`, `DMGetLabelByNum()`, `DMGetLabel()`, `DMGetLabelValue()`, `DMSetLabelValue()`, `DMGetStratumIS()`
7324: @*/
7325: PetscErrorCode DMGetLabelName(DM dm, PetscInt n, const char *name[])
7326: {
7327: DMLabelLink next = dm->labels;
7328: PetscInt l = 0;
7330: PetscFunctionBegin;
7332: PetscAssertPointer(name, 3);
7333: while (next) {
7334: if (l == n) {
7335: PetscCall(PetscObjectGetName((PetscObject)next->label, name));
7336: PetscFunctionReturn(PETSC_SUCCESS);
7337: }
7338: ++l;
7339: next = next->next;
7340: }
7341: SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Label %" PetscInt_FMT " does not exist in this DM", n);
7342: }
7344: /*@
7345: DMHasLabel - Determine whether the `DM` has a label of a given name
7347: Not Collective
7349: Input Parameters:
7350: + dm - The `DM` object
7351: - name - The label name
7353: Output Parameter:
7354: . hasLabel - `PETSC_TRUE` if the label is present
7356: Level: intermediate
7358: .seealso: [](ch_dmbase), `DM`, `DMLabel`, `DMGetLabel()`, `DMGetLabelByNum()`, `DMCreateLabel()`, `DMGetLabelValue()`, `DMSetLabelValue()`, `DMGetStratumIS()`
7359: @*/
7360: PetscErrorCode DMHasLabel(DM dm, const char name[], PetscBool *hasLabel)
7361: {
7362: DMLabelLink next = dm->labels;
7363: const char *lname;
7365: PetscFunctionBegin;
7367: PetscAssertPointer(name, 2);
7368: PetscAssertPointer(hasLabel, 3);
7369: *hasLabel = PETSC_FALSE;
7370: while (next) {
7371: PetscCall(PetscObjectGetName((PetscObject)next->label, &lname));
7372: PetscCall(PetscStrcmp(name, lname, hasLabel));
7373: if (*hasLabel) break;
7374: next = next->next;
7375: }
7376: PetscFunctionReturn(PETSC_SUCCESS);
7377: }
7379: // PetscClangLinter pragma ignore: -fdoc-section-header-unknown
7380: /*@
7381: DMGetLabel - Return the label of a given name, or `NULL`, from a `DM`
7383: Not Collective
7385: Input Parameters:
7386: + dm - The `DM` object
7387: - name - The label name
7389: Output Parameter:
7390: . label - The `DMLabel`, or `NULL` if the label is absent
7392: Default labels in a `DMPLEX`:
7393: + "depth" - Holds the depth (co-dimension) of each mesh point
7394: . "celltype" - Holds the topological type of each cell
7395: . "ghost" - If the DM is distributed with overlap, this marks the cells and faces in the overlap
7396: . "Cell Sets" - Mirrors the cell sets defined by GMsh and ExodusII
7397: . "Face Sets" - Mirrors the face sets defined by GMsh and ExodusII
7398: - "Vertex Sets" - Mirrors the vertex sets defined by GMsh
7400: Level: intermediate
7402: .seealso: [](ch_dmbase), `DM`, `DMLabel`, `DMHasLabel()`, `DMGetLabelByNum()`, `DMAddLabel()`, `DMCreateLabel()`, `DMPlexGetDepthLabel()`, `DMPlexGetCellType()`
7403: @*/
7404: PetscErrorCode DMGetLabel(DM dm, const char name[], DMLabel *label)
7405: {
7406: DMLabelLink next = dm->labels;
7407: PetscBool hasLabel;
7408: const char *lname;
7410: PetscFunctionBegin;
7412: PetscAssertPointer(name, 2);
7413: PetscAssertPointer(label, 3);
7414: *label = NULL;
7415: while (next) {
7416: PetscCall(PetscObjectGetName((PetscObject)next->label, &lname));
7417: PetscCall(PetscStrcmp(name, lname, &hasLabel));
7418: if (hasLabel) {
7419: *label = next->label;
7420: break;
7421: }
7422: next = next->next;
7423: }
7424: PetscFunctionReturn(PETSC_SUCCESS);
7425: }
7427: /*@
7428: DMGetLabelByNum - Return the nth label on a `DM`
7430: Not Collective
7432: Input Parameters:
7433: + dm - The `DM` object
7434: - n - the label number
7436: Output Parameter:
7437: . label - the label
7439: Level: intermediate
7441: .seealso: [](ch_dmbase), `DM`, `DMLabel`, `DMAddLabel()`, `DMGetLabelValue()`, `DMSetLabelValue()`, `DMGetStratumIS()`
7442: @*/
7443: PetscErrorCode DMGetLabelByNum(DM dm, PetscInt n, DMLabel *label)
7444: {
7445: DMLabelLink next = dm->labels;
7446: PetscInt l = 0;
7448: PetscFunctionBegin;
7450: PetscAssertPointer(label, 3);
7451: while (next) {
7452: if (l == n) {
7453: *label = next->label;
7454: PetscFunctionReturn(PETSC_SUCCESS);
7455: }
7456: ++l;
7457: next = next->next;
7458: }
7459: SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Label %" PetscInt_FMT " does not exist in this DM", n);
7460: }
7462: /*@
7463: DMAddLabel - Add the label to this `DM`
7465: Not Collective
7467: Input Parameters:
7468: + dm - The `DM` object
7469: - label - The `DMLabel`
7471: Level: developer
7473: .seealso: [](ch_dmbase), `DM`, `DMLabel`, `DMCreateLabel()`, `DMHasLabel()`, `DMGetLabelValue()`, `DMSetLabelValue()`, `DMGetStratumIS()`
7474: @*/
7475: PetscErrorCode DMAddLabel(DM dm, DMLabel label)
7476: {
7477: DMLabelLink l, *p, tmpLabel;
7478: PetscBool hasLabel;
7479: const char *lname;
7480: PetscBool flg;
7482: PetscFunctionBegin;
7484: PetscCall(PetscObjectGetName((PetscObject)label, &lname));
7485: PetscCall(DMHasLabel(dm, lname, &hasLabel));
7486: PetscCheck(!hasLabel, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Label %s already exists in this DM", lname);
7487: PetscCall(PetscCalloc1(1, &tmpLabel));
7488: tmpLabel->label = label;
7489: tmpLabel->output = PETSC_TRUE;
7490: for (p = &dm->labels; (l = *p); p = &l->next) { }
7491: *p = tmpLabel;
7492: PetscCall(PetscObjectReference((PetscObject)label));
7493: PetscCall(PetscStrcmp(lname, "depth", &flg));
7494: if (flg) dm->depthLabel = label;
7495: PetscCall(PetscStrcmp(lname, "celltype", &flg));
7496: if (flg) dm->celltypeLabel = label;
7497: PetscFunctionReturn(PETSC_SUCCESS);
7498: }
7500: // PetscClangLinter pragma ignore: -fdoc-section-header-unknown
7501: /*@
7502: DMSetLabel - Replaces the label of a given name, or ignores it if the name is not present
7504: Not Collective
7506: Input Parameters:
7507: + dm - The `DM` object
7508: - label - The `DMLabel`, having the same name, to substitute
7510: Default labels in a `DMPLEX`:
7511: + "depth" - Holds the depth (co-dimension) of each mesh point
7512: . "celltype" - Holds the topological type of each cell
7513: . "ghost" - If the DM is distributed with overlap, this marks the cells and faces in the overlap
7514: . "Cell Sets" - Mirrors the cell sets defined by GMsh and ExodusII
7515: . "Face Sets" - Mirrors the face sets defined by GMsh and ExodusII
7516: - "Vertex Sets" - Mirrors the vertex sets defined by GMsh
7518: Level: intermediate
7520: .seealso: [](ch_dmbase), `DM`, `DMLabel`, `DMCreateLabel()`, `DMHasLabel()`, `DMPlexGetDepthLabel()`, `DMPlexGetCellType()`
7521: @*/
7522: PetscErrorCode DMSetLabel(DM dm, DMLabel label)
7523: {
7524: DMLabelLink next = dm->labels;
7525: PetscBool hasLabel, flg;
7526: const char *name, *lname;
7528: PetscFunctionBegin;
7531: PetscCall(PetscObjectGetName((PetscObject)label, &name));
7532: while (next) {
7533: PetscCall(PetscObjectGetName((PetscObject)next->label, &lname));
7534: PetscCall(PetscStrcmp(name, lname, &hasLabel));
7535: if (hasLabel) {
7536: PetscCall(PetscObjectReference((PetscObject)label));
7537: PetscCall(PetscStrcmp(lname, "depth", &flg));
7538: if (flg) dm->depthLabel = label;
7539: PetscCall(PetscStrcmp(lname, "celltype", &flg));
7540: if (flg) dm->celltypeLabel = label;
7541: PetscCall(DMLabelDestroy(&next->label));
7542: next->label = label;
7543: break;
7544: }
7545: next = next->next;
7546: }
7547: PetscFunctionReturn(PETSC_SUCCESS);
7548: }
7550: /*@
7551: DMRemoveLabel - Remove the label given by name from this `DM`
7553: Not Collective
7555: Input Parameters:
7556: + dm - The `DM` object
7557: - name - The label name
7559: Output Parameter:
7560: . label - The `DMLabel`, or `NULL` if the label is absent. Pass in `NULL` to call `DMLabelDestroy()` on the label, otherwise the
7561: caller is responsible for calling `DMLabelDestroy()`.
7563: Level: developer
7565: .seealso: [](ch_dmbase), `DM`, `DMLabel`, `DMCreateLabel()`, `DMHasLabel()`, `DMGetLabel()`, `DMGetLabelValue()`, `DMSetLabelValue()`, `DMLabelDestroy()`, `DMRemoveLabelBySelf()`
7566: @*/
7567: PetscErrorCode DMRemoveLabel(DM dm, const char name[], DMLabel *label)
7568: {
7569: DMLabelLink link, *pnext;
7570: PetscBool hasLabel;
7571: const char *lname;
7573: PetscFunctionBegin;
7575: PetscAssertPointer(name, 2);
7576: if (label) {
7577: PetscAssertPointer(label, 3);
7578: *label = NULL;
7579: }
7580: for (pnext = &dm->labels; (link = *pnext); pnext = &link->next) {
7581: PetscCall(PetscObjectGetName((PetscObject)link->label, &lname));
7582: PetscCall(PetscStrcmp(name, lname, &hasLabel));
7583: if (hasLabel) {
7584: *pnext = link->next; /* Remove from list */
7585: PetscCall(PetscStrcmp(name, "depth", &hasLabel));
7586: if (hasLabel) dm->depthLabel = NULL;
7587: PetscCall(PetscStrcmp(name, "celltype", &hasLabel));
7588: if (hasLabel) dm->celltypeLabel = NULL;
7589: if (label) *label = link->label;
7590: else PetscCall(DMLabelDestroy(&link->label));
7591: PetscCall(PetscFree(link));
7592: break;
7593: }
7594: }
7595: PetscFunctionReturn(PETSC_SUCCESS);
7596: }
7598: /*@
7599: DMRemoveLabelBySelf - Remove the label from this `DM`
7601: Not Collective
7603: Input Parameters:
7604: + dm - The `DM` object
7605: . label - The `DMLabel` to be removed from the `DM`
7606: - failNotFound - Should it fail if the label is not found in the `DM`?
7608: Level: developer
7610: Note:
7611: Only exactly the same instance is removed if found, name match is ignored.
7612: If the `DM` has an exclusive reference to the label, the label gets destroyed and
7613: *label nullified.
7615: .seealso: [](ch_dmbase), `DM`, `DMLabel`, `DMCreateLabel()`, `DMHasLabel()`, `DMGetLabel()`, `DMGetLabelValue()`, `DMSetLabelValue()`, `DMLabelDestroy()`, `DMRemoveLabel()`
7616: @*/
7617: PetscErrorCode DMRemoveLabelBySelf(DM dm, DMLabel *label, PetscBool failNotFound)
7618: {
7619: DMLabelLink link, *pnext;
7620: PetscBool hasLabel = PETSC_FALSE;
7622: PetscFunctionBegin;
7624: PetscAssertPointer(label, 2);
7625: if (!*label && !failNotFound) PetscFunctionReturn(PETSC_SUCCESS);
7628: for (pnext = &dm->labels; (link = *pnext); pnext = &link->next) {
7629: if (*label == link->label) {
7630: hasLabel = PETSC_TRUE;
7631: *pnext = link->next; /* Remove from list */
7632: if (*label == dm->depthLabel) dm->depthLabel = NULL;
7633: if (*label == dm->celltypeLabel) dm->celltypeLabel = NULL;
7634: if (((PetscObject)link->label)->refct < 2) *label = NULL; /* nullify if exclusive reference */
7635: PetscCall(DMLabelDestroy(&link->label));
7636: PetscCall(PetscFree(link));
7637: break;
7638: }
7639: }
7640: PetscCheck(hasLabel || !failNotFound, PetscObjectComm((PetscObject)dm), PETSC_ERR_ARG_WRONG, "Given label not found in DM");
7641: PetscFunctionReturn(PETSC_SUCCESS);
7642: }
7644: /*@
7645: DMGetLabelOutput - Get the output flag for a given label
7647: Not Collective
7649: Input Parameters:
7650: + dm - The `DM` object
7651: - name - The label name
7653: Output Parameter:
7654: . output - The flag for output
7656: Level: developer
7658: .seealso: [](ch_dmbase), `DM`, `DMLabel`, `DMSetLabelOutput()`, `DMCreateLabel()`, `DMHasLabel()`, `DMGetLabelValue()`, `DMSetLabelValue()`, `DMGetStratumIS()`
7659: @*/
7660: PetscErrorCode DMGetLabelOutput(DM dm, const char name[], PetscBool *output)
7661: {
7662: DMLabelLink next = dm->labels;
7663: const char *lname;
7665: PetscFunctionBegin;
7667: PetscAssertPointer(name, 2);
7668: PetscAssertPointer(output, 3);
7669: while (next) {
7670: PetscBool flg;
7672: PetscCall(PetscObjectGetName((PetscObject)next->label, &lname));
7673: PetscCall(PetscStrcmp(name, lname, &flg));
7674: if (flg) {
7675: *output = next->output;
7676: PetscFunctionReturn(PETSC_SUCCESS);
7677: }
7678: next = next->next;
7679: }
7680: SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "No label named %s was present in this dm", name);
7681: }
7683: /*@
7684: DMSetLabelOutput - Set if a given label should be saved to a `PetscViewer` in calls to `DMView()`
7686: Not Collective
7688: Input Parameters:
7689: + dm - The `DM` object
7690: . name - The label name
7691: - output - `PETSC_TRUE` to save the label to the viewer
7693: Level: developer
7695: .seealso: [](ch_dmbase), `DM`, `DMLabel`, `DMGetOutputFlag()`, `DMGetLabelOutput()`, `DMCreateLabel()`, `DMHasLabel()`, `DMGetLabelValue()`, `DMSetLabelValue()`, `DMGetStratumIS()`
7696: @*/
7697: PetscErrorCode DMSetLabelOutput(DM dm, const char name[], PetscBool output)
7698: {
7699: DMLabelLink next = dm->labels;
7700: const char *lname;
7702: PetscFunctionBegin;
7704: PetscAssertPointer(name, 2);
7705: while (next) {
7706: PetscBool flg;
7708: PetscCall(PetscObjectGetName((PetscObject)next->label, &lname));
7709: PetscCall(PetscStrcmp(name, lname, &flg));
7710: if (flg) {
7711: next->output = output;
7712: PetscFunctionReturn(PETSC_SUCCESS);
7713: }
7714: next = next->next;
7715: }
7716: SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "No label named %s was present in this dm", name);
7717: }
7719: /*@
7720: DMCopyLabels - Copy labels from one `DM` mesh to another `DM` with a superset of the points
7722: Collective
7724: Input Parameters:
7725: + dmA - The `DM` object with initial labels
7726: . dmB - The `DM` object to which labels are copied
7727: . mode - Copy labels by pointers (`PETSC_OWN_POINTER`) or duplicate them (`PETSC_COPY_VALUES`)
7728: . all - Copy all labels including "depth", "dim", and "celltype" (`PETSC_TRUE`) which are otherwise ignored (`PETSC_FALSE`)
7729: - emode - How to behave when a `DMLabel` in the source and destination `DM`s with the same name is encountered (see `DMCopyLabelsMode`)
7731: Level: intermediate
7733: Note:
7734: This is typically used when interpolating or otherwise adding to a mesh, or testing.
7736: .seealso: [](ch_dmbase), `DM`, `DMLabel`, `DMAddLabel()`, `DMCopyLabelsMode`
7737: @*/
7738: PetscErrorCode DMCopyLabels(DM dmA, DM dmB, PetscCopyMode mode, PetscBool all, DMCopyLabelsMode emode)
7739: {
7740: DMLabel label, labelNew, labelOld;
7741: const char *name;
7742: PetscBool flg;
7743: DMLabelLink link;
7745: PetscFunctionBegin;
7750: PetscCheck(mode != PETSC_USE_POINTER, PetscObjectComm((PetscObject)dmA), PETSC_ERR_SUP, "PETSC_USE_POINTER not supported for objects");
7751: if (dmA == dmB) PetscFunctionReturn(PETSC_SUCCESS);
7752: for (link = dmA->labels; link; link = link->next) {
7753: label = link->label;
7754: PetscCall(PetscObjectGetName((PetscObject)label, &name));
7755: if (!all) {
7756: PetscCall(PetscStrcmp(name, "depth", &flg));
7757: if (flg) continue;
7758: PetscCall(PetscStrcmp(name, "dim", &flg));
7759: if (flg) continue;
7760: PetscCall(PetscStrcmp(name, "celltype", &flg));
7761: if (flg) continue;
7762: }
7763: PetscCall(DMGetLabel(dmB, name, &labelOld));
7764: if (labelOld) {
7765: switch (emode) {
7766: case DM_COPY_LABELS_KEEP:
7767: continue;
7768: case DM_COPY_LABELS_REPLACE:
7769: PetscCall(DMRemoveLabelBySelf(dmB, &labelOld, PETSC_TRUE));
7770: break;
7771: case DM_COPY_LABELS_FAIL:
7772: SETERRQ(PetscObjectComm((PetscObject)dmA), PETSC_ERR_ARG_OUTOFRANGE, "Label %s already exists in destination DM", name);
7773: default:
7774: SETERRQ(PetscObjectComm((PetscObject)dmA), PETSC_ERR_ARG_OUTOFRANGE, "Unhandled DMCopyLabelsMode %d", (int)emode);
7775: }
7776: }
7777: if (mode == PETSC_COPY_VALUES) PetscCall(DMLabelDuplicate(label, &labelNew));
7778: else labelNew = label;
7779: PetscCall(DMAddLabel(dmB, labelNew));
7780: if (mode == PETSC_COPY_VALUES) PetscCall(DMLabelDestroy(&labelNew));
7781: }
7782: PetscFunctionReturn(PETSC_SUCCESS);
7783: }
7785: /*@C
7786: DMCompareLabels - Compare labels between two `DM` objects
7788: Collective; No Fortran Support
7790: Input Parameters:
7791: + dm0 - First `DM` object
7792: - dm1 - Second `DM` object
7794: Output Parameters:
7795: + equal - (Optional) Flag whether labels of `dm0` and `dm1` are the same
7796: - message - (Optional) Message describing the difference, or `NULL` if there is no difference
7798: Level: intermediate
7800: Notes:
7801: The output flag equal will be the same on all processes.
7803: If equal is passed as `NULL` and difference is found, an error is thrown on all processes.
7805: Make sure to pass equal is `NULL` on all processes or none of them.
7807: The output message is set independently on each rank.
7809: message must be freed with `PetscFree()`
7811: If message is passed as `NULL` and a difference is found, the difference description is printed to `stderr` in synchronized manner.
7813: Make sure to pass message as `NULL` on all processes or no processes.
7815: Labels are matched by name. If the number of labels and their names are equal,
7816: `DMLabelCompare()` is used to compare each pair of labels with the same name.
7818: Developer Note:
7819: Cannot automatically generate the Fortran stub because `message` must be freed with `PetscFree()`
7821: .seealso: [](ch_dmbase), `DM`, `DMLabel`, `DMAddLabel()`, `DMCopyLabelsMode`, `DMLabelCompare()`
7822: @*/
7823: PetscErrorCode DMCompareLabels(DM dm0, DM dm1, PetscBool *equal, char *message[]) PeNS
7824: {
7825: PetscInt n, i;
7826: char msg[PETSC_MAX_PATH_LEN] = "";
7827: PetscBool eq;
7828: MPI_Comm comm;
7829: PetscMPIInt rank;
7831: PetscFunctionBegin;
7834: PetscCheckSameComm(dm0, 1, dm1, 2);
7835: if (equal) PetscAssertPointer(equal, 3);
7836: if (message) PetscAssertPointer(message, 4);
7837: PetscCall(PetscObjectGetComm((PetscObject)dm0, &comm));
7838: PetscCallMPI(MPI_Comm_rank(comm, &rank));
7839: {
7840: PetscInt n1;
7842: PetscCall(DMGetNumLabels(dm0, &n));
7843: PetscCall(DMGetNumLabels(dm1, &n1));
7844: eq = (PetscBool)(n == n1);
7845: if (!eq) PetscCall(PetscSNPrintf(msg, sizeof(msg), "Number of labels in dm0 = %" PetscInt_FMT " != %" PetscInt_FMT " = Number of labels in dm1", n, n1));
7846: PetscCallMPI(MPIU_Allreduce(MPI_IN_PLACE, &eq, 1, MPI_C_BOOL, MPI_LAND, comm));
7847: if (!eq) goto finish;
7848: }
7849: for (i = 0; i < n; i++) {
7850: DMLabel l0, l1;
7851: const char *name;
7852: char *msgInner;
7854: /* Ignore label order */
7855: PetscCall(DMGetLabelByNum(dm0, i, &l0));
7856: PetscCall(PetscObjectGetName((PetscObject)l0, &name));
7857: PetscCall(DMGetLabel(dm1, name, &l1));
7858: if (!l1) {
7859: PetscCall(PetscSNPrintf(msg, sizeof(msg), "Label \"%s\" (#%" PetscInt_FMT " in dm0) not found in dm1", name, i));
7860: eq = PETSC_FALSE;
7861: break;
7862: }
7863: PetscCall(DMLabelCompare(comm, l0, l1, &eq, &msgInner));
7864: PetscCall(PetscStrncpy(msg, msgInner, sizeof(msg)));
7865: PetscCall(PetscFree(msgInner));
7866: if (!eq) break;
7867: }
7868: PetscCallMPI(MPIU_Allreduce(MPI_IN_PLACE, &eq, 1, MPI_C_BOOL, MPI_LAND, comm));
7869: finish:
7870: /* If message output arg not set, print to stderr */
7871: if (message) {
7872: *message = NULL;
7873: if (msg[0]) PetscCall(PetscStrallocpy(msg, message));
7874: } else {
7875: if (msg[0]) PetscCall(PetscSynchronizedFPrintf(comm, PETSC_STDERR, "[%d] %s\n", rank, msg));
7876: PetscCall(PetscSynchronizedFlush(comm, PETSC_STDERR));
7877: }
7878: /* If same output arg not ser and labels are not equal, throw error */
7879: if (equal) *equal = eq;
7880: else PetscCheck(eq, comm, PETSC_ERR_ARG_INCOMP, "DMLabels are not the same in dm0 and dm1");
7881: PetscFunctionReturn(PETSC_SUCCESS);
7882: }
7884: PetscErrorCode DMSetLabelValue_Fast(DM dm, DMLabel *label, const char name[], PetscInt point, PetscInt value)
7885: {
7886: PetscFunctionBegin;
7887: PetscAssertPointer(label, 2);
7888: if (!*label) {
7889: PetscCall(DMCreateLabel(dm, name));
7890: PetscCall(DMGetLabel(dm, name, label));
7891: }
7892: PetscCall(DMLabelSetValue(*label, point, value));
7893: PetscFunctionReturn(PETSC_SUCCESS);
7894: }
7896: /*
7897: Many mesh programs, such as Triangle and TetGen, allow only a single label for each mesh point. Therefore, we would
7898: like to encode all label IDs using a single, universal label. We can do this by assigning an integer to every
7899: (label, id) pair in the DM.
7901: However, a mesh point can have multiple labels, so we must separate all these values. We will assign a bit range to
7902: each label.
7903: */
7904: PetscErrorCode DMUniversalLabelCreate(DM dm, DMUniversalLabel *universal)
7905: {
7906: DMUniversalLabel ul;
7907: PetscBool *active;
7908: PetscInt pStart, pEnd, p, Nl, l, m;
7910: PetscFunctionBegin;
7911: PetscCall(PetscMalloc1(1, &ul));
7912: PetscCall(DMLabelCreate(PETSC_COMM_SELF, "universal", &ul->label));
7913: PetscCall(DMGetNumLabels(dm, &Nl));
7914: PetscCall(PetscCalloc1(Nl, &active));
7915: ul->Nl = 0;
7916: for (l = 0; l < Nl; ++l) {
7917: PetscBool isdepth, iscelltype;
7918: const char *name;
7920: PetscCall(DMGetLabelName(dm, l, &name));
7921: PetscCall(PetscStrncmp(name, "depth", 6, &isdepth));
7922: PetscCall(PetscStrncmp(name, "celltype", 9, &iscelltype));
7923: active[l] = !(isdepth || iscelltype) ? PETSC_TRUE : PETSC_FALSE;
7924: if (active[l]) ++ul->Nl;
7925: }
7926: PetscCall(PetscCalloc5(ul->Nl, &ul->names, ul->Nl, &ul->indices, ul->Nl + 1, &ul->offsets, ul->Nl + 1, &ul->bits, ul->Nl, &ul->masks));
7927: ul->Nv = 0;
7928: for (l = 0, m = 0; l < Nl; ++l) {
7929: DMLabel label;
7930: PetscInt nv;
7931: const char *name;
7933: if (!active[l]) continue;
7934: PetscCall(DMGetLabelName(dm, l, &name));
7935: PetscCall(DMGetLabelByNum(dm, l, &label));
7936: PetscCall(DMLabelGetNumValues(label, &nv));
7937: PetscCall(PetscStrallocpy(name, &ul->names[m]));
7938: ul->indices[m] = l;
7939: ul->Nv += nv;
7940: ul->offsets[m + 1] = nv;
7941: ul->bits[m + 1] = PetscCeilReal(PetscLog2Real(nv + 1));
7942: ++m;
7943: }
7944: for (l = 1; l <= ul->Nl; ++l) {
7945: ul->offsets[l] = ul->offsets[l - 1] + ul->offsets[l];
7946: ul->bits[l] = ul->bits[l - 1] + ul->bits[l];
7947: }
7948: for (l = 0; l < ul->Nl; ++l) {
7949: PetscInt b;
7951: ul->masks[l] = 0;
7952: for (b = ul->bits[l]; b < ul->bits[l + 1]; ++b) ul->masks[l] |= 1 << b;
7953: }
7954: PetscCall(PetscMalloc1(ul->Nv, &ul->values));
7955: for (l = 0, m = 0; l < Nl; ++l) {
7956: DMLabel label;
7957: IS valueIS;
7958: const PetscInt *varr;
7959: PetscInt nv, v;
7961: if (!active[l]) continue;
7962: PetscCall(DMGetLabelByNum(dm, l, &label));
7963: PetscCall(DMLabelGetNumValues(label, &nv));
7964: PetscCall(DMLabelGetValueIS(label, &valueIS));
7965: PetscCall(ISGetIndices(valueIS, &varr));
7966: for (v = 0; v < nv; ++v) ul->values[ul->offsets[m] + v] = varr[v];
7967: PetscCall(ISRestoreIndices(valueIS, &varr));
7968: PetscCall(ISDestroy(&valueIS));
7969: PetscCall(PetscSortInt(nv, &ul->values[ul->offsets[m]]));
7970: ++m;
7971: }
7972: PetscCall(DMPlexGetChart(dm, &pStart, &pEnd));
7973: for (p = pStart; p < pEnd; ++p) {
7974: PetscInt uval = 0;
7975: PetscBool marked = PETSC_FALSE;
7977: for (l = 0, m = 0; l < Nl; ++l) {
7978: DMLabel label;
7979: PetscInt val, defval, loc, nv;
7981: if (!active[l]) continue;
7982: PetscCall(DMGetLabelByNum(dm, l, &label));
7983: PetscCall(DMLabelGetValue(label, p, &val));
7984: PetscCall(DMLabelGetDefaultValue(label, &defval));
7985: if (val == defval) {
7986: ++m;
7987: continue;
7988: }
7989: nv = ul->offsets[m + 1] - ul->offsets[m];
7990: marked = PETSC_TRUE;
7991: PetscCall(PetscFindInt(val, nv, &ul->values[ul->offsets[m]], &loc));
7992: PetscCheck(loc >= 0, PETSC_COMM_SELF, PETSC_ERR_PLIB, "Label value %" PetscInt_FMT " not found in compression array", val);
7993: uval += (loc + 1) << ul->bits[m];
7994: ++m;
7995: }
7996: if (marked) PetscCall(DMLabelSetValue(ul->label, p, uval));
7997: }
7998: PetscCall(PetscFree(active));
7999: *universal = ul;
8000: PetscFunctionReturn(PETSC_SUCCESS);
8001: }
8003: PetscErrorCode DMUniversalLabelDestroy(DMUniversalLabel *universal)
8004: {
8005: PetscInt l;
8007: PetscFunctionBegin;
8008: for (l = 0; l < (*universal)->Nl; ++l) PetscCall(PetscFree((*universal)->names[l]));
8009: PetscCall(DMLabelDestroy(&(*universal)->label));
8010: PetscCall(PetscFree5((*universal)->names, (*universal)->indices, (*universal)->offsets, (*universal)->bits, (*universal)->masks));
8011: PetscCall(PetscFree((*universal)->values));
8012: PetscCall(PetscFree(*universal));
8013: *universal = NULL;
8014: PetscFunctionReturn(PETSC_SUCCESS);
8015: }
8017: PetscErrorCode DMUniversalLabelGetLabel(DMUniversalLabel ul, DMLabel *ulabel)
8018: {
8019: PetscFunctionBegin;
8020: PetscAssertPointer(ulabel, 2);
8021: *ulabel = ul->label;
8022: PetscFunctionReturn(PETSC_SUCCESS);
8023: }
8025: PetscErrorCode DMUniversalLabelCreateLabels(DMUniversalLabel ul, PetscBool preserveOrder, DM dm)
8026: {
8027: PetscInt Nl = ul->Nl, l;
8029: PetscFunctionBegin;
8031: for (l = 0; l < Nl; ++l) {
8032: if (preserveOrder) PetscCall(DMCreateLabelAtIndex(dm, ul->indices[l], ul->names[l]));
8033: else PetscCall(DMCreateLabel(dm, ul->names[l]));
8034: }
8035: if (preserveOrder) {
8036: for (l = 0; l < ul->Nl; ++l) {
8037: const char *name;
8038: PetscBool match;
8040: PetscCall(DMGetLabelName(dm, ul->indices[l], &name));
8041: PetscCall(PetscStrcmp(name, ul->names[l], &match));
8042: 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]);
8043: }
8044: }
8045: PetscFunctionReturn(PETSC_SUCCESS);
8046: }
8048: PetscErrorCode DMUniversalLabelSetLabelValue(DMUniversalLabel ul, DM dm, PetscBool useIndex, PetscInt p, PetscInt value)
8049: {
8050: PetscInt l;
8052: PetscFunctionBegin;
8053: for (l = 0; l < ul->Nl; ++l) {
8054: DMLabel label;
8055: PetscInt lval = (value & ul->masks[l]) >> ul->bits[l];
8057: if (lval) {
8058: if (useIndex) PetscCall(DMGetLabelByNum(dm, ul->indices[l], &label));
8059: else PetscCall(DMGetLabel(dm, ul->names[l], &label));
8060: PetscCall(DMLabelSetValue(label, p, ul->values[ul->offsets[l] + lval - 1]));
8061: }
8062: }
8063: PetscFunctionReturn(PETSC_SUCCESS);
8064: }
8066: /*@
8067: DMGetCoarseDM - Get the coarse `DM`from which this `DM` was obtained by refinement
8069: Not Collective
8071: Input Parameter:
8072: . dm - The `DM` object
8074: Output Parameter:
8075: . cdm - The coarse `DM`
8077: Level: intermediate
8079: .seealso: [](ch_dmbase), `DM`, `DMSetCoarseDM()`, `DMCoarsen()`
8080: @*/
8081: PetscErrorCode DMGetCoarseDM(DM dm, DM *cdm)
8082: {
8083: PetscFunctionBegin;
8085: PetscAssertPointer(cdm, 2);
8086: *cdm = dm->coarseMesh;
8087: PetscFunctionReturn(PETSC_SUCCESS);
8088: }
8090: /*@
8091: DMSetCoarseDM - Set the coarse `DM` from which this `DM` was obtained by refinement
8093: Input Parameters:
8094: + dm - The `DM` object
8095: - cdm - The coarse `DM`
8097: Level: intermediate
8099: Note:
8100: Normally this is set automatically by `DMRefine()`
8102: .seealso: [](ch_dmbase), `DM`, `DMGetCoarseDM()`, `DMCoarsen()`, `DMSetRefine()`, `DMSetFineDM()`
8103: @*/
8104: PetscErrorCode DMSetCoarseDM(DM dm, DM cdm)
8105: {
8106: PetscFunctionBegin;
8109: if (dm == cdm) cdm = NULL;
8110: PetscCall(PetscObjectReference((PetscObject)cdm));
8111: PetscCall(DMDestroy(&dm->coarseMesh));
8112: dm->coarseMesh = cdm;
8113: PetscFunctionReturn(PETSC_SUCCESS);
8114: }
8116: /*@
8117: DMGetFineDM - Get the fine mesh from which this `DM` was obtained by coarsening
8119: Input Parameter:
8120: . dm - The `DM` object
8122: Output Parameter:
8123: . fdm - The fine `DM`
8125: Level: intermediate
8127: .seealso: [](ch_dmbase), `DM`, `DMSetFineDM()`, `DMCoarsen()`, `DMRefine()`
8128: @*/
8129: PetscErrorCode DMGetFineDM(DM dm, DM *fdm)
8130: {
8131: PetscFunctionBegin;
8133: PetscAssertPointer(fdm, 2);
8134: *fdm = dm->fineMesh;
8135: PetscFunctionReturn(PETSC_SUCCESS);
8136: }
8138: /*@
8139: DMSetFineDM - Set the fine mesh from which this was obtained by coarsening
8141: Input Parameters:
8142: + dm - The `DM` object
8143: - fdm - The fine `DM`
8145: Level: developer
8147: Note:
8148: Normally this is set automatically by `DMCoarsen()`
8150: .seealso: [](ch_dmbase), `DM`, `DMGetFineDM()`, `DMCoarsen()`, `DMRefine()`
8151: @*/
8152: PetscErrorCode DMSetFineDM(DM dm, DM fdm)
8153: {
8154: PetscFunctionBegin;
8157: if (dm == fdm) fdm = NULL;
8158: PetscCall(PetscObjectReference((PetscObject)fdm));
8159: PetscCall(DMDestroy(&dm->fineMesh));
8160: dm->fineMesh = fdm;
8161: PetscFunctionReturn(PETSC_SUCCESS);
8162: }
8164: /*@C
8165: DMAddBoundary - Add a boundary condition, for a single field, to a model represented by a `DM`
8167: Collective
8169: Input Parameters:
8170: + dm - The `DM`, with a `PetscDS` that matches the problem being constrained
8171: . type - The type of condition, e.g. `DM_BC_ESSENTIAL_ANALYTIC`, `DM_BC_ESSENTIAL_FIELD` (Dirichlet), or `DM_BC_NATURAL` (Neumann)
8172: . name - The BC name
8173: . label - The label defining constrained points
8174: . Nv - The number of `DMLabel` values for constrained points
8175: . values - An array of values for constrained points
8176: . field - The field to constrain
8177: . Nc - The number of constrained field components (0 will constrain all components)
8178: . comps - An array of constrained component numbers
8179: . bcFunc - A pointwise function giving boundary values
8180: . bcFunc_t - A pointwise function giving the time derivative of the boundary values, or `NULL`
8181: - ctx - An optional application context for `bcFunc`
8183: Output Parameter:
8184: . bd - (Optional) Boundary number
8186: Options Database Keys:
8187: + -bc_NAME values - Overrides the boundary ids for boundary named NAME
8188: - -bc_NAME_comp comps - Overrides the boundary components for boundary named NAME
8190: Level: intermediate
8192: Notes:
8193: If the `DM` is of type `DMPLEX` and the field is of type `PetscFE`, then this function completes the label using `DMPlexLabelComplete()`.
8195: Both bcFunc and bcFunc_t will depend on the boundary condition type. If the type if `DM_BC_ESSENTIAL`, then the calling sequence is\:
8196: .vb
8197: void bcFunc(PetscInt dim, PetscReal time, const PetscReal x[], PetscInt Nc, PetscScalar bcval[])
8198: .ve
8200: If the type is `DM_BC_ESSENTIAL_FIELD` or other _FIELD value, then the calling sequence is\:
8202: .vb
8203: void bcFunc(PetscInt dim, PetscInt Nf, PetscInt NfAux,
8204: const PetscInt uOff[], const PetscInt uOff_x[], const PetscScalar u[], const PetscScalar u_t[], const PetscScalar u_x[],
8205: const PetscInt aOff[], const PetscInt aOff_x[], const PetscScalar a[], const PetscScalar a_t[], const PetscScalar a_x[],
8206: PetscReal time, const PetscReal x[], PetscScalar bcval[])
8207: .ve
8208: + dim - the spatial dimension
8209: . Nf - the number of fields
8210: . uOff - the offset into u[] and u_t[] for each field
8211: . uOff_x - the offset into u_x[] for each field
8212: . u - each field evaluated at the current point
8213: . u_t - the time derivative of each field evaluated at the current point
8214: . u_x - the gradient of each field evaluated at the current point
8215: . aOff - the offset into a[] and a_t[] for each auxiliary field
8216: . aOff_x - the offset into a_x[] for each auxiliary field
8217: . a - each auxiliary field evaluated at the current point
8218: . a_t - the time derivative of each auxiliary field evaluated at the current point
8219: . a_x - the gradient of auxiliary each field evaluated at the current point
8220: . t - current time
8221: . x - coordinates of the current point
8222: . numConstants - number of constant parameters
8223: . constants - constant parameters
8224: - bcval - output values at the current point
8226: .seealso: [](ch_dmbase), `DM`, `DSGetBoundary()`, `PetscDSAddBoundary()`
8227: @*/
8228: 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)
8229: {
8230: PetscDS ds;
8232: PetscFunctionBegin;
8239: PetscCheck(!dm->localSection, PetscObjectComm((PetscObject)dm), PETSC_ERR_ARG_WRONGSTATE, "Cannot add boundary to DM after creating local section");
8240: PetscCall(DMGetDS(dm, &ds));
8241: /* Complete label */
8242: if (label) {
8243: PetscObject obj;
8244: PetscClassId id;
8246: PetscCall(DMGetField(dm, field, NULL, &obj));
8247: PetscCall(PetscObjectGetClassId(obj, &id));
8248: if (id == PETSCFE_CLASSID) {
8249: DM plex;
8251: PetscCall(DMConvert(dm, DMPLEX, &plex));
8252: if (plex) PetscCall(DMPlexLabelComplete(plex, label));
8253: PetscCall(DMDestroy(&plex));
8254: }
8255: }
8256: PetscCall(PetscDSAddBoundary(ds, type, name, label, Nv, values, field, Nc, comps, bcFunc, bcFunc_t, ctx, bd));
8257: PetscFunctionReturn(PETSC_SUCCESS);
8258: }
8260: /* TODO Remove this since now the structures are the same */
8261: static PetscErrorCode DMPopulateBoundary(DM dm)
8262: {
8263: PetscDS ds;
8264: DMBoundary *lastnext;
8265: DSBoundary dsbound;
8267: PetscFunctionBegin;
8268: PetscCall(DMGetDS(dm, &ds));
8269: dsbound = ds->boundary;
8270: if (dm->boundary) {
8271: DMBoundary next = dm->boundary;
8273: /* quick check to see if the PetscDS has changed */
8274: if (next->dsboundary == dsbound) PetscFunctionReturn(PETSC_SUCCESS);
8275: /* the PetscDS has changed: tear down and rebuild */
8276: while (next) {
8277: DMBoundary b = next;
8279: next = b->next;
8280: PetscCall(PetscFree(b));
8281: }
8282: dm->boundary = NULL;
8283: }
8285: lastnext = &dm->boundary;
8286: while (dsbound) {
8287: DMBoundary dmbound;
8289: PetscCall(PetscNew(&dmbound));
8290: dmbound->dsboundary = dsbound;
8291: dmbound->label = dsbound->label;
8292: /* push on the back instead of the front so that it is in the same order as in the PetscDS */
8293: *lastnext = dmbound;
8294: lastnext = &dmbound->next;
8295: dsbound = dsbound->next;
8296: }
8297: PetscFunctionReturn(PETSC_SUCCESS);
8298: }
8300: /*@
8301: DMIsBoundaryPoint - Determine whether a mesh point lies on a `DM` boundary
8303: Not Collective
8305: Input Parameters:
8306: + dm - the `DM` object
8307: - point - the mesh point number
8309: Output Parameter:
8310: . isBd - `PETSC_TRUE` if `point` belongs to any boundary label registered on the `DM`
8312: Level: developer
8314: .seealso: [](ch_dmbase), `DM`, `DMLabel`, `DMAddBoundary()`, `PetscDSGetBoundary()`
8315: @*/
8316: PetscErrorCode DMIsBoundaryPoint(DM dm, PetscInt point, PetscBool *isBd)
8317: {
8318: DMBoundary b;
8320: PetscFunctionBegin;
8322: PetscAssertPointer(isBd, 3);
8323: *isBd = PETSC_FALSE;
8324: PetscCall(DMPopulateBoundary(dm));
8325: b = dm->boundary;
8326: while (b && !*isBd) {
8327: DMLabel label = b->label;
8328: DSBoundary dsb = b->dsboundary;
8329: PetscInt i;
8331: if (label) {
8332: for (i = 0; i < dsb->Nv && !*isBd; ++i) PetscCall(DMLabelStratumHasPoint(label, dsb->values[i], point, isBd));
8333: }
8334: b = b->next;
8335: }
8336: PetscFunctionReturn(PETSC_SUCCESS);
8337: }
8339: /*@
8340: DMHasBound - Determine whether a bound condition was specified
8342: Logically collective
8344: Input Parameter:
8345: . dm - The `DM`, with a `PetscDS` that matches the problem being constrained
8347: Output Parameter:
8348: . hasBound - Flag indicating if a bound condition was specified
8350: Level: intermediate
8352: .seealso: [](ch_dmbase), `DM`, `DSAddBoundary()`, `PetscDSAddBoundary()`
8353: @*/
8354: PetscErrorCode DMHasBound(DM dm, PetscBool *hasBound)
8355: {
8356: PetscDS ds;
8357: PetscInt Nf, numBd;
8359: PetscFunctionBegin;
8360: *hasBound = PETSC_FALSE;
8361: PetscCall(DMGetDS(dm, &ds));
8362: PetscCall(PetscDSGetNumFields(ds, &Nf));
8363: for (PetscInt f = 0; f < Nf; ++f) {
8364: PetscSimplePointFn *lfunc, *ufunc;
8366: PetscCall(PetscDSGetLowerBound(ds, f, &lfunc, NULL));
8367: PetscCall(PetscDSGetUpperBound(ds, f, &ufunc, NULL));
8368: if (lfunc || ufunc) *hasBound = PETSC_TRUE;
8369: }
8371: PetscCall(PetscDSGetNumBoundary(ds, &numBd));
8372: PetscCall(PetscDSUpdateBoundaryLabels(ds, dm));
8373: for (PetscInt b = 0; b < numBd; ++b) {
8374: PetscWeakForm wf;
8375: DMBoundaryConditionType type;
8376: const char *name;
8377: DMLabel label;
8378: PetscInt numids;
8379: const PetscInt *ids;
8380: PetscInt field, Nc;
8381: const PetscInt *comps;
8382: PetscVoidFn *bvfunc;
8383: void *ctx;
8385: PetscCall(PetscDSGetBoundary(ds, b, &wf, &type, &name, &label, &numids, &ids, &field, &Nc, &comps, &bvfunc, NULL, &ctx));
8386: if (type == DM_BC_LOWER_BOUND || type == DM_BC_UPPER_BOUND) *hasBound = PETSC_TRUE;
8387: }
8388: PetscFunctionReturn(PETSC_SUCCESS);
8389: }
8391: /*@C
8392: DMProjectFunction - This projects the given function into the function space provided by a `DM`, putting the coefficients in a global vector.
8394: Collective
8396: Input Parameters:
8397: + dm - The `DM`
8398: . time - The time
8399: . funcs - The coordinate functions to evaluate, one per field
8400: . ctxs - Optional array of contexts to pass to each coordinate function. ctxs itself may be null.
8401: - mode - The insertion mode for values
8403: Output Parameter:
8404: . X - vector
8406: Calling sequence of `funcs`:
8407: + dim - The spatial dimension
8408: . time - The time at which to sample
8409: . x - The coordinates
8410: . Nc - The number of components
8411: . u - The output field values
8412: - ctx - optional function context
8414: Level: developer
8416: Developer Notes:
8417: This API is specific to only particular usage of `DM`
8419: The notes need to provide some information about what has to be provided to the `DM` to be able to perform the computation.
8421: .seealso: [](ch_dmbase), `DM`, `DMProjectFunctionLocal()`, `DMProjectFunctionLabel()`, `DMComputeL2Diff()`
8422: @*/
8423: 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)
8424: {
8425: Vec localX;
8427: PetscFunctionBegin;
8429: PetscCall(PetscLogEventBegin(DM_ProjectFunction, dm, X, 0, 0));
8430: PetscCall(DMGetLocalVector(dm, &localX));
8431: PetscCall(VecSet(localX, 0.));
8432: PetscCall(DMProjectFunctionLocal(dm, time, funcs, ctxs, mode, localX));
8433: PetscCall(DMLocalToGlobalBegin(dm, localX, mode, X));
8434: PetscCall(DMLocalToGlobalEnd(dm, localX, mode, X));
8435: PetscCall(DMRestoreLocalVector(dm, &localX));
8436: PetscCall(PetscLogEventEnd(DM_ProjectFunction, dm, X, 0, 0));
8437: PetscFunctionReturn(PETSC_SUCCESS);
8438: }
8440: /*@C
8441: DMProjectFunctionLocal - This projects the given function into the function space provided by a `DM`, putting the coefficients in a local vector.
8443: Not Collective
8445: Input Parameters:
8446: + dm - The `DM`
8447: . time - The time
8448: . funcs - The coordinate functions to evaluate, one per field
8449: . ctxs - Optional array of contexts to pass to each coordinate function. ctxs itself may be null.
8450: - mode - The insertion mode for values
8452: Output Parameter:
8453: . localX - vector
8455: Calling sequence of `funcs`:
8456: + dim - The spatial dimension
8457: . time - The current timestep
8458: . x - The coordinates
8459: . Nc - The number of components
8460: . u - The output field values
8461: - ctx - optional function context
8463: Level: developer
8465: Developer Notes:
8466: This API is specific to only particular usage of `DM`
8468: The notes need to provide some information about what has to be provided to the `DM` to be able to perform the computation.
8470: .seealso: [](ch_dmbase), `DM`, `DMProjectFunction()`, `DMProjectFunctionLabel()`, `DMComputeL2Diff()`
8471: @*/
8472: 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)
8473: {
8474: PetscFunctionBegin;
8477: PetscUseTypeMethod(dm, projectfunctionlocal, time, funcs, ctxs, mode, localX);
8478: PetscFunctionReturn(PETSC_SUCCESS);
8479: }
8481: /*@C
8482: 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.
8484: Collective
8486: Input Parameters:
8487: + dm - The `DM`
8488: . time - The time
8489: . numIds - The number of ids
8490: . ids - The ids
8491: . Nc - The number of components
8492: . comps - The components
8493: . label - The `DMLabel` selecting the portion of the mesh for projection
8494: . funcs - The coordinate functions to evaluate, one per field
8495: . ctxs - Optional array of contexts to pass to each coordinate function. ctxs may be null.
8496: - mode - The insertion mode for values
8498: Output Parameter:
8499: . X - vector
8501: Calling sequence of `funcs`:
8502: + dim - The spatial dimension
8503: . time - The current timestep
8504: . x - The coordinates
8505: . Nc - The number of components
8506: . u - The output field values
8507: - ctx - optional function context
8509: Level: developer
8511: Developer Notes:
8512: This API is specific to only particular usage of `DM`
8514: The notes need to provide some information about what has to be provided to the `DM` to be able to perform the computation.
8516: .seealso: [](ch_dmbase), `DM`, `DMProjectFunction()`, `DMProjectFunctionLocal()`, `DMProjectFunctionLabelLocal()`, `DMComputeL2Diff()`
8517: @*/
8518: 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)
8519: {
8520: Vec localX;
8522: PetscFunctionBegin;
8524: PetscCall(DMGetLocalVector(dm, &localX));
8525: PetscCall(VecSet(localX, 0.));
8526: PetscCall(DMProjectFunctionLabelLocal(dm, time, label, numIds, ids, Nc, comps, funcs, ctxs, mode, localX));
8527: PetscCall(DMLocalToGlobalBegin(dm, localX, mode, X));
8528: PetscCall(DMLocalToGlobalEnd(dm, localX, mode, X));
8529: PetscCall(DMRestoreLocalVector(dm, &localX));
8530: PetscFunctionReturn(PETSC_SUCCESS);
8531: }
8533: /*@C
8534: 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.
8536: Not Collective
8538: Input Parameters:
8539: + dm - The `DM`
8540: . time - The time
8541: . label - The `DMLabel` selecting the portion of the mesh for projection
8542: . numIds - The number of ids
8543: . ids - The ids
8544: . Nc - The number of components
8545: . comps - The components
8546: . funcs - The coordinate functions to evaluate, one per field
8547: . ctxs - Optional array of contexts to pass to each coordinate function. ctxs itself may be null.
8548: - mode - The insertion mode for values
8550: Output Parameter:
8551: . localX - vector
8553: Calling sequence of `funcs`:
8554: + dim - The spatial dimension
8555: . time - The current time
8556: . x - The coordinates
8557: . Nc - The number of components
8558: . u - The output field values
8559: - ctx - optional function context
8561: Level: developer
8563: Developer Notes:
8564: This API is specific to only particular usage of `DM`
8566: The notes need to provide some information about what has to be provided to the `DM` to be able to perform the computation.
8568: .seealso: [](ch_dmbase), `DM`, `DMProjectFunction()`, `DMProjectFunctionLocal()`, `DMProjectFunctionLabel()`, `DMComputeL2Diff()`
8569: @*/
8570: 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)
8571: {
8572: PetscFunctionBegin;
8575: PetscUseTypeMethod(dm, projectfunctionlabellocal, time, label, numIds, ids, Nc, comps, funcs, ctxs, mode, localX);
8576: PetscFunctionReturn(PETSC_SUCCESS);
8577: }
8579: /*@C
8580: 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.
8582: Not Collective
8584: Input Parameters:
8585: + dm - The `DM`
8586: . time - The time
8587: . localU - The input field vector; may be `NULL` if projection is defined purely by coordinates
8588: . funcs - The functions to evaluate, one per field
8589: - mode - The insertion mode for values
8591: Output Parameter:
8592: . localX - The output vector
8594: Calling sequence of `funcs`:
8595: + dim - The spatial dimension
8596: . Nf - The number of input fields
8597: . NfAux - The number of input auxiliary fields
8598: . uOff - The offset of each field in u[]
8599: . uOff_x - The offset of each field in u_x[]
8600: . u - The field values at this point in space
8601: . u_t - The field time derivative at this point in space (or `NULL`)
8602: . u_x - The field derivatives at this point in space
8603: . aOff - The offset of each auxiliary field in u[]
8604: . aOff_x - The offset of each auxiliary field in u_x[]
8605: . a - The auxiliary field values at this point in space
8606: . a_t - The auxiliary field time derivative at this point in space (or `NULL`)
8607: . a_x - The auxiliary field derivatives at this point in space
8608: . t - The current time
8609: . x - The coordinates of this point
8610: . numConstants - The number of constants
8611: . constants - The value of each constant
8612: - f - The value of the function at this point in space
8614: Level: intermediate
8616: Note:
8617: 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.
8618: 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
8619: a subdomain. You can also output a different number of fields than the input, with different discretizations. Last the auxiliary `DM`, attached to the
8620: auxiliary field vector, which is attached to dm, can also be different. It can have a different topology, number of fields, and discretizations.
8622: Developer Notes:
8623: This API is specific to only particular usage of `DM`
8625: The notes need to provide some information about what has to be provided to the `DM` to be able to perform the computation.
8627: .seealso: [](ch_dmbase), `DM`, `DMProjectField()`, `DMProjectFieldLabelLocal()`,
8628: `DMProjectFunction()`, `DMComputeL2Diff()`
8629: @*/
8630: 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)
8631: {
8632: PetscFunctionBegin;
8636: PetscUseTypeMethod(dm, projectfieldlocal, time, localU, funcs, mode, localX);
8637: PetscFunctionReturn(PETSC_SUCCESS);
8638: }
8640: /*@C
8641: 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.
8643: Not Collective
8645: Input Parameters:
8646: + dm - The `DM`
8647: . time - The time
8648: . label - The `DMLabel` marking the portion of the domain to output
8649: . numIds - The number of label ids to use
8650: . ids - The label ids to use for marking
8651: . Nc - The number of components to set in the output, or `PETSC_DETERMINE` for all components
8652: . comps - The components to set in the output, or `NULL` for all components
8653: . localU - The input field vector
8654: . funcs - The functions to evaluate, one per field
8655: - mode - The insertion mode for values
8657: Output Parameter:
8658: . localX - The output vector
8660: Calling sequence of `funcs`:
8661: + dim - The spatial dimension
8662: . Nf - The number of input fields
8663: . NfAux - The number of input auxiliary fields
8664: . uOff - The offset of each field in u[]
8665: . uOff_x - The offset of each field in u_x[]
8666: . u - The field values at this point in space
8667: . u_t - The field time derivative at this point in space (or `NULL`)
8668: . u_x - The field derivatives at this point in space
8669: . aOff - The offset of each auxiliary field in u[]
8670: . aOff_x - The offset of each auxiliary field in u_x[]
8671: . a - The auxiliary field values at this point in space
8672: . a_t - The auxiliary field time derivative at this point in space (or `NULL`)
8673: . a_x - The auxiliary field derivatives at this point in space
8674: . t - The current time
8675: . x - The coordinates of this point
8676: . numConstants - The number of constants
8677: . constants - The value of each constant
8678: - f - The value of the function at this point in space
8680: Level: intermediate
8682: Note:
8683: 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.
8684: 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
8685: a subdomain. You can also output a different number of fields than the input, with different discretizations. Last the auxiliary `DM`, attached to the
8686: auxiliary field vector, which is attached to dm, can also be different. It can have a different topology, number of fields, and discretizations.
8688: Developer Notes:
8689: This API is specific to only particular usage of `DM`
8691: The notes need to provide some information about what has to be provided to the `DM` to be able to perform the computation.
8693: .seealso: [](ch_dmbase), `DM`, `DMProjectField()`, `DMProjectFieldLabel()`, `DMProjectFunction()`, `DMComputeL2Diff()`
8694: @*/
8695: 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)
8696: {
8697: PetscFunctionBegin;
8701: PetscUseTypeMethod(dm, projectfieldlabellocal, time, label, numIds, ids, Nc, comps, localU, funcs, mode, localX);
8702: PetscFunctionReturn(PETSC_SUCCESS);
8703: }
8705: /*@C
8706: 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.
8708: Not Collective
8710: Input Parameters:
8711: + dm - The `DM`
8712: . time - The time
8713: . label - The `DMLabel` marking the portion of the domain to output
8714: . numIds - The number of label ids to use
8715: . ids - The label ids to use for marking
8716: . Nc - The number of components to set in the output, or `PETSC_DETERMINE` for all components
8717: . comps - The components to set in the output, or `NULL` for all components
8718: . U - The input field vector
8719: . funcs - The functions to evaluate, one per field
8720: - mode - The insertion mode for values
8722: Output Parameter:
8723: . X - The output vector
8725: Calling sequence of `funcs`:
8726: + dim - The spatial dimension
8727: . Nf - The number of input fields
8728: . NfAux - The number of input auxiliary fields
8729: . uOff - The offset of each field in u[]
8730: . uOff_x - The offset of each field in u_x[]
8731: . u - The field values at this point in space
8732: . u_t - The field time derivative at this point in space (or `NULL`)
8733: . u_x - The field derivatives at this point in space
8734: . aOff - The offset of each auxiliary field in u[]
8735: . aOff_x - The offset of each auxiliary field in u_x[]
8736: . a - The auxiliary field values at this point in space
8737: . a_t - The auxiliary field time derivative at this point in space (or `NULL`)
8738: . a_x - The auxiliary field derivatives at this point in space
8739: . t - The current time
8740: . x - The coordinates of this point
8741: . numConstants - The number of constants
8742: . constants - The value of each constant
8743: - f - The value of the function at this point in space
8745: Level: intermediate
8747: Note:
8748: 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.
8749: 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
8750: a subdomain. You can also output a different number of fields than the input, with different discretizations. Last the auxiliary `DM`, attached to the
8751: auxiliary field vector, which is attached to dm, can also be different. It can have a different topology, number of fields, and discretizations.
8753: Developer Notes:
8754: This API is specific to only particular usage of `DM`
8756: The notes need to provide some information about what has to be provided to the `DM` to be able to perform the computation.
8758: .seealso: [](ch_dmbase), `DM`, `DMProjectField()`, `DMProjectFieldLabelLocal()`, `DMProjectFunction()`, `DMComputeL2Diff()`
8759: @*/
8760: 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)
8761: {
8762: DM dmIn;
8763: Vec localU, localX;
8765: PetscFunctionBegin;
8767: PetscCall(VecGetDM(U, &dmIn));
8768: PetscCall(DMGetLocalVector(dmIn, &localU));
8769: PetscCall(DMGetLocalVector(dm, &localX));
8770: PetscCall(VecSet(localX, 0.));
8771: PetscCall(DMGlobalToLocalBegin(dmIn, U, mode, localU));
8772: PetscCall(DMGlobalToLocalEnd(dmIn, U, mode, localU));
8773: PetscCall(DMProjectFieldLabelLocal(dm, time, label, numIds, ids, Nc, comps, localU, funcs, mode, localX));
8774: PetscCall(DMLocalToGlobalBegin(dm, localX, mode, X));
8775: PetscCall(DMLocalToGlobalEnd(dm, localX, mode, X));
8776: PetscCall(DMRestoreLocalVector(dm, &localX));
8777: PetscCall(DMRestoreLocalVector(dmIn, &localU));
8778: PetscFunctionReturn(PETSC_SUCCESS);
8779: }
8781: /*@C
8782: 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.
8784: Not Collective
8786: Input Parameters:
8787: + dm - The `DM`
8788: . time - The time
8789: . label - The `DMLabel` marking the portion of the domain boundary to output
8790: . numIds - The number of label ids to use
8791: . ids - The label ids to use for marking
8792: . Nc - The number of components to set in the output, or `PETSC_DETERMINE` for all components
8793: . comps - The components to set in the output, or `NULL` for all components
8794: . localU - The input field vector
8795: . funcs - The functions to evaluate, one per field
8796: - mode - The insertion mode for values
8798: Output Parameter:
8799: . localX - The output vector
8801: Calling sequence of `funcs`:
8802: + dim - The spatial dimension
8803: . Nf - The number of input fields
8804: . NfAux - The number of input auxiliary fields
8805: . uOff - The offset of each field in u[]
8806: . uOff_x - The offset of each field in u_x[]
8807: . u - The field values at this point in space
8808: . u_t - The field time derivative at this point in space (or `NULL`)
8809: . u_x - The field derivatives at this point in space
8810: . aOff - The offset of each auxiliary field in u[]
8811: . aOff_x - The offset of each auxiliary field in u_x[]
8812: . a - The auxiliary field values at this point in space
8813: . a_t - The auxiliary field time derivative at this point in space (or `NULL`)
8814: . a_x - The auxiliary field derivatives at this point in space
8815: . t - The current time
8816: . x - The coordinates of this point
8817: . n - The face normal
8818: . numConstants - The number of constants
8819: . constants - The value of each constant
8820: - f - The value of the function at this point in space
8822: Level: intermediate
8824: Note:
8825: 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.
8826: 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
8827: a subdomain. You can also output a different number of fields than the input, with different discretizations. Last the auxiliary `DM`, attached to the
8828: auxiliary field vector, which is attached to dm, can also be different. It can have a different topology, number of fields, and discretizations.
8830: Developer Notes:
8831: This API is specific to only particular usage of `DM`
8833: The notes need to provide some information about what has to be provided to the `DM` to be able to perform the computation.
8835: .seealso: [](ch_dmbase), `DM`, `DMProjectField()`, `DMProjectFieldLabelLocal()`, `DMProjectFunction()`, `DMComputeL2Diff()`
8836: @*/
8837: 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)
8838: {
8839: PetscFunctionBegin;
8843: PetscUseTypeMethod(dm, projectbdfieldlabellocal, time, label, numIds, ids, Nc, comps, localU, funcs, mode, localX);
8844: PetscFunctionReturn(PETSC_SUCCESS);
8845: }
8847: /*@C
8848: DMComputeL2Diff - This function computes the L_2 difference between a function u and an FEM interpolant solution u_h.
8850: Collective
8852: Input Parameters:
8853: + dm - The `DM`
8854: . time - The time
8855: . funcs - The functions to evaluate for each field component
8856: . ctxs - Optional array of contexts to pass to each function, or `NULL`.
8857: - X - The coefficient vector u_h, a global vector
8859: Output Parameter:
8860: . diff - The diff ||u - u_h||_2
8862: Level: developer
8864: Developer Notes:
8865: This API is specific to only particular usage of `DM`
8867: The notes need to provide some information about what has to be provided to the `DM` to be able to perform the computation.
8869: .seealso: [](ch_dmbase), `DM`, `DMProjectFunction()`, `DMComputeL2FieldDiff()`, `DMComputeL2GradientDiff()`
8870: @*/
8871: PetscErrorCode DMComputeL2Diff(DM dm, PetscReal time, PetscErrorCode (**funcs)(PetscInt, PetscReal, const PetscReal[], PetscInt, PetscScalar *, void *), void **ctxs, Vec X, PetscReal *diff)
8872: {
8873: PetscFunctionBegin;
8876: PetscUseTypeMethod(dm, computel2diff, time, funcs, ctxs, X, diff);
8877: PetscFunctionReturn(PETSC_SUCCESS);
8878: }
8880: /*@C
8881: DMComputeL2GradientDiff - This function computes the L_2 difference between the gradient of a function u and an FEM interpolant solution grad u_h.
8883: Collective
8885: Input Parameters:
8886: + dm - The `DM`
8887: . time - The time
8888: . funcs - The gradient functions to evaluate for each field component
8889: . ctxs - Optional array of contexts to pass to each function, or `NULL`.
8890: . X - The coefficient vector u_h, a global vector
8891: - n - The vector to project along
8893: Output Parameter:
8894: . diff - The diff ||(grad u - grad u_h) . n||_2
8896: Level: developer
8898: Developer Notes:
8899: This API is specific to only particular usage of `DM`
8901: The notes need to provide some information about what has to be provided to the `DM` to be able to perform the computation.
8903: .seealso: [](ch_dmbase), `DM`, `DMProjectFunction()`, `DMComputeL2Diff()`, `DMComputeL2FieldDiff()`
8904: @*/
8905: 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)
8906: {
8907: PetscFunctionBegin;
8910: PetscUseTypeMethod(dm, computel2gradientdiff, time, funcs, ctxs, X, n, diff);
8911: PetscFunctionReturn(PETSC_SUCCESS);
8912: }
8914: /*@C
8915: DMComputeL2FieldDiff - This function computes the L_2 difference between a function u and an FEM interpolant solution u_h, separated into field components.
8917: Collective
8919: Input Parameters:
8920: + dm - The `DM`
8921: . time - The time
8922: . funcs - The functions to evaluate for each field component
8923: . ctxs - Optional array of contexts to pass to each function, or `NULL`.
8924: - X - The coefficient vector u_h, a global vector
8926: Output Parameter:
8927: . diff - The array of differences, ||u^f - u^f_h||_2
8929: Level: developer
8931: Developer Notes:
8932: This API is specific to only particular usage of `DM`
8934: The notes need to provide some information about what has to be provided to the `DM` to be able to perform the computation.
8936: .seealso: [](ch_dmbase), `DM`, `DMProjectFunction()`, `DMComputeL2GradientDiff()`
8937: @*/
8938: PetscErrorCode DMComputeL2FieldDiff(DM dm, PetscReal time, PetscErrorCode (**funcs)(PetscInt, PetscReal, const PetscReal[], PetscInt, PetscScalar *, void *), void **ctxs, Vec X, PetscReal diff[])
8939: {
8940: PetscFunctionBegin;
8943: PetscUseTypeMethod(dm, computel2fielddiff, time, funcs, ctxs, X, diff);
8944: PetscFunctionReturn(PETSC_SUCCESS);
8945: }
8947: /*@C
8948: DMGetNeighbors - Gets an array containing the MPI ranks of all the processes neighbors
8950: Not Collective
8952: Input Parameter:
8953: . dm - The `DM`
8955: Output Parameters:
8956: + nranks - the number of neighbours
8957: - ranks - the neighbors ranks
8959: Level: beginner
8961: Note:
8962: Do not free the array, it is freed when the `DM` is destroyed.
8964: .seealso: [](ch_dmbase), `DM`, `DMDAGetNeighbors()`, `PetscSFGetRootRanks()`
8965: @*/
8966: PetscErrorCode DMGetNeighbors(DM dm, PetscInt *nranks, const PetscMPIInt *ranks[])
8967: {
8968: PetscFunctionBegin;
8970: PetscUseTypeMethod(dm, getneighbors, nranks, ranks);
8971: PetscFunctionReturn(PETSC_SUCCESS);
8972: }
8974: #include <petsc/private/matimpl.h>
8976: /*
8977: Converts the input vector to a ghosted vector and then calls the standard coloring code.
8978: This must be a different function because it requires DM which is not defined in the Mat library
8979: */
8980: static PetscErrorCode MatFDColoringApply_AIJDM(Mat J, MatFDColoring coloring, Vec x1, void *sctx)
8981: {
8982: PetscFunctionBegin;
8983: if (coloring->ctype == IS_COLORING_LOCAL) {
8984: Vec x1local;
8985: DM dm;
8986: PetscCall(MatGetDM(J, &dm));
8987: PetscCheck(dm, PetscObjectComm((PetscObject)J), PETSC_ERR_ARG_INCOMP, "IS_COLORING_LOCAL requires a DM");
8988: PetscCall(DMGetLocalVector(dm, &x1local));
8989: PetscCall(DMGlobalToLocalBegin(dm, x1, INSERT_VALUES, x1local));
8990: PetscCall(DMGlobalToLocalEnd(dm, x1, INSERT_VALUES, x1local));
8991: x1 = x1local;
8992: }
8993: PetscCall(MatFDColoringApply_AIJ(J, coloring, x1, sctx));
8994: if (coloring->ctype == IS_COLORING_LOCAL) {
8995: DM dm;
8996: PetscCall(MatGetDM(J, &dm));
8997: PetscCall(DMRestoreLocalVector(dm, &x1));
8998: }
8999: PetscFunctionReturn(PETSC_SUCCESS);
9000: }
9002: /*@
9003: MatFDColoringUseDM - allows a `MatFDColoring` object to use the `DM` associated with the matrix to compute a `IS_COLORING_LOCAL` coloring
9005: Input Parameters:
9006: + coloring - The matrix to get the `DM` from
9007: - fdcoloring - the `MatFDColoring` object
9009: Level: advanced
9011: Developer Note:
9012: This routine exists because the PETSc `Mat` library does not know about the `DM` objects
9014: .seealso: [](ch_dmbase), `DM`, `MatFDColoring`, `MatFDColoringCreate()`, `ISColoringType`
9015: @*/
9016: PetscErrorCode MatFDColoringUseDM(Mat coloring, MatFDColoring fdcoloring)
9017: {
9018: PetscFunctionBegin;
9019: coloring->ops->fdcoloringapply = MatFDColoringApply_AIJDM;
9020: PetscFunctionReturn(PETSC_SUCCESS);
9021: }
9023: /*@
9024: DMGetCompatibility - determine if two `DM`s are compatible
9026: Collective
9028: Input Parameters:
9029: + dm1 - the first `DM`
9030: - dm2 - the second `DM`
9032: Output Parameters:
9033: + compatible - whether or not the two `DM`s are compatible
9034: - set - whether or not the compatible value was actually determined and set
9036: Level: advanced
9038: Notes:
9039: Two `DM`s are deemed compatible if they represent the same parallel decomposition
9040: of the same topology. This implies that the section (field data) on one
9041: "makes sense" with respect to the topology and parallel decomposition of the other.
9042: Loosely speaking, compatible `DM`s represent the same domain and parallel
9043: decomposition, but hold different data.
9045: Typically, one would confirm compatibility if intending to simultaneously iterate
9046: over a pair of vectors obtained from different `DM`s.
9048: For example, two `DMDA` objects are compatible if they have the same local
9049: and global sizes and the same stencil width. They can have different numbers
9050: of degrees of freedom per node. Thus, one could use the node numbering from
9051: either `DM` in bounds for a loop over vectors derived from either `DM`.
9053: Consider the operation of summing data living on a 2-dof `DMDA` to data living
9054: on a 1-dof `DMDA`, which should be compatible, as in the following snippet.
9055: .vb
9056: ...
9057: PetscCall(DMGetCompatibility(da1,da2,&compatible,&set));
9058: if (set && compatible) {
9059: PetscCall(DMDAVecGetArrayDOF(da1,vec1,&arr1));
9060: PetscCall(DMDAVecGetArrayDOF(da2,vec2,&arr2));
9061: PetscCall(DMDAGetCorners(da1,&x,&y,NULL,&m,&n,NULL));
9062: for (j=y; j<y+n; ++j) {
9063: for (i=x; i<x+m, ++i) {
9064: arr1[j][i][0] = arr2[j][i][0] + arr2[j][i][1];
9065: }
9066: }
9067: PetscCall(DMDAVecRestoreArrayDOF(da1,vec1,&arr1));
9068: PetscCall(DMDAVecRestoreArrayDOF(da2,vec2,&arr2));
9069: } else {
9070: SETERRQ(PetscObjectComm((PetscObject)da1,PETSC_ERR_ARG_INCOMP,"DMDA objects incompatible");
9071: }
9072: ...
9073: .ve
9075: Checking compatibility might be expensive for a given implementation of `DM`,
9076: or might be impossible to unambiguously confirm or deny. For this reason,
9077: this function may decline to determine compatibility, and hence users should
9078: always check the "set" output parameter.
9080: A `DM` is always compatible with itself.
9082: In the current implementation, `DM`s which live on "unequal" communicators
9083: (MPI_UNEQUAL in the terminology of MPI_Comm_compare()) are always deemed
9084: incompatible.
9086: This function is labeled "Collective," as information about all subdomains
9087: is required on each rank. However, in `DM` implementations which store all this
9088: information locally, this function may be merely "Logically Collective".
9090: Developer Note:
9091: Compatibility is assumed to be a symmetric concept; `DM` A is compatible with `DM` B
9092: iff B is compatible with A. Thus, this function checks the implementations
9093: of both dm and dmc (if they are of different types), attempting to determine
9094: compatibility. It is left to `DM` implementers to ensure that symmetry is
9095: preserved. The simplest way to do this is, when implementing type-specific
9096: logic for this function, is to check for existing logic in the implementation
9097: of other `DM` types and let *set = PETSC_FALSE if found.
9099: .seealso: [](ch_dmbase), `DM`, `DMDACreateCompatibleDMDA()`, `DMStagCreateCompatibleDMStag()`
9100: @*/
9101: PetscErrorCode DMGetCompatibility(DM dm1, DM dm2, PetscBool *compatible, PetscBool *set)
9102: {
9103: PetscMPIInt compareResult;
9104: DMType type, type2;
9105: PetscBool sameType;
9107: PetscFunctionBegin;
9111: /* Declare a DM compatible with itself */
9112: if (dm1 == dm2) {
9113: *set = PETSC_TRUE;
9114: *compatible = PETSC_TRUE;
9115: PetscFunctionReturn(PETSC_SUCCESS);
9116: }
9118: /* Declare a DM incompatible with a DM that lives on an "unequal"
9119: communicator. Note that this does not preclude compatibility with
9120: DMs living on "congruent" or "similar" communicators, but this must be
9121: determined by the implementation-specific logic */
9122: PetscCallMPI(MPI_Comm_compare(PetscObjectComm((PetscObject)dm1), PetscObjectComm((PetscObject)dm2), &compareResult));
9123: if (compareResult == MPI_UNEQUAL) {
9124: *set = PETSC_TRUE;
9125: *compatible = PETSC_FALSE;
9126: PetscFunctionReturn(PETSC_SUCCESS);
9127: }
9129: /* Pass to the implementation-specific routine, if one exists. */
9130: if (dm1->ops->getcompatibility) {
9131: PetscUseTypeMethod(dm1, getcompatibility, dm2, compatible, set);
9132: if (*set) PetscFunctionReturn(PETSC_SUCCESS);
9133: }
9135: /* If dm1 and dm2 are of different types, then attempt to check compatibility
9136: with an implementation of this function from dm2 */
9137: PetscCall(DMGetType(dm1, &type));
9138: PetscCall(DMGetType(dm2, &type2));
9139: PetscCall(PetscStrcmp(type, type2, &sameType));
9140: if (!sameType && dm2->ops->getcompatibility) {
9141: PetscUseTypeMethod(dm2, getcompatibility, dm1, compatible, set); /* Note argument order */
9142: } else {
9143: *set = PETSC_FALSE;
9144: }
9145: PetscFunctionReturn(PETSC_SUCCESS);
9146: }
9148: /*@C
9149: DMMonitorSet - Sets an additional monitor function that is to be used after a solve to monitor discretization performance.
9151: Logically Collective
9153: Input Parameters:
9154: + dm - the `DM`
9155: . f - the monitor function
9156: . mctx - [optional] context for private data for the monitor routine (use `NULL` if no context is desired)
9157: - monitordestroy - [optional] routine that frees monitor context (may be `NULL`), see `PetscCtxDestroyFn` for the calling sequence
9159: Options Database Key:
9160: . -dm_monitor_cancel - cancels all monitors that have been hardwired into a code by calls to `DMMonitorSet()`, but
9161: does not cancel those set via the options database.
9163: Level: intermediate
9165: Note:
9166: Several different monitoring routines may be set by calling
9167: `DMMonitorSet()` multiple times or with `DMMonitorSetFromOptions()`; all will be called in the
9168: order in which they were set.
9170: Fortran Note:
9171: Only a single monitor function can be set for each `DM` object
9173: Developer Note:
9174: This API has a generic name but seems specific to a very particular aspect of the use of `DM`
9176: .seealso: [](ch_dmbase), `DM`, `DMMonitorCancel()`, `DMMonitorSetFromOptions()`, `DMMonitor()`, `PetscCtxDestroyFn`
9177: @*/
9178: PetscErrorCode DMMonitorSet(DM dm, PetscErrorCode (*f)(DM, void *), void *mctx, PetscCtxDestroyFn *monitordestroy)
9179: {
9180: PetscFunctionBegin;
9182: for (PetscInt m = 0; m < dm->numbermonitors; ++m) {
9183: PetscBool identical;
9185: PetscCall(PetscMonitorCompare((PetscErrorCode (*)(void))(PetscVoidFn *)f, mctx, monitordestroy, (PetscErrorCode (*)(void))(PetscVoidFn *)dm->monitor[m], dm->monitorcontext[m], dm->monitordestroy[m], &identical));
9186: if (identical) PetscFunctionReturn(PETSC_SUCCESS);
9187: }
9188: PetscCheck(dm->numbermonitors < MAXDMMONITORS, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Too many monitors set");
9189: dm->monitor[dm->numbermonitors] = f;
9190: dm->monitordestroy[dm->numbermonitors] = monitordestroy;
9191: dm->monitorcontext[dm->numbermonitors++] = mctx;
9192: PetscFunctionReturn(PETSC_SUCCESS);
9193: }
9195: /*@
9196: DMMonitorCancel - Clears all the monitor functions for a `DM` object.
9198: Logically Collective
9200: Input Parameter:
9201: . dm - the DM
9203: Options Database Key:
9204: . -dm_monitor_cancel - cancels all monitors that have been hardwired
9205: into a code by calls to `DMonitorSet()`, but does not cancel those
9206: set via the options database
9208: Level: intermediate
9210: Note:
9211: There is no way to clear one specific monitor from a `DM` object.
9213: .seealso: [](ch_dmbase), `DM`, `DMMonitorSet()`, `DMMonitorSetFromOptions()`, `DMMonitor()`
9214: @*/
9215: PetscErrorCode DMMonitorCancel(DM dm)
9216: {
9217: PetscInt m;
9219: PetscFunctionBegin;
9221: for (m = 0; m < dm->numbermonitors; ++m) {
9222: if (dm->monitordestroy[m]) PetscCall((*dm->monitordestroy[m])(&dm->monitorcontext[m]));
9223: }
9224: dm->numbermonitors = 0;
9225: PetscFunctionReturn(PETSC_SUCCESS);
9226: }
9228: /*@C
9229: DMMonitorSetFromOptions - Sets a monitor function and viewer appropriate for the type indicated by the user
9231: Collective
9233: Input Parameters:
9234: + dm - `DM` object you wish to monitor
9235: . name - the monitor type one is seeking
9236: . help - message indicating what monitoring is done
9237: . manual - manual page for the monitor
9238: . monitor - the monitor function, this must use a `PetscViewerFormat` as its context
9239: - 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
9241: Output Parameter:
9242: . flg - Flag set if the monitor was created
9244: Calling sequence of `monitor`:
9245: + dm - the `DM` to be monitored
9246: - ctx - monitor context
9248: Calling sequence of `monitorsetup`:
9249: + dm - the `DM` to be monitored
9250: - vf - the `PetscViewer` and format to be used by the monitor
9252: Level: developer
9254: .seealso: [](ch_dmbase), `DM`, `PetscOptionsCreateViewer()`, `PetscOptionsGetReal()`, `PetscOptionsHasName()`, `PetscOptionsGetString()`,
9255: `PetscOptionsGetIntArray()`, `PetscOptionsGetRealArray()`, `PetscOptionsBool()`,
9256: `PetscOptionsInt()`, `PetscOptionsString()`, `PetscOptionsReal()`,
9257: `PetscOptionsName()`, `PetscOptionsBegin()`, `PetscOptionsEnd()`, `PetscOptionsHeadBegin()`,
9258: `PetscOptionsStringArray()`, `PetscOptionsRealArray()`, `PetscOptionsScalar()`,
9259: `PetscOptionsBoolGroupBegin()`, `PetscOptionsBoolGroup()`, `PetscOptionsBoolGroupEnd()`,
9260: `PetscOptionsFList()`, `PetscOptionsEList()`, `DMMonitor()`, `DMMonitorSet()`
9261: @*/
9262: 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)
9263: {
9264: PetscViewer viewer;
9265: PetscViewerFormat format;
9267: PetscFunctionBegin;
9269: PetscCall(PetscOptionsCreateViewer(PetscObjectComm((PetscObject)dm), ((PetscObject)dm)->options, ((PetscObject)dm)->prefix, name, &viewer, &format, flg));
9270: if (*flg) {
9271: PetscViewerAndFormat *vf;
9273: PetscCall(PetscViewerAndFormatCreate(viewer, format, &vf));
9274: PetscCall(PetscViewerDestroy(&viewer));
9275: if (monitorsetup) PetscCall((*monitorsetup)(dm, vf));
9276: PetscCall(DMMonitorSet(dm, monitor, vf, (PetscCtxDestroyFn *)PetscViewerAndFormatDestroy));
9277: }
9278: PetscFunctionReturn(PETSC_SUCCESS);
9279: }
9281: /*@
9282: DMMonitor - runs the user provided monitor routines, if they exist
9284: Collective
9286: Input Parameter:
9287: . dm - The `DM`
9289: Level: developer
9291: Developer Note:
9292: Note should indicate when during the life of the `DM` the monitor is run. It appears to be
9293: related to the discretization process seems rather specialized since some `DM` have no
9294: concept of discretization.
9296: .seealso: [](ch_dmbase), `DM`, `DMMonitorSet()`, `DMMonitorSetFromOptions()`
9297: @*/
9298: PetscErrorCode DMMonitor(DM dm)
9299: {
9300: PetscInt m;
9302: PetscFunctionBegin;
9303: if (!dm) PetscFunctionReturn(PETSC_SUCCESS);
9305: for (m = 0; m < dm->numbermonitors; ++m) PetscCall((*dm->monitor[m])(dm, dm->monitorcontext[m]));
9306: PetscFunctionReturn(PETSC_SUCCESS);
9307: }
9309: /*@
9310: DMComputeError - Computes the error assuming the user has provided the exact solution functions
9312: Collective
9314: Input Parameters:
9315: + dm - The `DM`
9316: - sol - The solution vector
9318: Input/Output Parameter:
9319: . errors - An array of length Nf, the number of fields, or `NULL` for no output; on output
9320: contains the error in each field
9322: Output Parameter:
9323: . errorVec - A vector to hold the cellwise error (may be `NULL`)
9325: Level: developer
9327: Note:
9328: The exact solutions come from the `PetscDS` object, and the time comes from `DMGetOutputSequenceNumber()`.
9330: .seealso: [](ch_dmbase), `DM`, `DMMonitorSet()`, `DMGetRegionNumDS()`, `PetscDSGetExactSolution()`, `DMGetOutputSequenceNumber()`
9331: @*/
9332: PetscErrorCode DMComputeError(DM dm, Vec sol, PetscReal errors[], Vec *errorVec)
9333: {
9334: PetscErrorCode (**exactSol)(PetscInt, PetscReal, const PetscReal[], PetscInt, PetscScalar[], void *);
9335: void **ctxs;
9336: PetscReal time;
9337: PetscInt Nf, f, Nds, s;
9339: PetscFunctionBegin;
9340: PetscCall(DMGetNumFields(dm, &Nf));
9341: PetscCall(PetscCalloc2(Nf, &exactSol, Nf, &ctxs));
9342: PetscCall(DMGetNumDS(dm, &Nds));
9343: for (s = 0; s < Nds; ++s) {
9344: PetscDS ds;
9345: DMLabel label;
9346: IS fieldIS;
9347: const PetscInt *fields;
9348: PetscInt dsNf;
9350: PetscCall(DMGetRegionNumDS(dm, s, &label, &fieldIS, &ds, NULL));
9351: PetscCall(PetscDSGetNumFields(ds, &dsNf));
9352: if (fieldIS) PetscCall(ISGetIndices(fieldIS, &fields));
9353: for (f = 0; f < dsNf; ++f) {
9354: const PetscInt field = fields[f];
9355: PetscCall(PetscDSGetExactSolution(ds, field, &exactSol[field], &ctxs[field]));
9356: }
9357: if (fieldIS) PetscCall(ISRestoreIndices(fieldIS, &fields));
9358: }
9359: 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);
9360: PetscCall(DMGetOutputSequenceNumber(dm, NULL, &time));
9361: if (errors) PetscCall(DMComputeL2FieldDiff(dm, time, exactSol, ctxs, sol, errors));
9362: if (errorVec) {
9363: DM edm;
9364: DMPolytopeType ct;
9365: PetscBool simplex;
9366: PetscInt dim, cStart, Nf;
9368: PetscCall(DMClone(dm, &edm));
9369: PetscCall(DMGetDimension(edm, &dim));
9370: PetscCall(DMPlexGetHeightStratum(dm, 0, &cStart, NULL));
9371: PetscCall(DMPlexGetCellType(dm, cStart, &ct));
9372: simplex = DMPolytopeTypeGetNumVertices(ct) == DMPolytopeTypeGetDim(ct) + 1 ? PETSC_TRUE : PETSC_FALSE;
9373: PetscCall(DMGetNumFields(dm, &Nf));
9374: for (f = 0; f < Nf; ++f) {
9375: PetscFE fe, efe;
9376: PetscQuadrature q;
9377: const char *name;
9379: PetscCall(DMGetField(dm, f, NULL, (PetscObject *)&fe));
9380: PetscCall(PetscFECreateLagrange(PETSC_COMM_SELF, dim, Nf, simplex, 0, PETSC_DETERMINE, &efe));
9381: PetscCall(PetscObjectGetName((PetscObject)fe, &name));
9382: PetscCall(PetscObjectSetName((PetscObject)efe, name));
9383: PetscCall(PetscFEGetQuadrature(fe, &q));
9384: PetscCall(PetscFESetQuadrature(efe, q));
9385: PetscCall(DMSetField(edm, f, NULL, (PetscObject)efe));
9386: PetscCall(PetscFEDestroy(&efe));
9387: }
9388: PetscCall(DMCreateDS(edm));
9390: PetscCall(DMCreateGlobalVector(edm, errorVec));
9391: PetscCall(PetscObjectSetName((PetscObject)*errorVec, "Error"));
9392: PetscCall(DMPlexComputeL2DiffVec(dm, time, exactSol, ctxs, sol, *errorVec));
9393: PetscCall(DMDestroy(&edm));
9394: }
9395: PetscCall(PetscFree2(exactSol, ctxs));
9396: PetscFunctionReturn(PETSC_SUCCESS);
9397: }
9399: /*@
9400: DMGetNumAuxiliaryVec - Get the number of auxiliary vectors associated with this `DM`
9402: Not Collective
9404: Input Parameter:
9405: . dm - The `DM`
9407: Output Parameter:
9408: . numAux - The number of auxiliary data vectors
9410: Level: advanced
9412: .seealso: [](ch_dmbase), `DM`, `DMClearAuxiliaryVec()`, `DMSetAuxiliaryVec()`, `DMGetAuxiliaryLabels()`, `DMGetAuxiliaryVec()`
9413: @*/
9414: PetscErrorCode DMGetNumAuxiliaryVec(DM dm, PetscInt *numAux)
9415: {
9416: PetscFunctionBegin;
9418: PetscCall(PetscHMapAuxGetSize(dm->auxData, numAux));
9419: PetscFunctionReturn(PETSC_SUCCESS);
9420: }
9422: /*@
9423: DMGetAuxiliaryVec - Get the auxiliary vector for region specified by the given label and value, and equation part
9425: Not Collective
9427: Input Parameters:
9428: + dm - The `DM`
9429: . label - The `DMLabel`
9430: . value - The label value indicating the region
9431: - part - The equation part, or 0 if unused
9433: Output Parameter:
9434: . aux - The `Vec` holding auxiliary field data
9436: Level: advanced
9438: Note:
9439: If no auxiliary vector is found for this (label, value), (`NULL`, 0, 0) is checked as well.
9441: .seealso: [](ch_dmbase), `DM`, `DMClearAuxiliaryVec()`, `DMSetAuxiliaryVec()`, `DMGetNumAuxiliaryVec()`, `DMGetAuxiliaryLabels()`
9442: @*/
9443: PetscErrorCode DMGetAuxiliaryVec(DM dm, DMLabel label, PetscInt value, PetscInt part, Vec *aux)
9444: {
9445: PetscHashAuxKey key, wild = {NULL, 0, 0};
9446: PetscBool has;
9448: PetscFunctionBegin;
9451: key.label = label;
9452: key.value = value;
9453: key.part = part;
9454: PetscCall(PetscHMapAuxHas(dm->auxData, key, &has));
9455: if (has) PetscCall(PetscHMapAuxGet(dm->auxData, key, aux));
9456: else PetscCall(PetscHMapAuxGet(dm->auxData, wild, aux));
9457: PetscFunctionReturn(PETSC_SUCCESS);
9458: }
9460: /*@
9461: DMSetAuxiliaryVec - Set an auxiliary vector for region specified by the given label and value, and equation part
9463: Not Collective because auxiliary vectors are not parallel
9465: Input Parameters:
9466: + dm - The `DM`
9467: . label - The `DMLabel`
9468: . value - The label value indicating the region
9469: . part - The equation part, or 0 if unused
9470: - aux - The `Vec` holding auxiliary field data
9472: Level: advanced
9474: .seealso: [](ch_dmbase), `DM`, `DMClearAuxiliaryVec()`, `DMGetAuxiliaryVec()`, `DMGetAuxiliaryLabels()`, `DMCopyAuxiliaryVec()`
9475: @*/
9476: PetscErrorCode DMSetAuxiliaryVec(DM dm, DMLabel label, PetscInt value, PetscInt part, Vec aux)
9477: {
9478: Vec old;
9479: PetscHashAuxKey key;
9481: PetscFunctionBegin;
9484: key.label = label;
9485: key.value = value;
9486: key.part = part;
9487: PetscCall(PetscHMapAuxGet(dm->auxData, key, &old));
9488: PetscCall(PetscObjectReference((PetscObject)aux));
9489: if (!aux) PetscCall(PetscHMapAuxDel(dm->auxData, key));
9490: else PetscCall(PetscHMapAuxSet(dm->auxData, key, aux));
9491: PetscCall(VecDestroy(&old));
9492: PetscFunctionReturn(PETSC_SUCCESS);
9493: }
9495: /*@
9496: DMGetAuxiliaryLabels - Get the labels, values, and parts for all auxiliary vectors in this `DM`
9498: Not Collective
9500: Input Parameter:
9501: . dm - The `DM`
9503: Output Parameters:
9504: + labels - The `DMLabel`s for each `Vec`
9505: . values - The label values for each `Vec`
9506: - parts - The equation parts for each `Vec`
9508: Level: advanced
9510: Note:
9511: The arrays passed in must be at least as large as `DMGetNumAuxiliaryVec()`.
9513: .seealso: [](ch_dmbase), `DM`, `DMClearAuxiliaryVec()`, `DMGetNumAuxiliaryVec()`, `DMGetAuxiliaryVec()`, `DMSetAuxiliaryVec()`, `DMCopyAuxiliaryVec()`
9514: @*/
9515: PetscErrorCode DMGetAuxiliaryLabels(DM dm, DMLabel labels[], PetscInt values[], PetscInt parts[])
9516: {
9517: PetscHashAuxKey *keys;
9518: PetscInt n, i, off = 0;
9520: PetscFunctionBegin;
9522: PetscAssertPointer(labels, 2);
9523: PetscAssertPointer(values, 3);
9524: PetscAssertPointer(parts, 4);
9525: PetscCall(DMGetNumAuxiliaryVec(dm, &n));
9526: PetscCall(PetscMalloc1(n, &keys));
9527: PetscCall(PetscHMapAuxGetKeys(dm->auxData, &off, keys));
9528: for (i = 0; i < n; ++i) {
9529: labels[i] = keys[i].label;
9530: values[i] = keys[i].value;
9531: parts[i] = keys[i].part;
9532: }
9533: PetscCall(PetscFree(keys));
9534: PetscFunctionReturn(PETSC_SUCCESS);
9535: }
9537: /*@
9538: DMCopyAuxiliaryVec - Copy the auxiliary vector data on a `DM` to a new `DM`
9540: Not Collective
9542: Input Parameter:
9543: . dm - The `DM`
9545: Output Parameter:
9546: . dmNew - The new `DM`, now with the same auxiliary data
9548: Level: advanced
9550: Note:
9551: This is a shallow copy of the auxiliary vectors
9553: .seealso: [](ch_dmbase), `DM`, `DMClearAuxiliaryVec()`, `DMGetNumAuxiliaryVec()`, `DMGetAuxiliaryVec()`, `DMSetAuxiliaryVec()`
9554: @*/
9555: PetscErrorCode DMCopyAuxiliaryVec(DM dm, DM dmNew)
9556: {
9557: PetscFunctionBegin;
9560: if (dm == dmNew) PetscFunctionReturn(PETSC_SUCCESS);
9561: PetscCall(DMClearAuxiliaryVec(dmNew));
9563: PetscCall(PetscHMapAuxDestroy(&dmNew->auxData));
9564: PetscCall(PetscHMapAuxDuplicate(dm->auxData, &dmNew->auxData));
9565: {
9566: Vec *auxData;
9567: PetscInt n, i, off = 0;
9569: PetscCall(PetscHMapAuxGetSize(dmNew->auxData, &n));
9570: PetscCall(PetscMalloc1(n, &auxData));
9571: PetscCall(PetscHMapAuxGetVals(dmNew->auxData, &off, auxData));
9572: for (i = 0; i < n; ++i) PetscCall(PetscObjectReference((PetscObject)auxData[i]));
9573: PetscCall(PetscFree(auxData));
9574: }
9575: PetscFunctionReturn(PETSC_SUCCESS);
9576: }
9578: /*@
9579: DMClearAuxiliaryVec - Destroys the auxiliary vector information and creates a new empty one
9581: Not Collective
9583: Input Parameter:
9584: . dm - The `DM`
9586: Level: advanced
9588: .seealso: [](ch_dmbase), `DM`, `DMCopyAuxiliaryVec()`, `DMGetNumAuxiliaryVec()`, `DMGetAuxiliaryVec()`, `DMSetAuxiliaryVec()`
9589: @*/
9590: PetscErrorCode DMClearAuxiliaryVec(DM dm)
9591: {
9592: Vec *auxData;
9593: PetscInt n, i, off = 0;
9595: PetscFunctionBegin;
9596: PetscCall(PetscHMapAuxGetSize(dm->auxData, &n));
9597: PetscCall(PetscMalloc1(n, &auxData));
9598: PetscCall(PetscHMapAuxGetVals(dm->auxData, &off, auxData));
9599: for (i = 0; i < n; ++i) PetscCall(VecDestroy(&auxData[i]));
9600: PetscCall(PetscFree(auxData));
9601: PetscCall(PetscHMapAuxDestroy(&dm->auxData));
9602: PetscCall(PetscHMapAuxCreate(&dm->auxData));
9603: PetscFunctionReturn(PETSC_SUCCESS);
9604: }
9606: /*@
9607: DMPolytopeMatchOrientation - Determine an orientation (transformation) that takes the source face arrangement to the target face arrangement
9609: Not Collective
9611: Input Parameters:
9612: + ct - The `DMPolytopeType`
9613: . sourceCone - The source arrangement of faces
9614: - targetCone - The target arrangement of faces
9616: Output Parameters:
9617: + ornt - The orientation (transformation) which will take the source arrangement to the target arrangement
9618: - found - Flag indicating that a suitable orientation was found
9620: Level: advanced
9622: Note:
9623: An arrangement is a face order combined with an orientation for each face
9625: Each orientation (transformation) is labeled with an integer from negative `DMPolytopeTypeGetNumArrangements(ct)`/2 to `DMPolytopeTypeGetNumArrangements(ct)`/2
9626: that labels each arrangement (face ordering plus orientation for each face).
9628: See `DMPolytopeMatchVertexOrientation()` to find a new vertex orientation that takes the source vertex arrangement to the target vertex arrangement
9630: .seealso: [](ch_dmbase), `DM`, `DMPolytopeGetOrientation()`, `DMPolytopeMatchVertexOrientation()`, `DMPolytopeGetVertexOrientation()`
9631: @*/
9632: PetscErrorCode DMPolytopeMatchOrientation(DMPolytopeType ct, const PetscInt sourceCone[], const PetscInt targetCone[], PetscInt *ornt, PetscBool *found)
9633: {
9634: const PetscInt cS = DMPolytopeTypeGetConeSize(ct);
9635: const PetscInt nO = DMPolytopeTypeGetNumArrangements(ct) / 2;
9636: PetscInt o, c;
9638: PetscFunctionBegin;
9639: if (!nO) {
9640: *ornt = 0;
9641: *found = PETSC_TRUE;
9642: PetscFunctionReturn(PETSC_SUCCESS);
9643: }
9644: for (o = -nO; o < nO; ++o) {
9645: const PetscInt *arr = DMPolytopeTypeGetArrangement(ct, o);
9647: for (c = 0; c < cS; ++c)
9648: if (sourceCone[arr[c * 2]] != targetCone[c]) break;
9649: if (c == cS) {
9650: *ornt = o;
9651: break;
9652: }
9653: }
9654: *found = o == nO ? PETSC_FALSE : PETSC_TRUE;
9655: PetscFunctionReturn(PETSC_SUCCESS);
9656: }
9658: /*@
9659: DMPolytopeGetOrientation - Determine an orientation (transformation) that takes the source face arrangement to the target face arrangement
9661: Not Collective
9663: Input Parameters:
9664: + ct - The `DMPolytopeType`
9665: . sourceCone - The source arrangement of faces
9666: - targetCone - The target arrangement of faces
9668: Output Parameter:
9669: . ornt - The orientation (transformation) which will take the source arrangement to the target arrangement
9671: Level: advanced
9673: Note:
9674: This function is the same as `DMPolytopeMatchOrientation()` except it will generate an error if no suitable orientation can be found.
9676: Developer Note:
9677: It is unclear why this function needs to exist since one can simply call `DMPolytopeMatchOrientation()` and error if none is found
9679: .seealso: [](ch_dmbase), `DM`, `DMPolytopeType`, `DMPolytopeMatchOrientation()`, `DMPolytopeGetVertexOrientation()`, `DMPolytopeMatchVertexOrientation()`
9680: @*/
9681: PetscErrorCode DMPolytopeGetOrientation(DMPolytopeType ct, const PetscInt sourceCone[], const PetscInt targetCone[], PetscInt *ornt)
9682: {
9683: PetscBool found;
9685: PetscFunctionBegin;
9686: PetscCall(DMPolytopeMatchOrientation(ct, sourceCone, targetCone, ornt, &found));
9687: PetscCheck(found, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Could not find orientation for %s", DMPolytopeTypes[ct]);
9688: PetscFunctionReturn(PETSC_SUCCESS);
9689: }
9691: /*@
9692: DMPolytopeMatchVertexOrientation - Determine an orientation (transformation) that takes the source vertex arrangement to the target vertex arrangement
9694: Not Collective
9696: Input Parameters:
9697: + ct - The `DMPolytopeType`
9698: . sourceVert - The source arrangement of vertices
9699: - targetVert - The target arrangement of vertices
9701: Output Parameters:
9702: + ornt - The orientation (transformation) which will take the source arrangement to the target arrangement
9703: - found - Flag indicating that a suitable orientation was found
9705: Level: advanced
9707: Notes:
9708: An arrangement is a vertex order
9710: Each orientation (transformation) is labeled with an integer from negative `DMPolytopeTypeGetNumArrangements(ct)`/2 to `DMPolytopeTypeGetNumArrangements(ct)`/2
9711: that labels each arrangement (vertex ordering).
9713: See `DMPolytopeMatchOrientation()` to find a new face orientation that takes the source face arrangement to the target face arrangement
9715: .seealso: [](ch_dmbase), `DM`, `DMPolytopeType`, `DMPolytopeGetOrientation()`, `DMPolytopeMatchOrientation()`, `DMPolytopeTypeGetNumVertices()`, `DMPolytopeTypeGetVertexArrangement()`
9716: @*/
9717: PetscErrorCode DMPolytopeMatchVertexOrientation(DMPolytopeType ct, const PetscInt sourceVert[], const PetscInt targetVert[], PetscInt *ornt, PetscBool *found)
9718: {
9719: const PetscInt cS = DMPolytopeTypeGetNumVertices(ct);
9720: const PetscInt nO = DMPolytopeTypeGetNumArrangements(ct) / 2;
9721: PetscInt o, c;
9723: PetscFunctionBegin;
9724: if (!nO) {
9725: *ornt = 0;
9726: *found = PETSC_TRUE;
9727: PetscFunctionReturn(PETSC_SUCCESS);
9728: }
9729: for (o = -nO; o < nO; ++o) {
9730: const PetscInt *arr = DMPolytopeTypeGetVertexArrangement(ct, o);
9732: for (c = 0; c < cS; ++c)
9733: if (sourceVert[arr[c]] != targetVert[c]) break;
9734: if (c == cS) {
9735: *ornt = o;
9736: break;
9737: }
9738: }
9739: *found = o == nO ? PETSC_FALSE : PETSC_TRUE;
9740: PetscFunctionReturn(PETSC_SUCCESS);
9741: }
9743: /*@
9744: DMPolytopeGetVertexOrientation - Determine an orientation (transformation) that takes the source vertex arrangement to the target vertex arrangement
9746: Not Collective
9748: Input Parameters:
9749: + ct - The `DMPolytopeType`
9750: . sourceCone - The source arrangement of vertices
9751: - targetCone - The target arrangement of vertices
9753: Output Parameter:
9754: . ornt - The orientation (transformation) which will take the source arrangement to the target arrangement
9756: Level: advanced
9758: Note:
9759: This function is the same as `DMPolytopeMatchVertexOrientation()` except it errors if not orientation is possible.
9761: Developer Note:
9762: It is unclear why this function needs to exist since one can simply call `DMPolytopeMatchVertexOrientation()` and error if none is found
9764: .seealso: [](ch_dmbase), `DM`, `DMPolytopeType`, `DMPolytopeMatchVertexOrientation()`, `DMPolytopeGetOrientation()`
9765: @*/
9766: PetscErrorCode DMPolytopeGetVertexOrientation(DMPolytopeType ct, const PetscInt sourceCone[], const PetscInt targetCone[], PetscInt *ornt)
9767: {
9768: PetscBool found;
9770: PetscFunctionBegin;
9771: PetscCall(DMPolytopeMatchVertexOrientation(ct, sourceCone, targetCone, ornt, &found));
9772: PetscCheck(found, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Could not find orientation for %s", DMPolytopeTypes[ct]);
9773: PetscFunctionReturn(PETSC_SUCCESS);
9774: }
9776: /*@
9777: DMPolytopeInCellTest - Check whether a point lies inside the reference cell of given type
9779: Not Collective
9781: Input Parameters:
9782: + ct - The `DMPolytopeType`
9783: - point - Coordinates of the point
9785: Output Parameter:
9786: . inside - Flag indicating whether the point is inside the reference cell of given type
9788: Level: advanced
9790: .seealso: [](ch_dmbase), `DM`, `DMPolytopeType`, `DMLocatePoints()`
9791: @*/
9792: PetscErrorCode DMPolytopeInCellTest(DMPolytopeType ct, const PetscReal point[], PetscBool *inside)
9793: {
9794: PetscReal sum = 0.0;
9795: PetscInt d;
9797: PetscFunctionBegin;
9798: *inside = PETSC_TRUE;
9799: switch (ct) {
9800: case DM_POLYTOPE_TRIANGLE:
9801: case DM_POLYTOPE_TETRAHEDRON:
9802: for (d = 0; d < DMPolytopeTypeGetDim(ct); ++d) {
9803: if (point[d] < -1.0) {
9804: *inside = PETSC_FALSE;
9805: break;
9806: }
9807: sum += point[d];
9808: }
9809: if (sum > PETSC_SMALL) {
9810: *inside = PETSC_FALSE;
9811: break;
9812: }
9813: break;
9814: case DM_POLYTOPE_QUADRILATERAL:
9815: case DM_POLYTOPE_HEXAHEDRON:
9816: for (d = 0; d < DMPolytopeTypeGetDim(ct); ++d)
9817: if (PetscAbsReal(point[d]) > 1. + PETSC_SMALL) {
9818: *inside = PETSC_FALSE;
9819: break;
9820: }
9821: break;
9822: default:
9823: SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Unsupported polytope type %s", DMPolytopeTypes[ct]);
9824: }
9825: PetscFunctionReturn(PETSC_SUCCESS);
9826: }
9828: /*@
9829: DMReorderSectionSetDefault - Set flag indicating whether the local section should be reordered by default
9831: Logically collective
9833: Input Parameters:
9834: + dm - The DM
9835: - reorder - Flag for reordering
9837: Level: intermediate
9839: .seealso: `DMReorderSectionGetDefault()`
9840: @*/
9841: PetscErrorCode DMReorderSectionSetDefault(DM dm, DMReorderDefaultFlag reorder)
9842: {
9843: PetscFunctionBegin;
9845: PetscTryMethod(dm, "DMReorderSectionSetDefault_C", (DM, DMReorderDefaultFlag), (dm, reorder));
9846: PetscFunctionReturn(PETSC_SUCCESS);
9847: }
9849: /*@
9850: DMReorderSectionGetDefault - Get flag indicating whether the local section should be reordered by default
9852: Not collective
9854: Input Parameter:
9855: . dm - The DM
9857: Output Parameter:
9858: . reorder - Flag for reordering
9860: Level: intermediate
9862: .seealso: `DMReorderSetDefault()`
9863: @*/
9864: PetscErrorCode DMReorderSectionGetDefault(DM dm, DMReorderDefaultFlag *reorder)
9865: {
9866: PetscFunctionBegin;
9868: PetscAssertPointer(reorder, 2);
9869: *reorder = DM_REORDER_DEFAULT_NOTSET;
9870: PetscTryMethod(dm, "DMReorderSectionGetDefault_C", (DM, DMReorderDefaultFlag *), (dm, reorder));
9871: PetscFunctionReturn(PETSC_SUCCESS);
9872: }
9874: /*@
9875: DMReorderSectionSetType - Set the type of local section reordering
9877: Logically collective
9879: Input Parameters:
9880: + dm - The DM
9881: - reorder - The reordering method
9883: Level: intermediate
9885: .seealso: `DMReorderSectionGetType()`, `DMReorderSectionSetDefault()`
9886: @*/
9887: PetscErrorCode DMReorderSectionSetType(DM dm, MatOrderingType reorder)
9888: {
9889: PetscFunctionBegin;
9891: PetscTryMethod(dm, "DMReorderSectionSetType_C", (DM, MatOrderingType), (dm, reorder));
9892: PetscFunctionReturn(PETSC_SUCCESS);
9893: }
9895: /*@
9896: DMReorderSectionGetType - Get the reordering type for the local section
9898: Not collective
9900: Input Parameter:
9901: . dm - The DM
9903: Output Parameter:
9904: . reorder - The reordering method
9906: Level: intermediate
9908: .seealso: `DMReorderSetDefault()`, `DMReorderSectionGetDefault()`
9909: @*/
9910: PetscErrorCode DMReorderSectionGetType(DM dm, MatOrderingType *reorder)
9911: {
9912: PetscFunctionBegin;
9914: PetscAssertPointer(reorder, 2);
9915: *reorder = NULL;
9916: PetscTryMethod(dm, "DMReorderSectionGetType_C", (DM, MatOrderingType *), (dm, reorder));
9917: PetscFunctionReturn(PETSC_SUCCESS);
9918: }