Actual source code: dm.c
1: #include <petscvec.h>
2: #include <petsc/private/dmimpl.h>
3: #include <petsc/private/dmlabelimpl.h>
4: #include <petsc/private/petscdsimpl.h>
5: #include <petscdmplex.h>
6: #include <petscdmceed.h>
7: #include <petscdmfield.h>
8: #include <petscsf.h>
9: #include <petscds.h>
11: #if PetscDefined(HAVE_LIBCEED)
12: #include <petscfeceed.h>
13: #endif
15: PetscClassId DM_CLASSID;
16: PetscClassId DMLABEL_CLASSID;
17: PetscLogEvent DM_Convert, DM_GlobalToLocal, DM_LocalToGlobal, DM_LocalToLocal, DM_LocatePoints, DM_Coarsen, DM_Refine, DM_CreateInterpolation, DM_CreateRestriction, DM_CreateInjection, DM_CreateMatrix, DM_CreateMassMatrix, DM_Load, DM_View, DM_AdaptInterpolator, DM_ProjectFunction;
19: const char *const DMBoundaryTypes[] = {"NONE", "GHOSTED", "MIRROR", "PERIODIC", "TWIST", "DMBoundaryType", "DM_BOUNDARY_", NULL};
20: const char *const DMBoundaryConditionTypes[] = {"INVALID", "ESSENTIAL", "NATURAL", "INVALID", "LOWER_BOUND", "ESSENTIAL_FIELD", "NATURAL_FIELD", "INVALID", "UPPER_BOUND", "ESSENTIAL_BD_FIELD", "NATURAL_RIEMANN", "DMBoundaryConditionType",
21: "DM_BC_", NULL};
22: const char *const DMBlockingTypes[] = {"TOPOLOGICAL_POINT", "FIELD_NODE", "DMBlockingType", "DM_BLOCKING_", NULL};
23: const char *const DMPolytopeTypes[] =
24: {"vertex", "segment", "tensor_segment", "triangle", "quadrilateral", "tensor_quad", "tetrahedron", "hexahedron", "triangular_prism", "tensor_triangular_prism", "tensor_quadrilateral_prism", "pyramid", "FV_ghost_cell", "interior_ghost_cell",
25: "unknown", "unknown_cell", "unknown_face", "invalid", "DMPolytopeType", "DM_POLYTOPE_", NULL};
26: const char *const DMCopyLabelsModes[] = {"replace", "keep", "fail", "DMCopyLabelsMode", "DM_COPY_LABELS_", NULL};
28: /*@
29: DMCreate - Creates an empty `DM` object. `DM`s are the abstract objects in PETSc that mediate between meshes and discretizations and the
30: algebraic solvers, time integrators, and optimization algorithms in PETSc.
32: Collective
34: Input Parameter:
35: . comm - The communicator for the `DM` object
37: Output Parameter:
38: . dm - The `DM` object
40: Level: beginner
42: Notes:
43: See `DMType` for a brief summary of available `DM`.
45: The type must then be set with `DMSetType()`. If you never call `DMSetType()` it will generate an
46: error when you try to use the `dm`.
48: `DM` is an orphan initialism or orphan acronym, the letters have no meaning and never did.
50: .seealso: [](ch_dmbase), `DM`, `DMSetType()`, `DMType`, `DMDACreate()`, `DMDA`, `DMSLICED`, `DMCOMPOSITE`, `DMPLEX`, `DMMOAB`, `DMNETWORK`
51: @*/
52: PetscErrorCode DMCreate(MPI_Comm comm, DM *dm)
53: {
54: DM v;
55: PetscDS ds;
57: PetscFunctionBegin;
58: PetscAssertPointer(dm, 2);
60: PetscCall(DMInitializePackage());
61: PetscCall(PetscHeaderCreate(v, DM_CLASSID, "DM", "Distribution Manager", "DM", comm, DMDestroy, DMView));
62: ((PetscObject)v)->non_cyclic_references = &DMCountNonCyclicReferences;
63: v->setupcalled = PETSC_FALSE;
64: v->setfromoptionscalled = PETSC_FALSE;
65: v->ltogmap = NULL;
66: v->bind_below = 0;
67: v->bs = 1;
68: v->coloringtype = IS_COLORING_GLOBAL;
69: PetscCall(PetscSFCreate(comm, &v->sf));
70: PetscCall(PetscSFCreate(comm, &v->sectionSF));
71: v->labels = NULL;
72: v->adjacency[0] = PETSC_FALSE;
73: v->adjacency[1] = PETSC_TRUE;
74: v->depthLabel = NULL;
75: v->celltypeLabel = NULL;
76: v->localSection = NULL;
77: v->globalSection = NULL;
78: v->defaultConstraint.section = NULL;
79: v->defaultConstraint.mat = NULL;
80: v->defaultConstraint.bias = NULL;
81: v->coordinates[0].dim = PETSC_DEFAULT;
82: v->coordinates[1].dim = PETSC_DEFAULT;
83: v->sparseLocalize = PETSC_TRUE;
84: v->dim = PETSC_DETERMINE;
85: PetscCall(PetscDSCreate(PETSC_COMM_SELF, &ds));
86: PetscCall(DMSetRegionDS(v, NULL, NULL, ds, NULL));
87: PetscCall(PetscDSDestroy(&ds));
88: PetscCall(PetscHMapAuxCreate(&v->auxData));
89: v->dmBC = NULL;
90: v->coarseMesh = NULL;
91: v->outputSequenceNum = -1;
92: v->outputSequenceVal = 0.0;
93: PetscCall(DMSetVecType(v, VECSTANDARD));
94: PetscCall(DMSetMatType(v, MATAIJ));
96: *dm = v;
97: PetscFunctionReturn(PETSC_SUCCESS);
98: }
100: /*@
101: DMClone - Creates a `DM` object with the same topology as the original.
103: Collective
105: Input Parameter:
106: . dm - The original `DM` object
108: Output Parameter:
109: . newdm - The new `DM` object
111: Level: beginner
113: Notes:
114: For some `DM` implementations this is a shallow clone, the result of which may share (reference counted) information with its parent. For example,
115: `DMClone()` applied to a `DMPLEX` object will result in a new `DMPLEX` that shares the topology with the original `DMPLEX`. It does not
116: share the `PetscSection` of the original `DM`.
118: The clone is considered set up if the original has been set up.
120: Use `DMConvert()` for a general way to create new `DM` from a given `DM`
122: .seealso: [](ch_dmbase), `DM`, `DMDestroy()`, `DMCreate()`, `DMSetType()`, `DMSetLocalSection()`, `DMSetGlobalSection()`, `DMPLEX`, `DMConvert()`
123: @*/
124: PetscErrorCode DMClone(DM dm, DM *newdm)
125: {
126: PetscSF sf;
127: Vec coords;
128: void *ctx;
129: MatOrderingType otype;
130: DMReorderDefaultFlag flg;
131: PetscInt dim, cdim, i;
132: PetscBool sparse;
134: PetscFunctionBegin;
136: PetscAssertPointer(newdm, 2);
137: PetscCall(DMCreate(PetscObjectComm((PetscObject)dm), newdm));
138: PetscCall(DMCopyLabels(dm, *newdm, PETSC_COPY_VALUES, PETSC_TRUE, DM_COPY_LABELS_FAIL));
139: (*newdm)->leveldown = dm->leveldown;
140: (*newdm)->levelup = dm->levelup;
141: (*newdm)->prealloc_only = dm->prealloc_only;
142: (*newdm)->prealloc_skip = dm->prealloc_skip;
143: PetscCall(PetscFree((*newdm)->vectype));
144: PetscCall(PetscStrallocpy(dm->vectype, (char **)&(*newdm)->vectype));
145: PetscCall(PetscFree((*newdm)->mattype));
146: PetscCall(PetscStrallocpy(dm->mattype, (char **)&(*newdm)->mattype));
147: PetscCall(DMGetDimension(dm, &dim));
148: PetscCall(DMSetDimension(*newdm, dim));
149: PetscTryTypeMethod(dm, clone, newdm);
150: (*newdm)->setupcalled = dm->setupcalled;
151: PetscCall(DMGetPointSF(dm, &sf));
152: PetscCall(DMSetPointSF(*newdm, sf));
153: PetscCall(DMGetApplicationContext(dm, &ctx));
154: PetscCall(DMSetApplicationContext(*newdm, ctx));
155: PetscCall(DMReorderSectionGetDefault(dm, &flg));
156: PetscCall(DMReorderSectionSetDefault(*newdm, flg));
157: PetscCall(DMReorderSectionGetType(dm, &otype));
158: PetscCall(DMReorderSectionSetType(*newdm, otype));
159: for (i = 0; i < 2; ++i) {
160: if (dm->coordinates[i].dm) {
161: DM ncdm;
162: PetscSection cs;
163: PetscInt pEndMax = -1;
165: PetscCall(DMGetLocalSection(dm->coordinates[i].dm, &cs));
166: if (cs) PetscCall(PetscSectionGetChart(cs, NULL, &pEndMax));
167: PetscCallMPI(MPIU_Allreduce(MPI_IN_PLACE, &pEndMax, 1, MPIU_INT, MPI_MAX, PetscObjectComm((PetscObject)dm)));
168: if (pEndMax >= 0) {
169: PetscCall(DMClone(dm->coordinates[i].dm, &ncdm));
170: PetscCall(DMCopyDisc(dm->coordinates[i].dm, ncdm));
171: PetscCall(DMSetLocalSection(ncdm, cs));
172: if (dm->coordinates[i].dm->periodic.setup) {
173: ncdm->periodic.setup = dm->coordinates[i].dm->periodic.setup;
174: PetscCall(ncdm->periodic.setup(ncdm));
175: }
176: if (i) PetscCall(DMSetCellCoordinateDM(*newdm, ncdm));
177: else PetscCall(DMSetCoordinateDM(*newdm, ncdm));
178: PetscCall(DMDestroy(&ncdm));
179: }
180: }
181: }
182: PetscCall(DMGetCoordinateDim(dm, &cdim));
183: PetscCall(DMSetCoordinateDim(*newdm, cdim));
184: PetscCall(DMGetCoordinatesLocal(dm, &coords));
185: if (coords) {
186: PetscCall(DMSetCoordinatesLocal(*newdm, coords));
187: } else {
188: PetscCall(DMGetCoordinates(dm, &coords));
189: if (coords) PetscCall(DMSetCoordinates(*newdm, coords));
190: }
191: PetscCall(DMGetSparseLocalize(dm, &sparse));
192: PetscCall(DMSetSparseLocalize(*newdm, sparse));
193: PetscCall(DMGetCellCoordinatesLocal(dm, &coords));
194: if (coords) {
195: PetscCall(DMSetCellCoordinatesLocal(*newdm, coords));
196: } else {
197: PetscCall(DMGetCellCoordinates(dm, &coords));
198: if (coords) PetscCall(DMSetCellCoordinates(*newdm, coords));
199: }
200: {
201: const PetscReal *maxCell, *Lstart, *L;
203: PetscCall(DMGetPeriodicity(dm, &maxCell, &Lstart, &L));
204: PetscCall(DMSetPeriodicity(*newdm, maxCell, Lstart, L));
205: }
206: {
207: PetscBool useCone, useClosure;
209: PetscCall(DMGetAdjacency(dm, PETSC_DEFAULT, &useCone, &useClosure));
210: PetscCall(DMSetAdjacency(*newdm, PETSC_DEFAULT, useCone, useClosure));
211: }
212: PetscFunctionReturn(PETSC_SUCCESS);
213: }
215: /*@
216: DMSetVecType - Sets the type of vector to be created with `DMCreateLocalVector()` and `DMCreateGlobalVector()`
218: Logically Collective
220: Input Parameters:
221: + dm - initial distributed array
222: - ctype - the vector type, for example `VECSTANDARD`, `VECCUDA`, or `VECVIENNACL`
224: Options Database Key:
225: . -dm_vec_type ctype - the type of vector to create
227: Level: intermediate
229: .seealso: [](ch_dmbase), `DM`, `DMCreate()`, `DMDestroy()`, `DMDAInterpolationType`, `VecType`, `DMGetVecType()`, `DMSetMatType()`, `DMGetMatType()`,
230: `VECSTANDARD`, `VECCUDA`, `VECVIENNACL`, `DMCreateLocalVector()`, `DMCreateGlobalVector()`
231: @*/
232: PetscErrorCode DMSetVecType(DM dm, VecType ctype)
233: {
234: char *tmp;
236: PetscFunctionBegin;
238: PetscAssertPointer(ctype, 2);
239: tmp = (char *)dm->vectype;
240: PetscCall(PetscStrallocpy(ctype, (char **)&dm->vectype));
241: PetscCall(PetscFree(tmp));
242: PetscFunctionReturn(PETSC_SUCCESS);
243: }
245: /*@
246: DMGetVecType - Gets the type of vector created with `DMCreateLocalVector()` and `DMCreateGlobalVector()`
248: Logically Collective
250: Input Parameter:
251: . da - initial distributed array
253: Output Parameter:
254: . ctype - the vector type
256: Level: intermediate
258: .seealso: [](ch_dmbase), `DM`, `DMCreate()`, `DMDestroy()`, `DMDAInterpolationType`, `VecType`, `DMSetMatType()`, `DMGetMatType()`, `DMSetVecType()`
259: @*/
260: PetscErrorCode DMGetVecType(DM da, VecType *ctype)
261: {
262: PetscFunctionBegin;
264: *ctype = da->vectype;
265: PetscFunctionReturn(PETSC_SUCCESS);
266: }
268: /*@
269: VecGetDM - Gets the `DM` defining the data layout of the vector
271: Not Collective
273: Input Parameter:
274: . v - The `Vec`
276: Output Parameter:
277: . dm - The `DM`
279: Level: intermediate
281: Note:
282: A `Vec` may not have a `DM` associated with it.
284: .seealso: [](ch_dmbase), `DM`, `VecSetDM()`, `DMGetLocalVector()`, `DMGetGlobalVector()`, `DMSetVecType()`
285: @*/
286: PetscErrorCode VecGetDM(Vec v, DM *dm)
287: {
288: PetscFunctionBegin;
290: PetscAssertPointer(dm, 2);
291: PetscCall(PetscObjectQuery((PetscObject)v, "__PETSc_dm", (PetscObject *)dm));
292: PetscFunctionReturn(PETSC_SUCCESS);
293: }
295: /*@
296: VecSetDM - Sets the `DM` defining the data layout of the vector.
298: Not Collective
300: Input Parameters:
301: + v - The `Vec`
302: - dm - The `DM`
304: Level: developer
306: Notes:
307: This is rarely used, generally one uses `DMGetLocalVector()` or `DMGetGlobalVector()` to create a vector associated with a given `DM`
309: This is NOT the same as `DMCreateGlobalVector()` since it does not change the view methods or perform other customization, but merely sets the `DM` member.
311: .seealso: [](ch_dmbase), `DM`, `VecGetDM()`, `DMGetLocalVector()`, `DMGetGlobalVector()`, `DMSetVecType()`
312: @*/
313: PetscErrorCode VecSetDM(Vec v, DM dm)
314: {
315: PetscFunctionBegin;
318: PetscCall(PetscObjectCompose((PetscObject)v, "__PETSc_dm", (PetscObject)dm));
319: PetscFunctionReturn(PETSC_SUCCESS);
320: }
322: /*@
323: DMSetISColoringType - Sets the type of coloring, `IS_COLORING_GLOBAL` or `IS_COLORING_LOCAL` that is created by the `DM`
325: Logically Collective
327: Input Parameters:
328: + dm - the `DM` context
329: - ctype - the matrix type
331: Options Database Key:
332: . -dm_is_coloring_type (global|local) - see `ISColoringType`
334: Level: intermediate
336: .seealso: [](ch_dmbase), `DM`, `DMDACreate1d()`, `DMDACreate2d()`, `DMDACreate3d()`, `DMCreateMatrix()`, `DMCreateMassMatrix()`, `DMSetMatrixPreallocateOnly()`, `MatType`, `DMGetMatType()`,
337: `DMGetISColoringType()`, `ISColoringType`, `IS_COLORING_GLOBAL`, `IS_COLORING_LOCAL`
338: @*/
339: PetscErrorCode DMSetISColoringType(DM dm, ISColoringType ctype)
340: {
341: PetscFunctionBegin;
343: dm->coloringtype = ctype;
344: PetscFunctionReturn(PETSC_SUCCESS);
345: }
347: /*@
348: DMGetISColoringType - Gets the type of coloring, `IS_COLORING_GLOBAL` or `IS_COLORING_LOCAL` that is created by the `DM`
350: Logically Collective
352: Input Parameter:
353: . dm - the `DM` context
355: Output Parameter:
356: . ctype - the matrix type
358: Level: intermediate
360: .seealso: [](ch_dmbase), `DM`, `DMDACreate1d()`, `DMDACreate2d()`, `DMDACreate3d()`, `DMCreateMatrix()`, `DMCreateMassMatrix()`, `DMSetMatrixPreallocateOnly()`, `MatType`, `DMGetMatType()`,
361: `ISColoringType`, `IS_COLORING_GLOBAL`, `IS_COLORING_LOCAL`
362: @*/
363: PetscErrorCode DMGetISColoringType(DM dm, ISColoringType *ctype)
364: {
365: PetscFunctionBegin;
367: *ctype = dm->coloringtype;
368: PetscFunctionReturn(PETSC_SUCCESS);
369: }
371: /*@
372: DMSetMatType - Sets the type of matrix created with `DMCreateMatrix()`
374: Logically Collective
376: Input Parameters:
377: + dm - the `DM` context
378: - ctype - the matrix type, for example `MATMPIAIJ`
380: Options Database Key:
381: . -dm_mat_type ctype - the type of the matrix to create, see `MatType`
383: Level: intermediate
385: .seealso: [](ch_dmbase), `DM`, `MatType`, `DMDACreate1d()`, `DMDACreate2d()`, `DMDACreate3d()`, `DMCreateMatrix()`, `DMCreateMassMatrix()`, `DMSetMatrixPreallocateOnly()`, `DMGetMatType()`, `DMCreateGlobalVector()`, `DMCreateLocalVector()`
386: @*/
387: PetscErrorCode DMSetMatType(DM dm, MatType ctype)
388: {
389: char *tmp;
391: PetscFunctionBegin;
393: PetscAssertPointer(ctype, 2);
394: tmp = (char *)dm->mattype;
395: PetscCall(PetscStrallocpy(ctype, (char **)&dm->mattype));
396: PetscCall(PetscFree(tmp));
397: PetscFunctionReturn(PETSC_SUCCESS);
398: }
400: /*@
401: DMGetMatType - Gets the type of matrix that would be created with `DMCreateMatrix()`
403: Logically Collective
405: Input Parameter:
406: . dm - the `DM` context
408: Output Parameter:
409: . ctype - the matrix type
411: Level: intermediate
413: .seealso: [](ch_dmbase), `DM`, `DMDACreate1d()`, `DMDACreate2d()`, `DMDACreate3d()`, `DMCreateMatrix()`, `DMCreateMassMatrix()`, `DMSetMatrixPreallocateOnly()`, `MatType`, `DMSetMatType()`
414: @*/
415: PetscErrorCode DMGetMatType(DM dm, MatType *ctype)
416: {
417: PetscFunctionBegin;
419: *ctype = dm->mattype;
420: PetscFunctionReturn(PETSC_SUCCESS);
421: }
423: /*@
424: MatGetDM - Gets the `DM` defining the data layout of the matrix
426: Not Collective
428: Input Parameter:
429: . A - The `Mat`
431: Output Parameter:
432: . dm - The `DM`
434: Level: intermediate
436: Note:
437: A matrix may not have a `DM` associated with it
439: Developer Note:
440: Since the `Mat` class doesn't know about the `DM` class the `DM` object is associated with the `Mat` through a `PetscObjectCompose()` operation
442: .seealso: [](ch_dmbase), `DM`, `MatSetDM()`, `DMCreateMatrix()`, `DMSetMatType()`
443: @*/
444: PetscErrorCode MatGetDM(Mat A, DM *dm)
445: {
446: PetscFunctionBegin;
448: PetscAssertPointer(dm, 2);
449: PetscCall(PetscObjectQuery((PetscObject)A, "__PETSc_dm", (PetscObject *)dm));
450: PetscFunctionReturn(PETSC_SUCCESS);
451: }
453: /*@
454: MatSetDM - Sets the `DM` defining the data layout of the matrix
456: Not Collective
458: Input Parameters:
459: + A - The `Mat`
460: - dm - The `DM`
462: Level: developer
464: Note:
465: This is rarely used in practice, rather `DMCreateMatrix()` is used to create a matrix associated with a particular `DM`
467: Developer Note:
468: Since the `Mat` class doesn't know about the `DM` class the `DM` object is associated with
469: the `Mat` through a `PetscObjectCompose()` operation
471: .seealso: [](ch_dmbase), `DM`, `MatGetDM()`, `DMCreateMatrix()`, `DMSetMatType()`
472: @*/
473: PetscErrorCode MatSetDM(Mat A, DM dm)
474: {
475: PetscFunctionBegin;
478: PetscCall(PetscObjectCompose((PetscObject)A, "__PETSc_dm", (PetscObject)dm));
479: PetscFunctionReturn(PETSC_SUCCESS);
480: }
482: /*@
483: DMSetOptionsPrefix - Sets the prefix prepended to all option names when searching through the options database
485: Logically Collective
487: Input Parameters:
488: + dm - the `DM` context
489: - prefix - the prefix to prepend
491: Level: advanced
493: Note:
494: A hyphen (-) must NOT be given at the beginning of the prefix name.
495: The first character of all runtime options is AUTOMATICALLY the hyphen.
497: .seealso: [](ch_dmbase), `DM`, `PetscObjectSetOptionsPrefix()`, `DMSetFromOptions()`
498: @*/
499: PetscErrorCode DMSetOptionsPrefix(DM dm, const char prefix[])
500: {
501: PetscFunctionBegin;
503: PetscCall(PetscObjectSetOptionsPrefix((PetscObject)dm, prefix));
504: if (dm->sf) PetscCall(PetscObjectSetOptionsPrefix((PetscObject)dm->sf, prefix));
505: if (dm->sectionSF) PetscCall(PetscObjectSetOptionsPrefix((PetscObject)dm->sectionSF, prefix));
506: PetscFunctionReturn(PETSC_SUCCESS);
507: }
509: /*@
510: DMAppendOptionsPrefix - Appends an additional string to an already existing prefix used for searching for
511: `DM` options in the options database.
513: Logically Collective
515: Input Parameters:
516: + dm - the `DM` context
517: - prefix - the string to append to the current prefix
519: Level: advanced
521: Note:
522: If the `DM` does not currently have an options prefix then this value is used alone as the prefix as if `DMSetOptionsPrefix()` had been called.
523: A hyphen (-) must NOT be given at the beginning of the prefix name.
524: The first character of all runtime options is AUTOMATICALLY the hyphen.
526: .seealso: [](ch_dmbase), `DM`, `DMSetOptionsPrefix()`, `DMGetOptionsPrefix()`, `PetscObjectAppendOptionsPrefix()`, `DMSetFromOptions()`
527: @*/
528: PetscErrorCode DMAppendOptionsPrefix(DM dm, const char prefix[])
529: {
530: PetscFunctionBegin;
532: PetscCall(PetscObjectAppendOptionsPrefix((PetscObject)dm, prefix));
533: PetscFunctionReturn(PETSC_SUCCESS);
534: }
536: /*@
537: DMGetOptionsPrefix - Gets the prefix used for searching for all
538: DM options in the options database.
540: Not Collective
542: Input Parameter:
543: . dm - the `DM` context
545: Output Parameter:
546: . prefix - pointer to the prefix string used is returned
548: Level: advanced
550: .seealso: [](ch_dmbase), `DM`, `DMSetOptionsPrefix()`, `DMAppendOptionsPrefix()`, `DMSetFromOptions()`
551: @*/
552: PetscErrorCode DMGetOptionsPrefix(DM dm, const char *prefix[])
553: {
554: PetscFunctionBegin;
556: PetscCall(PetscObjectGetOptionsPrefix((PetscObject)dm, prefix));
557: PetscFunctionReturn(PETSC_SUCCESS);
558: }
560: static PetscErrorCode DMCountNonCyclicReferences_Internal(DM dm, PetscBool recurseCoarse, PetscBool recurseFine, PetscInt *ncrefct)
561: {
562: PetscInt refct = ((PetscObject)dm)->refct;
564: PetscFunctionBegin;
565: *ncrefct = 0;
566: if (dm->coarseMesh && dm->coarseMesh->fineMesh == dm) {
567: refct--;
568: if (recurseCoarse) {
569: PetscInt coarseCount;
571: PetscCall(DMCountNonCyclicReferences_Internal(dm->coarseMesh, PETSC_TRUE, PETSC_FALSE, &coarseCount));
572: refct += coarseCount;
573: }
574: }
575: if (dm->fineMesh && dm->fineMesh->coarseMesh == dm) {
576: refct--;
577: if (recurseFine) {
578: PetscInt fineCount;
580: PetscCall(DMCountNonCyclicReferences_Internal(dm->fineMesh, PETSC_FALSE, PETSC_TRUE, &fineCount));
581: refct += fineCount;
582: }
583: }
584: *ncrefct = refct;
585: PetscFunctionReturn(PETSC_SUCCESS);
586: }
588: /* Generic wrapper for DMCountNonCyclicReferences_Internal() */
589: PetscErrorCode DMCountNonCyclicReferences(PetscObject dm, PetscInt *ncrefct)
590: {
591: PetscFunctionBegin;
592: PetscCall(DMCountNonCyclicReferences_Internal((DM)dm, PETSC_TRUE, PETSC_TRUE, ncrefct));
593: PetscFunctionReturn(PETSC_SUCCESS);
594: }
596: PetscErrorCode DMDestroyLabelLinkList_Internal(DM dm)
597: {
598: DMLabelLink next = dm->labels;
600: PetscFunctionBegin;
601: /* destroy the labels */
602: while (next) {
603: DMLabelLink tmp = next->next;
605: if (next->label == dm->depthLabel) dm->depthLabel = NULL;
606: if (next->label == dm->celltypeLabel) dm->celltypeLabel = NULL;
607: PetscCall(DMLabelDestroy(&next->label));
608: PetscCall(PetscFree(next));
609: next = tmp;
610: }
611: dm->labels = NULL;
612: PetscFunctionReturn(PETSC_SUCCESS);
613: }
615: PetscErrorCode DMDestroyCoordinates_Internal(DMCoordinates *c)
616: {
617: PetscFunctionBegin;
618: c->dim = PETSC_DEFAULT;
619: PetscCall(DMDestroy(&c->dm));
620: PetscCall(VecDestroy(&c->x));
621: PetscCall(VecDestroy(&c->xl));
622: PetscCall(DMFieldDestroy(&c->field));
623: PetscFunctionReturn(PETSC_SUCCESS);
624: }
626: /*@
627: DMDestroy - Destroys a `DM`.
629: Collective
631: Input Parameter:
632: . dm - the `DM` object to destroy
634: Level: developer
636: .seealso: [](ch_dmbase), `DM`, `DMCreate()`, `DMType`, `DMSetType()`, `DMView()`, `DMCreateGlobalVector()`, `DMCreateInterpolation()`, `DMCreateColoring()`, `DMCreateMatrix()`
637: @*/
638: PetscErrorCode DMDestroy(DM *dm)
639: {
640: PetscInt cnt;
642: PetscFunctionBegin;
643: if (!*dm) PetscFunctionReturn(PETSC_SUCCESS);
646: /* count all non-cyclic references in the doubly-linked list of coarse<->fine meshes */
647: PetscCall(DMCountNonCyclicReferences_Internal(*dm, PETSC_TRUE, PETSC_TRUE, &cnt));
648: --((PetscObject)*dm)->refct;
649: if (--cnt > 0) {
650: *dm = NULL;
651: PetscFunctionReturn(PETSC_SUCCESS);
652: }
653: if (((PetscObject)*dm)->refct < 0) PetscFunctionReturn(PETSC_SUCCESS);
654: ((PetscObject)*dm)->refct = 0;
656: PetscCall(DMClearGlobalVectors(*dm));
657: PetscCall(DMClearLocalVectors(*dm));
658: PetscCall(DMClearNamedGlobalVectors(*dm));
659: PetscCall(DMClearNamedLocalVectors(*dm));
661: /* Destroy the list of hooks */
662: {
663: DMCoarsenHookLink link, next;
664: for (link = (*dm)->coarsenhook; link; link = next) {
665: next = link->next;
666: PetscCall(PetscFree(link));
667: }
668: (*dm)->coarsenhook = NULL;
669: }
670: {
671: DMRefineHookLink link, next;
672: for (link = (*dm)->refinehook; link; link = next) {
673: next = link->next;
674: PetscCall(PetscFree(link));
675: }
676: (*dm)->refinehook = NULL;
677: }
678: {
679: DMSubDomainHookLink link, next;
680: for (link = (*dm)->subdomainhook; link; link = next) {
681: next = link->next;
682: PetscCall(PetscFree(link));
683: }
684: (*dm)->subdomainhook = NULL;
685: }
686: {
687: DMGlobalToLocalHookLink link, next;
688: for (link = (*dm)->gtolhook; link; link = next) {
689: next = link->next;
690: PetscCall(PetscFree(link));
691: }
692: (*dm)->gtolhook = NULL;
693: }
694: {
695: DMLocalToGlobalHookLink link, next;
696: for (link = (*dm)->ltoghook; link; link = next) {
697: next = link->next;
698: PetscCall(PetscFree(link));
699: }
700: (*dm)->ltoghook = NULL;
701: }
702: /* Destroy the work arrays */
703: {
704: DMWorkLink link, next;
705: PetscCheck(!(*dm)->workout, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Work array still checked out %p %p", (void *)(*dm)->workout, (*dm)->workout->mem);
706: for (link = (*dm)->workin; link; link = next) {
707: next = link->next;
708: PetscCall(PetscFree(link->mem));
709: PetscCall(PetscFree(link));
710: }
711: (*dm)->workin = NULL;
712: }
713: /* destroy the labels */
714: PetscCall(DMDestroyLabelLinkList_Internal(*dm));
715: /* destroy the fields */
716: PetscCall(DMClearFields(*dm));
717: /* destroy the boundaries */
718: {
719: DMBoundary next = (*dm)->boundary;
720: while (next) {
721: DMBoundary b = next;
723: next = b->next;
724: PetscCall(PetscFree(b));
725: }
726: }
728: PetscCall(PetscObjectDestroy(&(*dm)->dmksp));
729: PetscCall(PetscObjectDestroy(&(*dm)->dmsnes));
730: PetscCall(PetscObjectDestroy(&(*dm)->dmts));
732: if ((*dm)->ctx && (*dm)->ctxdestroy) PetscCall((*(*dm)->ctxdestroy)(&(*dm)->ctx));
733: PetscCall(MatFDColoringDestroy(&(*dm)->fd));
734: PetscCall(ISLocalToGlobalMappingDestroy(&(*dm)->ltogmap));
735: PetscCall(PetscFree((*dm)->vectype));
736: PetscCall(PetscFree((*dm)->mattype));
738: PetscCall(PetscSectionDestroy(&(*dm)->localSection));
739: PetscCall(PetscSectionDestroy(&(*dm)->globalSection));
740: PetscCall(PetscFree((*dm)->reorderSectionType));
741: PetscCall(PetscLayoutDestroy(&(*dm)->map));
742: PetscCall(PetscSectionDestroy(&(*dm)->defaultConstraint.section));
743: PetscCall(MatDestroy(&(*dm)->defaultConstraint.mat));
744: PetscCall(PetscSFDestroy(&(*dm)->sf));
745: PetscCall(PetscSFDestroy(&(*dm)->sectionSF));
746: PetscCall(PetscSFDestroy(&(*dm)->sfNatural));
747: PetscCall(PetscObjectDereference((PetscObject)(*dm)->sfMigration));
748: PetscCall(DMClearAuxiliaryVec(*dm));
749: PetscCall(PetscHMapAuxDestroy(&(*dm)->auxData));
750: if ((*dm)->coarseMesh && (*dm)->coarseMesh->fineMesh == *dm) PetscCall(DMSetFineDM((*dm)->coarseMesh, NULL));
752: PetscCall(DMDestroy(&(*dm)->coarseMesh));
753: if ((*dm)->fineMesh && (*dm)->fineMesh->coarseMesh == *dm) PetscCall(DMSetCoarseDM((*dm)->fineMesh, NULL));
754: PetscCall(DMDestroy(&(*dm)->fineMesh));
755: PetscCall(PetscFree((*dm)->Lstart));
756: PetscCall(PetscFree((*dm)->L));
757: PetscCall(PetscFree((*dm)->maxCell));
758: PetscCall(PetscFree2((*dm)->nullspaceConstructors, (*dm)->nearnullspaceConstructors));
759: PetscCall(DMDestroyCoordinates_Internal(&(*dm)->coordinates[0]));
760: PetscCall(DMDestroyCoordinates_Internal(&(*dm)->coordinates[1]));
761: if ((*dm)->transformDestroy) PetscCall((*(*dm)->transformDestroy)(*dm, (*dm)->transformCtx));
762: PetscCall(DMDestroy(&(*dm)->transformDM));
763: PetscCall(VecDestroy(&(*dm)->transform));
764: for (PetscInt i = 0; i < (*dm)->periodic.num_affines; i++) {
765: PetscCall(VecScatterDestroy(&(*dm)->periodic.affine_to_local[i]));
766: PetscCall(VecDestroy(&(*dm)->periodic.affine[i]));
767: }
768: if ((*dm)->periodic.num_affines > 0) PetscCall(PetscFree2((*dm)->periodic.affine_to_local, (*dm)->periodic.affine));
770: PetscCall(DMClearDS(*dm));
771: PetscCall(DMDestroy(&(*dm)->dmBC));
772: /* if memory was published with SAWs then destroy it */
773: PetscCall(PetscObjectSAWsViewOff((PetscObject)*dm));
775: PetscTryTypeMethod(*dm, destroy);
776: PetscCall(DMMonitorCancel(*dm));
777: PetscCall(DMCeedDestroy(&(*dm)->dmceed));
778: #if PetscDefined(HAVE_LIBCEED)
779: PetscCallCEED(CeedElemRestrictionDestroy(&(*dm)->ceedERestrict));
780: PetscCallCEED(CeedDestroy(&(*dm)->ceed));
781: #endif
782: /* We do not destroy (*dm)->data here so that we can reference count backend objects */
783: PetscCall(PetscHeaderDestroy(dm));
784: PetscFunctionReturn(PETSC_SUCCESS);
785: }
787: /*@
788: DMSetUp - sets up the data structures inside a `DM` object
790: Collective
792: Input Parameter:
793: . dm - the `DM` object to setup
795: Level: intermediate
797: Note:
798: This is usually called after various parameter setting operations and `DMSetFromOptions()` are called on the `DM`
800: .seealso: [](ch_dmbase), `DM`, `DMCreate()`, `DMSetType()`, `DMView()`, `DMCreateGlobalVector()`, `DMCreateInterpolation()`, `DMCreateColoring()`, `DMCreateMatrix()`
801: @*/
802: PetscErrorCode DMSetUp(DM dm)
803: {
804: PetscFunctionBegin;
806: if (dm->setupcalled) PetscFunctionReturn(PETSC_SUCCESS);
807: PetscTryTypeMethod(dm, setup);
808: dm->setupcalled = PETSC_TRUE;
809: PetscFunctionReturn(PETSC_SUCCESS);
810: }
812: /*@
813: DMSetFromOptions - sets parameters in a `DM` from the options database
815: Collective
817: Input Parameter:
818: . dm - the `DM` object to set options for
820: Options Database Keys:
821: + -dm_preallocate_only (true|false) - Only preallocate the matrix for `DMCreateMatrix()` and `DMCreateMassMatrix()`, but do not fill it with zeros
822: . -dm_vec_type type - type of vector to create inside `DM`
823: . -dm_mat_type type - type of matrix to create inside `DM`
824: . -dm_is_coloring_type (global|local) - see `ISColoringType`
825: . -dm_bind_below n - bind (force execution on CPU) for `Vec` and `Mat` objects with local size (number of vector entries or matrix rows) below n; currently only supported for `DMDA`
826: . -dm_plex_option_phases ph0_, ph1_, ... - List of prefixes for option processing phases
827: . -dm_plex_filename str - File containing a mesh
828: . -dm_plex_boundary_filename str - File containing a mesh boundary
829: . -dm_plex_name str - Name of the mesh in the file
830: . -dm_plex_shape shape - The domain shape, such as `BOX`, `SPHERE`, etc.
831: . -dm_plex_cell ct - Cell shape
832: . -dm_plex_reference_cell_domain (true|false) - Use a reference cell domain
833: . -dm_plex_dim dim - Set the topological dimension
834: . -dm_plex_simplex (true|false) - `PETSC_TRUE` for simplex elements, `PETSC_FALSE` for tensor elements
835: . -dm_plex_interpolate (true|false) - `PETSC_TRUE` turns on topological interpolation (creating edges and faces)
836: . -dm_plex_orient (true|false) - `PETSC_TRUE` turns on topological orientation (flipping edges and faces)
837: . -dm_plex_scale sc - Scale factor for mesh coordinates
838: . -dm_coord_remap (true|false) - Map coordinates using a function
839: . -dm_plex_coordinate_dim dim - Change the coordinate dimension of a mesh (usually given with cdm_ prefix)
840: . -dm_coord_map mapname - Select a builtin coordinate map
841: . -dm_coord_map_params p0,p1,p2,... - Set coordinate mapping parameters
842: . -dm_plex_box_faces m,n,p - Number of faces along each dimension
843: . -dm_plex_box_lower x,y,z - Specify lower-left-bottom coordinates for the box
844: . -dm_plex_box_upper x,y,z - Specify upper-right-top coordinates for the box
845: . -dm_plex_box_bd bx,by,bz - Specify the `DMBoundaryType` for each direction
846: . -dm_plex_sphere_radius r - The sphere radius
847: . -dm_plex_ball_radius r - Radius of the ball
848: . -dm_plex_cylinder_bd bz - Boundary type in the z direction
849: . -dm_plex_cylinder_num_wedges n - Number of wedges around the cylinder
850: . -dm_plex_reorder order - Reorder the mesh using the specified algorithm
851: . -dm_refine_pre n - The number of refinements before distribution
852: . -dm_refine_uniform_pre (true|false) - Flag for uniform refinement before distribution
853: . -dm_refine_volume_limit_pre v - The maximum cell volume after refinement before distribution
854: . -dm_refine n - The number of refinements after distribution
855: . -dm_extrude l - Activate extrusion and specify the number of layers to extrude
856: . -dm_plex_save_transform (true|false) - Save the `DMPlexTransform` that produced this mesh
857: . -dm_plex_transform_extrude_thickness t - The total thickness of extruded layers
858: . -dm_plex_transform_extrude_use_tensor (true|false) - Use tensor cells when extruding
859: . -dm_plex_transform_extrude_symmetric (true|false) - Extrude layers symmetrically about the surface
860: . -dm_plex_transform_extrude_normal n0,...,nd - Specify the extrusion direction
861: . -dm_plex_transform_extrude_thicknesses t0,...,tl - Specify thickness of each layer
862: . -dm_plex_create_fv_ghost_cells - Flag to create finite volume ghost cells on the boundary
863: . -dm_plex_fv_ghost_cells_label name - Label name for ghost cells boundary
864: . -dm_distribute (true|false) - Flag to redistribute a mesh among processes
865: . -dm_distribute_overlap n - The size of the overlap halo
866: . -dm_plex_adj_cone (true|false) - Set adjacency direction
867: . -dm_plex_adj_closure (true|false) - Set adjacency size
868: . -dm_plex_use_ceed (true|false) - Use LibCEED as the FEM backend
869: . -dm_plex_check_symmetry (true|false) - Check that the adjacency information in the mesh is symmetric - `DMPlexCheckSymmetry()`
870: . -dm_plex_check_skeleton (true|false) - Check that each cell has the correct number of vertices (only for homogeneous simplex or tensor meshes) - `DMPlexCheckSkeleton()`
871: . -dm_plex_check_faces (true|false) - Check that the faces of each cell give a vertex order this is consistent with what we expect from the cell type - `DMPlexCheckFaces()`
872: . -dm_plex_check_geometry (true|false) - Check that cells have positive volume - `DMPlexCheckGeometry()`
873: . -dm_plex_check_pointsf (true|false) - Check some necessary conditions for `PointSF` - `DMPlexCheckPointSF()`
874: . -dm_plex_check_interface_cones (true|false) - Check points on inter-partition interfaces have conforming order of cone points - `DMPlexCheckInterfaceCones()`
875: - -dm_plex_check_all (true|false) - Perform all the checks above
877: Level: intermediate
879: Note:
880: For some `DMType` such as `DMDA` this cannot be called after `DMSetUp()` has been called.
882: .seealso: [](ch_dmbase), `DM`, `DMView()`, `DMCreateGlobalVector()`, `DMCreateInterpolation()`, `DMCreateColoring()`, `DMCreateMatrix()`,
883: `DMPlexCheckSymmetry()`, `DMPlexCheckSkeleton()`, `DMPlexCheckFaces()`, `DMPlexCheckGeometry()`, `DMPlexCheckPointSF()`, `DMPlexCheckInterfaceCones()`,
884: `DMSetOptionsPrefix()`, `DMType`, `DMPLEX`, `DMDA`, `DMSetUp()`
885: @*/
886: PetscErrorCode DMSetFromOptions(DM dm)
887: {
888: char typeName[256];
889: PetscBool flg;
891: PetscFunctionBegin;
893: dm->setfromoptionscalled = PETSC_TRUE;
894: if (dm->sf) PetscCall(PetscSFSetFromOptions(dm->sf));
895: if (dm->sectionSF) PetscCall(PetscSFSetFromOptions(dm->sectionSF));
896: if (dm->coordinates[0].dm) PetscCall(DMSetFromOptions(dm->coordinates[0].dm));
897: PetscObjectOptionsBegin((PetscObject)dm);
898: PetscCall(PetscOptionsBool("-dm_preallocate_only", "only preallocate matrix, but do not set column indices", "DMSetMatrixPreallocateOnly", dm->prealloc_only, &dm->prealloc_only, NULL));
899: PetscCall(PetscOptionsFList("-dm_vec_type", "Vector type used for created vectors", "DMSetVecType", VecList, dm->vectype, typeName, sizeof(typeName), &flg));
900: if (flg) PetscCall(DMSetVecType(dm, typeName));
901: PetscCall(PetscOptionsFList("-dm_mat_type", "Matrix type used for created matrices", "DMSetMatType", MatList, dm->mattype ? dm->mattype : typeName, typeName, sizeof(typeName), &flg));
902: if (flg) PetscCall(DMSetMatType(dm, typeName));
903: PetscCall(PetscOptionsEnum("-dm_blocking_type", "Topological point or field node blocking", "DMSetBlockingType", DMBlockingTypes, (PetscEnum)dm->blocking_type, (PetscEnum *)&dm->blocking_type, NULL));
904: PetscCall(PetscOptionsEnum("-dm_is_coloring_type", "Global or local coloring of Jacobian", "DMSetISColoringType", ISColoringTypes, (PetscEnum)dm->coloringtype, (PetscEnum *)&dm->coloringtype, NULL));
905: PetscCall(PetscOptionsInt("-dm_bind_below", "Set the size threshold (in entries) below which the Vec is bound to the CPU", "VecBindToCPU", dm->bind_below, &dm->bind_below, &flg));
906: PetscCall(PetscOptionsBool("-dm_ignore_perm_output", "Ignore the local section permutation on output", "DMGetOutputDM", dm->ignorePermOutput, &dm->ignorePermOutput, NULL));
907: PetscTryTypeMethod(dm, setfromoptions, PetscOptionsObject);
908: /* process any options handlers added with PetscObjectAddOptionsHandler() */
909: PetscCall(PetscObjectProcessOptionsHandlers((PetscObject)dm, PetscOptionsObject));
910: PetscOptionsEnd();
911: PetscFunctionReturn(PETSC_SUCCESS);
912: }
914: /*@
915: DMViewFromOptions - View a `DM` in a particular way based on a request in the options database
917: Collective
919: Input Parameters:
920: + dm - the `DM` object
921: . obj - optional object that provides the prefix for the options database (if `NULL` then the prefix in `obj` is used)
922: - name - option string that is used to activate viewing
924: Options Database Key:
925: . -name viewer_specification - See `PetscOptionsCreateViewer()` for the values of `viewer_specification`
927: Level: intermediate
929: Note:
930: This checks the options database, creates the viewer on-the-fly, uses it and then destroys it. Hence it should not be called in heavily used routines,
931: rather `PetscOptionsCreateViewer()` should be used to construct the viewer once which can then be utilized in the heavily used routine.
933: .seealso: [](ch_dmbase), `DM`, `DMView()`, `PetscObjectViewFromOptions()`, `DMCreate()`, `PetscOptionsCreateViewer()`
934: @*/
935: PetscErrorCode DMViewFromOptions(DM dm, PeOp PetscObject obj, const char name[])
936: {
937: PetscFunctionBegin;
939: PetscCall(PetscObjectViewFromOptions((PetscObject)dm, obj, name));
940: PetscFunctionReturn(PETSC_SUCCESS);
941: }
943: /*@
944: DMView - Views a `DM`. Depending on the `PetscViewer` and its `PetscViewerFormat` it may print some ASCII information about the `DM` to the screen or a file or
945: save the `DM` in a binary file to be loaded later or create a visualization of the `DM`
947: Collective
949: Input Parameters:
950: + dm - the `DM` object to view
951: - v - the viewer
953: Options Database Keys:
954: + -view_pyvista_warp f - Warps the mesh by the active scalar with factor f
955: . -view_pyvista_clip xl,xu,yl,yu,zl,zu - Defines the clipping box
956: . -dm_view_draw_line_color color - Specify the X-window color for cell borders
957: . -dm_view_draw_cell_color color - Specify the X-window color for cells
958: - -dm_view_draw_affine (true|false) - Flag to ignore high-order edges
960: Level: beginner
962: Notes:
964: `PetscViewer` = `PETSCVIEWERHDF5` i.e. HDF5 format can be used with `PETSC_VIEWER_HDF5_PETSC` as the `PetscViewerFormat` to save multiple `DMPLEX`
965: meshes in a single HDF5 file. This in turn requires one to name the `DMPLEX` object with `PetscObjectSetName()`
966: before saving it with `DMView()` and before loading it with `DMLoad()` for identification of the mesh object.
968: `PetscViewer` = `PETSCVIEWEREXODUSII` i.e. ExodusII format assumes that element blocks (mapped to "Cell sets" labels)
969: consists of sequentially numbered cells.
971: If `dm` has been distributed, only the part of the `DM` on MPI rank 0 (including "ghost" cells and vertices) will be written.
973: Only TRI, TET, QUAD, and HEX cells are supported in ExodusII.
975: `DMPLEX` only represents geometry while most post-processing software expect that a mesh also provides information on the discretization space. This function assumes that the file represents Lagrange finite elements of order 1 or 2.
976: The order of the mesh shall be set using `PetscViewerExodusIISetOrder()`
978: Variable names can be set and queried using `PetscViewerExodusII[Set/Get][Nodal/Zonal]VariableNames[s]`.
980: .seealso: [](ch_dmbase), `DM`, `PetscViewer`, `PetscViewerFormat`, `PetscViewerSetFormat()`, `DMDestroy()`, `DMCreateGlobalVector()`, `DMCreateInterpolation()`, `DMCreateColoring()`, `DMCreateMatrix()`, `DMCreateMassMatrix()`, `DMLoad()`, `PetscObjectSetName()`
981: @*/
982: PetscErrorCode DMView(DM dm, PetscViewer v)
983: {
984: PetscBool isbinary;
985: PetscMPIInt size;
986: PetscViewerFormat format;
988: PetscFunctionBegin;
990: if (!v) PetscCall(PetscViewerASCIIGetStdout(PetscObjectComm((PetscObject)dm), &v));
992: /* Ideally, we would like to have this test on.
993: However, it currently breaks socket viz via GLVis.
994: During DMView(parallel_mesh,glvis_viewer), each
995: process opens a sequential ASCII socket to visualize
996: the local mesh, and PetscObjectView(dm,local_socket)
997: is internally called inside VecView_GLVis, incurring
998: in an error here */
999: /* PetscCheckSameComm(dm,1,v,2); */
1000: PetscCall(PetscViewerCheckWritable(v));
1002: PetscCall(PetscLogEventBegin(DM_View, v, 0, 0, 0));
1003: PetscCall(PetscViewerGetFormat(v, &format));
1004: PetscCallMPI(MPI_Comm_size(PetscObjectComm((PetscObject)dm), &size));
1005: if (size == 1 && format == PETSC_VIEWER_LOAD_BALANCE) PetscFunctionReturn(PETSC_SUCCESS);
1006: PetscCall(PetscObjectPrintClassNamePrefixType((PetscObject)dm, v));
1007: PetscCall(PetscObjectTypeCompare((PetscObject)v, PETSCVIEWERBINARY, &isbinary));
1008: if (isbinary) {
1009: PetscInt classid = DM_FILE_CLASSID;
1010: char type[256];
1012: PetscCall(PetscViewerBinaryWrite(v, &classid, 1, PETSC_INT));
1013: PetscCall(PetscStrncpy(type, ((PetscObject)dm)->type_name, sizeof(type)));
1014: PetscCall(PetscViewerBinaryWrite(v, type, 256, PETSC_CHAR));
1015: }
1016: PetscTryTypeMethod(dm, view, v);
1017: PetscCall(PetscLogEventEnd(DM_View, v, 0, 0, 0));
1018: PetscFunctionReturn(PETSC_SUCCESS);
1019: }
1021: /*@
1022: DMCreateGlobalVector - Creates a global vector from a `DM` object. A global vector is a parallel vector that has no duplicate values shared between MPI ranks,
1023: that is it has no ghost locations.
1025: Collective
1027: Input Parameter:
1028: . dm - the `DM` object
1030: Output Parameter:
1031: . vec - the global vector
1033: Level: beginner
1035: Note:
1036: PETSc `Vec` always have all zero entries when created with `DMCreateGlobalVector()` until routines such as `VecSet()` or `VecSetValues()`
1037: are used to change the values. There is no reason to call `VecZeroEntries()` after creation.
1039: .seealso: [](ch_dmbase), `DM`, `Vec`, `DMCreateLocalVector()`, `DMGetGlobalVector()`, `DMDestroy()`, `DMView()`, `DMCreateInterpolation()`, `DMCreateColoring()`, `DMCreateMatrix()`,
1040: `DMGlobalToLocalBegin()`, `DMGlobalToLocalEnd()`
1041: @*/
1042: PetscErrorCode DMCreateGlobalVector(DM dm, Vec *vec)
1043: {
1044: PetscFunctionBegin;
1046: PetscAssertPointer(vec, 2);
1047: PetscUseTypeMethod(dm, createglobalvector, vec);
1048: if (PetscDefined(USE_DEBUG)) {
1049: DM vdm;
1051: PetscCall(VecGetDM(*vec, &vdm));
1052: PetscCheck(vdm, PETSC_COMM_SELF, PETSC_ERR_PLIB, "DM type '%s' did not attach the DM to the vector", ((PetscObject)dm)->type_name);
1053: }
1054: PetscFunctionReturn(PETSC_SUCCESS);
1055: }
1057: /*@
1058: DMCreateLocalVector - Creates a local vector from a `DM` object.
1060: Not Collective
1062: Input Parameter:
1063: . dm - the `DM` object
1065: Output Parameter:
1066: . vec - the local vector
1068: Level: beginner
1070: Notes:
1071: A local vector usually has ghost locations that contain values that are owned by different MPI ranks. A global vector has no ghost locations.
1073: PETSc `Vec` always have all zero entries when created with `DMCreateLocalVector()` until routines such as `VecSet()` or `VecSetValues()`
1074: are used to change the values. There is no reason to call `VecZeroEntries()` after creation.
1076: .seealso: [](ch_dmbase), `DM`, `Vec`, `DMCreateGlobalVector()`, `DMGetLocalVector()`, `DMDestroy()`, `DMView()`, `DMCreateInterpolation()`, `DMCreateColoring()`, `DMCreateMatrix()`,
1077: `DMGlobalToLocalBegin()`, `DMGlobalToLocalEnd()`
1078: @*/
1079: PetscErrorCode DMCreateLocalVector(DM dm, Vec *vec)
1080: {
1081: PetscFunctionBegin;
1083: PetscAssertPointer(vec, 2);
1084: PetscUseTypeMethod(dm, createlocalvector, vec);
1085: if (PetscDefined(USE_DEBUG)) {
1086: DM vdm;
1088: PetscCall(VecGetDM(*vec, &vdm));
1089: PetscCheck(vdm, PETSC_COMM_SELF, PETSC_ERR_LIB, "DM type '%s' did not attach the DM to the vector", ((PetscObject)dm)->type_name);
1090: }
1091: PetscFunctionReturn(PETSC_SUCCESS);
1092: }
1094: /*@
1095: DMGetLocalToGlobalMapping - Accesses the local-to-global mapping in a `DM`.
1097: Collective
1099: Input Parameter:
1100: . dm - the `DM` that provides the mapping
1102: Output Parameter:
1103: . ltog - the mapping
1105: Level: advanced
1107: Notes:
1108: The global to local mapping allows one to set values into the global vector or matrix using `VecSetValuesLocal()` and `MatSetValuesLocal()`
1110: Vectors obtained with `DMCreateGlobalVector()` and matrices obtained with `DMCreateMatrix()` already contain the global mapping so you do
1111: need to use this function with those objects.
1113: This mapping can then be used by `VecSetLocalToGlobalMapping()` or `MatSetLocalToGlobalMapping()`.
1115: If the `DM` has a local section, it must have been set up with `PetscSectionSetUp()` before the mapping is built, otherwise an error is raised.
1117: The mapping is owned by the `DM`: do not destroy it. A mapping derived from the sections is invalidated by a subsequent call to `DMSetLocalSection()` or
1118: `DMSetGlobalSection()`.
1120: .seealso: [](ch_dmbase), `DM`, `DMCreateLocalVector()`, `DMCreateGlobalVector()`, `VecSetLocalToGlobalMapping()`, `MatSetLocalToGlobalMapping()`,
1121: `DMCreateMatrix()`
1122: @*/
1123: PetscErrorCode DMGetLocalToGlobalMapping(DM dm, ISLocalToGlobalMapping *ltog)
1124: {
1125: PetscInt bs = -1, bsLocal[2], bsMinMax[2];
1127: PetscFunctionBegin;
1129: PetscAssertPointer(ltog, 2);
1130: if (!dm->ltogmap) {
1131: PetscSection section, sectionGlobal;
1133: PetscCall(DMGetLocalSection(dm, §ion));
1134: if (section) {
1135: const PetscInt *cdofs;
1136: PetscInt *ltog;
1137: PetscInt pStart, pEnd, n, p, k, l;
1138: PetscBT seen;
1140: // The loop below indexes by the local section offsets, which are uninitialized before PetscSectionSetUp()
1141: PetscCheck(section->setup, PetscObjectComm((PetscObject)dm), PETSC_ERR_ARG_WRONGSTATE, "The local section must be set up with PetscSectionSetUp() before DMGetLocalToGlobalMapping()");
1142: PetscCall(DMGetGlobalSection(dm, §ionGlobal));
1143: PetscCall(PetscSectionGetChart(section, &pStart, &pEnd));
1144: PetscCall(PetscSectionGetStorageSize(section, &n));
1145: PetscCall(PetscMalloc1(n, <og)); /* We want the local+overlap size */
1146: PetscCall(PetscBTCreate(n, &seen));
1147: for (p = pStart; p < pEnd; ++p) {
1148: PetscInt bdof, cdof, dof, off, loff, c, cind;
1150: /* Should probably use constrained dofs */
1151: PetscCall(PetscSectionGetDof(section, p, &dof));
1152: PetscCall(PetscSectionGetConstraintDof(section, p, &cdof));
1153: PetscCall(PetscSectionGetConstraintIndices(section, p, &cdofs));
1154: PetscCall(PetscSectionGetOffset(sectionGlobal, p, &off));
1155: PetscCall(PetscSectionGetOffset(section, p, &loff));
1156: /* A set-up section can still carry offsets that do not index the local storage, e.g. a field-major
1157: section, whose point offsets PetscSectionSetUp() disables by setting them to -1 */
1158: PetscCheck(!dof || (loff >= 0 && loff + dof <= n), PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Local section offset %" PetscInt_FMT " + dof %" PetscInt_FMT " of point %" PetscInt_FMT " is outside the local storage [0, %" PetscInt_FMT ")", loff, dof, p, n);
1159: /* If you have dofs, and constraints, and they are unequal, we set the blocksize to 1 */
1160: bdof = cdof && (dof - cdof) ? 1 : dof;
1161: if (dof) bs = bs < 0 ? bdof : PetscGCD(bs, bdof);
1163: for (c = 0, cind = 0; c < dof; ++c) {
1164: l = loff + c;
1165: /* The storage size n is the sum of the dofs, so exactly n in-range slots are written: if no slot
1166: is written twice, the offsets tile [0, n) and every ltog[] entry is set (a non-bijective section
1167: permutation violates this, since PetscSectionSetPermutation() does not check for duplicates) */
1168: PetscCheck(!PetscBTLookupSet(seen, l), PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Local section offsets overlap: slot %" PetscInt_FMT " of point %" PetscInt_FMT " was already filled by another point", l, p);
1169: if (cind < cdof && c == cdofs[cind]) {
1170: ltog[l] = off < 0 ? off - c : -(off + c + 1);
1171: cind++;
1172: } else {
1173: ltog[l] = (off < 0 ? -(off + 1) : off) + c - cind;
1174: }
1175: }
1176: }
1177: PetscCall(PetscBTDestroy(&seen));
1178: /* Must have same blocksize on all procs (some might have no points) */
1179: bsLocal[0] = bs < 0 ? PETSC_INT_MAX : bs;
1180: bsLocal[1] = bs;
1181: PetscCall(PetscGlobalMinMaxInt(PetscObjectComm((PetscObject)dm), bsLocal, bsMinMax));
1182: if (bsMinMax[0] != bsMinMax[1]) bs = 1;
1183: else bs = bsMinMax[0];
1184: bs = bs < 0 ? 1 : bs;
1185: /* Must reduce indices by blocksize */
1186: if (bs > 1) {
1187: for (l = 0, k = 0; l < n; l += bs, ++k) {
1188: // Integer division of negative values truncates toward zero(!), not toward negative infinity
1189: ltog[k] = ltog[l] >= 0 ? ltog[l] / bs : -(-(ltog[l] + 1) / bs + 1);
1190: }
1191: n /= bs;
1192: }
1193: PetscCall(ISLocalToGlobalMappingCreate(PetscObjectComm((PetscObject)dm), bs, n, ltog, PETSC_OWN_POINTER, &dm->ltogmap));
1194: dm->ltogmapFromSection = PETSC_TRUE;
1195: } else {
1196: PetscUseTypeMethod(dm, getlocaltoglobalmapping);
1197: dm->ltogmapFromSection = PETSC_FALSE;
1198: }
1199: }
1200: *ltog = dm->ltogmap;
1201: PetscFunctionReturn(PETSC_SUCCESS);
1202: }
1204: /*@
1205: DMGetBlockSize - Gets the inherent block size associated with a `DM`
1207: Not Collective
1209: Input Parameter:
1210: . dm - the `DM` with block structure
1212: Output Parameter:
1213: . bs - the block size, 1 implies no exploitable block structure
1215: Level: intermediate
1217: Notes:
1218: This might be the number of degrees of freedom at each grid point for a structured grid.
1220: Complex `DM` that represent multiphysics or staggered grids or mixed-methods do not generally have a single inherent block size, but
1221: rather different locations in the vectors may have a different block size.
1223: .seealso: [](ch_dmbase), `DM`, `ISCreateBlock()`, `VecSetBlockSize()`, `MatSetBlockSize()`, `DMGetLocalToGlobalMapping()`
1224: @*/
1225: PetscErrorCode DMGetBlockSize(DM dm, PetscInt *bs)
1226: {
1227: PetscFunctionBegin;
1229: PetscAssertPointer(bs, 2);
1230: PetscCheck(dm->bs >= 1, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "DM does not have enough information to provide a block size yet");
1231: *bs = dm->bs;
1232: PetscFunctionReturn(PETSC_SUCCESS);
1233: }
1235: /*@
1236: DMCreateInterpolation - Gets the interpolation matrix between two `DM` objects. The resulting matrix map degrees of freedom in the vector obtained by
1237: `DMCreateGlobalVector()` on the coarse `DM` to similar vectors on the fine grid `DM`.
1239: Collective
1241: Input Parameters:
1242: + dmc - the `DM` object
1243: - dmf - the second, finer `DM` object
1245: Output Parameters:
1246: + mat - the interpolation
1247: - vec - the scaling (optional, pass `NULL` if not needed), see `DMCreateInterpolationScale()`
1249: Level: developer
1251: Notes:
1252: For `DMDA` objects this only works for "uniform refinement", that is the refined mesh was obtained `DMRefine()` or the coarse mesh was obtained by
1253: DMCoarsen(). The coordinates set into the `DMDA` are completely ignored in computing the interpolation.
1255: For `DMDA` objects you can use this interpolation (more precisely the interpolation from the `DMGetCoordinateDM()`) to interpolate the mesh coordinate
1256: vectors EXCEPT in the periodic case where it does not make sense since the coordinate vectors are not periodic.
1258: .seealso: [](ch_dmbase), `DM`, `DMDestroy()`, `DMView()`, `DMCreateGlobalVector()`, `DMCreateColoring()`, `DMCreateMatrix()`, `DMCreateMassMatrix()`, `DMRefine()`, `DMCoarsen()`, `DMCreateRestriction()`, `DMCreateInterpolationScale()`
1259: @*/
1260: PetscErrorCode DMCreateInterpolation(DM dmc, DM dmf, Mat *mat, Vec *vec)
1261: {
1262: PetscFunctionBegin;
1265: PetscAssertPointer(mat, 3);
1266: PetscCall(PetscLogEventBegin(DM_CreateInterpolation, dmc, dmf, 0, 0));
1267: PetscUseTypeMethod(dmc, createinterpolation, dmf, mat, vec);
1268: PetscCall(PetscLogEventEnd(DM_CreateInterpolation, dmc, dmf, 0, 0));
1269: PetscFunctionReturn(PETSC_SUCCESS);
1270: }
1272: /*@
1273: DMCreateInterpolationScale - Forms L = 1/(R*1) where 1 is the vector of all ones, and R is
1274: the transpose of the interpolation between the `DM`.
1276: Input Parameters:
1277: + dac - `DM` that defines a coarse mesh
1278: . daf - `DM` that defines a fine mesh
1279: - mat - the restriction (or interpolation operator) from fine to coarse
1281: Output Parameter:
1282: . scale - the scaled vector
1284: Level: advanced
1286: Note:
1287: xcoarse = diag(L)*R*xfine preserves scale and is thus suitable for state (versus residual)
1288: restriction. In other words xcoarse is the coarse representation of xfine.
1290: Developer Note:
1291: If the fine-scale `DMDA` has the -dm_bind_below option set to true, then `DMCreateInterpolationScale()` calls `MatSetBindingPropagates()`
1292: on the restriction/interpolation operator to set the bindingpropagates flag to true.
1294: .seealso: [](ch_dmbase), `DM`, `MatRestrict()`, `MatInterpolate()`, `DMCreateInterpolation()`, `DMCreateRestriction()`, `DMCreateGlobalVector()`
1295: @*/
1296: PetscErrorCode DMCreateInterpolationScale(DM dac, DM daf, Mat mat, Vec *scale)
1297: {
1298: Vec fine;
1299: PetscScalar one = 1.0;
1300: #if PetscDefined(HAVE_CUDA)
1301: PetscBool bindingpropagates, isbound;
1302: #endif
1304: PetscFunctionBegin;
1305: PetscCall(DMCreateGlobalVector(daf, &fine));
1306: PetscCall(DMCreateGlobalVector(dac, scale));
1307: PetscCall(VecSet(fine, one));
1308: #if PetscDefined(HAVE_CUDA)
1309: /* If the 'fine' Vec is bound to the CPU, it makes sense to bind 'mat' as well.
1310: * Note that we only do this for the CUDA case, right now, but if we add support for MatMultTranspose() via ViennaCL,
1311: * we'll need to do it for that case, too.*/
1312: PetscCall(VecGetBindingPropagates(fine, &bindingpropagates));
1313: if (bindingpropagates) {
1314: PetscCall(MatSetBindingPropagates(mat, PETSC_TRUE));
1315: PetscCall(VecBoundToCPU(fine, &isbound));
1316: PetscCall(MatBindToCPU(mat, isbound));
1317: }
1318: #endif
1319: PetscCall(MatRestrict(mat, fine, *scale));
1320: PetscCall(VecDestroy(&fine));
1321: PetscCall(VecReciprocal(*scale));
1322: PetscFunctionReturn(PETSC_SUCCESS);
1323: }
1325: /*@
1326: DMCreateRestriction - Gets restriction matrix between two `DM` objects. The resulting matrix map degrees of freedom in the vector obtained by
1327: `DMCreateGlobalVector()` on the fine `DM` to similar vectors on the coarse grid `DM`.
1329: Collective
1331: Input Parameters:
1332: + dmc - the `DM` object
1333: - dmf - the second, finer `DM` object
1335: Output Parameter:
1336: . mat - the restriction
1338: Level: developer
1340: Note:
1341: This only works for `DMSTAG`. For many situations either the transpose of the operator obtained with `DMCreateInterpolation()` or that
1342: matrix multiplied by the vector obtained with `DMCreateInterpolationScale()` provides the desired object.
1344: .seealso: [](ch_dmbase), `DM`, `DMRestrict()`, `DMInterpolate()`, `DMDestroy()`, `DMView()`, `DMCreateGlobalVector()`, `DMCreateColoring()`, `DMCreateMatrix()`, `DMCreateMassMatrix()`, `DMRefine()`, `DMCoarsen()`, `DMCreateInterpolation()`
1345: @*/
1346: PetscErrorCode DMCreateRestriction(DM dmc, DM dmf, Mat *mat)
1347: {
1348: PetscFunctionBegin;
1351: PetscAssertPointer(mat, 3);
1352: PetscCall(PetscLogEventBegin(DM_CreateRestriction, dmc, dmf, 0, 0));
1353: PetscUseTypeMethod(dmc, createrestriction, dmf, mat);
1354: PetscCall(PetscLogEventEnd(DM_CreateRestriction, dmc, dmf, 0, 0));
1355: PetscFunctionReturn(PETSC_SUCCESS);
1356: }
1358: /*@
1359: DMCreateInjection - Gets injection matrix between two `DM` objects.
1361: Collective
1363: Input Parameters:
1364: + dac - the `DM` object
1365: - daf - the second, finer `DM` object
1367: Output Parameter:
1368: . mat - the injection
1370: Level: developer
1372: Notes:
1373: This is an operator that applied to a vector obtained with `DMCreateGlobalVector()` on the
1374: fine grid maps the values to a vector on the vector on the coarse `DM` by simply selecting
1375: the values on the coarse grid points. This compares to the operator obtained by
1376: `DMCreateRestriction()` or the transpose of the operator obtained by
1377: `DMCreateInterpolation()` that uses a "local weighted average" of the values around the
1378: coarse grid point as the coarse grid value.
1380: For `DMDA` objects this only works for "uniform refinement", that is the refined mesh was obtained `DMRefine()` or the coarse mesh was obtained by
1381: `DMCoarsen()`. The coordinates set into the `DMDA` are completely ignored in computing the injection.
1383: .seealso: [](ch_dmbase), `DM`, `DMDestroy()`, `DMView()`, `DMCreateGlobalVector()`, `DMCreateColoring()`, `DMCreateMatrix()`, `DMCreateMassMatrix()`, `DMCreateInterpolation()`,
1384: `DMCreateRestriction()`, `MatRestrict()`, `MatInterpolate()`
1385: @*/
1386: PetscErrorCode DMCreateInjection(DM dac, DM daf, Mat *mat)
1387: {
1388: PetscFunctionBegin;
1391: PetscAssertPointer(mat, 3);
1392: PetscCall(PetscLogEventBegin(DM_CreateInjection, dac, daf, 0, 0));
1393: PetscUseTypeMethod(dac, createinjection, daf, mat);
1394: PetscCall(PetscLogEventEnd(DM_CreateInjection, dac, daf, 0, 0));
1395: PetscFunctionReturn(PETSC_SUCCESS);
1396: }
1398: /*@
1399: DMCreateMassMatrix - Gets the mass matrix between two `DM` objects, M_ij = \int \phi_i \psi_j where the \phi are Galerkin basis functions for a
1400: a Galerkin finite element model on the `DM`
1402: Collective
1404: Input Parameters:
1405: + dmc - the target `DM` object
1406: - dmf - the source `DM` object, can be `NULL`
1408: Output Parameter:
1409: . mat - the mass matrix
1411: Level: developer
1413: Notes:
1414: For `DMPLEX` the finite element model for the `DM` must have been already provided.
1416: if `dmc` is `dmf` or `NULL`, then x^t M x is an approximation to the L2 norm of the vector x which is obtained by `DMCreateGlobalVector()`
1418: .seealso: [](ch_dmbase), `DM`, `DMCreateMassMatrixLumped()`, `DMCreateMatrix()`, `DMRefine()`, `DMCoarsen()`, `DMCreateRestriction()`, `DMCreateInterpolation()`, `DMCreateInjection()`
1419: @*/
1420: PetscErrorCode DMCreateMassMatrix(DM dmc, DM dmf, Mat *mat)
1421: {
1422: PetscFunctionBegin;
1424: if (!dmf) dmf = dmc;
1426: PetscAssertPointer(mat, 3);
1427: PetscCall(PetscLogEventBegin(DM_CreateMassMatrix, dmc, dmf, 0, 0));
1428: PetscUseTypeMethod(dmc, createmassmatrix, dmf, mat);
1429: PetscCall(PetscLogEventEnd(DM_CreateMassMatrix, dmc, dmf, 0, 0));
1430: PetscFunctionReturn(PETSC_SUCCESS);
1431: }
1433: /*@
1434: DMCreateMassMatrixLumped - Gets the lumped mass matrix for a given `DM`
1436: Collective
1438: Input Parameter:
1439: . dm - the `DM` object
1441: Output Parameters:
1442: + llm - the local lumped mass matrix, which is a diagonal matrix, represented as a vector
1443: - lm - the global lumped mass matrix, which is a diagonal matrix, represented as a vector
1445: Level: developer
1447: Note:
1448: See `DMCreateMassMatrix()` for how to create the non-lumped version of the mass matrix.
1450: .seealso: [](ch_dmbase), `DM`, `DMCreateMassMatrix()`, `DMCreateMatrix()`, `DMRefine()`, `DMCoarsen()`, `DMCreateRestriction()`, `DMCreateInterpolation()`, `DMCreateInjection()`
1451: @*/
1452: PetscErrorCode DMCreateMassMatrixLumped(DM dm, Vec *llm, Vec *lm)
1453: {
1454: PetscFunctionBegin;
1456: if (llm) PetscAssertPointer(llm, 2);
1457: if (lm) PetscAssertPointer(lm, 3);
1458: if (llm || lm) PetscUseTypeMethod(dm, createmassmatrixlumped, llm, lm);
1459: PetscFunctionReturn(PETSC_SUCCESS);
1460: }
1462: /*@
1463: DMCreateGradientMatrix - Gets the gradient matrix between two `DM` objects, M_(ic)j = \int \partial_c \phi_i \psi_j where the \phi are Galerkin basis functions for a Galerkin finite element model on the `DM`
1465: Collective
1467: Input Parameters:
1468: + dmc - the target `DM` object
1469: - dmf - the source `DM` object, can be `NULL`
1471: Output Parameter:
1472: . mat - the gradient matrix
1474: Level: developer
1476: Notes:
1477: For `DMPLEX` the finite element model for the `DM` must have been already provided.
1479: .seealso: [](ch_dmbase), `DM`, `DMCreateMassMatrix()`, `DMCreateMassMatrixLumped()`, `DMCreateMatrix()`, `DMRefine()`, `DMCoarsen()`, `DMCreateRestriction()`, `DMCreateInterpolation()`, `DMCreateInjection()`
1480: @*/
1481: PetscErrorCode DMCreateGradientMatrix(DM dmc, DM dmf, Mat *mat)
1482: {
1483: PetscFunctionBegin;
1485: if (!dmf) dmf = dmc;
1487: PetscAssertPointer(mat, 3);
1488: PetscUseTypeMethod(dmc, creategradientmatrix, dmf, mat);
1489: PetscFunctionReturn(PETSC_SUCCESS);
1490: }
1492: /*@
1493: DMCreateColoring - Gets coloring of a graph associated with the `DM`. Often the graph represents the operator matrix associated with the discretization
1494: of a PDE on the `DM`.
1496: Collective
1498: Input Parameters:
1499: + dm - the `DM` object
1500: - ctype - `IS_COLORING_LOCAL` or `IS_COLORING_GLOBAL`
1502: Output Parameter:
1503: . coloring - the coloring
1505: Level: developer
1507: Notes:
1508: Coloring of matrices can also be computed directly from the sparse matrix nonzero structure via the `MatColoring` object or from the mesh from which the
1509: matrix comes from (what this function provides). In general using the mesh produces a more optimal coloring (fewer colors).
1511: This produces a coloring with the distance of 2, see `MatSetColoringDistance()` which can be used for efficiently computing Jacobians with `MatFDColoringCreate()`
1512: For `DMDA` in three dimensions with periodic boundary conditions the number of grid points in each dimension must be divisible by 2*stencil_width + 1,
1513: otherwise an error will be generated.
1515: .seealso: [](ch_dmbase), `DM`, `ISColoring`, `DMDestroy()`, `DMView()`, `DMCreateGlobalVector()`, `DMCreateInterpolation()`, `DMCreateMatrix()`, `DMCreateMassMatrix()`, `DMSetMatType()`, `MatColoring`, `MatFDColoringCreate()`
1516: @*/
1517: PetscErrorCode DMCreateColoring(DM dm, ISColoringType ctype, ISColoring *coloring)
1518: {
1519: PetscFunctionBegin;
1521: PetscAssertPointer(coloring, 3);
1522: PetscUseTypeMethod(dm, getcoloring, ctype, coloring);
1523: PetscFunctionReturn(PETSC_SUCCESS);
1524: }
1526: /*@
1527: DMCreateMatrix - Creates a matrix of appropriate size and nonzero structure for a `DM`. The matrix is most commonly used to store the Jacobian
1528: of a discrete PDE operator.
1530: Collective
1532: Input Parameter:
1533: . dm - the `DM` object
1535: Output Parameter:
1536: . mat - the matrix
1538: Options Database Key:
1539: . -dm_preallocate_only (true|false) - Only preallocate the matrix for `DMCreateMatrix()` and `DMCreateMassMatrix()`, but do not fill its nonzero structure
1541: Level: beginner
1543: Notes:
1544: This properly preallocates the number of nonzeros in the sparse matrix so you
1545: do not need to do it yourself.
1547: By default it also sets the nonzero structure and puts in the zero entries. To prevent setting
1548: the nonzero pattern call `DMSetMatrixPreallocateOnly()`
1550: For `DMDA`, when you call `MatView()` on this matrix it is displayed using the global natural ordering, NOT in the ordering used
1551: internally by PETSc.
1553: For `DMDA`, in general it is easiest to use `MatSetValuesStencil()` or `MatSetValuesLocal()` to put values into the matrix because
1554: `MatSetValues()` requires the indices for the global numbering for the `DMDA` which is complic`ated to compute
1556: .seealso: [](ch_dmbase), `DM`, `DMDestroy()`, `DMView()`, `DMCreateGlobalVector()`, `DMCreateInterpolation()`, `DMSetMatType()`, `DMCreateMassMatrix()`
1557: @*/
1558: PetscErrorCode DMCreateMatrix(DM dm, Mat *mat)
1559: {
1560: PetscFunctionBegin;
1562: PetscAssertPointer(mat, 2);
1563: PetscCall(MatInitializePackage());
1564: PetscCall(PetscLogEventBegin(DM_CreateMatrix, 0, 0, 0, 0));
1565: PetscUseTypeMethod(dm, creatematrix, mat);
1566: if (PetscDefined(USE_DEBUG)) {
1567: DM mdm;
1569: PetscCall(MatGetDM(*mat, &mdm));
1570: PetscCheck(mdm, PETSC_COMM_SELF, PETSC_ERR_PLIB, "DM type '%s' did not attach the DM to the matrix", ((PetscObject)dm)->type_name);
1571: }
1572: /* Handle nullspace and near nullspace */
1573: if (dm->Nf) {
1574: MatNullSpace nullSpace;
1575: PetscInt Nf;
1577: PetscCall(DMGetNumFields(dm, &Nf));
1578: for (PetscInt f = 0; f < Nf; ++f) {
1579: if (dm->nullspaceConstructors && dm->nullspaceConstructors[f]) {
1580: PetscCall((*dm->nullspaceConstructors[f])(dm, f, f, &nullSpace));
1581: PetscCall(MatSetNullSpace(*mat, nullSpace));
1582: PetscCall(MatNullSpaceDestroy(&nullSpace));
1583: break;
1584: }
1585: }
1586: for (PetscInt f = 0; f < Nf; ++f) {
1587: if (dm->nearnullspaceConstructors && dm->nearnullspaceConstructors[f]) {
1588: PetscCall((*dm->nearnullspaceConstructors[f])(dm, f, f, &nullSpace));
1589: PetscCall(MatSetNearNullSpace(*mat, nullSpace));
1590: PetscCall(MatNullSpaceDestroy(&nullSpace));
1591: }
1592: }
1593: }
1594: PetscCall(PetscLogEventEnd(DM_CreateMatrix, 0, 0, 0, 0));
1595: PetscFunctionReturn(PETSC_SUCCESS);
1596: }
1598: /*@
1599: DMSetMatrixPreallocateSkip - When `DMCreateMatrix()` is called the matrix sizes and
1600: `ISLocalToGlobalMapping` will be properly set, but the data structures to store values in the
1601: matrices will not be preallocated.
1603: Logically Collective
1605: Input Parameters:
1606: + dm - the `DM`
1607: - skip - `PETSC_TRUE` to skip preallocation
1609: Level: developer
1611: Note:
1612: This is most useful to reduce initialization costs when `MatSetPreallocationCOO()` and
1613: `MatSetValuesCOO()` will be used.
1615: .seealso: [](ch_dmbase), `DM`, `DMCreateMatrix()`, `DMSetMatrixStructureOnly()`, `DMSetMatrixPreallocateOnly()`
1616: @*/
1617: PetscErrorCode DMSetMatrixPreallocateSkip(DM dm, PetscBool skip)
1618: {
1619: PetscFunctionBegin;
1621: dm->prealloc_skip = skip;
1622: PetscFunctionReturn(PETSC_SUCCESS);
1623: }
1625: /*@
1626: DMSetMatrixPreallocateOnly - When `DMCreateMatrix()` is called the matrix will be properly
1627: preallocated but the nonzero structure and zero values will not be set.
1629: Logically Collective
1631: Input Parameters:
1632: + dm - the `DM`
1633: - only - `PETSC_TRUE` if only want preallocation
1635: Options Database Key:
1636: . -dm_preallocate_only - Only preallocate the matrix for `DMCreateMatrix()`, `DMCreateMassMatrix()`, but do not fill it with zeros
1638: Level: developer
1640: .seealso: [](ch_dmbase), `DM`, `DMCreateMatrix()`, `DMCreateMassMatrix()`, `DMSetMatrixStructureOnly()`, `DMSetMatrixPreallocateSkip()`
1641: @*/
1642: PetscErrorCode DMSetMatrixPreallocateOnly(DM dm, PetscBool only)
1643: {
1644: PetscFunctionBegin;
1646: dm->prealloc_only = only;
1647: PetscFunctionReturn(PETSC_SUCCESS);
1648: }
1650: /*@
1651: DMSetMatrixStructureOnly - When `DMCreateMatrix()` is called, the matrix nonzero structure will be created
1652: but the array for numerical values will not be allocated.
1654: Logically Collective
1656: Input Parameters:
1657: + dm - the `DM`
1658: - only - `PETSC_TRUE` if you only want matrix nonzero structure
1660: Level: developer
1662: .seealso: [](ch_dmbase), `DM`, `DMCreateMatrix()`, `DMSetMatrixPreallocateOnly()`, `DMSetMatrixPreallocateSkip()`
1663: @*/
1664: PetscErrorCode DMSetMatrixStructureOnly(DM dm, PetscBool only)
1665: {
1666: PetscFunctionBegin;
1668: dm->structure_only = only;
1669: PetscFunctionReturn(PETSC_SUCCESS);
1670: }
1672: /*@
1673: DMSetBlockingType - set the blocking granularity to be used for variable block size `DMCreateMatrix()` is called
1675: Logically Collective
1677: Input Parameters:
1678: + dm - the `DM`
1679: - btype - block by topological point or field node
1681: Options Database Key:
1682: . -dm_blocking_type (topological_point|field_node) - use topological point blocking or field node blocking
1684: Level: advanced
1686: .seealso: [](ch_dmbase), `DM`, `DMCreateMatrix()`, `MatSetVariableBlockSizes()`
1687: @*/
1688: PetscErrorCode DMSetBlockingType(DM dm, DMBlockingType btype)
1689: {
1690: PetscFunctionBegin;
1692: dm->blocking_type = btype;
1693: PetscFunctionReturn(PETSC_SUCCESS);
1694: }
1696: /*@
1697: DMGetBlockingType - get the blocking granularity to be used for variable block size `DMCreateMatrix()` is called
1699: Not Collective
1701: Input Parameter:
1702: . dm - the `DM`
1704: Output Parameter:
1705: . btype - block by topological point or field node
1707: Level: advanced
1709: .seealso: [](ch_dmbase), `DM`, `DMCreateMatrix()`, `MatSetVariableBlockSizes()`
1710: @*/
1711: PetscErrorCode DMGetBlockingType(DM dm, DMBlockingType *btype)
1712: {
1713: PetscFunctionBegin;
1715: PetscAssertPointer(btype, 2);
1716: *btype = dm->blocking_type;
1717: PetscFunctionReturn(PETSC_SUCCESS);
1718: }
1720: /*@
1721: DMGetWorkArray - Gets a work array guaranteed to be at least the input size, restore with `DMRestoreWorkArray()`
1723: Not Collective
1725: Input Parameters:
1726: + dm - the `DM` object
1727: . count - The minimum size
1728: - dtype - MPI data type, often `MPIU_REAL`, `MPIU_SCALAR`, or `MPIU_INT`)
1730: Output Parameter:
1731: . mem - the work array
1733: Level: developer
1735: Notes:
1736: A `DM` may stash the array between instantiations so using this routine may be more efficient than calling `PetscMalloc()`
1738: The array may contain nonzero values
1740: .seealso: [](ch_dmbase), `DM`, `DMDestroy()`, `DMCreate()`, `DMRestoreWorkArray()`, `PetscMalloc()`
1741: @*/
1742: PetscErrorCode DMGetWorkArray(DM dm, PetscInt count, MPI_Datatype dtype, void *mem)
1743: {
1744: DMWorkLink link;
1745: PetscMPIInt dsize;
1747: PetscFunctionBegin;
1749: PetscAssertPointer(mem, 4);
1750: if (!count) {
1751: *(void **)mem = NULL;
1752: PetscFunctionReturn(PETSC_SUCCESS);
1753: }
1754: if (dm->workin) {
1755: link = dm->workin;
1756: dm->workin = dm->workin->next;
1757: } else {
1758: PetscCall(PetscNew(&link));
1759: }
1760: /* Avoid MPI_Type_size for most used datatypes
1761: Get size directly */
1762: if (dtype == MPIU_INT) dsize = sizeof(PetscInt);
1763: else if (dtype == MPIU_REAL) dsize = sizeof(PetscReal);
1764: else if (PetscDefined(USE_64BIT_INDICES) && dtype == MPI_INT) dsize = sizeof(int);
1765: else if (PetscDefined(USE_COMPLEX) && dtype == MPIU_SCALAR) dsize = sizeof(PetscScalar);
1766: else PetscCallMPI(MPI_Type_size(dtype, &dsize));
1768: if (((size_t)dsize * count) > link->bytes) {
1769: PetscCall(PetscFree(link->mem));
1770: PetscCall(PetscMalloc(dsize * count, &link->mem));
1771: link->bytes = dsize * count;
1772: }
1773: link->next = dm->workout;
1774: dm->workout = link;
1775: *(void **)mem = link->mem;
1776: PetscFunctionReturn(PETSC_SUCCESS);
1777: }
1779: /*@
1780: DMRestoreWorkArray - Restores a work array obtained with `DMCreateWorkArray()`
1782: Not Collective
1784: Input Parameters:
1785: + dm - the `DM` object
1786: . count - The minimum size
1787: - dtype - MPI data type, often `MPIU_REAL`, `MPIU_SCALAR`, `MPIU_INT`
1789: Output Parameter:
1790: . mem - the work array
1792: Level: developer
1794: Developer Note:
1795: count and dtype are ignored, they are only needed for `DMGetWorkArray()`
1797: .seealso: [](ch_dmbase), `DM`, `DMDestroy()`, `DMCreate()`, `DMGetWorkArray()`
1798: @*/
1799: PetscErrorCode DMRestoreWorkArray(DM dm, PetscInt count, MPI_Datatype dtype, void *mem)
1800: {
1801: DMWorkLink *p, link;
1803: PetscFunctionBegin;
1804: PetscAssertPointer(mem, 4);
1805: (void)count;
1806: (void)dtype;
1807: if (!*(void **)mem) PetscFunctionReturn(PETSC_SUCCESS);
1808: for (p = &dm->workout; (link = *p); p = &link->next) {
1809: if (link->mem == *(void **)mem) {
1810: *p = link->next;
1811: link->next = dm->workin;
1812: dm->workin = link;
1813: *(void **)mem = NULL;
1814: PetscFunctionReturn(PETSC_SUCCESS);
1815: }
1816: }
1817: SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Array was not checked out");
1818: }
1820: /*@
1821: DMSetNullSpaceConstructor - Provide a callback function which constructs the nullspace for a given field, defined with `DMAddField()`, when function spaces
1822: are joined or split, such as in `DMCreateSubDM()`
1824: Logically Collective; No Fortran Support
1826: Input Parameters:
1827: + dm - The `DM`
1828: . field - The field number for the nullspace
1829: - nullsp - A callback to create the nullspace
1831: Calling sequence of `nullsp`:
1832: + dm - The present `DM`
1833: . origField - The field number given above, in the original `DM`
1834: . field - The field number in dm
1835: - nullSpace - The nullspace for the given field
1837: Level: intermediate
1839: .seealso: [](ch_dmbase), `DM`, `DMAddField()`, `DMGetNullSpaceConstructor()`, `DMSetNearNullSpaceConstructor()`, `DMGetNearNullSpaceConstructor()`, `DMCreateSubDM()`, `DMCreateSuperDM()`
1840: @*/
1841: PetscErrorCode DMSetNullSpaceConstructor(DM dm, PetscInt field, PetscErrorCode (*nullsp)(DM dm, PetscInt origField, PetscInt field, MatNullSpace *nullSpace))
1842: {
1843: PetscFunctionBegin;
1845: PetscCheck(field < dm->Nf, PetscObjectComm((PetscObject)dm), PETSC_ERR_ARG_OUTOFRANGE, "Cannot handle %" PetscInt_FMT " >= %" PetscInt_FMT " fields", field, dm->Nf);
1846: PetscCheck(dm->nullspaceConstructors, PetscObjectComm((PetscObject)dm), PETSC_ERR_ARG_WRONG, "Must call DMCreateDS() to setup nullspaces");
1847: dm->nullspaceConstructors[field] = nullsp;
1848: PetscFunctionReturn(PETSC_SUCCESS);
1849: }
1851: /*@
1852: DMGetNullSpaceConstructor - Return the callback function which constructs the nullspace for a given field, defined with `DMAddField()`
1854: Not Collective; No Fortran Support
1856: Input Parameters:
1857: + dm - The `DM`
1858: - field - The field number for the nullspace
1860: Output Parameter:
1861: . nullsp - A callback to create the nullspace
1863: Calling sequence of `nullsp`:
1864: + dm - The present DM
1865: . origField - The field number given above, in the original DM
1866: . field - The field number in dm
1867: - nullSpace - The nullspace for the given field
1869: Level: intermediate
1871: .seealso: [](ch_dmbase), `DM`, `DMAddField()`, `DMGetField()`, `DMSetNullSpaceConstructor()`, `DMSetNearNullSpaceConstructor()`, `DMGetNearNullSpaceConstructor()`, `DMCreateSubDM()`, `DMCreateSuperDM()`
1872: @*/
1873: PetscErrorCode DMGetNullSpaceConstructor(DM dm, PetscInt field, PetscErrorCode (**nullsp)(DM dm, PetscInt origField, PetscInt field, MatNullSpace *nullSpace))
1874: {
1875: PetscFunctionBegin;
1877: PetscAssertPointer(nullsp, 3);
1878: PetscCheck(field < dm->Nf, PetscObjectComm((PetscObject)dm), PETSC_ERR_ARG_OUTOFRANGE, "Cannot handle %" PetscInt_FMT " >= %" PetscInt_FMT " fields", field, dm->Nf);
1879: PetscCheck(dm->nullspaceConstructors, PetscObjectComm((PetscObject)dm), PETSC_ERR_ARG_WRONG, "Must call DMCreateDS() to setup nullspaces");
1880: *nullsp = dm->nullspaceConstructors[field];
1881: PetscFunctionReturn(PETSC_SUCCESS);
1882: }
1884: /*@
1885: DMSetNearNullSpaceConstructor - Provide a callback function which constructs the near-nullspace for a given field, defined with `DMAddField()`
1887: Logically Collective; No Fortran Support
1889: Input Parameters:
1890: + dm - The `DM`
1891: . field - The field number for the nullspace
1892: - nullsp - A callback to create the near-nullspace
1894: Calling sequence of `nullsp`:
1895: + dm - The present `DM`
1896: . origField - The field number given above, in the original `DM`
1897: . field - The field number in dm
1898: - nullSpace - The nullspace for the given field
1900: Level: intermediate
1902: .seealso: [](ch_dmbase), `DM`, `DMAddField()`, `DMGetNearNullSpaceConstructor()`, `DMSetNullSpaceConstructor()`, `DMGetNullSpaceConstructor()`, `DMCreateSubDM()`, `DMCreateSuperDM()`,
1903: `MatNullSpace`
1904: @*/
1905: PetscErrorCode DMSetNearNullSpaceConstructor(DM dm, PetscInt field, PetscErrorCode (*nullsp)(DM dm, PetscInt origField, PetscInt field, MatNullSpace *nullSpace))
1906: {
1907: PetscFunctionBegin;
1909: PetscCheck(field < dm->Nf, PetscObjectComm((PetscObject)dm), PETSC_ERR_ARG_OUTOFRANGE, "Cannot handle %" PetscInt_FMT " >= %" PetscInt_FMT " fields", field, dm->Nf);
1910: PetscCheck(dm->nearnullspaceConstructors, PetscObjectComm((PetscObject)dm), PETSC_ERR_ARG_WRONG, "Must call DMCreateDS() to setup nullspaces");
1911: dm->nearnullspaceConstructors[field] = nullsp;
1912: PetscFunctionReturn(PETSC_SUCCESS);
1913: }
1915: /*@
1916: DMGetNearNullSpaceConstructor - Return the callback function which constructs the near-nullspace for a given field, defined with `DMAddField()`
1918: Not Collective; No Fortran Support
1920: Input Parameters:
1921: + dm - The `DM`
1922: - field - The field number for the nullspace
1924: Output Parameter:
1925: . nullsp - A callback to create the near-nullspace
1927: Calling sequence of `nullsp`:
1928: + dm - The present `DM`
1929: . origField - The field number given above, in the original `DM`
1930: . field - The field number in dm
1931: - nullSpace - The nullspace for the given field
1933: Level: intermediate
1935: .seealso: [](ch_dmbase), `DM`, `DMAddField()`, `DMGetField()`, `DMSetNearNullSpaceConstructor()`, `DMSetNullSpaceConstructor()`, `DMGetNullSpaceConstructor()`, `DMCreateSubDM()`,
1936: `MatNullSpace`, `DMCreateSuperDM()`
1937: @*/
1938: PetscErrorCode DMGetNearNullSpaceConstructor(DM dm, PetscInt field, PetscErrorCode (**nullsp)(DM dm, PetscInt origField, PetscInt field, MatNullSpace *nullSpace))
1939: {
1940: PetscFunctionBegin;
1942: PetscAssertPointer(nullsp, 3);
1943: PetscCheck(field < dm->Nf, PetscObjectComm((PetscObject)dm), PETSC_ERR_ARG_OUTOFRANGE, "Cannot handle %" PetscInt_FMT " >= %" PetscInt_FMT " fields", field, dm->Nf);
1944: PetscCheck(dm->nearnullspaceConstructors, PetscObjectComm((PetscObject)dm), PETSC_ERR_ARG_WRONG, "Must call DMCreateDS() to setup nullspaces");
1945: *nullsp = dm->nearnullspaceConstructors[field];
1946: PetscFunctionReturn(PETSC_SUCCESS);
1947: }
1949: /*@
1950: DMCreateFieldIS - Creates a set of `IS` objects with the global indices of dofs for each field defined with `DMAddField()`
1952: Not Collective; No Fortran Support
1954: Input Parameter:
1955: . dm - the `DM` object
1957: Output Parameters:
1958: + numFields - The number of fields (or `NULL` if not requested)
1959: . fieldNames - The name of each field (or `NULL` if not requested)
1960: - fields - The global indices for each field (or `NULL` if not requested)
1962: Level: intermediate
1964: Note:
1965: The user is responsible for freeing all requested arrays. In particular, every entry of `fieldNames` should be freed with
1966: `PetscFree()`, every entry of `fields` should be destroyed with `ISDestroy()`, and both arrays should be freed with
1967: `PetscFree()`.
1969: Developer Note:
1970: It is not clear why both this function and `DMCreateFieldDecomposition()` exist. Having two seems redundant and confusing. This function should
1971: likely be removed.
1973: .seealso: [](ch_dmbase), `DM`, `DMAddField()`, `DMGetField()`, `DMDestroy()`, `DMView()`, `DMCreateInterpolation()`, `DMCreateColoring()`, `DMCreateMatrix()`,
1974: `DMCreateFieldDecomposition()`
1975: @*/
1976: PetscErrorCode DMCreateFieldIS(DM dm, PetscInt *numFields, char ***fieldNames, IS *fields[])
1977: {
1978: PetscSection section, sectionGlobal;
1980: PetscFunctionBegin;
1982: if (numFields) {
1983: PetscAssertPointer(numFields, 2);
1984: *numFields = 0;
1985: }
1986: if (fieldNames) {
1987: PetscAssertPointer(fieldNames, 3);
1988: *fieldNames = NULL;
1989: }
1990: if (fields) {
1991: PetscAssertPointer(fields, 4);
1992: *fields = NULL;
1993: }
1994: PetscCall(DMGetLocalSection(dm, §ion));
1995: if (section) {
1996: PetscInt *fieldSizes, *fieldNc, **fieldIndices;
1997: PetscInt nF, f, pStart, pEnd, p;
1999: PetscCall(DMGetGlobalSection(dm, §ionGlobal));
2000: PetscCall(PetscSectionGetNumFields(section, &nF));
2001: PetscCall(PetscMalloc3(nF, &fieldSizes, nF, &fieldNc, nF, &fieldIndices));
2002: PetscCall(PetscSectionGetChart(sectionGlobal, &pStart, &pEnd));
2003: for (f = 0; f < nF; ++f) {
2004: fieldSizes[f] = 0;
2005: PetscCall(PetscSectionGetFieldComponents(section, f, &fieldNc[f]));
2006: }
2007: for (p = pStart; p < pEnd; ++p) {
2008: PetscInt gdof;
2010: PetscCall(PetscSectionGetDof(sectionGlobal, p, &gdof));
2011: if (gdof > 0) {
2012: for (f = 0; f < nF; ++f) {
2013: PetscInt fdof, fcdof, fpdof;
2015: PetscCall(PetscSectionGetFieldDof(section, p, f, &fdof));
2016: PetscCall(PetscSectionGetFieldConstraintDof(section, p, f, &fcdof));
2017: fpdof = fdof - fcdof;
2018: if (fpdof && fpdof != fieldNc[f]) {
2019: /* Layout does not admit a pointwise block size */
2020: fieldNc[f] = 1;
2021: }
2022: fieldSizes[f] += fpdof;
2023: }
2024: }
2025: }
2026: for (f = 0; f < nF; ++f) {
2027: PetscCall(PetscMalloc1(fieldSizes[f], &fieldIndices[f]));
2028: fieldSizes[f] = 0;
2029: }
2030: for (p = pStart; p < pEnd; ++p) {
2031: PetscInt gdof, goff;
2033: PetscCall(PetscSectionGetDof(sectionGlobal, p, &gdof));
2034: if (gdof > 0) {
2035: PetscCall(PetscSectionGetOffset(sectionGlobal, p, &goff));
2036: for (f = 0; f < nF; ++f) {
2037: PetscInt fdof, fcdof, fc;
2039: PetscCall(PetscSectionGetFieldDof(section, p, f, &fdof));
2040: PetscCall(PetscSectionGetFieldConstraintDof(section, p, f, &fcdof));
2041: for (fc = 0; fc < fdof - fcdof; ++fc, ++fieldSizes[f]) fieldIndices[f][fieldSizes[f]] = goff++;
2042: }
2043: }
2044: }
2045: if (numFields) *numFields = nF;
2046: if (fieldNames) {
2047: PetscCall(PetscMalloc1(nF, fieldNames));
2048: for (f = 0; f < nF; ++f) {
2049: const char *fieldName;
2051: PetscCall(PetscSectionGetFieldName(section, f, &fieldName));
2052: PetscCall(PetscStrallocpy(fieldName, &(*fieldNames)[f]));
2053: }
2054: }
2055: if (fields) {
2056: PetscCall(PetscMalloc1(nF, fields));
2057: for (f = 0; f < nF; ++f) {
2058: PetscInt bs, out[2];
2060: PetscCall(ISCreateGeneral(PetscObjectComm((PetscObject)dm), fieldSizes[f], fieldIndices[f], PETSC_OWN_POINTER, &(*fields)[f]));
2061: out[0] = -fieldNc[f];
2062: out[1] = fieldNc[f];
2063: PetscCallMPI(MPIU_Allreduce(MPI_IN_PLACE, out, 2, MPIU_INT, MPI_MAX, PetscObjectComm((PetscObject)dm)));
2064: bs = (-out[0] == out[1]) ? out[1] : 1;
2065: PetscCall(ISSetBlockSize((*fields)[f], bs));
2066: }
2067: }
2068: PetscCall(PetscFree3(fieldSizes, fieldNc, fieldIndices));
2069: } else PetscTryTypeMethod(dm, createfieldis, numFields, fieldNames, fields);
2070: PetscFunctionReturn(PETSC_SUCCESS);
2071: }
2073: /*@
2074: DMCreateFieldDecomposition - Returns a list of `IS` objects defining a decomposition of a problem into subproblems
2075: corresponding to different fields.
2077: Not Collective; No Fortran Support
2079: Input Parameter:
2080: . dm - the `DM` object
2082: Output Parameters:
2083: + len - The number of fields (or `NULL` if not requested)
2084: . namelist - The name for each field (or `NULL` if not requested)
2085: . islist - The global indices for each field (or `NULL` if not requested)
2086: - dmlist - The `DM`s for each field subproblem (or `NULL`, if not requested; if `NULL` is returned, no `DM`s are defined)
2088: Level: intermediate
2090: Notes:
2091: Each `IS` contains the global indices of the dofs of the corresponding field, defined by
2092: `DMAddField()`. The optional list of `DM`s define the `DM` for each subproblem.
2094: The same as `DMCreateFieldIS()` but also returns a `DM` for each field.
2096: The user is responsible for freeing all requested arrays. In particular, every entry of `namelist` should be freed with
2097: `PetscFree()`, every entry of `islist` should be destroyed with `ISDestroy()`, every entry of `dmlist` should be destroyed with `DMDestroy()`,
2098: and all of the arrays should be freed with `PetscFree()`.
2100: Fortran Notes:
2101: Use the declarations
2102: .vb
2103: character(80), pointer :: namelist(:)
2104: IS, pointer :: islist(:)
2105: DM, pointer :: dmlist(:)
2106: .ve
2108: `namelist` must be provided, `islist` may be `PETSC_NULL_IS_POINTER` and `dmlist` may be `PETSC_NULL_DM_POINTER`
2110: Use `DMDestroyFieldDecomposition()` to free the returned objects
2112: Developer Notes:
2113: It is not clear why this function and `DMCreateFieldIS()` exist. Having two seems redundant and confusing.
2115: Unlike `DMRefine()`, `DMCoarsen()`, and `DMCreateDomainDecomposition()` this provides no mechanism to provide hooks that are called after the
2116: decomposition is computed.
2118: .seealso: [](ch_dmbase), `DM`, `DMAddField()`, `DMCreateFieldIS()`, `DMCreateSubDM()`, `DMCreateDomainDecomposition()`, `DMDestroy()`, `DMView()`, `DMCreateInterpolation()`, `DMCreateColoring()`, `DMCreateMatrix()`, `DMCreateMassMatrix()`, `DMRefine()`, `DMCoarsen()`
2119: @*/
2120: PetscErrorCode DMCreateFieldDecomposition(DM dm, PetscInt *len, char ***namelist, IS *islist[], DM *dmlist[])
2121: {
2122: PetscFunctionBegin;
2124: if (len) {
2125: PetscAssertPointer(len, 2);
2126: *len = 0;
2127: }
2128: if (namelist) {
2129: PetscAssertPointer(namelist, 3);
2130: *namelist = NULL;
2131: }
2132: if (islist) {
2133: PetscAssertPointer(islist, 4);
2134: *islist = NULL;
2135: }
2136: if (dmlist) {
2137: PetscAssertPointer(dmlist, 5);
2138: *dmlist = NULL;
2139: }
2140: /*
2141: Is it a good idea to apply the following check across all impls?
2142: Perhaps some impls can have a well-defined decomposition before DMSetUp?
2143: This, however, follows the general principle that accessors are not well-behaved until the object is set up.
2144: */
2145: PetscCheck(dm->setupcalled, PetscObjectComm((PetscObject)dm), PETSC_ERR_ARG_WRONGSTATE, "Decomposition defined only after DMSetUp");
2146: if (!dm->ops->createfielddecomposition) {
2147: PetscSection section;
2148: PetscInt numFields;
2150: PetscCall(DMGetLocalSection(dm, §ion));
2151: if (section) PetscCall(PetscSectionGetNumFields(section, &numFields));
2152: if (section && numFields && dm->ops->createsubdm) {
2153: if (len) *len = numFields;
2154: if (namelist) PetscCall(PetscMalloc1(numFields, namelist));
2155: if (islist) PetscCall(PetscMalloc1(numFields, islist));
2156: if (dmlist) PetscCall(PetscMalloc1(numFields, dmlist));
2157: for (PetscInt f = 0; f < numFields; ++f) {
2158: const char *fieldName;
2160: PetscCall(DMCreateSubDM(dm, 1, &f, islist ? &(*islist)[f] : NULL, dmlist ? &(*dmlist)[f] : NULL));
2161: if (namelist) {
2162: PetscCall(PetscSectionGetFieldName(section, f, &fieldName));
2163: PetscCall(PetscStrallocpy(fieldName, &(*namelist)[f]));
2164: }
2165: }
2166: } else {
2167: PetscCall(DMCreateFieldIS(dm, len, namelist, islist));
2168: /* By default there are no DMs associated with subproblems. */
2169: if (dmlist) *dmlist = NULL;
2170: }
2171: } else PetscUseTypeMethod(dm, createfielddecomposition, len, namelist, islist, dmlist);
2172: PetscFunctionReturn(PETSC_SUCCESS);
2173: }
2175: /*@
2176: DMCreateSubDM - Returns an `IS` and `DM` encapsulating a subproblem defined by the fields passed in.
2177: The fields are defined by `DMCreateFieldIS()`.
2179: Not collective
2181: Input Parameters:
2182: + dm - The `DM` object
2183: . numFields - The number of fields to select
2184: - fields - The field numbers of the selected fields
2186: Output Parameters:
2187: + is - The global indices for all the degrees of freedom in the new sub `DM`, use `NULL` if not needed
2188: - subdm - The `DM` for the subproblem, use `NULL` if not needed
2190: Level: intermediate
2192: Note:
2193: You need to call `DMPlexSetMigrationSF()` on the original `DM` if you want the Global-To-Natural map to be automatically constructed
2195: .seealso: [](ch_dmbase), `DM`, `DMCreateFieldIS()`, `DMCreateFieldDecomposition()`, `DMAddField()`, `DMCreateSuperDM()`, `IS`, `VecISCopy()`, `DMPlexSetMigrationSF()`, `DMDestroy()`, `DMView()`, `DMCreateInterpolation()`, `DMCreateColoring()`, `DMCreateMatrix()`, `DMCreateMassMatrix()`
2196: @*/
2197: PetscErrorCode DMCreateSubDM(DM dm, PetscInt numFields, const PetscInt fields[], IS *is, DM *subdm)
2198: {
2199: PetscFunctionBegin;
2201: PetscAssertPointer(fields, 3);
2202: if (is) PetscAssertPointer(is, 4);
2203: if (subdm) PetscAssertPointer(subdm, 5);
2204: PetscUseTypeMethod(dm, createsubdm, numFields, fields, is, subdm);
2205: PetscFunctionReturn(PETSC_SUCCESS);
2206: }
2208: /*@
2209: DMCreateSuperDM - Returns an arrays of `IS` and a single `DM` encapsulating a superproblem defined by multiple `DM`s passed in.
2211: Not collective
2213: Input Parameters:
2214: + dms - The `DM` objects
2215: - n - The number of `DM`s
2217: Output Parameters:
2218: + is - The global indices for each of subproblem within the super `DM`, or `NULL`, its length is `n`
2219: - superdm - The `DM` for the superproblem
2221: Level: intermediate
2223: Note:
2224: You need to call `DMPlexSetMigrationSF()` on the original `DM` if you want the Global-To-Natural map to be automatically constructed
2226: .seealso: [](ch_dmbase), `DM`, `DMCreateSubDM()`, `DMPlexSetMigrationSF()`, `DMDestroy()`, `DMView()`, `DMCreateInterpolation()`, `DMCreateColoring()`, `DMCreateMatrix()`, `DMCreateMassMatrix()`, `DMCreateFieldIS()`, `DMCreateDomainDecomposition()`
2227: @*/
2228: PetscErrorCode DMCreateSuperDM(DM dms[], PetscInt n, IS *is[], DM *superdm)
2229: {
2230: PetscFunctionBegin;
2231: PetscAssertPointer(dms, 1);
2233: if (is) PetscAssertPointer(is, 3);
2234: PetscAssertPointer(superdm, 4);
2235: PetscCheck(n >= 0, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Number of DMs must be nonnegative: %" PetscInt_FMT, n);
2236: if (n) {
2237: DM dm = dms[0];
2238: PetscCheck(dm->ops->createsuperdm, PetscObjectComm((PetscObject)dm), PETSC_ERR_SUP, "No method createsuperdm for DM of type %s", ((PetscObject)dm)->type_name);
2239: PetscCall((*dm->ops->createsuperdm)(dms, n, is, superdm));
2240: }
2241: PetscFunctionReturn(PETSC_SUCCESS);
2242: }
2244: /*@
2245: DMCreateDomainDecomposition - Returns lists of `IS` objects defining a decomposition of a
2246: problem into subproblems corresponding to restrictions to pairs of nested subdomains.
2248: Not Collective
2250: Input Parameter:
2251: . dm - the `DM` object
2253: Output Parameters:
2254: + n - The number of subproblems in the domain decomposition (or `NULL` if not requested), also the length of the four arrays below
2255: . namelist - The name for each subdomain (or `NULL` if not requested)
2256: . innerislist - The global indices for each inner subdomain (or `NULL`, if not requested)
2257: . outerislist - The global indices for each outer subdomain (or `NULL`, if not requested)
2258: - dmlist - The `DM`s for each subdomain subproblem (or `NULL`, if not requested; if `NULL` is returned, no `DM`s are defined)
2260: Level: intermediate
2262: Notes:
2263: Each `IS` contains the global indices of the dofs of the corresponding subdomains with in the
2264: dofs of the original `DM`. The inner subdomains conceptually define a nonoverlapping
2265: covering, while outer subdomains can overlap.
2267: The optional list of `DM`s define a `DM` for each subproblem.
2269: The user is responsible for freeing all requested arrays. In particular, every entry of `namelist` should be freed with
2270: `PetscFree()`, every entry of `innerislist` and `outerislist` should be destroyed with `ISDestroy()`, every entry of `dmlist` should be destroyed with `DMDestroy()`,
2271: and all of the arrays should be freed with `PetscFree()`.
2273: Developer Notes:
2274: The `dmlist` is for the inner subdomains or the outer subdomains or all subdomains?
2276: The names are inconsistent, the hooks use `DMSubDomainHook` which is nothing like `DMCreateDomainDecomposition()` while `DMRefineHook` is used for `DMRefine()`.
2278: .seealso: [](ch_dmbase), `DM`, `DMCreateFieldDecomposition()`, `DMDestroy()`, `DMCreateDomainDecompositionScatters()`, `DMView()`, `DMCreateInterpolation()`,
2279: `DMSubDomainHookAdd()`, `DMSubDomainHookRemove()`, `DMCreateColoring()`, `DMCreateMatrix()`, `DMCreateMassMatrix()`, `DMRefine()`, `DMCoarsen()`
2280: @*/
2281: PetscErrorCode DMCreateDomainDecomposition(DM dm, PetscInt *n, char **namelist[], IS *innerislist[], IS *outerislist[], DM *dmlist[])
2282: {
2283: DMSubDomainHookLink link;
2284: PetscInt l;
2286: PetscFunctionBegin;
2288: if (n) {
2289: PetscAssertPointer(n, 2);
2290: *n = 0;
2291: }
2292: if (namelist) {
2293: PetscAssertPointer(namelist, 3);
2294: *namelist = NULL;
2295: }
2296: if (innerislist) {
2297: PetscAssertPointer(innerislist, 4);
2298: *innerislist = NULL;
2299: }
2300: if (outerislist) {
2301: PetscAssertPointer(outerislist, 5);
2302: *outerislist = NULL;
2303: }
2304: if (dmlist) {
2305: PetscAssertPointer(dmlist, 6);
2306: *dmlist = NULL;
2307: }
2308: /*
2309: Is it a good idea to apply the following check across all impls?
2310: Perhaps some impls can have a well-defined decomposition before DMSetUp?
2311: This, however, follows the general principle that accessors are not well-behaved until the object is set up.
2312: */
2313: PetscCheck(dm->setupcalled, PetscObjectComm((PetscObject)dm), PETSC_ERR_ARG_WRONGSTATE, "Decomposition defined only after DMSetUp");
2314: if (dm->ops->createdomaindecomposition) {
2315: PetscUseTypeMethod(dm, createdomaindecomposition, &l, namelist, innerislist, outerislist, dmlist);
2316: /* copy subdomain hooks and context over to the subdomain DMs */
2317: if (dmlist && *dmlist) {
2318: for (PetscInt i = 0; i < l; i++) {
2319: for (link = dm->subdomainhook; link; link = link->next) {
2320: if (link->ddhook) PetscCall((*link->ddhook)(dm, (*dmlist)[i], link->ctx));
2321: }
2322: if (dm->ctx) (*dmlist)[i]->ctx = dm->ctx;
2323: }
2324: }
2325: if (n) *n = l;
2326: }
2327: PetscFunctionReturn(PETSC_SUCCESS);
2328: }
2330: /*@
2331: DMCreateDomainDecompositionScatters - Returns scatters to the subdomain vectors from the global vector for subdomains created with
2332: `DMCreateDomainDecomposition()`
2334: Not Collective
2336: Input Parameters:
2337: + dm - the `DM` object
2338: . n - the number of subdomains
2339: - subdms - the local subdomains
2341: Output Parameters:
2342: + iscat - scatter from global vector to nonoverlapping global vector entries on subdomain
2343: . oscat - scatter from global vector to overlapping global vector entries on subdomain
2344: - gscat - scatter from global vector to local vector on subdomain (fills in ghosts)
2346: Level: developer
2348: Note:
2349: This is an alternative to the `iis` and `ois` arguments in `DMCreateDomainDecomposition()` that allow for the solution
2350: of general nonlinear problems with overlapping subdomain methods. While merely having index sets that enable subsets
2351: of the residual equations to be created is fine for linear problems, nonlinear problems require local assembly of
2352: solution and residual data.
2354: Developer Note:
2355: Can the `subdms` input be anything or are they exactly the `DM` obtained from
2356: `DMCreateDomainDecomposition()`?
2358: .seealso: [](ch_dmbase), `DM`, `DMCreateDomainDecomposition()`, `DMDestroy()`, `DMView()`, `DMCreateInterpolation()`, `DMCreateColoring()`, `DMCreateMatrix()`, `DMCreateMassMatrix()`, `DMCreateFieldIS()`
2359: @*/
2360: PetscErrorCode DMCreateDomainDecompositionScatters(DM dm, PetscInt n, DM subdms[], VecScatter *iscat[], VecScatter *oscat[], VecScatter *gscat[])
2361: {
2362: PetscFunctionBegin;
2364: PetscAssertPointer(subdms, 3);
2365: PetscUseTypeMethod(dm, createddscatters, n, subdms, iscat, oscat, gscat);
2366: PetscFunctionReturn(PETSC_SUCCESS);
2367: }
2369: /*@
2370: DMRefine - Refines a `DM` object using a standard nonadaptive refinement of the underlying mesh
2372: Collective
2374: Input Parameters:
2375: + dm - the `DM` object
2376: - comm - the communicator to contain the new `DM` object (or `MPI_COMM_NULL`)
2378: Output Parameter:
2379: . dmf - the refined `DM`, or `NULL`
2381: Options Database Key:
2382: . -dm_plex_cell_refiner strategy - chooses the refinement strategy, e.g. regular, tohex
2384: Level: developer
2386: Note:
2387: If no refinement was done, the return value is `NULL`
2389: .seealso: [](ch_dmbase), `DM`, `DMCoarsen()`, `DMDestroy()`, `DMView()`, `DMCreateGlobalVector()`, `DMCreateInterpolation()`, `DMCreateDomainDecomposition()`,
2390: `DMRefineHookAdd()`, `DMRefineHookRemove()`
2391: @*/
2392: PetscErrorCode DMRefine(DM dm, MPI_Comm comm, DM *dmf)
2393: {
2394: DMRefineHookLink link;
2396: PetscFunctionBegin;
2398: PetscCall(PetscLogEventBegin(DM_Refine, dm, 0, 0, 0));
2399: PetscUseTypeMethod(dm, refine, comm, dmf);
2400: if (*dmf) {
2401: (*dmf)->ops->creatematrix = dm->ops->creatematrix;
2403: PetscCall(PetscObjectCopyFortranFunctionPointers((PetscObject)dm, (PetscObject)*dmf));
2405: (*dmf)->ctx = dm->ctx;
2406: (*dmf)->leveldown = dm->leveldown;
2407: (*dmf)->levelup = dm->levelup + 1;
2409: PetscCall(DMSetMatType(*dmf, dm->mattype));
2410: for (link = dm->refinehook; link; link = link->next) {
2411: if (link->refinehook) PetscCall((*link->refinehook)(dm, *dmf, link->ctx));
2412: }
2413: }
2414: PetscCall(PetscLogEventEnd(DM_Refine, dm, 0, 0, 0));
2415: PetscFunctionReturn(PETSC_SUCCESS);
2416: }
2418: /*@
2419: DMRefineHookAdd - adds a callback to be run when interpolating a nonlinear problem to a finer grid
2421: Logically Collective; No Fortran Support
2423: Input Parameters:
2424: + coarse - `DM` on which to run a hook when interpolating to a finer level
2425: . refinehook - function to run when setting up the finer level
2426: . interphook - function to run to update data on finer levels (once per `SNESSolve()`)
2427: - ctx - [optional] context for provide data for the hooks (may be `NULL`)
2429: Calling sequence of `refinehook`:
2430: + coarse - coarse level `DM`
2431: . fine - fine level `DM` to interpolate problem to
2432: - ctx - optional function context
2434: Calling sequence of `interphook`:
2435: + coarse - coarse level `DM`
2436: . interp - matrix interpolating a coarse-level solution to the finer grid
2437: . fine - fine level `DM` to update
2438: - ctx - optional function context
2440: Level: advanced
2442: Notes:
2443: This function is only needed if auxiliary data that is attached to the `DM`s via, for example, `PetscObjectCompose()`, needs to be
2444: passed to fine grids while grid sequencing.
2446: The actual interpolation is done when `DMInterpolate()` is called.
2448: If this function is called multiple times, the hooks will be run in the order they are added.
2450: .seealso: [](ch_dmbase), `DM`, `DMCoarsenHookAdd()`, `DMInterpolate()`, `SNESFASGetInterpolation()`, `SNESFASGetInjection()`, `PetscObjectCompose()`, `PetscContainerCreate()`
2451: @*/
2452: PetscErrorCode DMRefineHookAdd(DM coarse, PetscErrorCode (*refinehook)(DM coarse, DM fine, PetscCtx ctx), PetscErrorCode (*interphook)(DM coarse, Mat interp, DM fine, PetscCtx ctx), PetscCtx ctx)
2453: {
2454: DMRefineHookLink link, *p;
2456: PetscFunctionBegin;
2458: for (p = &coarse->refinehook; *p; p = &(*p)->next) { /* Scan to the end of the current list of hooks */
2459: if ((*p)->refinehook == refinehook && (*p)->interphook == interphook && (*p)->ctx == ctx) PetscFunctionReturn(PETSC_SUCCESS);
2460: }
2461: PetscCall(PetscNew(&link));
2462: link->refinehook = refinehook;
2463: link->interphook = interphook;
2464: link->ctx = ctx;
2465: link->next = NULL;
2466: *p = link;
2467: PetscFunctionReturn(PETSC_SUCCESS);
2468: }
2470: /*@
2471: DMRefineHookRemove - remove a callback from the list of hooks, that have been set with `DMRefineHookAdd()`, to be run when interpolating
2472: a nonlinear problem to a finer grid
2474: Logically Collective; No Fortran Support
2476: Input Parameters:
2477: + coarse - the `DM` on which to run a hook when restricting to a coarser level
2478: . refinehook - function to run when setting up a finer level
2479: . interphook - function to run to update data on finer levels
2480: - ctx - [optional] application context for provide data for the hooks (may be `NULL`)
2482: Calling sequence of refinehook:
2483: + coarse - the coarse `DM`
2484: . fine - the fine `DM`
2485: - ctx - context for the function
2487: Calling sequence of interphook:
2488: + coarse - the coarse `DM`
2489: . interp - the interpolation `Mat` from coarse to fine
2490: . fine - the fine `DM`
2491: - ctx - context for the function
2493: Level: advanced
2495: Note:
2496: This function does nothing if the hook is not in the list.
2498: .seealso: [](ch_dmbase), `DM`, `DMRefineHookAdd()`, `DMCoarsenHookRemove()`, `DMInterpolate()`, `SNESFASGetInterpolation()`, `SNESFASGetInjection()`, `PetscObjectCompose()`, `PetscContainerCreate()`
2499: @*/
2500: PetscErrorCode DMRefineHookRemove(DM coarse, PetscErrorCode (*refinehook)(DM coarse, DM fine, PetscCtx ctx), PetscErrorCode (*interphook)(DM coarse, Mat interp, DM fine, PetscCtx ctx), PetscCtx ctx)
2501: {
2502: DMRefineHookLink link, *p;
2504: PetscFunctionBegin;
2506: for (p = &coarse->refinehook; *p; p = &(*p)->next) { /* Search the list of current hooks */
2507: if ((*p)->refinehook == refinehook && (*p)->interphook == interphook && (*p)->ctx == ctx) {
2508: link = *p;
2509: *p = link->next;
2510: PetscCall(PetscFree(link));
2511: break;
2512: }
2513: }
2514: PetscFunctionReturn(PETSC_SUCCESS);
2515: }
2517: /*@
2518: DMInterpolate - interpolates user-defined problem data attached to a `DM` to a finer `DM` by running hooks registered by `DMRefineHookAdd()`
2520: Collective if any hooks are
2522: Input Parameters:
2523: + coarse - coarser `DM` to use as a base
2524: . interp - interpolation matrix, apply using `MatInterpolate()`
2525: - fine - finer `DM` to update
2527: Level: developer
2529: Developer Note:
2530: This routine is called `DMInterpolate()` while the hook is called `DMRefineHookAdd()`. It would be better to have an
2531: an API with consistent terminology.
2533: .seealso: [](ch_dmbase), `DM`, `DMRefineHookAdd()`, `MatInterpolate()`
2534: @*/
2535: PetscErrorCode DMInterpolate(DM coarse, Mat interp, DM fine)
2536: {
2537: DMRefineHookLink link;
2539: PetscFunctionBegin;
2540: for (link = fine->refinehook; link; link = link->next) {
2541: if (link->interphook) PetscCall((*link->interphook)(coarse, interp, fine, link->ctx));
2542: }
2543: PetscFunctionReturn(PETSC_SUCCESS);
2544: }
2546: /*@
2547: DMInterpolateSolution - Interpolates a solution from a coarse mesh to a fine mesh.
2549: Collective
2551: Input Parameters:
2552: + coarse - coarse `DM`
2553: . fine - fine `DM`
2554: . interp - (optional) the matrix computed by `DMCreateInterpolation()`. Implementations may not need this, but if it
2555: is available it can avoid some recomputation. If it is provided, `MatInterpolate()` will be used if
2556: the coarse `DM` does not have a specialized implementation.
2557: - coarseSol - solution on the coarse mesh
2559: Output Parameter:
2560: . fineSol - the interpolation of coarseSol to the fine mesh
2562: Level: developer
2564: Note:
2565: This function exists because the interpolation of a solution vector between meshes is not always a linear
2566: map. For example, if a boundary value problem has an inhomogeneous Dirichlet boundary condition that is compressed
2567: out of the solution vector. Or if interpolation is inherently a nonlinear operation, such as a method using
2568: slope-limiting reconstruction.
2570: Developer Note:
2571: This doesn't just interpolate "solutions" so its API name is questionable.
2573: .seealso: [](ch_dmbase), `DM`, `DMInterpolate()`, `DMCreateInterpolation()`
2574: @*/
2575: PetscErrorCode DMInterpolateSolution(DM coarse, DM fine, Mat interp, Vec coarseSol, Vec fineSol)
2576: {
2577: PetscErrorCode (*interpsol)(DM, DM, Mat, Vec, Vec) = NULL;
2579: PetscFunctionBegin;
2585: PetscCall(PetscObjectQueryFunction((PetscObject)coarse, "DMInterpolateSolution_C", &interpsol));
2586: if (interpsol) {
2587: PetscCall((*interpsol)(coarse, fine, interp, coarseSol, fineSol));
2588: } else if (interp) {
2589: PetscCall(MatInterpolate(interp, coarseSol, fineSol));
2590: } else SETERRQ(PetscObjectComm((PetscObject)coarse), PETSC_ERR_SUP, "DM %s does not implement DMInterpolateSolution()", ((PetscObject)coarse)->type_name);
2591: PetscFunctionReturn(PETSC_SUCCESS);
2592: }
2594: /*@
2595: DMGetRefineLevel - Gets the number of refinements that have generated this `DM` from some initial `DM`.
2597: Not Collective
2599: Input Parameter:
2600: . dm - the `DM` object
2602: Output Parameter:
2603: . level - number of refinements
2605: Level: developer
2607: Note:
2608: This can be used, by example, to set the number of coarser levels associated with this `DM` for a multigrid solver.
2610: .seealso: [](ch_dmbase), `DM`, `DMRefine()`, `DMCoarsen()`, `DMGetCoarsenLevel()`, `DMDestroy()`, `DMView()`, `DMCreateGlobalVector()`, `DMCreateInterpolation()`
2611: @*/
2612: PetscErrorCode DMGetRefineLevel(DM dm, PetscInt *level)
2613: {
2614: PetscFunctionBegin;
2616: *level = dm->levelup;
2617: PetscFunctionReturn(PETSC_SUCCESS);
2618: }
2620: /*@
2621: DMSetRefineLevel - Sets the number of refinements that have generated this `DM`.
2623: Not Collective
2625: Input Parameters:
2626: + dm - the `DM` object
2627: - level - number of refinements
2629: Level: advanced
2631: Notes:
2632: This value is used by `PCMG` to determine how many multigrid levels to use
2634: The values are usually set automatically by the process that is causing the refinements of an initial `DM` by calling this routine.
2636: .seealso: [](ch_dmbase), `DM`, `DMGetRefineLevel()`, `DMCoarsen()`, `DMGetCoarsenLevel()`, `DMDestroy()`, `DMView()`, `DMCreateGlobalVector()`, `DMCreateInterpolation()`
2637: @*/
2638: PetscErrorCode DMSetRefineLevel(DM dm, PetscInt level)
2639: {
2640: PetscFunctionBegin;
2642: dm->levelup = level;
2643: PetscFunctionReturn(PETSC_SUCCESS);
2644: }
2646: /*@
2647: DMExtrude - Extrude a `DM` object from a surface
2649: Collective
2651: Input Parameters:
2652: + dm - the `DM` object
2653: - layers - the number of extruded cell layers
2655: Output Parameter:
2656: . dme - the extruded `DM`, or `NULL`
2658: Level: developer
2660: Note:
2661: If no extrusion was done, the return value is `NULL`
2663: .seealso: [](ch_dmbase), `DM`, `DMRefine()`, `DMCoarsen()`, `DMDestroy()`, `DMView()`, `DMCreateGlobalVector()`
2664: @*/
2665: PetscErrorCode DMExtrude(DM dm, PetscInt layers, DM *dme)
2666: {
2667: PetscFunctionBegin;
2669: PetscUseTypeMethod(dm, extrude, layers, dme);
2670: if (*dme) {
2671: (*dme)->ops->creatematrix = dm->ops->creatematrix;
2672: PetscCall(PetscObjectCopyFortranFunctionPointers((PetscObject)dm, (PetscObject)*dme));
2673: (*dme)->ctx = dm->ctx;
2674: PetscCall(DMSetMatType(*dme, dm->mattype));
2675: }
2676: PetscFunctionReturn(PETSC_SUCCESS);
2677: }
2679: PetscErrorCode DMGetBasisTransformDM_Internal(DM dm, DM *tdm)
2680: {
2681: PetscFunctionBegin;
2683: PetscAssertPointer(tdm, 2);
2684: *tdm = dm->transformDM;
2685: PetscFunctionReturn(PETSC_SUCCESS);
2686: }
2688: PetscErrorCode DMGetBasisTransformVec_Internal(DM dm, Vec *tv)
2689: {
2690: PetscFunctionBegin;
2692: PetscAssertPointer(tv, 2);
2693: *tv = dm->transform;
2694: PetscFunctionReturn(PETSC_SUCCESS);
2695: }
2697: /*@
2698: DMHasBasisTransform - Whether the `DM` employs a basis transformation from functions in global vectors to functions in local vectors
2700: Input Parameter:
2701: . dm - The `DM`
2703: Output Parameter:
2704: . flg - `PETSC_TRUE` if a basis transformation should be done
2706: Level: developer
2708: .seealso: [](ch_dmbase), `DM`, `DMPlexGlobalToLocalBasis()`, `DMPlexLocalToGlobalBasis()`, `DMPlexCreateBasisRotation()`
2709: @*/
2710: PetscErrorCode DMHasBasisTransform(DM dm, PetscBool *flg)
2711: {
2712: Vec tv;
2714: PetscFunctionBegin;
2716: PetscAssertPointer(flg, 2);
2717: PetscCall(DMGetBasisTransformVec_Internal(dm, &tv));
2718: *flg = tv ? PETSC_TRUE : PETSC_FALSE;
2719: PetscFunctionReturn(PETSC_SUCCESS);
2720: }
2722: PetscErrorCode DMConstructBasisTransform_Internal(DM dm)
2723: {
2724: PetscSection s, ts;
2725: PetscScalar *ta;
2726: PetscInt cdim, pStart, pEnd, p, Nf, f, Nc, dof;
2728: PetscFunctionBegin;
2729: PetscCall(DMGetCoordinateDim(dm, &cdim));
2730: PetscCall(DMGetLocalSection(dm, &s));
2731: PetscCall(PetscSectionGetChart(s, &pStart, &pEnd));
2732: PetscCall(PetscSectionGetNumFields(s, &Nf));
2733: PetscCall(DMClone(dm, &dm->transformDM));
2734: PetscCall(DMGetLocalSection(dm->transformDM, &ts));
2735: PetscCall(PetscSectionSetNumFields(ts, Nf));
2736: PetscCall(PetscSectionSetChart(ts, pStart, pEnd));
2737: for (f = 0; f < Nf; ++f) {
2738: PetscCall(PetscSectionGetFieldComponents(s, f, &Nc));
2739: /* We could start to label fields by their transformation properties */
2740: if (Nc != cdim) continue;
2741: for (p = pStart; p < pEnd; ++p) {
2742: PetscCall(PetscSectionGetFieldDof(s, p, f, &dof));
2743: if (!dof) continue;
2744: PetscCall(PetscSectionSetFieldDof(ts, p, f, PetscSqr(cdim)));
2745: PetscCall(PetscSectionAddDof(ts, p, PetscSqr(cdim)));
2746: }
2747: }
2748: PetscCall(PetscSectionSetUp(ts));
2749: PetscCall(DMCreateLocalVector(dm->transformDM, &dm->transform));
2750: PetscCall(VecGetArray(dm->transform, &ta));
2751: for (p = pStart; p < pEnd; ++p) {
2752: for (f = 0; f < Nf; ++f) {
2753: PetscCall(PetscSectionGetFieldDof(ts, p, f, &dof));
2754: if (dof) {
2755: PetscReal x[3] = {0.0, 0.0, 0.0};
2756: PetscScalar *tva;
2757: const PetscScalar *A;
2759: /* TODO Get quadrature point for this dual basis vector for coordinate */
2760: PetscCall((*dm->transformGetMatrix)(dm, x, PETSC_TRUE, &A, dm->transformCtx));
2761: PetscCall(DMPlexPointLocalFieldRef(dm->transformDM, p, f, ta, (void *)&tva));
2762: PetscCall(PetscArraycpy(tva, A, PetscSqr(cdim)));
2763: }
2764: }
2765: }
2766: PetscCall(VecRestoreArray(dm->transform, &ta));
2767: PetscFunctionReturn(PETSC_SUCCESS);
2768: }
2770: /*@
2771: DMCopyTransform - Copy the basis transform context and callbacks from `dm` to `newdm`
2773: Not Collective
2775: Input Parameter:
2776: . dm - the source `DM`
2778: Output Parameter:
2779: . newdm - the destination `DM`
2781: Level: developer
2783: Note:
2784: If the transform requires setup, `DMConstructBasisTransform_Internal()` is invoked on `newdm`.
2786: .seealso: [](ch_dmbase), `DM`, `DMCopyDS()`, `DMCopyDisc()`
2787: @*/
2788: PetscErrorCode DMCopyTransform(DM dm, DM newdm)
2789: {
2790: PetscFunctionBegin;
2793: newdm->transformCtx = dm->transformCtx;
2794: newdm->transformSetUp = dm->transformSetUp;
2795: newdm->transformDestroy = NULL;
2796: newdm->transformGetMatrix = dm->transformGetMatrix;
2797: if (newdm->transformSetUp) PetscCall(DMConstructBasisTransform_Internal(newdm));
2798: PetscFunctionReturn(PETSC_SUCCESS);
2799: }
2801: /*@
2802: DMGlobalToLocalHookAdd - adds a callback to be run when `DMGlobalToLocal()` is called
2804: Logically Collective
2806: Input Parameters:
2807: + dm - the `DM`
2808: . beginhook - function to run at the beginning of `DMGlobalToLocalBegin()`
2809: . endhook - function to run after `DMGlobalToLocalEnd()` has completed
2810: - ctx - [optional] context for provide data for the hooks (may be `NULL`)
2812: Calling sequence of `beginhook`:
2813: + dm - global `DM`
2814: . g - global vector
2815: . mode - mode
2816: . l - local vector
2817: - ctx - optional function context
2819: Calling sequence of `endhook`:
2820: + dm - global `DM`
2821: . g - global vector
2822: . mode - mode
2823: . l - local vector
2824: - ctx - optional function context
2826: Level: advanced
2828: Note:
2829: The hook may be used to provide, for example, values that represent boundary conditions in the local vectors that do not exist on the global vector.
2831: .seealso: [](ch_dmbase), `DM`, `DMGlobalToLocal()`, `DMRefineHookAdd()`, `SNESFASGetInterpolation()`, `SNESFASGetInjection()`, `PetscObjectCompose()`, `PetscContainerCreate()`
2832: @*/
2833: PetscErrorCode DMGlobalToLocalHookAdd(DM dm, PetscErrorCode (*beginhook)(DM dm, Vec g, InsertMode mode, Vec l, PetscCtx ctx), PetscErrorCode (*endhook)(DM dm, Vec g, InsertMode mode, Vec l, PetscCtx ctx), PetscCtx ctx)
2834: {
2835: DMGlobalToLocalHookLink link, *p;
2837: PetscFunctionBegin;
2839: for (p = &dm->gtolhook; *p; p = &(*p)->next) { } /* Scan to the end of the current list of hooks */
2840: PetscCall(PetscNew(&link));
2841: link->beginhook = beginhook;
2842: link->endhook = endhook;
2843: link->ctx = ctx;
2844: link->next = NULL;
2845: *p = link;
2846: PetscFunctionReturn(PETSC_SUCCESS);
2847: }
2849: static PetscErrorCode DMGlobalToLocalHook_Constraints(DM dm, Vec g, InsertMode mode, Vec l, PetscCtx ctx)
2850: {
2851: Mat cMat;
2852: Vec cVec, cBias;
2853: PetscSection section, cSec;
2854: PetscInt pStart, pEnd, p, dof;
2856: PetscFunctionBegin;
2857: (void)g;
2858: (void)ctx;
2860: PetscCall(DMGetDefaultConstraints(dm, &cSec, &cMat, &cBias));
2861: if (cMat && (mode == INSERT_VALUES || mode == INSERT_ALL_VALUES || mode == INSERT_BC_VALUES)) {
2862: PetscInt nRows;
2864: PetscCall(MatGetSize(cMat, &nRows, NULL));
2865: if (nRows <= 0) PetscFunctionReturn(PETSC_SUCCESS);
2866: PetscCall(DMGetLocalSection(dm, §ion));
2867: PetscCall(MatCreateVecs(cMat, NULL, &cVec));
2868: PetscCall(MatMult(cMat, l, cVec));
2869: if (cBias) PetscCall(VecAXPY(cVec, 1., cBias));
2870: PetscCall(PetscSectionGetChart(cSec, &pStart, &pEnd));
2871: for (p = pStart; p < pEnd; p++) {
2872: PetscCall(PetscSectionGetDof(cSec, p, &dof));
2873: if (dof) {
2874: PetscScalar *vals;
2875: PetscCall(VecGetValuesSection(cVec, cSec, p, &vals));
2876: PetscCall(VecSetValuesSection(l, section, p, vals, INSERT_ALL_VALUES));
2877: }
2878: }
2879: PetscCall(VecDestroy(&cVec));
2880: }
2881: PetscFunctionReturn(PETSC_SUCCESS);
2882: }
2884: /*@
2885: DMGlobalToLocal - update local vectors from global vector
2887: Neighbor-wise Collective
2889: Input Parameters:
2890: + dm - the `DM` object
2891: . g - the global vector
2892: . mode - `INSERT_VALUES` or `ADD_VALUES`
2893: - l - the local vector
2895: Level: beginner
2897: Notes:
2898: The communication involved in this update can be overlapped with computation by instead using
2899: `DMGlobalToLocalBegin()` and `DMGlobalToLocalEnd()`.
2901: `DMGlobalToLocalHookAdd()` may be used to provide additional operations that are performed during the update process.
2903: .seealso: [](ch_dmbase), `DM`, `DMGlobalToLocalHookAdd()`, `DMCoarsen()`, `DMDestroy()`, `DMView()`, `DMCreateGlobalVector()`, `DMCreateInterpolation()`,
2904: `DMLocalToGlobalBegin()`, `DMLocalToGlobal()`, `DMLocalToGlobalEnd()`,
2905: `DMGlobalToLocalBegin()`, `DMGlobalToLocalEnd()`
2906: @*/
2907: PetscErrorCode DMGlobalToLocal(DM dm, Vec g, InsertMode mode, Vec l)
2908: {
2909: PetscFunctionBegin;
2910: PetscCall(DMGlobalToLocalBegin(dm, g, mode, l));
2911: PetscCall(DMGlobalToLocalEnd(dm, g, mode, l));
2912: PetscFunctionReturn(PETSC_SUCCESS);
2913: }
2915: /*@
2916: DMGlobalToLocalBegin - Begins updating local vectors from global vector
2918: Neighbor-wise Collective
2920: Input Parameters:
2921: + dm - the `DM` object
2922: . g - the global vector
2923: . mode - `INSERT_VALUES` or `ADD_VALUES`
2924: - l - the local vector
2926: Level: intermediate
2928: Notes:
2929: The operation is completed with `DMGlobalToLocalEnd()`
2931: One can perform local computations between the `DMGlobalToLocalBegin()` and `DMGlobalToLocalEnd()` to overlap communication and computation
2933: `DMGlobalToLocal()` is a short form of `DMGlobalToLocalBegin()` and `DMGlobalToLocalEnd()`
2935: `DMGlobalToLocalHookAdd()` may be used to provide additional operations that are performed during the update process.
2937: .seealso: [](ch_dmbase), `DM`, `DMCoarsen()`, `DMDestroy()`, `DMView()`, `DMCreateGlobalVector()`, `DMCreateInterpolation()`, `DMGlobalToLocal()`, `DMGlobalToLocalEnd()`, `DMLocalToGlobalBegin()`, `DMLocalToGlobal()`, `DMLocalToGlobalEnd()`
2938: @*/
2939: PetscErrorCode DMGlobalToLocalBegin(DM dm, Vec g, InsertMode mode, Vec l)
2940: {
2941: PetscSF sf;
2942: DMGlobalToLocalHookLink link;
2944: PetscFunctionBegin;
2946: for (link = dm->gtolhook; link; link = link->next) {
2947: if (link->beginhook) PetscCall((*link->beginhook)(dm, g, mode, l, link->ctx));
2948: }
2949: PetscCall(DMGetSectionSF(dm, &sf));
2950: if (sf) {
2951: const PetscScalar *gArray;
2952: PetscScalar *lArray;
2953: PetscMemType lmtype, gmtype;
2955: PetscCheck(mode != ADD_VALUES, PetscObjectComm((PetscObject)dm), PETSC_ERR_ARG_OUTOFRANGE, "Invalid insertion mode %d", (int)mode);
2956: PetscCall(VecGetArrayAndMemType(l, &lArray, &lmtype));
2957: PetscCall(VecGetArrayReadAndMemType(g, &gArray, &gmtype));
2958: PetscCall(PetscSFBcastWithMemTypeBegin(sf, MPIU_SCALAR, gmtype, gArray, lmtype, lArray, MPI_REPLACE));
2959: PetscCall(VecRestoreArrayAndMemType(l, &lArray));
2960: PetscCall(VecRestoreArrayReadAndMemType(g, &gArray));
2961: } else {
2962: PetscUseTypeMethod(dm, globaltolocalbegin, g, mode == INSERT_ALL_VALUES ? INSERT_VALUES : (mode == ADD_ALL_VALUES ? ADD_VALUES : mode), l);
2963: }
2964: PetscFunctionReturn(PETSC_SUCCESS);
2965: }
2967: /*@
2968: DMGlobalToLocalEnd - Ends updating local vectors from global vector
2970: Neighbor-wise Collective
2972: Input Parameters:
2973: + dm - the `DM` object
2974: . g - the global vector
2975: . mode - `INSERT_VALUES` or `ADD_VALUES`
2976: - l - the local vector
2978: Level: intermediate
2980: Note:
2981: See `DMGlobalToLocalBegin()` for details.
2983: .seealso: [](ch_dmbase), `DM`, `DMCoarsen()`, `DMDestroy()`, `DMView()`, `DMCreateGlobalVector()`, `DMCreateInterpolation()`, `DMGlobalToLocal()`, `DMLocalToGlobalBegin()`, `DMLocalToGlobal()`, `DMLocalToGlobalEnd()`
2984: @*/
2985: PetscErrorCode DMGlobalToLocalEnd(DM dm, Vec g, InsertMode mode, Vec l)
2986: {
2987: PetscSF sf;
2988: const PetscScalar *gArray;
2989: PetscScalar *lArray;
2990: PetscBool transform;
2991: DMGlobalToLocalHookLink link;
2992: PetscMemType lmtype, gmtype;
2994: PetscFunctionBegin;
2996: PetscCall(DMGetSectionSF(dm, &sf));
2997: PetscCall(DMHasBasisTransform(dm, &transform));
2998: if (sf) {
2999: PetscCheck(mode != ADD_VALUES, PetscObjectComm((PetscObject)dm), PETSC_ERR_ARG_OUTOFRANGE, "Invalid insertion mode %d", (int)mode);
3001: PetscCall(VecGetArrayAndMemType(l, &lArray, &lmtype));
3002: PetscCall(VecGetArrayReadAndMemType(g, &gArray, &gmtype));
3003: PetscCall(PetscSFBcastEnd(sf, MPIU_SCALAR, gArray, lArray, MPI_REPLACE));
3004: PetscCall(VecRestoreArrayAndMemType(l, &lArray));
3005: PetscCall(VecRestoreArrayReadAndMemType(g, &gArray));
3006: if (transform) PetscCall(DMPlexGlobalToLocalBasis(dm, l));
3007: } else {
3008: PetscUseTypeMethod(dm, globaltolocalend, g, mode == INSERT_ALL_VALUES ? INSERT_VALUES : (mode == ADD_ALL_VALUES ? ADD_VALUES : mode), l);
3009: }
3010: PetscCall(DMGlobalToLocalHook_Constraints(dm, g, mode, l, NULL));
3011: for (link = dm->gtolhook; link; link = link->next) {
3012: if (link->endhook) PetscCall((*link->endhook)(dm, g, mode, l, link->ctx));
3013: }
3014: PetscFunctionReturn(PETSC_SUCCESS);
3015: }
3017: /*@
3018: DMLocalToGlobalHookAdd - adds a callback to be run when a local to global is called
3020: Logically Collective
3022: Input Parameters:
3023: + dm - the `DM`
3024: . beginhook - function to run at the beginning of `DMLocalToGlobalBegin()`
3025: . endhook - function to run after `DMLocalToGlobalEnd()` has completed
3026: - ctx - [optional] context for provide data for the hooks (may be `NULL`)
3028: Calling sequence of `beginhook`:
3029: + global - global `DM`
3030: . l - local vector
3031: . mode - mode
3032: . g - global vector
3033: - ctx - optional function context
3035: Calling sequence of `endhook`:
3036: + global - global `DM`
3037: . l - local vector
3038: . mode - mode
3039: . g - global vector
3040: - ctx - optional function context
3042: Level: advanced
3044: .seealso: [](ch_dmbase), `DM`, `DMLocalToGlobal()`, `DMRefineHookAdd()`, `DMGlobalToLocalHookAdd()`, `SNESFASGetInterpolation()`, `SNESFASGetInjection()`, `PetscObjectCompose()`, `PetscContainerCreate()`
3045: @*/
3046: PetscErrorCode DMLocalToGlobalHookAdd(DM dm, PetscErrorCode (*beginhook)(DM global, Vec l, InsertMode mode, Vec g, PetscCtx ctx), PetscErrorCode (*endhook)(DM global, Vec l, InsertMode mode, Vec g, PetscCtx ctx), PetscCtx ctx)
3047: {
3048: DMLocalToGlobalHookLink link, *p;
3050: PetscFunctionBegin;
3052: for (p = &dm->ltoghook; *p; p = &(*p)->next) { } /* Scan to the end of the current list of hooks */
3053: PetscCall(PetscNew(&link));
3054: link->beginhook = beginhook;
3055: link->endhook = endhook;
3056: link->ctx = ctx;
3057: link->next = NULL;
3058: *p = link;
3059: PetscFunctionReturn(PETSC_SUCCESS);
3060: }
3062: static PetscErrorCode DMLocalToGlobalHook_Constraints(DM dm, Vec l, InsertMode mode, Vec g, PetscCtx ctx)
3063: {
3064: PetscFunctionBegin;
3065: (void)g;
3066: (void)ctx;
3068: if (mode == ADD_VALUES || mode == ADD_ALL_VALUES || mode == ADD_BC_VALUES) {
3069: Mat cMat;
3070: Vec cVec;
3071: PetscInt nRows;
3072: PetscSection section, cSec;
3073: PetscInt pStart, pEnd, p, dof;
3075: PetscCall(DMGetDefaultConstraints(dm, &cSec, &cMat, NULL));
3076: if (!cMat) PetscFunctionReturn(PETSC_SUCCESS);
3078: PetscCall(MatGetSize(cMat, &nRows, NULL));
3079: if (nRows <= 0) PetscFunctionReturn(PETSC_SUCCESS);
3080: PetscCall(DMGetLocalSection(dm, §ion));
3081: PetscCall(MatCreateVecs(cMat, NULL, &cVec));
3082: PetscCall(PetscSectionGetChart(cSec, &pStart, &pEnd));
3083: for (p = pStart; p < pEnd; p++) {
3084: PetscCall(PetscSectionGetDof(cSec, p, &dof));
3085: if (dof) {
3086: PetscInt d;
3087: PetscScalar *vals;
3088: PetscCall(VecGetValuesSection(l, section, p, &vals));
3089: PetscCall(VecSetValuesSection(cVec, cSec, p, vals, mode));
3090: /* for this to be the true transpose, we have to zero the values that
3091: * we just extracted */
3092: for (d = 0; d < dof; d++) vals[d] = 0.;
3093: }
3094: }
3095: PetscCall(MatMultTransposeAdd(cMat, cVec, l, l));
3096: PetscCall(VecDestroy(&cVec));
3097: }
3098: PetscFunctionReturn(PETSC_SUCCESS);
3099: }
3100: /*@
3101: DMLocalToGlobal - updates global vectors from local vectors
3103: Neighbor-wise Collective
3105: Input Parameters:
3106: + dm - the `DM` object
3107: . l - the local vector
3108: . mode - if `INSERT_VALUES` then no parallel communication is used, if `ADD_VALUES` then all ghost points from the same base point accumulate into that base point.
3109: - g - the global vector
3111: Level: beginner
3113: Notes:
3114: The communication involved in this update can be overlapped with computation by using
3115: `DMLocalToGlobalBegin()` and `DMLocalToGlobalEnd()`.
3117: In the `ADD_VALUES` case you normally would zero the receiving vector before beginning this operation.
3119: `INSERT_VALUES` is not supported for `DMDA`; in that case simply compute the values directly into a global vector instead of a local one.
3121: Use `DMLocalToGlobalHookAdd()` to add additional operations that are performed on the data during the update process
3123: .seealso: [](ch_dmbase), `DM`, `DMLocalToGlobalBegin()`, `DMLocalToGlobalEnd()`, `DMCoarsen()`, `DMDestroy()`, `DMView()`, `DMCreateGlobalVector()`, `DMCreateInterpolation()`, `DMGlobalToLocal()`, `DMGlobalToLocalEnd()`, `DMGlobalToLocalBegin()`, `DMLocalToGlobalHookAdd()`, `DMGlobaToLocallHookAdd()`
3124: @*/
3125: PetscErrorCode DMLocalToGlobal(DM dm, Vec l, InsertMode mode, Vec g)
3126: {
3127: PetscFunctionBegin;
3128: PetscCall(DMLocalToGlobalBegin(dm, l, mode, g));
3129: PetscCall(DMLocalToGlobalEnd(dm, l, mode, g));
3130: PetscFunctionReturn(PETSC_SUCCESS);
3131: }
3133: /*@
3134: DMLocalToGlobalBegin - begins updating global vectors from local vectors
3136: Neighbor-wise Collective
3138: Input Parameters:
3139: + dm - the `DM` object
3140: . l - the local vector
3141: . mode - if `INSERT_VALUES` then no parallel communication is used, if `ADD_VALUES` then all ghost points from the same base point accumulate into that base point.
3142: - g - the global vector
3144: Level: intermediate
3146: Notes:
3147: In the `ADD_VALUES` case you normally would zero the receiving vector before beginning this operation.
3149: `INSERT_VALUES is` not supported for `DMDA`, in that case simply compute the values directly into a global vector instead of a local one.
3151: Use `DMLocalToGlobalEnd()` to complete the communication process.
3153: `DMLocalToGlobal()` is a short form of `DMLocalToGlobalBegin()` and `DMLocalToGlobalEnd()`
3155: `DMLocalToGlobalHookAdd()` may be used to provide additional operations that are performed during the update process.
3157: .seealso: [](ch_dmbase), `DM`, `DMLocalToGlobal()`, `DMLocalToGlobalEnd()`, `DMCoarsen()`, `DMDestroy()`, `DMView()`, `DMCreateGlobalVector()`, `DMCreateInterpolation()`, `DMGlobalToLocal()`, `DMGlobalToLocalEnd()`, `DMGlobalToLocalBegin()`
3158: @*/
3159: PetscErrorCode DMLocalToGlobalBegin(DM dm, Vec l, InsertMode mode, Vec g)
3160: {
3161: PetscSF sf;
3162: PetscSection s, gs;
3163: DMLocalToGlobalHookLink link;
3164: Vec tmpl;
3165: const PetscScalar *lArray;
3166: PetscScalar *gArray;
3167: PetscBool isInsert, transform, l_inplace = PETSC_FALSE, g_inplace = PETSC_FALSE;
3168: PetscMemType lmtype = PETSC_MEMTYPE_HOST, gmtype = PETSC_MEMTYPE_HOST;
3170: PetscFunctionBegin;
3172: for (link = dm->ltoghook; link; link = link->next) {
3173: if (link->beginhook) PetscCall((*link->beginhook)(dm, l, mode, g, link->ctx));
3174: }
3175: PetscCall(DMLocalToGlobalHook_Constraints(dm, l, mode, g, NULL));
3176: PetscCall(DMGetSectionSF(dm, &sf));
3177: PetscCall(DMGetLocalSection(dm, &s));
3178: switch (mode) {
3179: case INSERT_VALUES:
3180: case INSERT_ALL_VALUES:
3181: case INSERT_BC_VALUES:
3182: isInsert = PETSC_TRUE;
3183: break;
3184: case ADD_VALUES:
3185: case ADD_ALL_VALUES:
3186: case ADD_BC_VALUES:
3187: isInsert = PETSC_FALSE;
3188: break;
3189: default:
3190: SETERRQ(PetscObjectComm((PetscObject)dm), PETSC_ERR_ARG_OUTOFRANGE, "Invalid insertion mode %d", mode);
3191: }
3192: if ((sf && !isInsert) || (s && isInsert)) {
3193: PetscCall(DMHasBasisTransform(dm, &transform));
3194: if (transform) {
3195: PetscCall(DMGetNamedLocalVector(dm, "__petsc_dm_transform_local_copy", &tmpl));
3196: PetscCall(VecCopy(l, tmpl));
3197: PetscCall(DMPlexLocalToGlobalBasis(dm, tmpl));
3198: PetscCall(VecGetArrayRead(tmpl, &lArray));
3199: } else if (isInsert) {
3200: PetscCall(VecGetArrayRead(l, &lArray));
3201: } else {
3202: PetscCall(VecGetArrayReadAndMemType(l, &lArray, &lmtype));
3203: l_inplace = PETSC_TRUE;
3204: }
3205: if (s && isInsert) {
3206: PetscCall(VecGetArray(g, &gArray));
3207: } else {
3208: PetscCall(VecGetArrayAndMemType(g, &gArray, &gmtype));
3209: g_inplace = PETSC_TRUE;
3210: }
3211: if (sf && !isInsert) {
3212: PetscCall(PetscSFReduceWithMemTypeBegin(sf, MPIU_SCALAR, lmtype, lArray, gmtype, gArray, MPIU_SUM));
3213: } else if (s && isInsert) {
3214: PetscInt gStart, pStart, pEnd, p;
3216: PetscCall(DMGetGlobalSection(dm, &gs));
3217: PetscCall(PetscSectionGetChart(s, &pStart, &pEnd));
3218: PetscCall(VecGetOwnershipRange(g, &gStart, NULL));
3219: for (p = pStart; p < pEnd; ++p) {
3220: PetscInt dof, gdof, cdof, gcdof, off, goff, d, e;
3222: PetscCall(PetscSectionGetDof(s, p, &dof));
3223: PetscCall(PetscSectionGetDof(gs, p, &gdof));
3224: PetscCall(PetscSectionGetConstraintDof(s, p, &cdof));
3225: PetscCall(PetscSectionGetConstraintDof(gs, p, &gcdof));
3226: PetscCall(PetscSectionGetOffset(s, p, &off));
3227: PetscCall(PetscSectionGetOffset(gs, p, &goff));
3228: /* Ignore off-process data and points with no global data */
3229: if (!gdof || goff < 0) continue;
3230: PetscCheck(dof == gdof, PETSC_COMM_SELF, PETSC_ERR_ARG_SIZ, "Inconsistent sizes, p: %" PetscInt_FMT " dof: %" PetscInt_FMT " gdof: %" PetscInt_FMT " cdof: %" PetscInt_FMT " gcdof: %" PetscInt_FMT, p, dof, gdof, cdof, gcdof);
3231: /* If no constraints are enforced in the global vector */
3232: if (!gcdof) {
3233: for (d = 0; d < dof; ++d) gArray[goff - gStart + d] = lArray[off + d];
3234: /* If constraints are enforced in the global vector */
3235: } else if (cdof == gcdof) {
3236: const PetscInt *cdofs;
3237: PetscInt cind = 0;
3239: PetscCall(PetscSectionGetConstraintIndices(s, p, &cdofs));
3240: for (d = 0, e = 0; d < dof; ++d) {
3241: if ((cind < cdof) && (d == cdofs[cind])) {
3242: ++cind;
3243: continue;
3244: }
3245: gArray[goff - gStart + e++] = lArray[off + d];
3246: }
3247: } else SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_SIZ, "Inconsistent sizes, p: %" PetscInt_FMT " dof: %" PetscInt_FMT " gdof: %" PetscInt_FMT " cdof: %" PetscInt_FMT " gcdof: %" PetscInt_FMT, p, dof, gdof, cdof, gcdof);
3248: }
3249: }
3250: if (g_inplace) {
3251: PetscCall(VecRestoreArrayAndMemType(g, &gArray));
3252: } else {
3253: PetscCall(VecRestoreArray(g, &gArray));
3254: }
3255: if (transform) {
3256: PetscCall(VecRestoreArrayRead(tmpl, &lArray));
3257: PetscCall(DMRestoreNamedLocalVector(dm, "__petsc_dm_transform_local_copy", &tmpl));
3258: } else if (l_inplace) {
3259: PetscCall(VecRestoreArrayReadAndMemType(l, &lArray));
3260: } else {
3261: PetscCall(VecRestoreArrayRead(l, &lArray));
3262: }
3263: } else {
3264: PetscUseTypeMethod(dm, localtoglobalbegin, l, mode == INSERT_ALL_VALUES ? INSERT_VALUES : (mode == ADD_ALL_VALUES ? ADD_VALUES : mode), g);
3265: }
3266: PetscFunctionReturn(PETSC_SUCCESS);
3267: }
3269: /*@
3270: DMLocalToGlobalEnd - updates global vectors from local vectors
3272: Neighbor-wise Collective
3274: Input Parameters:
3275: + dm - the `DM` object
3276: . l - the local vector
3277: . mode - `INSERT_VALUES` or `ADD_VALUES`
3278: - g - the global vector
3280: Level: intermediate
3282: Note:
3283: See `DMLocalToGlobalBegin()` for full details
3285: .seealso: [](ch_dmbase), `DM`, `DMLocalToGlobalBegin()`, `DMCoarsen()`, `DMDestroy()`, `DMView()`, `DMCreateGlobalVector()`, `DMCreateInterpolation()`, `DMGlobalToLocalEnd()`
3286: @*/
3287: PetscErrorCode DMLocalToGlobalEnd(DM dm, Vec l, InsertMode mode, Vec g)
3288: {
3289: PetscSF sf;
3290: PetscSection s;
3291: DMLocalToGlobalHookLink link;
3292: PetscBool isInsert, transform;
3294: PetscFunctionBegin;
3296: PetscCall(DMGetSectionSF(dm, &sf));
3297: PetscCall(DMGetLocalSection(dm, &s));
3298: switch (mode) {
3299: case INSERT_VALUES:
3300: case INSERT_ALL_VALUES:
3301: isInsert = PETSC_TRUE;
3302: break;
3303: case ADD_VALUES:
3304: case ADD_ALL_VALUES:
3305: isInsert = PETSC_FALSE;
3306: break;
3307: default:
3308: SETERRQ(PetscObjectComm((PetscObject)dm), PETSC_ERR_ARG_OUTOFRANGE, "Invalid insertion mode %d", mode);
3309: }
3310: if (sf && !isInsert) {
3311: const PetscScalar *lArray;
3312: PetscScalar *gArray;
3313: Vec tmpl;
3315: PetscCall(DMHasBasisTransform(dm, &transform));
3316: if (transform) {
3317: PetscCall(DMGetNamedLocalVector(dm, "__petsc_dm_transform_local_copy", &tmpl));
3318: PetscCall(VecGetArrayRead(tmpl, &lArray));
3319: } else {
3320: PetscCall(VecGetArrayReadAndMemType(l, &lArray, NULL));
3321: }
3322: PetscCall(VecGetArrayAndMemType(g, &gArray, NULL));
3323: PetscCall(PetscSFReduceEnd(sf, MPIU_SCALAR, lArray, gArray, MPIU_SUM));
3324: if (transform) {
3325: PetscCall(VecRestoreArrayRead(tmpl, &lArray));
3326: PetscCall(DMRestoreNamedLocalVector(dm, "__petsc_dm_transform_local_copy", &tmpl));
3327: } else {
3328: PetscCall(VecRestoreArrayReadAndMemType(l, &lArray));
3329: }
3330: PetscCall(VecRestoreArrayAndMemType(g, &gArray));
3331: } else if (s && isInsert) {
3332: } else {
3333: PetscUseTypeMethod(dm, localtoglobalend, l, mode == INSERT_ALL_VALUES ? INSERT_VALUES : (mode == ADD_ALL_VALUES ? ADD_VALUES : mode), g);
3334: }
3335: for (link = dm->ltoghook; link; link = link->next) {
3336: if (link->endhook) PetscCall((*link->endhook)(dm, g, mode, l, link->ctx));
3337: }
3338: PetscFunctionReturn(PETSC_SUCCESS);
3339: }
3341: /*@
3342: DMLocalToLocalBegin - Begins the process of mapping values from a local vector (that include
3343: ghost points that contain irrelevant values) to another local vector where the ghost points
3344: in the second are set correctly from values on other MPI ranks.
3346: Neighbor-wise Collective
3348: Input Parameters:
3349: + dm - the `DM` object
3350: . g - the original local vector
3351: - mode - one of `INSERT_VALUES` or `ADD_VALUES`
3353: Output Parameter:
3354: . l - the local vector with correct ghost values
3356: Level: intermediate
3358: Note:
3359: Must be followed by `DMLocalToLocalEnd()`.
3361: .seealso: [](ch_dmbase), `DM`, `DMLocalToLocalEnd()`, `DMCoarsen()`, `DMDestroy()`, `DMView()`, `DMCreateLocalVector()`, `DMCreateGlobalVector()`, `DMCreateInterpolation()`, `DMGlobalToLocalEnd()`, `DMLocalToGlobalBegin()`
3362: @*/
3363: PetscErrorCode DMLocalToLocalBegin(DM dm, Vec g, InsertMode mode, Vec l)
3364: {
3365: PetscFunctionBegin;
3369: PetscUseTypeMethod(dm, localtolocalbegin, g, mode == INSERT_ALL_VALUES ? INSERT_VALUES : (mode == ADD_ALL_VALUES ? ADD_VALUES : mode), l);
3370: PetscFunctionReturn(PETSC_SUCCESS);
3371: }
3373: /*@
3374: DMLocalToLocalEnd - Maps from a local vector to another local vector where the ghost
3375: points in the second are set correctly. Must be preceded by `DMLocalToLocalBegin()`.
3377: Neighbor-wise Collective
3379: Input Parameters:
3380: + dm - the `DM` object
3381: . g - the original local vector
3382: - mode - one of `INSERT_VALUES` or `ADD_VALUES`
3384: Output Parameter:
3385: . l - the local vector with correct ghost values
3387: Level: intermediate
3389: .seealso: [](ch_dmbase), `DM`, `DMLocalToLocalBegin()`, `DMCoarsen()`, `DMDestroy()`, `DMView()`, `DMCreateLocalVector()`, `DMCreateGlobalVector()`, `DMCreateInterpolation()`, `DMGlobalToLocalEnd()`, `DMLocalToGlobalBegin()`
3390: @*/
3391: PetscErrorCode DMLocalToLocalEnd(DM dm, Vec g, InsertMode mode, Vec l)
3392: {
3393: PetscFunctionBegin;
3397: PetscUseTypeMethod(dm, localtolocalend, g, mode == INSERT_ALL_VALUES ? INSERT_VALUES : (mode == ADD_ALL_VALUES ? ADD_VALUES : mode), l);
3398: PetscFunctionReturn(PETSC_SUCCESS);
3399: }
3401: /*@
3402: DMCoarsen - Coarsens a `DM` object using a standard, non-adaptive coarsening of the underlying mesh
3404: Collective
3406: Input Parameters:
3407: + dm - the `DM` object
3408: - comm - the communicator to contain the new `DM` object (or `MPI_COMM_NULL`)
3410: Output Parameter:
3411: . dmc - the coarsened `DM`
3413: Level: developer
3415: .seealso: [](ch_dmbase), `DM`, `DMRefine()`, `DMDestroy()`, `DMView()`, `DMCreateGlobalVector()`, `DMCreateInterpolation()`, `DMCreateDomainDecomposition()`,
3416: `DMCoarsenHookAdd()`, `DMCoarsenHookRemove()`
3417: @*/
3418: PetscErrorCode DMCoarsen(DM dm, MPI_Comm comm, DM *dmc)
3419: {
3420: DMCoarsenHookLink link;
3422: PetscFunctionBegin;
3424: PetscCall(PetscLogEventBegin(DM_Coarsen, dm, 0, 0, 0));
3425: PetscUseTypeMethod(dm, coarsen, comm, dmc);
3426: if (*dmc) {
3427: (*dmc)->bind_below = dm->bind_below; /* Propagate this from parent DM; otherwise -dm_bind_below will be useless for multigrid cases. */
3428: PetscCall(DMSetCoarseDM(dm, *dmc));
3429: (*dmc)->ops->creatematrix = dm->ops->creatematrix;
3430: PetscCall(PetscObjectCopyFortranFunctionPointers((PetscObject)dm, (PetscObject)*dmc));
3431: (*dmc)->ctx = dm->ctx;
3432: (*dmc)->levelup = dm->levelup;
3433: (*dmc)->leveldown = dm->leveldown + 1;
3434: PetscCall(DMSetMatType(*dmc, dm->mattype));
3435: for (link = dm->coarsenhook; link; link = link->next) {
3436: if (link->coarsenhook) PetscCall((*link->coarsenhook)(dm, *dmc, link->ctx));
3437: }
3438: }
3439: PetscCall(PetscLogEventEnd(DM_Coarsen, dm, 0, 0, 0));
3440: PetscCheck(*dmc, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "NULL coarse mesh produced");
3441: PetscFunctionReturn(PETSC_SUCCESS);
3442: }
3444: /*@
3445: DMCoarsenHookAdd - adds a callback to be run when restricting a nonlinear problem to the coarse grid
3447: Logically Collective; No Fortran Support
3449: Input Parameters:
3450: + fine - `DM` on which to run a hook when restricting to a coarser level
3451: . coarsenhook - function to run when setting up a coarser level
3452: . restricthook - function to run to update data on coarser levels (called once per `SNESSolve()`)
3453: - ctx - [optional] application context for provide data for the hooks (may be `NULL`)
3455: Calling sequence of `coarsenhook`:
3456: + fine - fine level `DM`
3457: . coarse - coarse level `DM` to restrict problem to
3458: - ctx - optional application function context
3460: Calling sequence of `restricthook`:
3461: + fine - fine level `DM`
3462: . mrestrict - matrix restricting a fine-level solution to the coarse grid, usually the transpose of the interpolation
3463: . rscale - scaling vector for restriction
3464: . inject - matrix restricting by injection
3465: . coarse - coarse level DM to update
3466: - ctx - optional application function context
3468: Level: advanced
3470: Notes:
3471: This function is only needed if auxiliary data, attached to the `DM` with `PetscObjectCompose()`, needs to be set up or passed from the fine `DM` to the coarse `DM`.
3473: If this function is called multiple times, the hooks will be run in the order they are added.
3475: In order to compose with nonlinear preconditioning without duplicating storage, the hook should be implemented to
3476: extract the finest level information from its context (instead of from the `SNES`).
3478: The hooks are automatically called by `DMRestrict()`
3480: .seealso: [](ch_dmbase), `DM`, `DMCoarsenHookRemove()`, `DMRefineHookAdd()`, `SNESFASGetInterpolation()`, `SNESFASGetInjection()`, `PetscObjectCompose()`, `PetscContainerCreate()`
3481: @*/
3482: PetscErrorCode DMCoarsenHookAdd(DM fine, PetscErrorCode (*coarsenhook)(DM fine, DM coarse, PetscCtx ctx), PetscErrorCode (*restricthook)(DM fine, Mat mrestrict, Vec rscale, Mat inject, DM coarse, PetscCtx ctx), PetscCtx ctx)
3483: {
3484: DMCoarsenHookLink link, *p;
3486: PetscFunctionBegin;
3488: for (p = &fine->coarsenhook; *p; p = &(*p)->next) { /* Scan to the end of the current list of hooks */
3489: if ((*p)->coarsenhook == coarsenhook && (*p)->restricthook == restricthook && (*p)->ctx == ctx) PetscFunctionReturn(PETSC_SUCCESS);
3490: }
3491: PetscCall(PetscNew(&link));
3492: link->coarsenhook = coarsenhook;
3493: link->restricthook = restricthook;
3494: link->ctx = ctx;
3495: link->next = NULL;
3496: *p = link;
3497: PetscFunctionReturn(PETSC_SUCCESS);
3498: }
3500: /*@
3501: DMCoarsenHookRemove - remove a callback set with `DMCoarsenHookAdd()`
3503: Logically Collective; No Fortran Support
3505: Input Parameters:
3506: + fine - `DM` on which to run a hook when restricting to a coarser level
3507: . coarsenhook - function to run when setting up a coarser level
3508: . restricthook - function to run to update data on coarser levels
3509: - ctx - [optional] application context for provide data for the hooks (may be `NULL`)
3511: Calling sequence of `coarsenhook`:
3512: + fine - fine level `DM`
3513: . coarse - coarse level `DM` to restrict problem to
3514: - ctx - optional application function context
3516: Calling sequence of `restricthook`:
3517: + fine - fine level `DM`
3518: . rstrict - matrix restricting a fine-level solution to the coarse grid, usually the transpose of the interpolation
3519: . rscale - scaling vector for restriction
3520: . inject - matrix restricting by injection
3521: . coarse - coarse level DM to update
3522: - ctx - optional application function context
3524: Level: advanced
3526: Notes:
3527: This function does nothing if the `coarsenhook` is not in the list.
3529: See `DMCoarsenHookAdd()` for the calling sequence of `coarsenhook` and `restricthook`
3531: .seealso: [](ch_dmbase), `DM`, `DMCoarsenHookAdd()`, `DMRefineHookAdd()`, `SNESFASGetInterpolation()`, `SNESFASGetInjection()`, `PetscObjectCompose()`, `PetscContainerCreate()`
3532: @*/
3533: PetscErrorCode DMCoarsenHookRemove(DM fine, PetscErrorCode (*coarsenhook)(DM fine, DM coarse, PetscCtx ctx), PetscErrorCode (*restricthook)(DM fine, Mat rstrict, Vec rscale, Mat inject, DM coarse, PetscCtx ctx), PetscCtx ctx)
3534: {
3535: DMCoarsenHookLink link, *p;
3537: PetscFunctionBegin;
3539: for (p = &fine->coarsenhook; *p; p = &(*p)->next) { /* Search the list of current hooks */
3540: if ((*p)->coarsenhook == coarsenhook && (*p)->restricthook == restricthook && (*p)->ctx == ctx) {
3541: link = *p;
3542: *p = link->next;
3543: PetscCall(PetscFree(link));
3544: break;
3545: }
3546: }
3547: PetscFunctionReturn(PETSC_SUCCESS);
3548: }
3550: /*@
3551: DMRestrict - restricts user-defined problem data to a coarser `DM` by running hooks registered by `DMCoarsenHookAdd()`
3553: Collective if any hooks are
3555: Input Parameters:
3556: + fine - finer `DM` from which the data is obtained
3557: . restrct - restriction matrix, apply using `MatRestrict()`, usually the transpose of the interpolation
3558: . rscale - scaling vector for restriction
3559: . inject - injection matrix, also use `MatRestrict()`
3560: - coarse - coarser `DM` to update
3562: Level: developer
3564: Developer Note:
3565: Though this routine is called `DMRestrict()` the hooks are added with `DMCoarsenHookAdd()`, a consistent terminology would be better
3567: .seealso: [](ch_dmbase), `DM`, `DMCoarsenHookAdd()`, `MatRestrict()`, `DMInterpolate()`, `DMRefineHookAdd()`
3568: @*/
3569: PetscErrorCode DMRestrict(DM fine, Mat restrct, Vec rscale, Mat inject, DM coarse)
3570: {
3571: DMCoarsenHookLink link;
3573: PetscFunctionBegin;
3574: for (link = fine->coarsenhook; link; link = link->next) {
3575: if (link->restricthook) PetscCall((*link->restricthook)(fine, restrct, rscale, inject, coarse, link->ctx));
3576: }
3577: PetscFunctionReturn(PETSC_SUCCESS);
3578: }
3580: /*@
3581: DMSubDomainHookAdd - adds a callback to be run when restricting a problem to subdomain `DM`s with `DMCreateDomainDecomposition()`
3583: Logically Collective; No Fortran Support
3585: Input Parameters:
3586: + global - global `DM`
3587: . ddhook - function to run to pass data to the decomposition `DM` upon its creation
3588: . restricthook - function to run to update data on block solve (at the beginning of the block solve)
3589: - ctx - [optional] application context for provide data for the hooks (may be `NULL`)
3591: Calling sequence of `ddhook`:
3592: + global - global `DM`
3593: . block - subdomain `DM`
3594: - ctx - optional application function context
3596: Calling sequence of `restricthook`:
3597: + global - global `DM`
3598: . out - scatter to the outer (with ghost and overlap points) sub vector
3599: . in - scatter to sub vector values only owned locally
3600: . block - subdomain `DM`
3601: - ctx - optional application function context
3603: Level: advanced
3605: Notes:
3606: This function can be used if auxiliary data needs to be set up on subdomain `DM`s.
3608: If this function is called multiple times, the hooks will be run in the order they are added.
3610: In order to compose with nonlinear preconditioning without duplicating storage, the hook should be implemented to
3611: extract the global information from its context (instead of from the `SNES`).
3613: Developer Note:
3614: It is unclear what "block solve" means within the definition of `restricthook`
3616: .seealso: [](ch_dmbase), `DM`, `DMSubDomainHookRemove()`, `DMRefineHookAdd()`, `SNESFASGetInterpolation()`, `SNESFASGetInjection()`, `PetscObjectCompose()`, `PetscContainerCreate()`, `DMCreateDomainDecomposition()`
3617: @*/
3618: PetscErrorCode DMSubDomainHookAdd(DM global, PetscErrorCode (*ddhook)(DM global, DM block, PetscCtx ctx), PetscErrorCode (*restricthook)(DM global, VecScatter out, VecScatter in, DM block, PetscCtx ctx), PetscCtx ctx)
3619: {
3620: DMSubDomainHookLink link, *p;
3622: PetscFunctionBegin;
3624: for (p = &global->subdomainhook; *p; p = &(*p)->next) { /* Scan to the end of the current list of hooks */
3625: if ((*p)->ddhook == ddhook && (*p)->restricthook == restricthook && (*p)->ctx == ctx) PetscFunctionReturn(PETSC_SUCCESS);
3626: }
3627: PetscCall(PetscNew(&link));
3628: link->restricthook = restricthook;
3629: link->ddhook = ddhook;
3630: link->ctx = ctx;
3631: link->next = NULL;
3632: *p = link;
3633: PetscFunctionReturn(PETSC_SUCCESS);
3634: }
3636: /*@
3637: DMSubDomainHookRemove - remove a callback from the list to be run when restricting a problem to subdomain `DM`s with `DMCreateDomainDecomposition()`
3639: Logically Collective; No Fortran Support
3641: Input Parameters:
3642: + global - global `DM`
3643: . ddhook - function to run to pass data to the decomposition `DM` upon its creation
3644: . restricthook - function to run to update data on block solve (at the beginning of the block solve)
3645: - ctx - [optional] application context for provide data for the hooks (may be `NULL`)
3647: Calling sequence of `ddhook`:
3648: + dm - global `DM`
3649: . block - subdomain `DM`
3650: - ctx - optional application function context
3652: Calling sequence of `restricthook`:
3653: + dm - global `DM`
3654: . oscatter - scatter to the outer (with ghost and overlap points) sub vector
3655: . gscatter - scatter to sub vector values only owned locally
3656: . block - subdomain `DM`
3657: - ctx - optional application function context
3659: Level: advanced
3661: .seealso: [](ch_dmbase), `DM`, `DMSubDomainHookAdd()`, `SNESFASGetInterpolation()`, `SNESFASGetInjection()`, `PetscObjectCompose()`, `PetscContainerCreate()`,
3662: `DMCreateDomainDecomposition()`
3663: @*/
3664: PetscErrorCode DMSubDomainHookRemove(DM global, PetscErrorCode (*ddhook)(DM dm, DM block, PetscCtx ctx), PetscErrorCode (*restricthook)(DM dm, VecScatter oscatter, VecScatter gscatter, DM block, PetscCtx ctx), PetscCtx ctx)
3665: {
3666: DMSubDomainHookLink link, *p;
3668: PetscFunctionBegin;
3670: for (p = &global->subdomainhook; *p; p = &(*p)->next) { /* Search the list of current hooks */
3671: if ((*p)->ddhook == ddhook && (*p)->restricthook == restricthook && (*p)->ctx == ctx) {
3672: link = *p;
3673: *p = link->next;
3674: PetscCall(PetscFree(link));
3675: break;
3676: }
3677: }
3678: PetscFunctionReturn(PETSC_SUCCESS);
3679: }
3681: /*@
3682: DMSubDomainRestrict - restricts user-defined problem data to a subdomain `DM` by running hooks registered by `DMSubDomainHookAdd()`
3684: Collective if any hooks are
3686: Input Parameters:
3687: + global - The global `DM` to use as a base
3688: . oscatter - The scatter from domain global vector filling subdomain global vector with overlap
3689: . gscatter - The scatter from domain global vector filling subdomain local vector with ghosts
3690: - subdm - The subdomain `DM` to update
3692: Level: developer
3694: .seealso: [](ch_dmbase), `DM`, `DMCoarsenHookAdd()`, `MatRestrict()`, `DMCreateDomainDecomposition()`
3695: @*/
3696: PetscErrorCode DMSubDomainRestrict(DM global, VecScatter oscatter, VecScatter gscatter, DM subdm)
3697: {
3698: DMSubDomainHookLink link;
3700: PetscFunctionBegin;
3701: for (link = global->subdomainhook; link; link = link->next) {
3702: if (link->restricthook) PetscCall((*link->restricthook)(global, oscatter, gscatter, subdm, link->ctx));
3703: }
3704: PetscFunctionReturn(PETSC_SUCCESS);
3705: }
3707: /*@
3708: DMGetCoarsenLevel - Gets the number of coarsenings that have generated this `DM`.
3710: Not Collective
3712: Input Parameter:
3713: . dm - the `DM` object
3715: Output Parameter:
3716: . level - number of coarsenings
3718: Level: developer
3720: .seealso: [](ch_dmbase), `DM`, `DMCoarsen()`, `DMSetCoarsenLevel()`, `DMGetRefineLevel()`, `DMDestroy()`, `DMView()`, `DMCreateGlobalVector()`, `DMCreateInterpolation()`
3721: @*/
3722: PetscErrorCode DMGetCoarsenLevel(DM dm, PetscInt *level)
3723: {
3724: PetscFunctionBegin;
3726: PetscAssertPointer(level, 2);
3727: *level = dm->leveldown;
3728: PetscFunctionReturn(PETSC_SUCCESS);
3729: }
3731: /*@
3732: DMSetCoarsenLevel - Sets the number of coarsenings that have generated this `DM`.
3734: Collective
3736: Input Parameters:
3737: + dm - the `DM` object
3738: - level - number of coarsenings
3740: Level: developer
3742: Note:
3743: This is rarely used directly, the information is automatically set when a `DM` is created with `DMCoarsen()`
3745: .seealso: [](ch_dmbase), `DM`, `DMCoarsen()`, `DMGetCoarsenLevel()`, `DMGetRefineLevel()`, `DMDestroy()`, `DMView()`, `DMCreateGlobalVector()`, `DMCreateInterpolation()`
3746: @*/
3747: PetscErrorCode DMSetCoarsenLevel(DM dm, PetscInt level)
3748: {
3749: PetscFunctionBegin;
3751: dm->leveldown = level;
3752: PetscFunctionReturn(PETSC_SUCCESS);
3753: }
3755: /*@
3756: DMRefineHierarchy - Refines a `DM` object, all levels at once
3758: Collective
3760: Input Parameters:
3761: + dm - the `DM` object
3762: - nlevels - the number of levels of refinement
3764: Output Parameter:
3765: . dmf - the refined `DM` hierarchy
3767: Level: developer
3769: .seealso: [](ch_dmbase), `DM`, `DMCoarsen()`, `DMCoarsenHierarchy()`, `DMDestroy()`, `DMView()`, `DMCreateGlobalVector()`, `DMCreateInterpolation()`
3770: @*/
3771: PetscErrorCode DMRefineHierarchy(DM dm, PetscInt nlevels, DM dmf[])
3772: {
3773: PetscFunctionBegin;
3775: PetscCheck(nlevels >= 0, PetscObjectComm((PetscObject)dm), PETSC_ERR_ARG_OUTOFRANGE, "nlevels cannot be negative");
3776: if (nlevels == 0) PetscFunctionReturn(PETSC_SUCCESS);
3777: PetscAssertPointer(dmf, 3);
3778: if (dm->ops->refine && !dm->ops->refinehierarchy) {
3779: PetscCall(DMRefine(dm, PetscObjectComm((PetscObject)dm), &dmf[0]));
3780: for (PetscInt i = 1; i < nlevels; i++) PetscCall(DMRefine(dmf[i - 1], PetscObjectComm((PetscObject)dm), &dmf[i]));
3781: } else PetscUseTypeMethod(dm, refinehierarchy, nlevels, dmf);
3782: PetscFunctionReturn(PETSC_SUCCESS);
3783: }
3785: /*@
3786: DMCoarsenHierarchy - Coarsens a `DM` object, all levels at once
3788: Collective
3790: Input Parameters:
3791: + dm - the `DM` object
3792: - nlevels - the number of levels of coarsening
3794: Output Parameter:
3795: . dmc - the coarsened `DM` hierarchy
3797: Level: developer
3799: .seealso: [](ch_dmbase), `DM`, `DMCoarsen()`, `DMRefineHierarchy()`, `DMDestroy()`, `DMView()`, `DMCreateGlobalVector()`, `DMCreateInterpolation()`
3800: @*/
3801: PetscErrorCode DMCoarsenHierarchy(DM dm, PetscInt nlevels, DM dmc[])
3802: {
3803: PetscFunctionBegin;
3805: PetscCheck(nlevels >= 0, PetscObjectComm((PetscObject)dm), PETSC_ERR_ARG_OUTOFRANGE, "nlevels cannot be negative");
3806: if (nlevels == 0) PetscFunctionReturn(PETSC_SUCCESS);
3807: PetscAssertPointer(dmc, 3);
3808: if (dm->ops->coarsen && !dm->ops->coarsenhierarchy) {
3809: PetscCall(DMCoarsen(dm, PetscObjectComm((PetscObject)dm), &dmc[0]));
3810: for (PetscInt i = 1; i < nlevels; i++) PetscCall(DMCoarsen(dmc[i - 1], PetscObjectComm((PetscObject)dm), &dmc[i]));
3811: } else PetscUseTypeMethod(dm, coarsenhierarchy, nlevels, dmc);
3812: PetscFunctionReturn(PETSC_SUCCESS);
3813: }
3815: /*@
3816: DMSetApplicationContextDestroy - Sets a user function that will be called to destroy the application context when the `DM` is destroyed
3818: Logically Collective if the function is collective
3820: Input Parameters:
3821: + dm - the `DM` object
3822: - destroy - the destroy function, see `PetscCtxDestroyFn` for the calling sequence
3824: Level: intermediate
3826: .seealso: [](ch_dmbase), `DM`, `DMSetApplicationContext()`, `DMView()`, `DMCreateGlobalVector()`, `DMCreateInterpolation()`, `DMCreateColoring()`, `DMCreateMatrix()`, `DMCreateMassMatrix()`,
3827: `DMGetApplicationContext()`, `PetscCtxDestroyFn`
3828: @*/
3829: PetscErrorCode DMSetApplicationContextDestroy(DM dm, PetscCtxDestroyFn *destroy)
3830: {
3831: PetscFunctionBegin;
3833: dm->ctxdestroy = destroy;
3834: PetscFunctionReturn(PETSC_SUCCESS);
3835: }
3837: /*@
3838: DMSetApplicationContext - Set an application context into a `DM` object
3840: Not Collective
3842: Input Parameters:
3843: + dm - the `DM` object
3844: - ctx - the application context
3846: Level: intermediate
3848: Note:
3849: An application context is a way to pass problem specific information that is accessible whenever the `DM` is available
3850: In a multilevel solver, the application context is shared by all the `DM` in the hierarchy; it is thus not advisable
3851: to store objects that represent discretized quantities inside the context.
3853: Fortran Notes:
3854: This only works when the context is a Fortran derived type or a `PetscObject`. Declare `ctx` with
3855: .vb
3856: type(tUsertype), pointer :: ctx
3857: .ve
3859: .seealso: [](ch_dmbase), `DM`, `DMGetApplicationContext()`, `DMView()`, `DMCreateGlobalVector()`, `DMCreateInterpolation()`, `DMCreateColoring()`, `DMCreateMatrix()`, `DMCreateMassMatrix()`
3860: @*/
3861: PetscErrorCode DMSetApplicationContext(DM dm, PetscCtx ctx)
3862: {
3863: PetscFunctionBegin;
3865: dm->ctx = ctx;
3866: PetscFunctionReturn(PETSC_SUCCESS);
3867: }
3869: /*@
3870: DMGetApplicationContext - Gets an application context from a `DM` object provided with `DMSetApplicationContext()`
3872: Not Collective
3874: Input Parameter:
3875: . dm - the `DM` object
3877: Output Parameter:
3878: . ctx - a pointer to the application context
3880: Level: intermediate
3882: Note:
3883: An application context is a way to pass problem specific information that is accessible whenever the `DM` is available
3885: Fortran Notes:
3886: This only works when the context is a Fortran derived type (it cannot be a `PetscObject`) and you **must** write a Fortran interface definition for this
3887: function that tells the Fortran compiler the derived data type that is returned as the `ctx` argument. For example,
3888: .vb
3889: Interface DMGetApplicationContext
3890: Subroutine DMGetApplicationContext(dm,ctx,ierr)
3891: #include <petsc/finclude/petscdm.h>
3892: use petscdm
3893: DM dm
3894: type(tUsertype), pointer :: ctx
3895: PetscErrorCode ierr
3896: End Subroutine
3897: End Interface DMGetApplicationContext
3898: .ve
3900: The prototype for `ctx` must be
3901: .vb
3902: type(tUsertype), pointer :: ctx
3903: .ve
3905: .seealso: [](ch_dmbase), `DM`, `DMView()`, `DMCreateGlobalVector()`, `DMCreateInterpolation()`, `DMCreateColoring()`, `DMCreateMatrix()`, `DMCreateMassMatrix()`
3906: @*/
3907: PetscErrorCode DMGetApplicationContext(DM dm, PetscCtxRt ctx)
3908: {
3909: PetscFunctionBegin;
3911: *(void **)ctx = dm->ctx;
3912: PetscFunctionReturn(PETSC_SUCCESS);
3913: }
3915: /*@
3916: DMSetVariableBounds - sets a function to compute the lower and upper bound vectors for `SNESVI`.
3918: Logically Collective
3920: Input Parameters:
3921: + dm - the `DM` object
3922: - f - the function that computes variable bounds used by `SNESVI` (use `NULL` to cancel a previous function that was set)
3924: Calling sequence of f:
3925: + dm - the `DM`
3926: . lower - the vector to hold the lower bounds
3927: - upper - the vector to hold the upper bounds
3929: Level: intermediate
3931: Developer Note:
3932: Should be called `DMSetComputeVIBounds()` or something similar
3934: .seealso: [](ch_dmbase), `DM`, `DMComputeVariableBounds()`, `DMHasVariableBounds()`, `DMView()`, `DMCreateGlobalVector()`, `DMCreateInterpolation()`, `DMCreateColoring()`, `DMCreateMatrix()`, `DMCreateMassMatrix()`, `DMGetApplicationContext()`,
3935: `DMSetJacobian()`
3936: @*/
3937: PetscErrorCode DMSetVariableBounds(DM dm, PetscErrorCode (*f)(DM dm, Vec lower, Vec upper))
3938: {
3939: PetscFunctionBegin;
3941: dm->ops->computevariablebounds = f;
3942: PetscFunctionReturn(PETSC_SUCCESS);
3943: }
3945: /*@
3946: DMHasVariableBounds - does the `DM` object have a variable bounds function?
3948: Not Collective
3950: Input Parameter:
3951: . dm - the `DM` object to destroy
3953: Output Parameter:
3954: . flg - `PETSC_TRUE` if the variable bounds function exists
3956: Level: developer
3958: .seealso: [](ch_dmbase), `DM`, `DMComputeVariableBounds()`, `DMView()`, `DMCreateGlobalVector()`, `DMCreateInterpolation()`, `DMCreateColoring()`, `DMCreateMatrix()`, `DMCreateMassMatrix()`, `DMGetApplicationContext()`
3959: @*/
3960: PetscErrorCode DMHasVariableBounds(DM dm, PetscBool *flg)
3961: {
3962: PetscFunctionBegin;
3964: PetscAssertPointer(flg, 2);
3965: *flg = (dm->ops->computevariablebounds) ? PETSC_TRUE : PETSC_FALSE;
3966: PetscFunctionReturn(PETSC_SUCCESS);
3967: }
3969: /*@
3970: DMComputeVariableBounds - compute variable bounds used by `SNESVI`.
3972: Logically Collective
3974: Input Parameter:
3975: . dm - the `DM` object
3977: Output Parameters:
3978: + xl - lower bound
3979: - xu - upper bound
3981: Level: advanced
3983: Note:
3984: This is generally not called by users. It calls the function provided by the user with DMSetVariableBounds()
3986: .seealso: [](ch_dmbase), `DM`, `DMHasVariableBounds()`, `DMView()`, `DMCreateGlobalVector()`, `DMCreateInterpolation()`, `DMCreateColoring()`, `DMCreateMatrix()`, `DMCreateMassMatrix()`, `DMGetApplicationContext()`
3987: @*/
3988: PetscErrorCode DMComputeVariableBounds(DM dm, Vec xl, Vec xu)
3989: {
3990: PetscFunctionBegin;
3994: PetscUseTypeMethod(dm, computevariablebounds, xl, xu);
3995: PetscFunctionReturn(PETSC_SUCCESS);
3996: }
3998: /*@
3999: DMHasColoring - does the `DM` object have a method of providing a coloring?
4001: Not Collective
4003: Input Parameter:
4004: . dm - the DM object
4006: Output Parameter:
4007: . flg - `PETSC_TRUE` if the `DM` has facilities for `DMCreateColoring()`.
4009: Level: developer
4011: .seealso: [](ch_dmbase), `DM`, `DMCreateColoring()`
4012: @*/
4013: PetscErrorCode DMHasColoring(DM dm, PetscBool *flg)
4014: {
4015: PetscFunctionBegin;
4017: PetscAssertPointer(flg, 2);
4018: *flg = (dm->ops->getcoloring) ? PETSC_TRUE : PETSC_FALSE;
4019: PetscFunctionReturn(PETSC_SUCCESS);
4020: }
4022: /*@
4023: DMHasCreateRestriction - does the `DM` object have a method of providing a restriction?
4025: Not Collective
4027: Input Parameter:
4028: . dm - the `DM` object
4030: Output Parameter:
4031: . flg - `PETSC_TRUE` if the `DM` has facilities for `DMCreateRestriction()`.
4033: Level: developer
4035: .seealso: [](ch_dmbase), `DM`, `DMCreateRestriction()`, `DMHasCreateInterpolation()`, `DMHasCreateInjection()`
4036: @*/
4037: PetscErrorCode DMHasCreateRestriction(DM dm, PetscBool *flg)
4038: {
4039: PetscFunctionBegin;
4041: PetscAssertPointer(flg, 2);
4042: *flg = (dm->ops->createrestriction) ? PETSC_TRUE : PETSC_FALSE;
4043: PetscFunctionReturn(PETSC_SUCCESS);
4044: }
4046: /*@
4047: DMHasCreateInjection - does the `DM` object have a method of providing an injection?
4049: Not Collective
4051: Input Parameter:
4052: . dm - the `DM` object
4054: Output Parameter:
4055: . flg - `PETSC_TRUE` if the `DM` has facilities for `DMCreateInjection()`.
4057: Level: developer
4059: .seealso: [](ch_dmbase), `DM`, `DMCreateInjection()`, `DMHasCreateRestriction()`, `DMHasCreateInterpolation()`
4060: @*/
4061: PetscErrorCode DMHasCreateInjection(DM dm, PetscBool *flg)
4062: {
4063: PetscFunctionBegin;
4065: PetscAssertPointer(flg, 2);
4066: if (dm->ops->hascreateinjection) PetscUseTypeMethod(dm, hascreateinjection, flg);
4067: else *flg = (dm->ops->createinjection) ? PETSC_TRUE : PETSC_FALSE;
4068: PetscFunctionReturn(PETSC_SUCCESS);
4069: }
4071: PetscFunctionList DMList = NULL;
4072: PetscBool DMRegisterAllCalled = PETSC_FALSE;
4074: /*@
4075: DMSetType - Builds a `DM`, for a particular `DM` implementation.
4077: Collective
4079: Input Parameters:
4080: + dm - The `DM` object
4081: - method - The name of the `DMType`, for example `DMDA`, `DMPLEX`
4083: Options Database Key:
4084: . -dm_type type - Sets the `DM` type; use -help for a list of available types
4086: Level: intermediate
4088: Note:
4089: Of the `DM` is constructed by directly calling a function to construct a particular `DM`, for example, `DMDACreate2d()` or `DMPlexCreateBoxMesh()`
4091: .seealso: [](ch_dmbase), `DM`, `DMType`, `DMDA`, `DMPLEX`, `DMGetType()`, `DMCreate()`, `DMDACreate2d()`
4092: @*/
4093: PetscErrorCode DMSetType(DM dm, DMType method)
4094: {
4095: PetscErrorCode (*r)(DM);
4096: PetscBool match;
4098: PetscFunctionBegin;
4100: PetscCall(PetscObjectTypeCompare((PetscObject)dm, method, &match));
4101: if (match) PetscFunctionReturn(PETSC_SUCCESS);
4103: PetscCall(DMRegisterAll());
4104: PetscCall(PetscFunctionListFind(DMList, method, &r));
4105: PetscCheck(r, PetscObjectComm((PetscObject)dm), PETSC_ERR_ARG_UNKNOWN_TYPE, "Unknown DM type: %s", method);
4107: PetscTryTypeMethod(dm, destroy);
4108: PetscCall(PetscMemzero(dm->ops, sizeof(*dm->ops)));
4109: PetscCall(PetscObjectChangeTypeName((PetscObject)dm, method));
4110: PetscCall((*r)(dm));
4111: PetscFunctionReturn(PETSC_SUCCESS);
4112: }
4114: /*@
4115: DMGetType - Gets the `DM` type name (as a string) from the `DM`.
4117: Not Collective
4119: Input Parameter:
4120: . dm - The `DM`
4122: Output Parameter:
4123: . type - The `DMType` name
4125: Level: intermediate
4127: Note:
4128: `type` should not be retained for later use as it will be an invalid pointer if the `DMType` of `dm` is changed.
4130: .seealso: [](ch_dmbase), `DM`, `DMType`, `DMDA`, `DMPLEX`, `DMSetType()`, `DMCreate()`, `PetscObjectTypeCompare()`, `PetscObjectTypeCompareAny()`
4131: @*/
4132: PetscErrorCode DMGetType(DM dm, DMType *type)
4133: {
4134: PetscFunctionBegin;
4136: PetscAssertPointer(type, 2);
4137: PetscCall(DMRegisterAll());
4138: *type = ((PetscObject)dm)->type_name;
4139: PetscFunctionReturn(PETSC_SUCCESS);
4140: }
4142: /*@
4143: DMConvert - Converts a `DM` to another `DM`, either of the same or different type.
4145: Collective
4147: Input Parameters:
4148: + dm - the `DM`
4149: - newtype - new `DM` type (use "same" for the same type)
4151: Output Parameter:
4152: . M - pointer to new `DM`
4154: Level: intermediate
4156: Note:
4157: Cannot be used to convert a sequential `DM` to a parallel or a parallel to sequential,
4158: the MPI communicator of the generated `DM` is always the same as the communicator
4159: of the input `DM`.
4161: .seealso: [](ch_dmbase), `DM`, `DMSetType()`, `DMCreate()`, `DMClone()`
4162: @*/
4163: PetscErrorCode DMConvert(DM dm, DMType newtype, DM *M)
4164: {
4165: DM B;
4166: char convname[256];
4167: PetscBool sametype /*, issame */;
4169: PetscFunctionBegin;
4172: PetscAssertPointer(M, 3);
4173: PetscCall(PetscObjectTypeCompare((PetscObject)dm, newtype, &sametype));
4174: /* PetscCall(PetscStrcmp(newtype, "same", &issame)); */
4175: if (sametype) {
4176: *M = dm;
4177: PetscCall(PetscObjectReference((PetscObject)dm));
4178: PetscFunctionReturn(PETSC_SUCCESS);
4179: } else {
4180: PetscErrorCode (*conv)(DM, DMType, DM *) = NULL;
4182: /*
4183: Order of precedence:
4184: 1) See if a specialized converter is known to the current DM.
4185: 2) See if a specialized converter is known to the desired DM class.
4186: 3) See if a good general converter is registered for the desired class
4187: 4) See if a good general converter is known for the current matrix.
4188: 5) Use a really basic converter.
4189: */
4191: /* 1) See if a specialized converter is known to the current DM and the desired class */
4192: PetscCall(PetscStrncpy(convname, "DMConvert_", sizeof(convname)));
4193: PetscCall(PetscStrlcat(convname, ((PetscObject)dm)->type_name, sizeof(convname)));
4194: PetscCall(PetscStrlcat(convname, "_", sizeof(convname)));
4195: PetscCall(PetscStrlcat(convname, newtype, sizeof(convname)));
4196: PetscCall(PetscStrlcat(convname, "_C", sizeof(convname)));
4197: PetscCall(PetscObjectQueryFunction((PetscObject)dm, convname, &conv));
4198: if (conv) goto foundconv;
4200: /* 2) See if a specialized converter is known to the desired DM class. */
4201: PetscCall(DMCreate(PetscObjectComm((PetscObject)dm), &B));
4202: PetscCall(DMSetType(B, newtype));
4203: PetscCall(PetscStrncpy(convname, "DMConvert_", sizeof(convname)));
4204: PetscCall(PetscStrlcat(convname, ((PetscObject)dm)->type_name, sizeof(convname)));
4205: PetscCall(PetscStrlcat(convname, "_", sizeof(convname)));
4206: PetscCall(PetscStrlcat(convname, newtype, sizeof(convname)));
4207: PetscCall(PetscStrlcat(convname, "_C", sizeof(convname)));
4208: PetscCall(PetscObjectQueryFunction((PetscObject)B, convname, &conv));
4209: if (conv) {
4210: PetscCall(DMDestroy(&B));
4211: goto foundconv;
4212: }
4214: #if 0
4215: /* 3) See if a good general converter is registered for the desired class */
4216: conv = B->ops->convertfrom;
4217: PetscCall(DMDestroy(&B));
4218: if (conv) goto foundconv;
4220: /* 4) See if a good general converter is known for the current matrix */
4221: if (dm->ops->convert) conv = dm->ops->convert;
4222: if (conv) goto foundconv;
4223: #endif
4225: /* 5) Use a really basic converter. */
4226: SETERRQ(PetscObjectComm((PetscObject)dm), PETSC_ERR_SUP, "No conversion possible between DM types %s and %s", ((PetscObject)dm)->type_name, newtype);
4228: foundconv:
4229: PetscCall(PetscLogEventBegin(DM_Convert, dm, 0, 0, 0));
4230: PetscCall((*conv)(dm, newtype, M));
4231: /* Things that are independent of DM type: We should consult DMClone() here */
4232: {
4233: const PetscReal *maxCell, *Lstart, *L;
4235: PetscCall(DMGetPeriodicity(dm, &maxCell, &Lstart, &L));
4236: PetscCall(DMSetPeriodicity(*M, maxCell, Lstart, L));
4237: (*M)->prealloc_only = dm->prealloc_only;
4238: PetscCall(PetscFree((*M)->vectype));
4239: PetscCall(PetscStrallocpy(dm->vectype, (char **)&(*M)->vectype));
4240: PetscCall(PetscFree((*M)->mattype));
4241: PetscCall(PetscStrallocpy(dm->mattype, (char **)&(*M)->mattype));
4242: }
4243: PetscCall(PetscLogEventEnd(DM_Convert, dm, 0, 0, 0));
4244: }
4245: PetscCall(PetscObjectStateIncrease((PetscObject)*M));
4246: PetscFunctionReturn(PETSC_SUCCESS);
4247: }
4249: /*@
4250: DMRegister - Adds a new `DM` type implementation
4252: Not Collective, No Fortran Support
4254: Input Parameters:
4255: + sname - The name of a new user-defined creation routine
4256: - function - The creation routine itself
4258: Calling sequence of function:
4259: . dm - the new `DM` that is being created
4261: Level: advanced
4263: Note:
4264: `DMRegister()` may be called multiple times to add several user-defined `DM`s
4266: Example Usage:
4267: .vb
4268: DMRegister("my_da", MyDMCreate);
4269: .ve
4271: Then, your `DM` type can be chosen with the procedural interface via
4272: .vb
4273: DMCreate(MPI_Comm, DM *);
4274: DMSetType(DM,"my_da");
4275: .ve
4276: or at runtime via the option
4277: .vb
4278: -da_type my_da
4279: .ve
4281: .seealso: [](ch_dmbase), `DM`, `DMType`, `DMSetType()`, `DMRegisterAll()`
4282: @*/
4283: PetscErrorCode DMRegister(const char sname[], PetscErrorCode (*function)(DM dm))
4284: {
4285: PetscFunctionBegin;
4286: PetscCall(DMInitializePackage());
4287: PetscCall(PetscFunctionListAdd(&DMList, sname, function));
4288: PetscFunctionReturn(PETSC_SUCCESS);
4289: }
4291: /*@
4292: DMLoad - Loads a DM that has been stored in binary with `DMView()`.
4294: Collective
4296: Input Parameters:
4297: + newdm - the newly loaded `DM`, this needs to have been created with `DMCreate()` or
4298: some related function before a call to `DMLoad()`.
4299: - viewer - binary file viewer, obtained from `PetscViewerBinaryOpen()` or
4300: `PETSCVIEWERHDF5` file viewer, obtained from `PetscViewerHDF5Open()`
4302: Level: intermediate
4304: Notes:
4305: The type is determined by the data in the file, any type set into the DM before this call is ignored.
4307: Using `PETSCVIEWERHDF5` type with `PETSC_VIEWER_HDF5_PETSC` format, one can save multiple `DMPLEX`
4308: meshes in a single HDF5 file. This in turn requires one to name the `DMPLEX` object with `PetscObjectSetName()`
4309: before saving it with `DMView()` and before loading it with `DMLoad()` for identification of the mesh object.
4311: .seealso: [](ch_dmbase), `DM`, `PetscViewerBinaryOpen()`, `DMView()`, `MatLoad()`, `VecLoad()`
4312: @*/
4313: PetscErrorCode DMLoad(DM newdm, PetscViewer viewer)
4314: {
4315: PetscBool isbinary, ishdf5;
4317: PetscFunctionBegin;
4320: PetscCall(PetscViewerCheckReadable(viewer));
4321: PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERBINARY, &isbinary));
4322: PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERHDF5, &ishdf5));
4323: PetscCall(PetscLogEventBegin(DM_Load, viewer, 0, 0, 0));
4324: if (isbinary) {
4325: PetscInt classid;
4326: char type[256];
4328: PetscCall(PetscViewerBinaryRead(viewer, &classid, 1, NULL, PETSC_INT));
4329: PetscCheck(classid == DM_FILE_CLASSID, PetscObjectComm((PetscObject)newdm), PETSC_ERR_ARG_WRONG, "Not DM next in file, classid found %" PetscInt_FMT, classid);
4330: PetscCall(PetscViewerBinaryRead(viewer, type, 256, NULL, PETSC_CHAR));
4331: PetscCall(DMSetType(newdm, type));
4332: PetscTryTypeMethod(newdm, load, viewer);
4333: } else if (ishdf5) {
4334: PetscTryTypeMethod(newdm, load, viewer);
4335: } else SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Invalid viewer; open viewer with PetscViewerBinaryOpen() or PetscViewerHDF5Open()");
4336: PetscCall(PetscLogEventEnd(DM_Load, viewer, 0, 0, 0));
4337: PetscFunctionReturn(PETSC_SUCCESS);
4338: }
4340: /* FEM Support */
4342: /*@
4343: DMPrintCellIndices - Print an integer array of per-cell indices to `PETSC_COMM_SELF`
4345: Not Collective
4347: Input Parameters:
4348: + c - the cell number
4349: . name - the label to print with the cell (typically the element or field name)
4350: . len - the length of `x`
4351: - x - the array of integer indices
4353: Level: developer
4355: .seealso: [](ch_dmbase), `DM`, `DMPrintCellVector()`, `DMPrintCellVectorReal()`, `DMPrintCellMatrix()`, `DMPrintLocalVec()`
4356: @*/
4357: PetscErrorCode DMPrintCellIndices(PetscInt c, const char name[], PetscInt len, const PetscInt x[])
4358: {
4359: PetscInt f;
4361: PetscFunctionBegin;
4362: PetscCall(PetscPrintf(PETSC_COMM_SELF, "Cell %" PetscInt_FMT " Element %s\n", c, name));
4363: for (f = 0; f < len; ++f) PetscCall(PetscPrintf(PETSC_COMM_SELF, " | %" PetscInt_FMT " |\n", x[f]));
4364: PetscFunctionReturn(PETSC_SUCCESS);
4365: }
4367: /*@
4368: DMPrintCellVector - Print a scalar array representing a per-cell vector to `PETSC_COMM_SELF`
4370: Not Collective
4372: Input Parameters:
4373: + c - the cell number
4374: . name - the label to print with the cell (typically the element or field name)
4375: . len - the length of `x`
4376: - x - the array of `PetscScalar` values
4378: Level: developer
4380: Note:
4381: Only the real part of each entry is printed.
4383: .seealso: [](ch_dmbase), `DM`, `DMPrintCellIndices()`, `DMPrintCellVectorReal()`, `DMPrintCellMatrix()`, `DMPrintLocalVec()`
4384: @*/
4385: PetscErrorCode DMPrintCellVector(PetscInt c, const char name[], PetscInt len, const PetscScalar x[])
4386: {
4387: PetscInt f;
4389: PetscFunctionBegin;
4390: PetscCall(PetscPrintf(PETSC_COMM_SELF, "Cell %" PetscInt_FMT " Element %s\n", c, name));
4391: for (f = 0; f < len; ++f) PetscCall(PetscPrintf(PETSC_COMM_SELF, " | %g |\n", (double)PetscRealPart(x[f])));
4392: PetscFunctionReturn(PETSC_SUCCESS);
4393: }
4395: /*@
4396: DMPrintCellVectorReal - Print a real array representing a per-cell vector to `PETSC_COMM_SELF`
4398: Not Collective
4400: Input Parameters:
4401: + c - the cell number
4402: . name - the label to print with the cell (typically the element or field name)
4403: . len - the length of `x`
4404: - x - the array of `PetscReal` values
4406: Level: developer
4408: .seealso: [](ch_dmbase), `DM`, `DMPrintCellIndices()`, `DMPrintCellVector()`, `DMPrintCellMatrix()`, `DMPrintLocalVec()`
4409: @*/
4410: PetscErrorCode DMPrintCellVectorReal(PetscInt c, const char name[], PetscInt len, const PetscReal x[])
4411: {
4412: PetscFunctionBegin;
4413: PetscCall(PetscPrintf(PETSC_COMM_SELF, "Cell %" PetscInt_FMT " Element %s\n", c, name));
4414: for (PetscInt f = 0; f < len; ++f) PetscCall(PetscPrintf(PETSC_COMM_SELF, " | %g |\n", (double)x[f]));
4415: PetscFunctionReturn(PETSC_SUCCESS);
4416: }
4418: /*@
4419: DMPrintCellMatrix - Print a scalar array representing a per-cell matrix to `PETSC_COMM_SELF`
4421: Not Collective
4423: Input Parameters:
4424: + c - the cell number
4425: . name - the label to print with the cell (typically the element or field name)
4426: . rows - number of rows in the matrix
4427: . cols - number of columns in the matrix
4428: - A - the row-major array of `PetscScalar` matrix entries
4430: Level: developer
4432: Note:
4433: Only the real part of each entry is printed.
4435: .seealso: [](ch_dmbase), `DM`, `DMPrintCellIndices()`, `DMPrintCellVector()`, `DMPrintCellVectorReal()`, `DMPrintLocalVec()`
4436: @*/
4437: PetscErrorCode DMPrintCellMatrix(PetscInt c, const char name[], PetscInt rows, PetscInt cols, const PetscScalar A[])
4438: {
4439: PetscFunctionBegin;
4440: PetscCall(PetscPrintf(PETSC_COMM_SELF, "Cell %" PetscInt_FMT " Element %s\n", c, name));
4441: for (PetscInt f = 0; f < rows; ++f) {
4442: PetscCall(PetscPrintf(PETSC_COMM_SELF, " |"));
4443: for (PetscInt g = 0; g < cols; ++g) PetscCall(PetscPrintf(PETSC_COMM_SELF, " % 9.5g", (double)PetscRealPart(A[f * cols + g])));
4444: PetscCall(PetscPrintf(PETSC_COMM_SELF, " |\n"));
4445: }
4446: PetscFunctionReturn(PETSC_SUCCESS);
4447: }
4449: /*@
4450: DMPrintLocalVec - Print a `Vec` associated with a `DM`, filtering out very small entries
4452: Collective
4454: Input Parameters:
4455: + dm - the `DM` providing the communicator
4456: . name - a label printed before the vector values
4457: . tol - tolerance below which entries are filtered to zero using `VecFilter()`
4458: - X - the `Vec` to print
4460: Level: developer
4462: Note:
4463: Runs in parallel by wrapping the local portion of the vector in an MPI vector for viewing.
4465: .seealso: [](ch_dmbase), `DM`, `DMPrintCellIndices()`, `DMPrintCellVector()`, `DMPrintCellVectorReal()`, `DMPrintCellMatrix()`, `VecFilter()`
4466: @*/
4467: PetscErrorCode DMPrintLocalVec(DM dm, const char name[], PetscReal tol, Vec X)
4468: {
4469: PetscInt localSize, bs;
4470: PetscMPIInt size;
4471: Vec x, xglob;
4472: const PetscScalar *xarray;
4474: PetscFunctionBegin;
4475: PetscCallMPI(MPI_Comm_size(PetscObjectComm((PetscObject)dm), &size));
4476: PetscCall(VecDuplicate(X, &x));
4477: PetscCall(VecCopy(X, x));
4478: PetscCall(VecFilter(x, tol));
4479: PetscCall(PetscPrintf(PetscObjectComm((PetscObject)dm), "%s:\n", name));
4480: if (size > 1) {
4481: PetscCall(VecGetLocalSize(x, &localSize));
4482: PetscCall(VecGetArrayRead(x, &xarray));
4483: PetscCall(VecGetBlockSize(x, &bs));
4484: PetscCall(VecCreateMPIWithArray(PetscObjectComm((PetscObject)dm), bs, localSize, PETSC_DETERMINE, xarray, &xglob));
4485: } else {
4486: xglob = x;
4487: }
4488: PetscCall(VecView(xglob, PETSC_VIEWER_STDOUT_(PetscObjectComm((PetscObject)dm))));
4489: if (size > 1) {
4490: PetscCall(VecDestroy(&xglob));
4491: PetscCall(VecRestoreArrayRead(x, &xarray));
4492: }
4493: PetscCall(VecDestroy(&x));
4494: PetscFunctionReturn(PETSC_SUCCESS);
4495: }
4497: PetscErrorCode DMViewDSFromOptions_Internal(DM dm, const char opt[])
4498: {
4499: PetscObject obj = (PetscObject)dm;
4500: PetscViewer viewer;
4501: PetscViewerFormat format;
4502: PetscBool flg;
4504: PetscFunctionBegin;
4505: PetscCall(PetscOptionsCreateViewer(PetscObjectComm(obj), obj->options, obj->prefix, opt, &viewer, &format, &flg));
4506: if (flg) {
4507: PetscCall(PetscViewerPushFormat(viewer, format));
4508: for (PetscInt d = 0; d < dm->Nds; ++d) PetscCall(PetscDSView(dm->probs[d].ds, viewer));
4509: PetscCall(PetscViewerFlush(viewer));
4510: PetscCall(PetscViewerPopFormat(viewer));
4511: PetscCall(PetscViewerDestroy(&viewer));
4512: }
4513: PetscFunctionReturn(PETSC_SUCCESS);
4514: }
4516: PetscErrorCode DMViewSectionFromOptions_Internal(DM dm, const char opt[])
4517: {
4518: PetscObject obj = (PetscObject)dm;
4519: PetscViewer viewer;
4520: PetscViewerFormat format;
4521: PetscBool flg;
4523: PetscFunctionBegin;
4524: PetscCall(PetscOptionsCreateViewer(PetscObjectComm(obj), obj->options, obj->prefix, opt, &viewer, &format, &flg));
4525: if (flg) {
4526: PetscCall(PetscViewerPushFormat(viewer, format));
4527: if (dm->localSection) PetscCall(PetscSectionView(dm->localSection, viewer));
4528: PetscCall(PetscViewerFlush(viewer));
4529: PetscCall(PetscViewerPopFormat(viewer));
4530: PetscCall(PetscViewerDestroy(&viewer));
4531: }
4532: PetscFunctionReturn(PETSC_SUCCESS);
4533: }
4535: /*@
4536: DMGetLocalSection - Get the `PetscSection` encoding the local data layout for the `DM`.
4538: Input Parameter:
4539: . dm - The `DM`
4541: Output Parameter:
4542: . section - The `PetscSection`
4544: Options Database Key:
4545: . -dm_petscsection_view - View the section created by the `DM`
4547: Level: intermediate
4549: Note:
4550: This gets a borrowed reference, so the user should not destroy this `PetscSection`.
4552: .seealso: [](ch_dmbase), `DM`, `DMSetLocalSection()`, `DMGetGlobalSection()`
4553: @*/
4554: PetscErrorCode DMGetLocalSection(DM dm, PetscSection *section)
4555: {
4556: PetscFunctionBegin;
4558: PetscAssertPointer(section, 2);
4559: if (!dm->localSection && dm->ops->createlocalsection) {
4560: if (dm->setfromoptionscalled) {
4561: for (PetscInt d = 0; d < dm->Nds; ++d) PetscCall(PetscDSSetFromOptions(dm->probs[d].ds));
4562: PetscCall(DMViewDSFromOptions_Internal(dm, "-dm_petscds_view"));
4563: }
4564: PetscUseTypeMethod(dm, createlocalsection);
4565: if (dm->localSection) PetscCall(PetscObjectViewFromOptions((PetscObject)dm->localSection, NULL, "-dm_petscsection_view"));
4566: }
4567: *section = dm->localSection;
4568: PetscFunctionReturn(PETSC_SUCCESS);
4569: }
4571: /*@
4572: DMSetLocalSection - Set the `PetscSection` encoding the local data layout for the `DM`.
4574: Input Parameters:
4575: + dm - The `DM`
4576: - section - The `PetscSection`
4578: Level: intermediate
4580: Note:
4581: Any existing Section will be destroyed. The global section, the section `PetscSF`, and any local-to-global mapping previously derived from the sections are
4582: invalidated and will be rebuilt on their next access. A mapping built by the `DM` implementation itself, such as by `DMDA` in `DMSetUp()`, is kept.
4584: .seealso: [](ch_dmbase), `DM`, `PetscSection`, `DMGetLocalSection()`, `DMSetGlobalSection()`
4585: @*/
4586: PetscErrorCode DMSetLocalSection(DM dm, PetscSection section)
4587: {
4588: PetscInt numFields = 0;
4590: PetscFunctionBegin;
4593: PetscCall(PetscObjectReference((PetscObject)section));
4594: PetscCall(PetscSectionDestroy(&dm->localSection));
4595: dm->localSection = section;
4596: if (section) PetscCall(PetscSectionGetNumFields(dm->localSection, &numFields));
4597: if (numFields) {
4598: PetscCall(DMSetNumFields(dm, numFields));
4599: for (PetscInt f = 0; f < numFields; ++f) {
4600: PetscObject disc;
4601: const char *name;
4603: PetscCall(PetscSectionGetFieldName(dm->localSection, f, &name));
4604: PetscCall(DMGetField(dm, f, NULL, &disc));
4605: PetscCall(PetscObjectSetName(disc, name));
4606: }
4607: }
4608: /* The global section, the SectionSF, and a section-derived local-to-global mapping will be rebuilt
4609: in the next call to DMGetGlobalSection(), DMGetSectionSF(), and DMGetLocalToGlobalMapping().
4610: A mapping built by the implementation (e.g. DMDA in DMSetUp()) does not depend on the sections and could not be rebuilt, so it is kept. */
4611: PetscCall(PetscSectionDestroy(&dm->globalSection));
4612: PetscCall(PetscSFDestroy(&dm->sectionSF));
4613: PetscCall(PetscSFCreate(PetscObjectComm((PetscObject)dm), &dm->sectionSF));
4614: if (dm->ltogmapFromSection) PetscCall(ISLocalToGlobalMappingDestroy(&dm->ltogmap));
4616: /* Clear scratch vectors */
4617: PetscCall(DMClearGlobalVectors(dm));
4618: PetscCall(DMClearLocalVectors(dm));
4619: PetscCall(DMClearNamedGlobalVectors(dm));
4620: PetscCall(DMClearNamedLocalVectors(dm));
4621: PetscFunctionReturn(PETSC_SUCCESS);
4622: }
4624: /*@
4625: DMCreateSectionPermutation - Create a permutation of the `PetscSection` chart and optionally a block structure.
4627: Input Parameter:
4628: . dm - The `DM`
4630: Output Parameters:
4631: + perm - A permutation of the mesh points in the chart
4632: - blockStarts - A high bit is set for the point that begins every block, or `NULL` for default blocking
4634: Level: developer
4636: .seealso: [](ch_dmbase), `DM`, `PetscSection`, `DMGetLocalSection()`, `DMGetGlobalSection()`
4637: @*/
4638: PetscErrorCode DMCreateSectionPermutation(DM dm, IS *perm, PetscBT *blockStarts)
4639: {
4640: PetscFunctionBegin;
4641: *perm = NULL;
4642: *blockStarts = NULL;
4643: PetscTryTypeMethod(dm, createsectionpermutation, perm, blockStarts);
4644: PetscFunctionReturn(PETSC_SUCCESS);
4645: }
4647: /*@
4648: DMGetDefaultConstraints - Get the `PetscSection` and `Mat` that specify the local constraint interpolation. See `DMSetDefaultConstraints()` for a description of the purpose of constraint interpolation.
4650: not Collective
4652: Input Parameter:
4653: . dm - The `DM`
4655: Output Parameters:
4656: + 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.
4657: . 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.
4658: - bias - Vector containing bias to be added to constrained dofs
4660: Level: advanced
4662: Note:
4663: This gets borrowed references, so the user should not destroy the `PetscSection`, `Mat`, or `Vec`.
4665: .seealso: [](ch_dmbase), `DM`, `DMSetDefaultConstraints()`
4666: @*/
4667: PetscErrorCode DMGetDefaultConstraints(DM dm, PetscSection *section, Mat *mat, Vec *bias)
4668: {
4669: PetscFunctionBegin;
4671: if (!dm->defaultConstraint.section && !dm->defaultConstraint.mat && dm->ops->createdefaultconstraints) PetscUseTypeMethod(dm, createdefaultconstraints);
4672: if (section) *section = dm->defaultConstraint.section;
4673: if (mat) *mat = dm->defaultConstraint.mat;
4674: if (bias) *bias = dm->defaultConstraint.bias;
4675: PetscFunctionReturn(PETSC_SUCCESS);
4676: }
4678: /*@
4679: DMSetDefaultConstraints - Set the `PetscSection` and `Mat` that specify the local constraint interpolation.
4681: Collective
4683: Input Parameters:
4684: + dm - The `DM`
4685: . 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).
4686: . 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).
4687: - 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).
4689: Level: advanced
4691: Notes:
4692: 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()`.
4694: 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.
4696: This increments the references of the `PetscSection`, `Mat`, and `Vec`, so they user can destroy them.
4698: .seealso: [](ch_dmbase), `DM`, `DMGetDefaultConstraints()`
4699: @*/
4700: PetscErrorCode DMSetDefaultConstraints(DM dm, PetscSection section, Mat mat, Vec bias)
4701: {
4702: PetscMPIInt result;
4704: PetscFunctionBegin;
4706: if (section) {
4708: PetscCallMPI(MPI_Comm_compare(PETSC_COMM_SELF, PetscObjectComm((PetscObject)section), &result));
4709: PetscCheck(result == MPI_CONGRUENT || result == MPI_IDENT, PETSC_COMM_SELF, PETSC_ERR_ARG_NOTSAMECOMM, "constraint section must have local communicator");
4710: }
4711: if (mat) {
4713: PetscCallMPI(MPI_Comm_compare(PETSC_COMM_SELF, PetscObjectComm((PetscObject)mat), &result));
4714: PetscCheck(result == MPI_CONGRUENT || result == MPI_IDENT, PETSC_COMM_SELF, PETSC_ERR_ARG_NOTSAMECOMM, "constraint matrix must have local communicator");
4715: }
4716: if (bias) {
4718: PetscCallMPI(MPI_Comm_compare(PETSC_COMM_SELF, PetscObjectComm((PetscObject)bias), &result));
4719: PetscCheck(result == MPI_CONGRUENT || result == MPI_IDENT, PETSC_COMM_SELF, PETSC_ERR_ARG_NOTSAMECOMM, "constraint bias must have local communicator");
4720: }
4721: PetscCall(PetscObjectReference((PetscObject)section));
4722: PetscCall(PetscSectionDestroy(&dm->defaultConstraint.section));
4723: dm->defaultConstraint.section = section;
4724: PetscCall(PetscObjectReference((PetscObject)mat));
4725: PetscCall(MatDestroy(&dm->defaultConstraint.mat));
4726: dm->defaultConstraint.mat = mat;
4727: PetscCall(PetscObjectReference((PetscObject)bias));
4728: PetscCall(VecDestroy(&dm->defaultConstraint.bias));
4729: dm->defaultConstraint.bias = bias;
4730: PetscFunctionReturn(PETSC_SUCCESS);
4731: }
4733: /*
4734: DMDefaultSectionCheckConsistency - Check the consistentcy of the global and local sections. Generates and error if they are not consistent.
4736: Input Parameters:
4737: + dm - The `DM`
4738: . localSection - `PetscSection` describing the local data layout
4739: - globalSection - `PetscSection` describing the global data layout
4741: Level: intermediate
4743: .seealso: [](ch_dmbase), `DM`, `DMGetSectionSF()`, `DMSetSectionSF()`
4744: */
4745: static PetscErrorCode DMDefaultSectionCheckConsistency_Internal(DM dm, PetscSection localSection, PetscSection globalSection)
4746: {
4747: MPI_Comm comm;
4748: PetscLayout layout;
4749: const PetscInt *ranges;
4750: PetscInt pStart, pEnd, p, nroots;
4751: PetscMPIInt size, rank;
4752: PetscBool valid = PETSC_TRUE;
4754: PetscFunctionBegin;
4755: PetscCall(PetscObjectGetComm((PetscObject)dm, &comm));
4757: PetscCallMPI(MPI_Comm_size(comm, &size));
4758: PetscCallMPI(MPI_Comm_rank(comm, &rank));
4759: PetscCall(PetscSectionGetChart(globalSection, &pStart, &pEnd));
4760: PetscCall(PetscSectionGetConstrainedStorageSize(globalSection, &nroots));
4761: PetscCall(PetscLayoutCreate(comm, &layout));
4762: PetscCall(PetscLayoutSetBlockSize(layout, 1));
4763: PetscCall(PetscLayoutSetLocalSize(layout, nroots));
4764: PetscCall(PetscLayoutSetUp(layout));
4765: PetscCall(PetscLayoutGetRanges(layout, &ranges));
4766: for (p = pStart; p < pEnd; ++p) {
4767: PetscInt dof, cdof, off, gdof, gcdof, goff, gsize, d;
4769: PetscCall(PetscSectionGetDof(localSection, p, &dof));
4770: PetscCall(PetscSectionGetOffset(localSection, p, &off));
4771: PetscCall(PetscSectionGetConstraintDof(localSection, p, &cdof));
4772: PetscCall(PetscSectionGetDof(globalSection, p, &gdof));
4773: PetscCall(PetscSectionGetConstraintDof(globalSection, p, &gcdof));
4774: PetscCall(PetscSectionGetOffset(globalSection, p, &goff));
4775: if (!gdof) continue; /* Censored point */
4776: if ((gdof < 0 ? -(gdof + 1) : gdof) != dof) {
4777: PetscCall(PetscSynchronizedPrintf(comm, "[%d]Global dof %" PetscInt_FMT " for point %" PetscInt_FMT " not equal to local dof %" PetscInt_FMT "\n", rank, gdof, p, dof));
4778: valid = PETSC_FALSE;
4779: }
4780: if (gcdof && (gcdof != cdof)) {
4781: PetscCall(PetscSynchronizedPrintf(comm, "[%d]Global constraints %" PetscInt_FMT " for point %" PetscInt_FMT " not equal to local constraints %" PetscInt_FMT "\n", rank, gcdof, p, cdof));
4782: valid = PETSC_FALSE;
4783: }
4784: if (gdof < 0) {
4785: gsize = gdof < 0 ? -(gdof + 1) - gcdof : gdof - gcdof;
4786: for (d = 0; d < gsize; ++d) {
4787: PetscInt offset = -(goff + 1) + d, r;
4789: PetscCall(PetscFindInt(offset, size + 1, ranges, &r));
4790: if (r < 0) r = -(r + 2);
4791: if ((r < 0) || (r >= size)) {
4792: PetscCall(PetscSynchronizedPrintf(comm, "[%d]Point %" PetscInt_FMT " mapped to invalid process %" PetscInt_FMT " (%" PetscInt_FMT ", %" PetscInt_FMT ")\n", rank, p, r, gdof, goff));
4793: valid = PETSC_FALSE;
4794: break;
4795: }
4796: }
4797: }
4798: }
4799: PetscCall(PetscLayoutDestroy(&layout));
4800: PetscCall(PetscSynchronizedFlush(comm, NULL));
4801: PetscCallMPI(MPIU_Allreduce(MPI_IN_PLACE, &valid, 1, MPI_C_BOOL, MPI_LAND, comm));
4802: if (!valid) {
4803: PetscCall(DMView(dm, NULL));
4804: SETERRQ(comm, PETSC_ERR_ARG_WRONG, "Inconsistent local and global sections");
4805: }
4806: PetscFunctionReturn(PETSC_SUCCESS);
4807: }
4809: PetscErrorCode DMGetIsoperiodicPointSF_Internal(DM dm, PetscSF *sf)
4810: {
4811: PetscErrorCode (*f)(DM, PetscSF *);
4813: PetscFunctionBegin;
4815: PetscAssertPointer(sf, 2);
4816: PetscCall(PetscObjectQueryFunction((PetscObject)dm, "DMGetIsoperiodicPointSF_C", &f));
4817: if (f) PetscCall(f(dm, sf));
4818: else *sf = dm->sf;
4819: PetscFunctionReturn(PETSC_SUCCESS);
4820: }
4822: /*@
4823: DMGetGlobalSection - Get the `PetscSection` encoding the global data layout for the `DM`.
4825: Collective
4827: Input Parameter:
4828: . dm - The `DM`
4830: Output Parameter:
4831: . section - The `PetscSection`
4833: Level: intermediate
4835: Note:
4836: This gets a borrowed reference, so the user should not destroy this `PetscSection`.
4838: .seealso: [](ch_dmbase), `DM`, `DMSetLocalSection()`, `DMGetLocalSection()`
4839: @*/
4840: PetscErrorCode DMGetGlobalSection(DM dm, PetscSection *section)
4841: {
4842: PetscFunctionBegin;
4844: PetscAssertPointer(section, 2);
4845: if (!dm->globalSection) {
4846: PetscSection s;
4847: PetscSF sf;
4849: PetscCall(DMGetLocalSection(dm, &s));
4850: PetscCheck(s, PetscObjectComm((PetscObject)dm), PETSC_ERR_ARG_WRONGSTATE, "DM must have a default PetscSection in order to create a global PetscSection");
4851: PetscCheck(dm->sf, PetscObjectComm((PetscObject)dm), PETSC_ERR_ARG_WRONGSTATE, "DM must have a point PetscSF in order to create a global PetscSection");
4852: PetscCall(DMGetIsoperiodicPointSF_Internal(dm, &sf));
4853: PetscCall(PetscSectionCreateGlobalSection(s, sf, PETSC_TRUE, PETSC_FALSE, PETSC_FALSE, &dm->globalSection));
4854: PetscCall(PetscLayoutDestroy(&dm->map));
4855: PetscCall(PetscSectionGetValueLayout(PetscObjectComm((PetscObject)dm), dm->globalSection, &dm->map));
4856: PetscCall(PetscSectionViewFromOptions(dm->globalSection, NULL, "-global_section_view"));
4857: }
4858: *section = dm->globalSection;
4859: PetscFunctionReturn(PETSC_SUCCESS);
4860: }
4862: /*@
4863: DMSetGlobalSection - Set the `PetscSection` encoding the global data layout for the `DM`.
4865: Input Parameters:
4866: + dm - The `DM`
4867: - section - The PetscSection, or `NULL`
4869: Level: intermediate
4871: Note:
4872: Any existing `PetscSection` will be destroyed. The section `PetscSF` and any local-to-global mapping previously derived from the sections are invalidated
4873: and will be rebuilt on their next access. A mapping built by the `DM` implementation itself, such as by `DMDA` in `DMSetUp()`, is kept.
4875: .seealso: [](ch_dmbase), `DM`, `DMGetGlobalSection()`, `DMSetLocalSection()`
4876: @*/
4877: PetscErrorCode DMSetGlobalSection(DM dm, PetscSection section)
4878: {
4879: PetscFunctionBegin;
4882: PetscCall(PetscObjectReference((PetscObject)section));
4883: PetscCall(PetscSectionDestroy(&dm->globalSection));
4884: dm->globalSection = section;
4885: if (PetscDefined(USE_DEBUG) && section) PetscCall(DMDefaultSectionCheckConsistency_Internal(dm, dm->localSection, section));
4886: /* Clear global scratch vectors, sectionSF, and a section-derived local-to-global mapping, which encodes the old section's offsets */
4887: PetscCall(PetscSFDestroy(&dm->sectionSF));
4888: PetscCall(PetscSFCreate(PetscObjectComm((PetscObject)dm), &dm->sectionSF));
4889: if (dm->ltogmapFromSection) PetscCall(ISLocalToGlobalMappingDestroy(&dm->ltogmap));
4890: PetscCall(DMClearGlobalVectors(dm));
4891: PetscCall(DMClearNamedGlobalVectors(dm));
4892: PetscFunctionReturn(PETSC_SUCCESS);
4893: }
4895: /*@
4896: DMGetSectionSF - Get the `PetscSF` encoding the parallel dof overlap for the `DM`. If it has not been set,
4897: it is created from the default `PetscSection` layouts in the `DM`.
4899: Input Parameter:
4900: . dm - The `DM`
4902: Output Parameter:
4903: . sf - The `PetscSF`
4905: Level: intermediate
4907: Note:
4908: This gets a borrowed reference, so the user should not destroy this `PetscSF`.
4910: .seealso: [](ch_dmbase), `DM`, `DMSetSectionSF()`, `DMCreateSectionSF()`
4911: @*/
4912: PetscErrorCode DMGetSectionSF(DM dm, PetscSF *sf)
4913: {
4914: PetscInt nroots;
4916: PetscFunctionBegin;
4918: PetscAssertPointer(sf, 2);
4919: if (!dm->sectionSF) PetscCall(PetscSFCreate(PetscObjectComm((PetscObject)dm), &dm->sectionSF));
4920: PetscCall(PetscSFGetGraph(dm->sectionSF, &nroots, NULL, NULL, NULL));
4921: if (nroots < 0) {
4922: PetscSection section, gSection;
4924: PetscCall(DMGetLocalSection(dm, §ion));
4925: if (section) {
4926: PetscCall(DMGetGlobalSection(dm, &gSection));
4927: PetscCall(DMCreateSectionSF(dm, section, gSection));
4928: } else {
4929: *sf = NULL;
4930: PetscFunctionReturn(PETSC_SUCCESS);
4931: }
4932: }
4933: *sf = dm->sectionSF;
4934: PetscFunctionReturn(PETSC_SUCCESS);
4935: }
4937: /*@
4938: DMSetSectionSF - Set the `PetscSF` encoding the parallel dof overlap for the `DM`
4940: Input Parameters:
4941: + dm - The `DM`
4942: - sf - The `PetscSF`
4944: Level: intermediate
4946: Note:
4947: Any previous `PetscSF` is destroyed
4949: .seealso: [](ch_dmbase), `DM`, `DMGetSectionSF()`, `DMCreateSectionSF()`
4950: @*/
4951: PetscErrorCode DMSetSectionSF(DM dm, PetscSF sf)
4952: {
4953: PetscFunctionBegin;
4956: PetscCall(PetscObjectReference((PetscObject)sf));
4957: PetscCall(PetscSFDestroy(&dm->sectionSF));
4958: dm->sectionSF = sf;
4959: PetscFunctionReturn(PETSC_SUCCESS);
4960: }
4962: /*@
4963: DMCreateSectionSF - Create the `PetscSF` encoding the parallel dof overlap for the `DM` based upon the `PetscSection`s
4964: describing the data layout.
4966: Input Parameters:
4967: + dm - The `DM`
4968: . localSection - `PetscSection` describing the local data layout
4969: - globalSection - `PetscSection` describing the global data layout
4971: Level: developer
4973: Note:
4974: One usually uses `DMGetSectionSF()` to obtain the `PetscSF`
4976: Developer Note:
4977: Since this routine has for arguments the two sections from the `DM` and puts the resulting `PetscSF`
4978: directly into the `DM`, perhaps this function should not take the local and global sections as
4979: input and should just obtain them from the `DM`? Plus PETSc creation functions return the thing
4980: they create, this returns nothing
4982: .seealso: [](ch_dmbase), `DM`, `DMGetSectionSF()`, `DMSetSectionSF()`, `DMGetLocalSection()`, `DMGetGlobalSection()`
4983: @*/
4984: PetscErrorCode DMCreateSectionSF(DM dm, PetscSection localSection, PetscSection globalSection)
4985: {
4986: PetscFunctionBegin;
4988: PetscCall(PetscSFSetGraphSection(dm->sectionSF, localSection, globalSection));
4989: PetscFunctionReturn(PETSC_SUCCESS);
4990: }
4992: /*@
4993: DMGetPointSF - Get the `PetscSF` encoding the parallel section point overlap for the `DM`.
4995: Not collective but the resulting `PetscSF` is collective
4997: Input Parameter:
4998: . dm - The `DM`
5000: Output Parameter:
5001: . sf - The `PetscSF`
5003: Level: intermediate
5005: Note:
5006: This gets a borrowed reference, so the user should not destroy this `PetscSF`.
5008: .seealso: [](ch_dmbase), `DM`, `DMSetPointSF()`, `DMGetSectionSF()`, `DMSetSectionSF()`, `DMCreateSectionSF()`
5009: @*/
5010: PetscErrorCode DMGetPointSF(DM dm, PetscSF *sf)
5011: {
5012: PetscFunctionBegin;
5014: PetscAssertPointer(sf, 2);
5015: *sf = dm->sf;
5016: PetscFunctionReturn(PETSC_SUCCESS);
5017: }
5019: /*@
5020: DMSetPointSF - Set the `PetscSF` encoding the parallel section point overlap for the `DM`.
5022: Collective
5024: Input Parameters:
5025: + dm - The `DM`
5026: - sf - The `PetscSF`
5028: Level: intermediate
5030: .seealso: [](ch_dmbase), `DM`, `DMGetPointSF()`, `DMGetSectionSF()`, `DMSetSectionSF()`, `DMCreateSectionSF()`
5031: @*/
5032: PetscErrorCode DMSetPointSF(DM dm, PetscSF sf)
5033: {
5034: PetscFunctionBegin;
5037: PetscCall(PetscObjectReference((PetscObject)sf));
5038: PetscCall(PetscSFDestroy(&dm->sf));
5039: dm->sf = sf;
5040: PetscFunctionReturn(PETSC_SUCCESS);
5041: }
5043: /*@
5044: DMGetNaturalSF - Get the `PetscSF` encoding the map back to the original mesh ordering
5046: Input Parameter:
5047: . dm - The `DM`
5049: Output Parameter:
5050: . sf - The `PetscSF`
5052: Level: intermediate
5054: Note:
5055: This gets a borrowed reference, so the user should not destroy this `PetscSF`.
5057: .seealso: [](ch_dmbase), `DM`, `DMSetNaturalSF()`, `DMSetUseNatural()`, `DMGetUseNatural()`, `DMPlexCreateGlobalToNaturalSF()`, `DMPlexDistribute()`
5058: @*/
5059: PetscErrorCode DMGetNaturalSF(DM dm, PetscSF *sf)
5060: {
5061: PetscFunctionBegin;
5063: PetscAssertPointer(sf, 2);
5064: *sf = dm->sfNatural;
5065: PetscFunctionReturn(PETSC_SUCCESS);
5066: }
5068: /*@
5069: DMSetNaturalSF - Set the PetscSF encoding the map back to the original mesh ordering
5071: Input Parameters:
5072: + dm - The DM
5073: - sf - The PetscSF
5075: Level: intermediate
5077: .seealso: [](ch_dmbase), `DM`, `DMGetNaturalSF()`, `DMSetUseNatural()`, `DMGetUseNatural()`, `DMPlexCreateGlobalToNaturalSF()`, `DMPlexDistribute()`
5078: @*/
5079: PetscErrorCode DMSetNaturalSF(DM dm, PetscSF sf)
5080: {
5081: PetscFunctionBegin;
5084: PetscCall(PetscObjectReference((PetscObject)sf));
5085: PetscCall(PetscSFDestroy(&dm->sfNatural));
5086: dm->sfNatural = sf;
5087: PetscFunctionReturn(PETSC_SUCCESS);
5088: }
5090: static PetscErrorCode DMSetDefaultAdjacency_Private(DM dm, PetscInt f, PetscObject disc)
5091: {
5092: PetscClassId id;
5094: PetscFunctionBegin;
5095: PetscCall(PetscObjectGetClassId(disc, &id));
5096: if (id == PETSCFE_CLASSID) PetscCall(DMSetAdjacency(dm, f, PETSC_FALSE, PETSC_TRUE));
5097: else if (id == PETSCFV_CLASSID) PetscCall(DMSetAdjacency(dm, f, PETSC_TRUE, PETSC_FALSE));
5098: else PetscCall(DMSetAdjacency(dm, f, PETSC_FALSE, PETSC_TRUE));
5099: PetscFunctionReturn(PETSC_SUCCESS);
5100: }
5102: static PetscErrorCode DMFieldEnlarge_Static(DM dm, PetscInt NfNew)
5103: {
5104: RegionField *tmpr;
5105: PetscInt Nf = dm->Nf, f;
5107: PetscFunctionBegin;
5108: if (Nf >= NfNew) PetscFunctionReturn(PETSC_SUCCESS);
5109: PetscCall(PetscMalloc1(NfNew, &tmpr));
5110: for (f = 0; f < Nf; ++f) tmpr[f] = dm->fields[f];
5111: for (f = Nf; f < NfNew; ++f) {
5112: tmpr[f].disc = NULL;
5113: tmpr[f].label = NULL;
5114: tmpr[f].avoidTensor = PETSC_FALSE;
5115: }
5116: PetscCall(PetscFree(dm->fields));
5117: dm->Nf = NfNew;
5118: dm->fields = tmpr;
5119: PetscFunctionReturn(PETSC_SUCCESS);
5120: }
5122: /*@
5123: DMClearFields - Remove all fields from the `DM`
5125: Logically Collective
5127: Input Parameter:
5128: . dm - The `DM`
5130: Level: intermediate
5132: .seealso: [](ch_dmbase), `DM`, `DMGetNumFields()`, `DMSetNumFields()`, `DMSetField()`
5133: @*/
5134: PetscErrorCode DMClearFields(DM dm)
5135: {
5136: PetscInt f;
5138: PetscFunctionBegin;
5140: if (!dm->fields) PetscFunctionReturn(PETSC_SUCCESS); // DMDA does not use fields field in DM
5141: for (f = 0; f < dm->Nf; ++f) {
5142: PetscCall(PetscObjectDestroy(&dm->fields[f].disc));
5143: PetscCall(DMLabelDestroy(&dm->fields[f].label));
5144: }
5145: PetscCall(PetscFree(dm->fields));
5146: dm->fields = NULL;
5147: dm->Nf = 0;
5148: PetscFunctionReturn(PETSC_SUCCESS);
5149: }
5151: /*@
5152: DMGetNumFields - Get the number of fields in the `DM`
5154: Not Collective
5156: Input Parameter:
5157: . dm - The `DM`
5159: Output Parameter:
5160: . numFields - The number of fields
5162: Level: intermediate
5164: .seealso: [](ch_dmbase), `DM`, `DMSetNumFields()`, `DMSetField()`
5165: @*/
5166: PetscErrorCode DMGetNumFields(DM dm, PetscInt *numFields)
5167: {
5168: PetscFunctionBegin;
5170: PetscAssertPointer(numFields, 2);
5171: *numFields = dm->Nf;
5172: PetscFunctionReturn(PETSC_SUCCESS);
5173: }
5175: /*@
5176: DMSetNumFields - Set the number of fields in the `DM`
5178: Logically Collective
5180: Input Parameters:
5181: + dm - The `DM`
5182: - numFields - The number of fields
5184: Level: intermediate
5186: .seealso: [](ch_dmbase), `DM`, `DMGetNumFields()`, `DMSetField()`
5187: @*/
5188: PetscErrorCode DMSetNumFields(DM dm, PetscInt numFields)
5189: {
5190: PetscInt Nf;
5192: PetscFunctionBegin;
5194: PetscCall(DMGetNumFields(dm, &Nf));
5195: for (PetscInt f = Nf; f < numFields; ++f) {
5196: PetscContainer obj;
5198: PetscCall(PetscContainerCreate(PetscObjectComm((PetscObject)dm), &obj));
5199: PetscCall(DMAddField(dm, NULL, (PetscObject)obj));
5200: PetscCall(PetscContainerDestroy(&obj));
5201: }
5202: PetscFunctionReturn(PETSC_SUCCESS);
5203: }
5205: /*@
5206: DMGetField - Return the `DMLabel` and discretization object for a given `DM` field
5208: Not Collective
5210: Input Parameters:
5211: + dm - The `DM`
5212: - f - The field number
5214: Output Parameters:
5215: + label - The label indicating the support of the field, or `NULL` for the entire mesh (pass in `NULL` if not needed)
5216: - disc - The discretization object (pass in `NULL` if not needed)
5218: Level: intermediate
5220: .seealso: [](ch_dmbase), `DM`, `DMAddField()`, `DMSetField()`
5221: @*/
5222: PetscErrorCode DMGetField(DM dm, PetscInt f, DMLabel *label, PetscObject *disc)
5223: {
5224: PetscFunctionBegin;
5226: PetscAssertPointer(disc, 4);
5227: 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);
5228: if (!dm->fields) {
5229: if (label) *label = NULL;
5230: if (disc) *disc = NULL;
5231: } else { // some DM such as DMDA do not have dm->fields
5232: if (label) *label = dm->fields[f].label;
5233: if (disc) *disc = dm->fields[f].disc;
5234: }
5235: PetscFunctionReturn(PETSC_SUCCESS);
5236: }
5238: /* Does not clear the DS */
5239: PetscErrorCode DMSetField_Internal(DM dm, PetscInt f, DMLabel label, PetscObject disc)
5240: {
5241: PetscFunctionBegin;
5242: PetscCall(DMFieldEnlarge_Static(dm, f + 1));
5243: PetscCall(DMLabelDestroy(&dm->fields[f].label));
5244: PetscCall(PetscObjectDestroy(&dm->fields[f].disc));
5245: dm->fields[f].label = label;
5246: dm->fields[f].disc = disc;
5247: PetscCall(PetscObjectReference((PetscObject)label));
5248: PetscCall(PetscObjectReference(disc));
5249: PetscFunctionReturn(PETSC_SUCCESS);
5250: }
5252: /*@
5253: DMSetField - Set the discretization object for a given `DM` field. Usually one would call `DMAddField()` which automatically handles
5254: the field numbering.
5256: Logically Collective
5258: Input Parameters:
5259: + dm - The `DM`
5260: . f - The field number
5261: . label - The label indicating the support of the field, or `NULL` for the entire mesh
5262: - disc - The discretization object
5264: Level: intermediate
5266: .seealso: [](ch_dmbase), `DM`, `DMAddField()`, `DMGetField()`
5267: @*/
5268: PetscErrorCode DMSetField(DM dm, PetscInt f, DMLabel label, PetscObject disc)
5269: {
5270: PetscFunctionBegin;
5274: PetscCheck(f >= 0, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Field number %" PetscInt_FMT " must be non-negative", f);
5275: PetscCall(DMSetField_Internal(dm, f, label, disc));
5276: PetscCall(DMSetDefaultAdjacency_Private(dm, f, disc));
5277: PetscCall(DMClearDS(dm));
5278: PetscFunctionReturn(PETSC_SUCCESS);
5279: }
5281: /*@
5282: DMAddField - Add a field to a `DM` object. A field is a function space defined by of a set of discretization points (geometric entities)
5283: and a discretization object that defines the function space associated with those points.
5285: Logically Collective
5287: Input Parameters:
5288: + dm - The `DM`
5289: . label - The label indicating the support of the field, or `NULL` for the entire mesh
5290: - disc - The discretization object
5292: Level: intermediate
5294: Notes:
5295: The label already exists or will be added to the `DM` with `DMSetLabel()`.
5297: For example, a piecewise continuous pressure field can be defined by coefficients at the cell centers of a mesh and piecewise constant functions
5298: 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
5299: geometry entities, a `DMLabel` indicating a subset of those geometric entities, and a discretization object, such as a `PetscFE`.
5301: Fortran Note:
5302: Use the argument `PetscObjectCast(disc)` as the second argument
5304: .seealso: [](ch_dmbase), `DM`, `DMSetLabel()`, `DMSetField()`, `DMGetField()`, `PetscFE`
5305: @*/
5306: PetscErrorCode DMAddField(DM dm, DMLabel label, PetscObject disc)
5307: {
5308: PetscInt Nf = dm->Nf;
5310: PetscFunctionBegin;
5314: PetscCall(DMFieldEnlarge_Static(dm, Nf + 1));
5315: dm->fields[Nf].label = label;
5316: dm->fields[Nf].disc = disc;
5317: PetscCall(PetscObjectReference((PetscObject)label));
5318: PetscCall(PetscObjectReference(disc));
5319: PetscCall(DMSetDefaultAdjacency_Private(dm, Nf, disc));
5320: PetscCall(DMClearDS(dm));
5321: PetscFunctionReturn(PETSC_SUCCESS);
5322: }
5324: /*@
5325: DMSetFieldAvoidTensor - Set flag to avoid defining the field on tensor cells
5327: Logically Collective
5329: Input Parameters:
5330: + dm - The `DM`
5331: . f - The field index
5332: - avoidTensor - `PETSC_TRUE` to skip defining the field on tensor cells
5334: Level: intermediate
5336: .seealso: [](ch_dmbase), `DM`, `DMGetFieldAvoidTensor()`, `DMSetField()`, `DMGetField()`
5337: @*/
5338: PetscErrorCode DMSetFieldAvoidTensor(DM dm, PetscInt f, PetscBool avoidTensor)
5339: {
5340: PetscFunctionBegin;
5341: 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);
5342: dm->fields[f].avoidTensor = avoidTensor;
5343: PetscFunctionReturn(PETSC_SUCCESS);
5344: }
5346: /*@
5347: DMGetFieldAvoidTensor - Get flag to avoid defining the field on tensor cells
5349: Not Collective
5351: Input Parameters:
5352: + dm - The `DM`
5353: - f - The field index
5355: Output Parameter:
5356: . avoidTensor - The flag to avoid defining the field on tensor cells
5358: Level: intermediate
5360: .seealso: [](ch_dmbase), `DM`, `DMAddField()`, `DMSetField()`, `DMGetField()`, `DMSetFieldAvoidTensor()`
5361: @*/
5362: PetscErrorCode DMGetFieldAvoidTensor(DM dm, PetscInt f, PetscBool *avoidTensor)
5363: {
5364: PetscFunctionBegin;
5365: 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);
5366: *avoidTensor = dm->fields[f].avoidTensor;
5367: PetscFunctionReturn(PETSC_SUCCESS);
5368: }
5370: /*@
5371: DMCopyFields - Copy the discretizations for the `DM` into another `DM`
5373: Collective
5375: Input Parameters:
5376: + dm - The `DM`
5377: . minDegree - Minimum degree for a discretization, or `PETSC_DETERMINE` for no limit
5378: - maxDegree - Maximum degree for a discretization, or `PETSC_DETERMINE` for no limit
5380: Output Parameter:
5381: . newdm - The `DM`
5383: Level: advanced
5385: .seealso: [](ch_dmbase), `DM`, `DMGetField()`, `DMSetField()`, `DMAddField()`, `DMCopyDS()`, `DMGetDS()`, `DMGetCellDS()`
5386: @*/
5387: PetscErrorCode DMCopyFields(DM dm, PetscInt minDegree, PetscInt maxDegree, DM newdm)
5388: {
5389: PetscInt Nf;
5391: PetscFunctionBegin;
5392: if (dm == newdm) PetscFunctionReturn(PETSC_SUCCESS);
5393: PetscCall(DMGetNumFields(dm, &Nf));
5394: PetscCall(DMClearFields(newdm));
5395: for (PetscInt f = 0; f < Nf; ++f) {
5396: DMLabel label;
5397: PetscObject field;
5398: PetscClassId id;
5399: PetscBool useCone, useClosure;
5401: PetscCall(DMGetField(dm, f, &label, &field));
5402: PetscCall(PetscObjectGetClassId(field, &id));
5403: if (id == PETSCFE_CLASSID) {
5404: PetscFE newfe;
5406: PetscCall(PetscFELimitDegree((PetscFE)field, minDegree, maxDegree, &newfe));
5407: PetscCall(DMSetField(newdm, f, label, (PetscObject)newfe));
5408: PetscCall(PetscFEDestroy(&newfe));
5409: } else {
5410: PetscCall(DMSetField(newdm, f, label, field));
5411: }
5412: PetscCall(DMGetAdjacency(dm, f, &useCone, &useClosure));
5413: PetscCall(DMSetAdjacency(newdm, f, useCone, useClosure));
5414: }
5415: // Create nullspace constructor slots
5416: if (dm->nullspaceConstructors) {
5417: PetscCall(PetscFree2(newdm->nullspaceConstructors, newdm->nearnullspaceConstructors));
5418: PetscCall(PetscCalloc2(Nf, &newdm->nullspaceConstructors, Nf, &newdm->nearnullspaceConstructors));
5419: }
5420: PetscFunctionReturn(PETSC_SUCCESS);
5421: }
5423: /*@
5424: DMGetAdjacency - Returns the flags for determining variable influence
5426: Not Collective
5428: Input Parameters:
5429: + dm - The `DM` object
5430: - f - The field number, or `PETSC_DEFAULT` for the default adjacency
5432: Output Parameters:
5433: + useCone - Flag for variable influence starting with the cone operation
5434: - useClosure - Flag for variable influence using transitive closure
5436: Level: developer
5438: Notes:
5439: .vb
5440: FEM: Two points p and q are adjacent if q \in closure(star(p)), useCone = PETSC_FALSE, useClosure = PETSC_TRUE
5441: FVM: Two points p and q are adjacent if q \in support(p+cone(p)), useCone = PETSC_TRUE, useClosure = PETSC_FALSE
5442: FVM++: Two points p and q are adjacent if q \in star(closure(p)), useCone = PETSC_TRUE, useClosure = PETSC_TRUE
5443: .ve
5444: Further explanation can be found in the User's Manual Section on the Influence of Variables on One Another.
5446: .seealso: [](ch_dmbase), `DM`, `DMSetAdjacency()`, `DMGetField()`, `DMSetField()`
5447: @*/
5448: PetscErrorCode DMGetAdjacency(DM dm, PetscInt f, PetscBool *useCone, PetscBool *useClosure)
5449: {
5450: PetscFunctionBegin;
5452: if (useCone) PetscAssertPointer(useCone, 3);
5453: if (useClosure) PetscAssertPointer(useClosure, 4);
5454: if (f < 0) {
5455: if (useCone) *useCone = dm->adjacency[0];
5456: if (useClosure) *useClosure = dm->adjacency[1];
5457: } else {
5458: PetscInt Nf;
5460: PetscCall(DMGetNumFields(dm, &Nf));
5461: PetscCheck(f < Nf, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Field number %" PetscInt_FMT " must be in [0, %" PetscInt_FMT ")", f, Nf);
5462: if (useCone) *useCone = dm->fields[f].adjacency[0];
5463: if (useClosure) *useClosure = dm->fields[f].adjacency[1];
5464: }
5465: PetscFunctionReturn(PETSC_SUCCESS);
5466: }
5468: /*@
5469: DMSetAdjacency - Set the flags for determining variable influence
5471: Not Collective
5473: Input Parameters:
5474: + dm - The `DM` object
5475: . f - The field number
5476: . useCone - Flag for variable influence starting with the cone operation
5477: - useClosure - Flag for variable influence using transitive closure
5479: Level: developer
5481: Notes:
5482: .vb
5483: FEM: Two points p and q are adjacent if q \in closure(star(p)), useCone = PETSC_FALSE, useClosure = PETSC_TRUE
5484: FVM: Two points p and q are adjacent if q \in support(p+cone(p)), useCone = PETSC_TRUE, useClosure = PETSC_FALSE
5485: FVM++: Two points p and q are adjacent if q \in star(closure(p)), useCone = PETSC_TRUE, useClosure = PETSC_TRUE
5486: .ve
5487: Further explanation can be found in the User's Manual Section on the Influence of Variables on One Another.
5489: .seealso: [](ch_dmbase), `DM`, `DMGetAdjacency()`, `DMGetField()`, `DMSetField()`
5490: @*/
5491: PetscErrorCode DMSetAdjacency(DM dm, PetscInt f, PetscBool useCone, PetscBool useClosure)
5492: {
5493: PetscFunctionBegin;
5495: if (f < 0) {
5496: dm->adjacency[0] = useCone;
5497: dm->adjacency[1] = useClosure;
5498: } else {
5499: PetscInt Nf;
5501: PetscCall(DMGetNumFields(dm, &Nf));
5502: PetscCheck(f < Nf, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Field number %" PetscInt_FMT " must be in [0, %" PetscInt_FMT ")", f, Nf);
5503: dm->fields[f].adjacency[0] = useCone;
5504: dm->fields[f].adjacency[1] = useClosure;
5505: }
5506: PetscFunctionReturn(PETSC_SUCCESS);
5507: }
5509: /*@
5510: DMGetBasicAdjacency - Returns the flags for determining variable influence, using either the default or field 0 if it is defined
5512: Not collective
5514: Input Parameter:
5515: . dm - The `DM` object
5517: Output Parameters:
5518: + useCone - Flag for variable influence starting with the cone operation
5519: - useClosure - Flag for variable influence using transitive closure
5521: Level: developer
5523: Notes:
5524: .vb
5525: FEM: Two points p and q are adjacent if q \in closure(star(p)), useCone = PETSC_FALSE, useClosure = PETSC_TRUE
5526: FVM: Two points p and q are adjacent if q \in support(p+cone(p)), useCone = PETSC_TRUE, useClosure = PETSC_FALSE
5527: FVM++: Two points p and q are adjacent if q \in star(closure(p)), useCone = PETSC_TRUE, useClosure = PETSC_TRUE
5528: .ve
5530: .seealso: [](ch_dmbase), `DM`, `DMSetBasicAdjacency()`, `DMGetField()`, `DMSetField()`
5531: @*/
5532: PetscErrorCode DMGetBasicAdjacency(DM dm, PetscBool *useCone, PetscBool *useClosure)
5533: {
5534: PetscInt Nf;
5536: PetscFunctionBegin;
5538: if (useCone) PetscAssertPointer(useCone, 2);
5539: if (useClosure) PetscAssertPointer(useClosure, 3);
5540: PetscCall(DMGetNumFields(dm, &Nf));
5541: if (!Nf) {
5542: PetscCall(DMGetAdjacency(dm, PETSC_DEFAULT, useCone, useClosure));
5543: } else {
5544: PetscCall(DMGetAdjacency(dm, 0, useCone, useClosure));
5545: }
5546: PetscFunctionReturn(PETSC_SUCCESS);
5547: }
5549: /*@
5550: DMSetBasicAdjacency - Set the flags for determining variable influence, using either the default or field 0 if it is defined
5552: Not Collective
5554: Input Parameters:
5555: + dm - The `DM` object
5556: . useCone - Flag for variable influence starting with the cone operation
5557: - useClosure - Flag for variable influence using transitive closure
5559: Level: developer
5561: Notes:
5562: .vb
5563: FEM: Two points p and q are adjacent if q \in closure(star(p)), useCone = PETSC_FALSE, useClosure = PETSC_TRUE
5564: FVM: Two points p and q are adjacent if q \in support(p+cone(p)), useCone = PETSC_TRUE, useClosure = PETSC_FALSE
5565: FVM++: Two points p and q are adjacent if q \in star(closure(p)), useCone = PETSC_TRUE, useClosure = PETSC_TRUE
5566: .ve
5568: .seealso: [](ch_dmbase), `DM`, `DMGetBasicAdjacency()`, `DMGetField()`, `DMSetField()`
5569: @*/
5570: PetscErrorCode DMSetBasicAdjacency(DM dm, PetscBool useCone, PetscBool useClosure)
5571: {
5572: PetscInt Nf;
5574: PetscFunctionBegin;
5576: PetscCall(DMGetNumFields(dm, &Nf));
5577: if (!Nf) {
5578: PetscCall(DMSetAdjacency(dm, PETSC_DEFAULT, useCone, useClosure));
5579: } else {
5580: PetscCall(DMSetAdjacency(dm, 0, useCone, useClosure));
5581: }
5582: PetscFunctionReturn(PETSC_SUCCESS);
5583: }
5585: PetscErrorCode DMCompleteBCLabels_Internal(DM dm)
5586: {
5587: DM plex;
5588: DMLabel *labels, *glabels;
5589: const char **names;
5590: char *sendNames, *recvNames;
5591: PetscInt Nds, s, maxLabels = 0, maxLen = 0, Nl = 0, gNl, l, gl, m;
5592: size_t len;
5593: MPI_Comm comm;
5594: PetscMPIInt rank, size, p, *counts, *displs;
5596: PetscFunctionBegin;
5597: PetscCall(PetscObjectGetComm((PetscObject)dm, &comm));
5598: PetscCallMPI(MPI_Comm_size(comm, &size));
5599: PetscCallMPI(MPI_Comm_rank(comm, &rank));
5600: PetscCall(DMGetNumDS(dm, &Nds));
5601: for (s = 0; s < Nds; ++s) {
5602: PetscDS dsBC;
5603: PetscInt numBd;
5605: PetscCall(DMGetRegionNumDS(dm, s, NULL, NULL, &dsBC, NULL));
5606: PetscCall(PetscDSGetNumBoundary(dsBC, &numBd));
5607: maxLabels += numBd;
5608: }
5609: PetscCall(PetscCalloc1(maxLabels, &labels));
5610: /* Get list of labels to be completed */
5611: for (s = 0; s < Nds; ++s) {
5612: PetscDS dsBC;
5613: PetscInt numBd;
5615: PetscCall(DMGetRegionNumDS(dm, s, NULL, NULL, &dsBC, NULL));
5616: PetscCall(PetscDSGetNumBoundary(dsBC, &numBd));
5617: for (PetscInt bd = 0; bd < numBd; ++bd) {
5618: DMLabel label;
5619: PetscInt field;
5620: PetscObject obj;
5621: PetscClassId id;
5623: PetscCall(PetscDSGetBoundary(dsBC, bd, NULL, NULL, NULL, &label, NULL, NULL, &field, NULL, NULL, NULL, NULL, NULL));
5624: PetscCall(DMGetField(dm, field, NULL, &obj));
5625: PetscCall(PetscObjectGetClassId(obj, &id));
5626: if (id != PETSCFE_CLASSID || !label) continue;
5627: for (l = 0; l < Nl; ++l)
5628: if (labels[l] == label) break;
5629: if (l == Nl) labels[Nl++] = label;
5630: }
5631: }
5632: /* Get label names */
5633: PetscCall(PetscMalloc1(Nl, &names));
5634: for (l = 0; l < Nl; ++l) PetscCall(PetscObjectGetName((PetscObject)labels[l], &names[l]));
5635: for (l = 0; l < Nl; ++l) {
5636: PetscCall(PetscStrlen(names[l], &len));
5637: maxLen = PetscMax(maxLen, (PetscInt)len + 2);
5638: }
5639: PetscCall(PetscFree(labels));
5640: PetscCallMPI(MPIU_Allreduce(MPI_IN_PLACE, &maxLen, 1, MPIU_INT, MPI_MAX, comm));
5641: PetscCall(PetscCalloc1(Nl * maxLen, &sendNames));
5642: for (l = 0; l < Nl; ++l) PetscCall(PetscStrncpy(&sendNames[maxLen * l], names[l], maxLen));
5643: PetscCall(PetscFree(names));
5644: /* Put all names on all processes */
5645: PetscCall(PetscCalloc2(size, &counts, size + 1, &displs));
5646: PetscCallMPI(MPI_Allgather(&Nl, 1, MPI_INT, counts, 1, MPI_INT, comm));
5647: for (p = 0; p < size; ++p) displs[p + 1] = displs[p] + counts[p];
5648: gNl = displs[size];
5649: for (p = 0; p < size; ++p) {
5650: counts[p] *= maxLen;
5651: displs[p] *= maxLen;
5652: }
5653: PetscCall(PetscCalloc2(gNl * maxLen, &recvNames, gNl, &glabels));
5654: PetscCallMPI(MPI_Allgatherv(sendNames, counts[rank], MPI_CHAR, recvNames, counts, displs, MPI_CHAR, comm));
5655: PetscCall(PetscFree2(counts, displs));
5656: PetscCall(PetscFree(sendNames));
5657: for (l = 0, gl = 0; l < gNl; ++l) {
5658: PetscCall(DMGetLabel(dm, &recvNames[l * maxLen], &glabels[gl]));
5659: PetscCheck(glabels[gl], PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Label %s missing on rank %d", &recvNames[l * maxLen], rank);
5660: for (m = 0; m < gl; ++m)
5661: if (glabels[m] == glabels[gl]) goto next_label;
5662: PetscCall(DMConvert(dm, DMPLEX, &plex));
5663: PetscCall(DMPlexLabelComplete(plex, glabels[gl]));
5664: PetscCall(DMDestroy(&plex));
5665: ++gl;
5666: next_label:
5667: continue;
5668: }
5669: PetscCall(PetscFree2(recvNames, glabels));
5670: PetscFunctionReturn(PETSC_SUCCESS);
5671: }
5673: static PetscErrorCode DMDSEnlarge_Static(DM dm, PetscInt NdsNew)
5674: {
5675: DMSpace *tmpd;
5676: PetscInt Nds = dm->Nds, s;
5678: PetscFunctionBegin;
5679: if (Nds >= NdsNew) PetscFunctionReturn(PETSC_SUCCESS);
5680: PetscCall(PetscMalloc1(NdsNew, &tmpd));
5681: for (s = 0; s < Nds; ++s) tmpd[s] = dm->probs[s];
5682: for (s = Nds; s < NdsNew; ++s) {
5683: tmpd[s].ds = NULL;
5684: tmpd[s].label = NULL;
5685: tmpd[s].fields = NULL;
5686: }
5687: PetscCall(PetscFree(dm->probs));
5688: dm->Nds = NdsNew;
5689: dm->probs = tmpd;
5690: PetscFunctionReturn(PETSC_SUCCESS);
5691: }
5693: /*@
5694: DMGetNumDS - Get the number of discrete systems in the `DM`
5696: Not Collective
5698: Input Parameter:
5699: . dm - The `DM`
5701: Output Parameter:
5702: . Nds - The number of `PetscDS` objects
5704: Level: intermediate
5706: .seealso: [](ch_dmbase), `DM`, `DMGetDS()`, `DMGetCellDS()`
5707: @*/
5708: PetscErrorCode DMGetNumDS(DM dm, PetscInt *Nds)
5709: {
5710: PetscFunctionBegin;
5712: PetscAssertPointer(Nds, 2);
5713: *Nds = dm->Nds;
5714: PetscFunctionReturn(PETSC_SUCCESS);
5715: }
5717: /*@
5718: DMClearDS - Remove all discrete systems from the `DM`
5720: Logically Collective
5722: Input Parameter:
5723: . dm - The `DM`
5725: Level: intermediate
5727: .seealso: [](ch_dmbase), `DM`, `DMGetNumDS()`, `DMGetDS()`, `DMSetField()`
5728: @*/
5729: PetscErrorCode DMClearDS(DM dm)
5730: {
5731: PetscInt s;
5733: PetscFunctionBegin;
5735: for (s = 0; s < dm->Nds; ++s) {
5736: PetscCall(PetscDSDestroy(&dm->probs[s].ds));
5737: PetscCall(PetscDSDestroy(&dm->probs[s].dsIn));
5738: PetscCall(DMLabelDestroy(&dm->probs[s].label));
5739: PetscCall(ISDestroy(&dm->probs[s].fields));
5740: }
5741: PetscCall(PetscFree(dm->probs));
5742: dm->probs = NULL;
5743: dm->Nds = 0;
5744: PetscFunctionReturn(PETSC_SUCCESS);
5745: }
5747: /*@
5748: DMGetDS - Get the default `PetscDS`
5750: Not Collective
5752: Input Parameter:
5753: . dm - The `DM`
5755: Output Parameter:
5756: . ds - The default `PetscDS`
5758: Level: intermediate
5760: Note:
5761: The `ds` is owned by the `dm` and should not be destroyed directly.
5763: .seealso: [](ch_dmbase), `DM`, `DMGetCellDS()`, `DMGetRegionDS()`
5764: @*/
5765: PetscErrorCode DMGetDS(DM dm, PetscDS *ds)
5766: {
5767: PetscFunctionBeginHot;
5769: PetscAssertPointer(ds, 2);
5770: PetscCheck(dm->Nds > 0, PetscObjectComm((PetscObject)dm), PETSC_ERR_ARG_WRONGSTATE, "Need to call DMCreateDS() before calling DMGetDS()");
5771: *ds = dm->probs[0].ds;
5772: PetscFunctionReturn(PETSC_SUCCESS);
5773: }
5775: /*@
5776: DMGetCellDS - Get the `PetscDS` defined on a given cell
5778: Not Collective
5780: Input Parameters:
5781: + dm - The `DM`
5782: - point - Cell for the `PetscDS`
5784: Output Parameters:
5785: + ds - The `PetscDS` defined on the given cell
5786: - dsIn - The `PetscDS` for input on the given cell, or `NULL` if the same ds
5788: Level: developer
5790: .seealso: [](ch_dmbase), `DM`, `DMGetDS()`, `DMSetRegionDS()`
5791: @*/
5792: PetscErrorCode DMGetCellDS(DM dm, PetscInt point, PetscDS *ds, PetscDS *dsIn)
5793: {
5794: PetscDS dsDef = NULL;
5795: PetscInt s;
5797: PetscFunctionBeginHot;
5799: if (ds) PetscAssertPointer(ds, 3);
5800: if (dsIn) PetscAssertPointer(dsIn, 4);
5801: PetscCheck(point >= 0, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Mesh point cannot be negative: %" PetscInt_FMT, point);
5802: if (ds) *ds = NULL;
5803: if (dsIn) *dsIn = NULL;
5804: for (s = 0; s < dm->Nds; ++s) {
5805: PetscInt val;
5807: if (!dm->probs[s].label) {
5808: dsDef = dm->probs[s].ds;
5809: } else {
5810: PetscCall(DMLabelGetValue(dm->probs[s].label, point, &val));
5811: if (val >= 0) {
5812: if (ds) *ds = dm->probs[s].ds;
5813: if (dsIn) *dsIn = dm->probs[s].dsIn;
5814: break;
5815: }
5816: }
5817: }
5818: if (ds && !*ds) *ds = dsDef;
5819: PetscFunctionReturn(PETSC_SUCCESS);
5820: }
5822: /*@
5823: DMGetRegionDS - Get the `PetscDS` for a given mesh region, defined by a `DMLabel`
5825: Not Collective
5827: Input Parameters:
5828: + dm - The `DM`
5829: - label - The `DMLabel` defining the mesh region, or `NULL` for the entire mesh
5831: Output Parameters:
5832: + fields - The `IS` containing the `DM` field numbers for the fields in this `PetscDS`, or `NULL`
5833: . ds - The `PetscDS` defined on the given region, or `NULL`
5834: - dsIn - The `PetscDS` for input in the given region, or `NULL`
5836: Level: advanced
5838: Note:
5839: If a non-`NULL` label is given, but there is no `PetscDS` on that specific label,
5840: the `PetscDS` for the full domain (if present) is returned. Returns with
5841: fields = `NULL` and ds = `NULL` if there is no `PetscDS` for the full domain.
5843: .seealso: [](ch_dmbase), `DM`, `DMGetRegionNumDS()`, `DMSetRegionDS()`, `DMGetDS()`, `DMGetCellDS()`
5844: @*/
5845: PetscErrorCode DMGetRegionDS(DM dm, DMLabel label, IS *fields, PetscDS *ds, PetscDS *dsIn)
5846: {
5847: PetscInt Nds = dm->Nds, s;
5849: PetscFunctionBegin;
5852: if (fields) {
5853: PetscAssertPointer(fields, 3);
5854: *fields = NULL;
5855: }
5856: if (ds) {
5857: PetscAssertPointer(ds, 4);
5858: *ds = NULL;
5859: }
5860: if (dsIn) {
5861: PetscAssertPointer(dsIn, 5);
5862: *dsIn = NULL;
5863: }
5864: for (s = 0; s < Nds; ++s) {
5865: if (dm->probs[s].label == label || !dm->probs[s].label) {
5866: if (fields) *fields = dm->probs[s].fields;
5867: if (ds) *ds = dm->probs[s].ds;
5868: if (dsIn) *dsIn = dm->probs[s].dsIn;
5869: if (dm->probs[s].label) PetscFunctionReturn(PETSC_SUCCESS);
5870: }
5871: }
5872: PetscFunctionReturn(PETSC_SUCCESS);
5873: }
5875: /*@
5876: DMSetRegionDS - Set the `PetscDS` for a given mesh region, defined by a `DMLabel`
5878: Collective
5880: Input Parameters:
5881: + dm - The `DM`
5882: . label - The `DMLabel` defining the mesh region, or `NULL` for the entire mesh
5883: . fields - The `IS` containing the `DM` field numbers for the fields in this `PetscDS`, or `NULL` for all fields
5884: . ds - The `PetscDS` defined on the given region
5885: - dsIn - The `PetscDS` for input on the given cell, or `NULL` if it is the same `PetscDS`
5887: Level: advanced
5889: Note:
5890: If the label has a `PetscDS` defined, it will be replaced. Otherwise, it will be added to the `DM`. If the `PetscDS` is replaced,
5891: the fields argument is ignored.
5893: .seealso: [](ch_dmbase), `DM`, `DMGetRegionDS()`, `DMSetRegionNumDS()`, `DMGetDS()`, `DMGetCellDS()`
5894: @*/
5895: PetscErrorCode DMSetRegionDS(DM dm, DMLabel label, IS fields, PetscDS ds, PetscDS dsIn)
5896: {
5897: PetscInt Nds = dm->Nds, s;
5899: PetscFunctionBegin;
5905: for (s = 0; s < Nds; ++s) {
5906: if (dm->probs[s].label == label) {
5907: PetscCall(PetscDSDestroy(&dm->probs[s].ds));
5908: PetscCall(PetscDSDestroy(&dm->probs[s].dsIn));
5909: dm->probs[s].ds = ds;
5910: dm->probs[s].dsIn = dsIn;
5911: PetscFunctionReturn(PETSC_SUCCESS);
5912: }
5913: }
5914: PetscCall(DMDSEnlarge_Static(dm, Nds + 1));
5915: PetscCall(PetscObjectReference((PetscObject)label));
5916: PetscCall(PetscObjectReference((PetscObject)fields));
5917: PetscCall(PetscObjectReference((PetscObject)ds));
5918: PetscCall(PetscObjectReference((PetscObject)dsIn));
5919: if (!label) {
5920: /* Put the NULL label at the front, so it is returned as the default */
5921: for (s = Nds - 1; s >= 0; --s) dm->probs[s + 1] = dm->probs[s];
5922: Nds = 0;
5923: }
5924: dm->probs[Nds].label = label;
5925: dm->probs[Nds].fields = fields;
5926: dm->probs[Nds].ds = ds;
5927: dm->probs[Nds].dsIn = dsIn;
5928: PetscFunctionReturn(PETSC_SUCCESS);
5929: }
5931: /*@
5932: DMGetRegionNumDS - Get the `PetscDS` for a given mesh region, defined by the region number
5934: Not Collective
5936: Input Parameters:
5937: + dm - The `DM`
5938: - num - The region number, in [0, Nds)
5940: Output Parameters:
5941: + label - The region label, or `NULL`
5942: . fields - The `IS` containing the `DM` field numbers for the fields in this `PetscDS`, or `NULL`
5943: . ds - The `PetscDS` defined on the given region, or `NULL`
5944: - dsIn - The `PetscDS` for input in the given region, or `NULL`
5946: Level: advanced
5948: .seealso: [](ch_dmbase), `DM`, `DMGetRegionDS()`, `DMSetRegionDS()`, `DMGetDS()`, `DMGetCellDS()`
5949: @*/
5950: PetscErrorCode DMGetRegionNumDS(DM dm, PetscInt num, DMLabel *label, IS *fields, PetscDS *ds, PetscDS *dsIn)
5951: {
5952: PetscInt Nds;
5954: PetscFunctionBegin;
5956: PetscCall(DMGetNumDS(dm, &Nds));
5957: PetscCheck((num >= 0) && (num < Nds), PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Region number %" PetscInt_FMT " is not in [0, %" PetscInt_FMT ")", num, Nds);
5958: if (label) {
5959: PetscAssertPointer(label, 3);
5960: *label = dm->probs[num].label;
5961: }
5962: if (fields) {
5963: PetscAssertPointer(fields, 4);
5964: *fields = dm->probs[num].fields;
5965: }
5966: if (ds) {
5967: PetscAssertPointer(ds, 5);
5968: *ds = dm->probs[num].ds;
5969: }
5970: if (dsIn) {
5971: PetscAssertPointer(dsIn, 6);
5972: *dsIn = dm->probs[num].dsIn;
5973: }
5974: PetscFunctionReturn(PETSC_SUCCESS);
5975: }
5977: /*@
5978: DMSetRegionNumDS - Set the `PetscDS` for a given mesh region, defined by the region number
5980: Not Collective
5982: Input Parameters:
5983: + dm - The `DM`
5984: . num - The region number, in [0, Nds)
5985: . label - The region label, or `NULL`
5986: . fields - The `IS` containing the `DM` field numbers for the fields in this `PetscDS`, or `NULL` to prevent setting
5987: . ds - The `PetscDS` defined on the given region, or `NULL` to prevent setting
5988: - dsIn - The `PetscDS` for input on the given cell, or `NULL` if it is the same `PetscDS`
5990: Level: advanced
5992: .seealso: [](ch_dmbase), `DM`, `DMGetRegionDS()`, `DMSetRegionDS()`, `DMGetDS()`, `DMGetCellDS()`
5993: @*/
5994: PetscErrorCode DMSetRegionNumDS(DM dm, PetscInt num, DMLabel label, IS fields, PetscDS ds, PetscDS dsIn)
5995: {
5996: PetscInt Nds;
5998: PetscFunctionBegin;
6001: PetscCall(DMGetNumDS(dm, &Nds));
6002: PetscCheck((num >= 0) && (num < Nds), PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Region number %" PetscInt_FMT " is not in [0, %" PetscInt_FMT ")", num, Nds);
6003: PetscCall(PetscObjectReference((PetscObject)label));
6004: PetscCall(DMLabelDestroy(&dm->probs[num].label));
6005: dm->probs[num].label = label;
6006: if (fields) {
6008: PetscCall(PetscObjectReference((PetscObject)fields));
6009: PetscCall(ISDestroy(&dm->probs[num].fields));
6010: dm->probs[num].fields = fields;
6011: }
6012: if (ds) {
6014: PetscCall(PetscObjectReference((PetscObject)ds));
6015: PetscCall(PetscDSDestroy(&dm->probs[num].ds));
6016: dm->probs[num].ds = ds;
6017: }
6018: if (dsIn) {
6020: PetscCall(PetscObjectReference((PetscObject)dsIn));
6021: PetscCall(PetscDSDestroy(&dm->probs[num].dsIn));
6022: dm->probs[num].dsIn = dsIn;
6023: }
6024: PetscFunctionReturn(PETSC_SUCCESS);
6025: }
6027: /*@
6028: DMFindRegionNum - Find the region number for a given `PetscDS`, or -1 if it is not found.
6030: Not Collective
6032: Input Parameters:
6033: + dm - The `DM`
6034: - ds - The `PetscDS` defined on the given region
6036: Output Parameter:
6037: . num - The region number, in [0, Nds), or -1 if not found
6039: Level: advanced
6041: .seealso: [](ch_dmbase), `DM`, `DMGetRegionNumDS()`, `DMGetRegionDS()`, `DMSetRegionDS()`, `DMGetDS()`, `DMGetCellDS()`
6042: @*/
6043: PetscErrorCode DMFindRegionNum(DM dm, PetscDS ds, PetscInt *num)
6044: {
6045: PetscInt Nds, n;
6047: PetscFunctionBegin;
6050: PetscAssertPointer(num, 3);
6051: PetscCall(DMGetNumDS(dm, &Nds));
6052: for (n = 0; n < Nds; ++n)
6053: if (ds == dm->probs[n].ds) break;
6054: if (n >= Nds) *num = -1;
6055: else *num = n;
6056: PetscFunctionReturn(PETSC_SUCCESS);
6057: }
6059: /*@
6060: DMCreateFEDefault - Create a `PetscFE` based on the celltype for the mesh
6062: Not Collective
6064: Input Parameters:
6065: + dm - The `DM`
6066: . Nc - The number of components for the field
6067: . prefix - The options prefix for the output `PetscFE`, or `NULL`
6068: - qorder - The quadrature order or `PETSC_DETERMINE` to use `PetscSpace` polynomial degree
6070: Output Parameter:
6071: . fem - The `PetscFE`
6073: Level: intermediate
6075: Note:
6076: This is a convenience method that just calls `PetscFECreateByCell()` underneath.
6078: .seealso: [](ch_dmbase), `DM`, `PetscFECreateByCell()`, `DMAddField()`, `DMCreateDS()`, `DMGetCellDS()`, `DMGetRegionDS()`
6079: @*/
6080: PetscErrorCode DMCreateFEDefault(DM dm, PetscInt Nc, const char prefix[], PetscInt qorder, PetscFE *fem)
6081: {
6082: DMPolytopeType ct;
6083: PetscInt dim, cStart;
6085: PetscFunctionBegin;
6088: if (prefix) PetscAssertPointer(prefix, 3);
6090: PetscAssertPointer(fem, 5);
6091: PetscCall(DMGetDimension(dm, &dim));
6092: PetscCall(DMPlexGetHeightStratum(dm, 0, &cStart, NULL));
6093: PetscCall(DMPlexGetCellType(dm, cStart, &ct));
6094: PetscCall(PetscFECreateByCell(PETSC_COMM_SELF, dim, Nc, ct, prefix, qorder, fem));
6095: PetscFunctionReturn(PETSC_SUCCESS);
6096: }
6098: /*@
6099: DMCreateDS - Create the discrete systems for the `DM` based upon the fields added to the `DM`
6101: Collective
6103: Input Parameter:
6104: . dm - The `DM`
6106: Options Database Key:
6107: . -dm_petscds_view - View all the `PetscDS` objects in this `DM`
6109: Level: intermediate
6111: Developer Note:
6112: The name of this function is wrong. Create functions always return the created object as one of the arguments.
6114: .seealso: [](ch_dmbase), `DM`, `DMSetField`, `DMAddField()`, `DMGetDS()`, `DMGetCellDS()`, `DMGetRegionDS()`, `DMSetRegionDS()`
6115: @*/
6116: PetscErrorCode DMCreateDS(DM dm)
6117: {
6118: MPI_Comm comm;
6119: PetscDS dsDef;
6120: DMLabel *labelSet;
6121: PetscInt dE, Nf = dm->Nf, f, s, Nl, l, Ndef, k;
6122: PetscBool doSetup = PETSC_TRUE, flg;
6124: PetscFunctionBegin;
6126: if (!dm->fields) PetscFunctionReturn(PETSC_SUCCESS);
6127: PetscCall(PetscObjectGetComm((PetscObject)dm, &comm));
6128: PetscCall(DMGetCoordinateDim(dm, &dE));
6129: // Create nullspace constructor slots
6130: PetscCall(PetscFree2(dm->nullspaceConstructors, dm->nearnullspaceConstructors));
6131: PetscCall(PetscCalloc2(Nf, &dm->nullspaceConstructors, Nf, &dm->nearnullspaceConstructors));
6132: /* Determine how many regions we have */
6133: PetscCall(PetscMalloc1(Nf, &labelSet));
6134: Nl = 0;
6135: Ndef = 0;
6136: for (f = 0; f < Nf; ++f) {
6137: DMLabel label = dm->fields[f].label;
6138: PetscInt l;
6140: #if PetscDefined(HAVE_LIBCEED)
6141: /* Move CEED context to discretizations */
6142: {
6143: PetscClassId id;
6145: PetscCall(PetscObjectGetClassId(dm->fields[f].disc, &id));
6146: if (id == PETSCFE_CLASSID) {
6147: Ceed ceed;
6149: PetscCall(DMGetCeed(dm, &ceed));
6150: PetscCall(PetscFESetCeed((PetscFE)dm->fields[f].disc, ceed));
6151: }
6152: }
6153: #endif
6154: if (!label) {
6155: ++Ndef;
6156: continue;
6157: }
6158: for (l = 0; l < Nl; ++l)
6159: if (label == labelSet[l]) break;
6160: if (l < Nl) continue;
6161: labelSet[Nl++] = label;
6162: }
6163: /* Create default DS if there are no labels to intersect with */
6164: PetscCall(DMGetRegionDS(dm, NULL, NULL, &dsDef, NULL));
6165: if (!dsDef && Ndef && !Nl) {
6166: IS fields;
6167: PetscInt *fld, nf;
6169: for (f = 0, nf = 0; f < Nf; ++f)
6170: if (!dm->fields[f].label) ++nf;
6171: PetscCheck(nf, comm, PETSC_ERR_PLIB, "All fields have labels, but we are trying to create a default DS");
6172: PetscCall(PetscMalloc1(nf, &fld));
6173: for (f = 0, nf = 0; f < Nf; ++f)
6174: if (!dm->fields[f].label) fld[nf++] = f;
6175: PetscCall(ISCreate(PETSC_COMM_SELF, &fields));
6176: PetscCall(PetscObjectSetOptionsPrefix((PetscObject)fields, "dm_fields_"));
6177: PetscCall(ISSetType(fields, ISGENERAL));
6178: PetscCall(ISGeneralSetIndices(fields, nf, fld, PETSC_OWN_POINTER));
6180: PetscCall(PetscDSCreate(PETSC_COMM_SELF, &dsDef));
6181: PetscCall(DMSetRegionDS(dm, NULL, fields, dsDef, NULL));
6182: PetscCall(PetscDSDestroy(&dsDef));
6183: PetscCall(ISDestroy(&fields));
6184: }
6185: PetscCall(DMGetRegionDS(dm, NULL, NULL, &dsDef, NULL));
6186: if (dsDef) PetscCall(PetscDSSetCoordinateDimension(dsDef, dE));
6187: /* Intersect labels with default fields */
6188: if (Ndef && Nl) {
6189: DM plex;
6190: DMLabel cellLabel;
6191: IS fieldIS, allcellIS, defcellIS = NULL;
6192: PetscInt *fields;
6193: const PetscInt *cells;
6194: PetscInt depth, nf = 0, n, c;
6196: PetscCall(DMConvert(dm, DMPLEX, &plex));
6197: PetscCall(DMPlexGetDepth(plex, &depth));
6198: PetscCall(DMGetStratumIS(plex, "dim", depth, &allcellIS));
6199: if (!allcellIS) PetscCall(DMGetStratumIS(plex, "depth", depth, &allcellIS));
6200: /* TODO This looks like it only works for one label */
6201: for (l = 0; l < Nl; ++l) {
6202: DMLabel label = labelSet[l];
6203: IS pointIS;
6205: PetscCall(ISDestroy(&defcellIS));
6206: PetscCall(DMLabelGetStratumIS(label, 1, &pointIS));
6207: PetscCall(ISDifference(allcellIS, pointIS, &defcellIS));
6208: PetscCall(ISDestroy(&pointIS));
6209: }
6210: PetscCall(ISDestroy(&allcellIS));
6212: PetscCall(DMLabelCreate(PETSC_COMM_SELF, "defaultCells", &cellLabel));
6213: PetscCall(ISGetLocalSize(defcellIS, &n));
6214: PetscCall(ISGetIndices(defcellIS, &cells));
6215: for (c = 0; c < n; ++c) PetscCall(DMLabelSetValue(cellLabel, cells[c], 1));
6216: PetscCall(ISRestoreIndices(defcellIS, &cells));
6217: PetscCall(ISDestroy(&defcellIS));
6218: PetscCall(DMPlexLabelComplete(plex, cellLabel));
6220: PetscCall(PetscMalloc1(Ndef, &fields));
6221: for (f = 0; f < Nf; ++f)
6222: if (!dm->fields[f].label) fields[nf++] = f;
6223: PetscCall(ISCreate(PETSC_COMM_SELF, &fieldIS));
6224: PetscCall(PetscObjectSetOptionsPrefix((PetscObject)fieldIS, "dm_fields_"));
6225: PetscCall(ISSetType(fieldIS, ISGENERAL));
6226: PetscCall(ISGeneralSetIndices(fieldIS, nf, fields, PETSC_OWN_POINTER));
6228: PetscCall(PetscDSCreate(PETSC_COMM_SELF, &dsDef));
6229: PetscCall(DMSetRegionDS(dm, cellLabel, fieldIS, dsDef, NULL));
6230: PetscCall(PetscDSSetCoordinateDimension(dsDef, dE));
6231: PetscCall(DMLabelDestroy(&cellLabel));
6232: PetscCall(PetscDSDestroy(&dsDef));
6233: PetscCall(ISDestroy(&fieldIS));
6234: PetscCall(DMDestroy(&plex));
6235: }
6236: /* Create label DSes
6237: - WE ONLY SUPPORT IDENTICAL OR DISJOINT LABELS
6238: */
6239: /* TODO Should check that labels are disjoint */
6240: for (l = 0; l < Nl; ++l) {
6241: DMLabel label = labelSet[l];
6242: PetscDS ds, dsIn = NULL;
6243: IS fields;
6244: PetscInt *fld, nf;
6246: PetscCall(PetscDSCreate(PETSC_COMM_SELF, &ds));
6247: for (f = 0, nf = 0; f < Nf; ++f)
6248: if (label == dm->fields[f].label || !dm->fields[f].label) ++nf;
6249: PetscCall(PetscMalloc1(nf, &fld));
6250: for (f = 0, nf = 0; f < Nf; ++f)
6251: if (label == dm->fields[f].label || !dm->fields[f].label) fld[nf++] = f;
6252: PetscCall(ISCreate(PETSC_COMM_SELF, &fields));
6253: PetscCall(PetscObjectSetOptionsPrefix((PetscObject)fields, "dm_fields_"));
6254: PetscCall(ISSetType(fields, ISGENERAL));
6255: PetscCall(ISGeneralSetIndices(fields, nf, fld, PETSC_OWN_POINTER));
6256: PetscCall(PetscDSSetCoordinateDimension(ds, dE));
6257: {
6258: DMPolytopeType ct;
6259: PetscInt lStart, lEnd;
6260: PetscBool isCohesive = PETSC_FALSE;
6262: PetscCall(DMLabelGetBounds(label, &lStart, &lEnd));
6263: if (lStart >= 0) {
6264: PetscCall(DMPlexGetCellType(dm, lStart, &ct));
6265: switch (ct) {
6266: case DM_POLYTOPE_POINT_PRISM_TENSOR:
6267: case DM_POLYTOPE_SEG_PRISM_TENSOR:
6268: case DM_POLYTOPE_TRI_PRISM_TENSOR:
6269: case DM_POLYTOPE_QUAD_PRISM_TENSOR:
6270: isCohesive = PETSC_TRUE;
6271: break;
6272: default:
6273: break;
6274: }
6275: }
6276: PetscCallMPI(MPIU_Allreduce(MPI_IN_PLACE, &isCohesive, 1, MPI_C_BOOL, MPI_LOR, comm));
6277: if (isCohesive) {
6278: PetscCall(PetscDSCreate(PETSC_COMM_SELF, &dsIn));
6279: PetscCall(PetscDSSetCoordinateDimension(dsIn, dE));
6280: }
6281: for (f = 0, nf = 0; f < Nf; ++f) {
6282: if (label == dm->fields[f].label || !dm->fields[f].label) {
6283: if (label == dm->fields[f].label) {
6284: PetscCall(PetscDSSetDiscretization(ds, nf, NULL));
6285: PetscCall(PetscDSSetCohesive(ds, nf, isCohesive));
6286: if (dsIn) {
6287: PetscCall(PetscDSSetDiscretization(dsIn, nf, NULL));
6288: PetscCall(PetscDSSetCohesive(dsIn, nf, isCohesive));
6289: }
6290: }
6291: ++nf;
6292: }
6293: }
6294: }
6295: PetscCall(DMSetRegionDS(dm, label, fields, ds, dsIn));
6296: PetscCall(ISDestroy(&fields));
6297: PetscCall(PetscDSDestroy(&ds));
6298: PetscCall(PetscDSDestroy(&dsIn));
6299: }
6300: PetscCall(PetscFree(labelSet));
6301: /* Set fields in DSes */
6302: for (s = 0; s < dm->Nds; ++s) {
6303: PetscDS ds = dm->probs[s].ds;
6304: PetscDS dsIn = dm->probs[s].dsIn;
6305: IS fields = dm->probs[s].fields;
6306: const PetscInt *fld;
6307: PetscInt nf, dsnf;
6308: PetscBool isCohesive;
6310: PetscCall(PetscDSGetNumFields(ds, &dsnf));
6311: PetscCall(PetscDSIsCohesive(ds, &isCohesive));
6312: PetscCall(ISGetLocalSize(fields, &nf));
6313: PetscCall(ISGetIndices(fields, &fld));
6314: for (f = 0; f < nf; ++f) {
6315: PetscObject disc = dm->fields[fld[f]].disc;
6316: PetscBool isCohesiveField;
6317: PetscClassId id;
6319: /* Handle DS with no fields */
6320: if (dsnf) PetscCall(PetscDSGetCohesive(ds, f, &isCohesiveField));
6321: /* If this is a cohesive cell, then regular fields need the lower dimensional discretization */
6322: if (isCohesive) {
6323: if (!isCohesiveField) {
6324: PetscObject bdDisc;
6326: PetscCall(PetscFEGetHeightSubspace((PetscFE)disc, 1, (PetscFE *)&bdDisc));
6327: PetscCall(PetscDSSetDiscretization(ds, f, bdDisc));
6328: PetscCall(PetscDSSetDiscretization(dsIn, f, disc));
6329: } else {
6330: PetscCall(PetscDSSetDiscretization(ds, f, disc));
6331: PetscCall(PetscDSSetDiscretization(dsIn, f, disc));
6332: }
6333: } else {
6334: PetscCall(PetscDSSetDiscretization(ds, f, disc));
6335: }
6336: /* We allow people to have placeholder fields and construct the Section by hand */
6337: PetscCall(PetscObjectGetClassId(disc, &id));
6338: if ((id != PETSCFE_CLASSID) && (id != PETSCFV_CLASSID)) doSetup = PETSC_FALSE;
6339: }
6340: PetscCall(ISRestoreIndices(fields, &fld));
6341: }
6342: /* Allow k-jet tabulation */
6343: PetscCall(PetscOptionsGetInt(NULL, ((PetscObject)dm)->prefix, "-dm_ds_jet_degree", &k, &flg));
6344: if (flg) {
6345: for (s = 0; s < dm->Nds; ++s) {
6346: PetscDS ds = dm->probs[s].ds;
6347: PetscDS dsIn = dm->probs[s].dsIn;
6348: PetscInt Nf;
6350: PetscCall(PetscDSGetNumFields(ds, &Nf));
6351: for (PetscInt f = 0; f < Nf; ++f) {
6352: PetscCall(PetscDSSetJetDegree(ds, f, k));
6353: if (dsIn) PetscCall(PetscDSSetJetDegree(dsIn, f, k));
6354: }
6355: }
6356: }
6357: /* Setup DSes */
6358: if (doSetup) {
6359: for (s = 0; s < dm->Nds; ++s) {
6360: if (dm->setfromoptionscalled) {
6361: PetscCall(PetscDSSetFromOptions(dm->probs[s].ds));
6362: if (dm->probs[s].dsIn) PetscCall(PetscDSSetFromOptions(dm->probs[s].dsIn));
6363: }
6364: PetscCall(PetscDSSetUp(dm->probs[s].ds));
6365: if (dm->probs[s].dsIn) PetscCall(PetscDSSetUp(dm->probs[s].dsIn));
6366: }
6367: }
6368: PetscFunctionReturn(PETSC_SUCCESS);
6369: }
6371: /*@
6372: DMUseTensorOrder - Use a tensor product closure ordering for the default section
6374: Input Parameters:
6375: + dm - The DM
6376: - tensor - Flag for tensor order
6378: Level: developer
6380: .seealso: `DMPlexSetClosurePermutationTensor()`, `PetscSectionResetClosurePermutation()`
6381: @*/
6382: PetscErrorCode DMUseTensorOrder(DM dm, PetscBool tensor)
6383: {
6384: PetscInt Nf;
6385: PetscBool reorder = PETSC_TRUE, isPlex;
6387: PetscFunctionBegin;
6388: PetscCall(PetscObjectTypeCompare((PetscObject)dm, DMPLEX, &isPlex));
6389: PetscCall(DMGetNumFields(dm, &Nf));
6390: for (PetscInt f = 0; f < Nf; ++f) {
6391: PetscObject obj;
6392: PetscClassId id;
6394: PetscCall(DMGetField(dm, f, NULL, &obj));
6395: PetscCall(PetscObjectGetClassId(obj, &id));
6396: if (id == PETSCFE_CLASSID) {
6397: PetscSpace sp;
6398: PetscBool tensor;
6400: PetscCall(PetscFEGetBasisSpace((PetscFE)obj, &sp));
6401: PetscCall(PetscSpacePolynomialGetTensor(sp, &tensor));
6402: reorder = reorder && tensor ? PETSC_TRUE : PETSC_FALSE;
6403: } else reorder = PETSC_FALSE;
6404: }
6405: if (tensor) {
6406: if (reorder && isPlex) PetscCall(DMPlexSetClosurePermutationTensor(dm, PETSC_DETERMINE, NULL));
6407: } else {
6408: PetscSection s;
6410: PetscCall(DMGetLocalSection(dm, &s));
6411: if (s) PetscCall(PetscSectionResetClosurePermutation(s));
6412: }
6413: PetscFunctionReturn(PETSC_SUCCESS);
6414: }
6416: /*@
6417: DMComputeExactSolution - Compute the exact solution for a given `DM`, using the `PetscDS` information.
6419: Collective
6421: Input Parameters:
6422: + dm - The `DM`
6423: - time - The time
6425: Output Parameters:
6426: + u - The vector will be filled with exact solution values, or `NULL`
6427: - u_t - The vector will be filled with the time derivative of exact solution values, or `NULL`
6429: Level: developer
6431: Note:
6432: The user must call `PetscDSSetExactSolution()` before using this routine
6434: .seealso: [](ch_dmbase), `DM`, `PetscDSSetExactSolution()`
6435: @*/
6436: PetscErrorCode DMComputeExactSolution(DM dm, PetscReal time, Vec u, Vec u_t)
6437: {
6438: PetscErrorCode (**exacts)(PetscInt, PetscReal, const PetscReal x[], PetscInt, PetscScalar *u, PetscCtx ctx);
6439: void **ectxs;
6440: Vec locu, locu_t;
6441: PetscInt Nf, Nds, s;
6443: PetscFunctionBegin;
6445: if (u) {
6447: PetscCall(DMGetLocalVector(dm, &locu));
6448: PetscCall(VecSet(locu, 0.));
6449: }
6450: if (u_t) {
6452: PetscCall(DMGetLocalVector(dm, &locu_t));
6453: PetscCall(VecSet(locu_t, 0.));
6454: }
6455: PetscCall(DMGetNumFields(dm, &Nf));
6456: PetscCall(PetscMalloc2(Nf, &exacts, Nf, &ectxs));
6457: PetscCall(DMGetNumDS(dm, &Nds));
6458: for (s = 0; s < Nds; ++s) {
6459: PetscDS ds;
6460: DMLabel label;
6461: IS fieldIS;
6462: const PetscInt *fields, id = 1;
6463: PetscInt dsNf;
6465: PetscCall(DMGetRegionNumDS(dm, s, &label, &fieldIS, &ds, NULL));
6466: PetscCall(PetscDSGetNumFields(ds, &dsNf));
6467: PetscCall(ISGetIndices(fieldIS, &fields));
6468: PetscCall(PetscArrayzero(exacts, Nf));
6469: PetscCall(PetscArrayzero(ectxs, Nf));
6470: if (u) {
6471: for (PetscInt f = 0; f < dsNf; ++f) PetscCall(PetscDSGetExactSolution(ds, fields[f], &exacts[fields[f]], &ectxs[fields[f]]));
6472: if (label) PetscCall(DMProjectFunctionLabelLocal(dm, time, label, 1, &id, 0, NULL, exacts, ectxs, INSERT_ALL_VALUES, locu));
6473: else PetscCall(DMProjectFunctionLocal(dm, time, exacts, ectxs, INSERT_ALL_VALUES, locu));
6474: }
6475: if (u_t) {
6476: PetscCall(PetscArrayzero(exacts, Nf));
6477: PetscCall(PetscArrayzero(ectxs, Nf));
6478: for (PetscInt f = 0; f < dsNf; ++f) PetscCall(PetscDSGetExactSolutionTimeDerivative(ds, fields[f], &exacts[fields[f]], &ectxs[fields[f]]));
6479: if (label) PetscCall(DMProjectFunctionLabelLocal(dm, time, label, 1, &id, 0, NULL, exacts, ectxs, INSERT_ALL_VALUES, locu_t));
6480: else PetscCall(DMProjectFunctionLocal(dm, time, exacts, ectxs, INSERT_ALL_VALUES, locu_t));
6481: }
6482: PetscCall(ISRestoreIndices(fieldIS, &fields));
6483: }
6484: if (u) {
6485: PetscCall(PetscObjectSetName((PetscObject)u, "Exact Solution"));
6486: PetscCall(PetscObjectSetOptionsPrefix((PetscObject)u, "exact_"));
6487: }
6488: if (u_t) {
6489: PetscCall(PetscObjectSetName((PetscObject)u, "Exact Solution Time Derivative"));
6490: PetscCall(PetscObjectSetOptionsPrefix((PetscObject)u_t, "exact_t_"));
6491: }
6492: PetscCall(PetscFree2(exacts, ectxs));
6493: if (u) {
6494: PetscCall(DMLocalToGlobalBegin(dm, locu, INSERT_ALL_VALUES, u));
6495: PetscCall(DMLocalToGlobalEnd(dm, locu, INSERT_ALL_VALUES, u));
6496: PetscCall(DMRestoreLocalVector(dm, &locu));
6497: }
6498: if (u_t) {
6499: PetscCall(DMLocalToGlobalBegin(dm, locu_t, INSERT_ALL_VALUES, u_t));
6500: PetscCall(DMLocalToGlobalEnd(dm, locu_t, INSERT_ALL_VALUES, u_t));
6501: PetscCall(DMRestoreLocalVector(dm, &locu_t));
6502: }
6503: PetscFunctionReturn(PETSC_SUCCESS);
6504: }
6506: static PetscErrorCode DMTransferDS_Internal(DM dm, DMLabel label, IS fields, PetscInt minDegree, PetscInt maxDegree, PetscDS ds, PetscDS dsIn)
6507: {
6508: PetscDS dsNew, dsInNew = NULL;
6510: PetscFunctionBegin;
6511: PetscCall(PetscDSCreate(PetscObjectComm((PetscObject)ds), &dsNew));
6512: PetscCall(PetscDSCopy(ds, minDegree, maxDegree, dm, dsNew));
6513: if (dsIn) {
6514: PetscCall(PetscDSCreate(PetscObjectComm((PetscObject)dsIn), &dsInNew));
6515: PetscCall(PetscDSCopy(dsIn, minDegree, maxDegree, dm, dsInNew));
6516: }
6517: PetscCall(DMSetRegionDS(dm, label, fields, dsNew, dsInNew));
6518: PetscCall(PetscDSDestroy(&dsNew));
6519: PetscCall(PetscDSDestroy(&dsInNew));
6520: PetscFunctionReturn(PETSC_SUCCESS);
6521: }
6523: /*@
6524: DMCopyDS - Copy the discrete systems for the `DM` into another `DM`
6526: Collective
6528: Input Parameters:
6529: + dm - The `DM`
6530: . minDegree - Minimum degree for a discretization, or `PETSC_DETERMINE` for no limit
6531: - maxDegree - Maximum degree for a discretization, or `PETSC_DETERMINE` for no limit
6533: Output Parameter:
6534: . newdm - The `DM`
6536: Level: advanced
6538: .seealso: [](ch_dmbase), `DM`, `DMCopyFields()`, `DMAddField()`, `DMGetDS()`, `DMGetCellDS()`, `DMGetRegionDS()`, `DMSetRegionDS()`
6539: @*/
6540: PetscErrorCode DMCopyDS(DM dm, PetscInt minDegree, PetscInt maxDegree, DM newdm)
6541: {
6542: PetscInt Nds;
6544: PetscFunctionBegin;
6545: if (dm == newdm) PetscFunctionReturn(PETSC_SUCCESS);
6546: PetscCall(DMGetNumDS(dm, &Nds));
6547: PetscCall(DMClearDS(newdm));
6548: for (PetscInt s = 0; s < Nds; ++s) {
6549: DMLabel label;
6550: IS fields;
6551: PetscDS ds, dsIn, newds;
6552: PetscInt Nbd;
6554: PetscCall(DMGetRegionNumDS(dm, s, &label, &fields, &ds, &dsIn));
6555: /* TODO: We need to change all keys from labels in the old DM to labels in the new DM */
6556: PetscCall(DMTransferDS_Internal(newdm, label, fields, minDegree, maxDegree, ds, dsIn));
6557: /* Complete new labels in the new DS */
6558: PetscCall(DMGetRegionDS(newdm, label, NULL, &newds, NULL));
6559: PetscCall(PetscDSGetNumBoundary(newds, &Nbd));
6560: for (PetscInt bd = 0; bd < Nbd; ++bd) {
6561: PetscWeakForm wf;
6562: DMLabel label;
6563: PetscInt field;
6565: PetscCall(PetscDSGetBoundary(newds, bd, &wf, NULL, NULL, &label, NULL, NULL, &field, NULL, NULL, NULL, NULL, NULL));
6566: PetscCall(PetscWeakFormReplaceLabel(wf, label));
6567: }
6568: }
6569: PetscCall(DMCompleteBCLabels_Internal(newdm));
6570: PetscFunctionReturn(PETSC_SUCCESS);
6571: }
6573: /*@
6574: DMCopyDisc - Copy the fields and discrete systems for the `DM` into another `DM`
6576: Collective
6578: Input Parameter:
6579: . dm - The `DM`
6581: Output Parameter:
6582: . newdm - The `DM`
6584: Level: advanced
6586: Developer Note:
6587: Really ugly name, nothing in PETSc is called a `Disc` plus it is an ugly abbreviation
6589: .seealso: [](ch_dmbase), `DM`, `DMCopyFields()`, `DMCopyDS()`
6590: @*/
6591: PetscErrorCode DMCopyDisc(DM dm, DM newdm)
6592: {
6593: PetscFunctionBegin;
6594: PetscCall(DMCopyFields(dm, PETSC_DETERMINE, PETSC_DETERMINE, newdm));
6595: PetscCall(DMCopyDS(dm, PETSC_DETERMINE, PETSC_DETERMINE, newdm));
6596: PetscFunctionReturn(PETSC_SUCCESS);
6597: }
6599: /*@
6600: DMGetDimension - Return the topological dimension of the `DM`
6602: Not Collective
6604: Input Parameter:
6605: . dm - The `DM`
6607: Output Parameter:
6608: . dim - The topological dimension
6610: Level: beginner
6612: .seealso: [](ch_dmbase), `DM`, `DMSetDimension()`, `DMCreate()`
6613: @*/
6614: PetscErrorCode DMGetDimension(DM dm, PetscInt *dim)
6615: {
6616: PetscFunctionBegin;
6618: PetscAssertPointer(dim, 2);
6619: *dim = dm->dim;
6620: PetscFunctionReturn(PETSC_SUCCESS);
6621: }
6623: /*@
6624: DMSetDimension - Set the topological dimension of the `DM`
6626: Collective
6628: Input Parameters:
6629: + dm - The `DM`
6630: - dim - The topological dimension
6632: Level: beginner
6634: .seealso: [](ch_dmbase), `DM`, `DMGetDimension()`, `DMCreate()`
6635: @*/
6636: PetscErrorCode DMSetDimension(DM dm, PetscInt dim)
6637: {
6638: PetscDS ds;
6639: PetscInt Nds;
6641: PetscFunctionBegin;
6644: if (dm->dim != dim) PetscCall(DMSetPeriodicity(dm, NULL, NULL, NULL));
6645: dm->dim = dim;
6646: if (dm->dim >= 0) {
6647: PetscCall(DMGetNumDS(dm, &Nds));
6648: for (PetscInt n = 0; n < Nds; ++n) {
6649: PetscCall(DMGetRegionNumDS(dm, n, NULL, NULL, &ds, NULL));
6650: if (ds->dimEmbed < 0) PetscCall(PetscDSSetCoordinateDimension(ds, dim));
6651: }
6652: }
6653: PetscFunctionReturn(PETSC_SUCCESS);
6654: }
6656: /*@
6657: DMGetDimPoints - Get the half-open interval for all points of a given dimension
6659: Collective
6661: Input Parameters:
6662: + dm - the `DM`
6663: - dim - the dimension
6665: Output Parameters:
6666: + pStart - The first point of the given dimension
6667: - pEnd - The first point following points of the given dimension
6669: Level: intermediate
6671: Note:
6672: The points are vertices in the Hasse diagram encoding the topology. This is explained in
6673: https://arxiv.org/abs/0908.4427. If no points exist of this dimension in the storage scheme,
6674: then the interval is empty.
6676: .seealso: [](ch_dmbase), `DM`, `DMPLEX`, `DMPlexGetDepthStratum()`, `DMPlexGetHeightStratum()`
6677: @*/
6678: PetscErrorCode DMGetDimPoints(DM dm, PetscInt dim, PetscInt *pStart, PetscInt *pEnd)
6679: {
6680: PetscInt d;
6682: PetscFunctionBegin;
6684: PetscCall(DMGetDimension(dm, &d));
6685: PetscCheck((dim >= 0) && (dim <= d), PetscObjectComm((PetscObject)dm), PETSC_ERR_ARG_OUTOFRANGE, "Invalid dimension %" PetscInt_FMT, dim);
6686: PetscUseTypeMethod(dm, getdimpoints, dim, pStart, pEnd);
6687: PetscFunctionReturn(PETSC_SUCCESS);
6688: }
6690: /*@
6691: DMGetOutputDM - Retrieve the `DM` associated with the layout for output
6693: Collective
6695: Input Parameter:
6696: . dm - The original `DM`
6698: Output Parameter:
6699: . odm - The `DM` which provides the layout for output
6701: Level: intermediate
6703: Note:
6704: In some situations the vector obtained with `DMCreateGlobalVector()` excludes points for degrees of freedom that are associated with fixed (Dirichelet) boundary
6705: conditions since the algebraic solver does not solve for those variables. The output `DM` includes these excluded points and its global vector contains the
6706: locations for those dof so that they can be output to a file or other viewer along with the unconstrained dof.
6708: .seealso: [](ch_dmbase), `DM`, `VecView()`, `DMGetGlobalSection()`, `DMCreateGlobalVector()`, `PetscSectionHasConstraints()`, `DMSetGlobalSection()`
6709: @*/
6710: PetscErrorCode DMGetOutputDM(DM dm, DM *odm)
6711: {
6712: PetscSection section;
6713: IS perm;
6714: PetscBool hasConstraints, newDM;
6715: PetscInt num_face_sfs = 0;
6717: PetscFunctionBegin;
6719: PetscAssertPointer(odm, 2);
6720: PetscCall(DMGetLocalSection(dm, §ion));
6721: PetscCall(PetscSectionHasConstraints(section, &hasConstraints));
6722: PetscCall(PetscSectionGetPermutation(section, &perm));
6723: PetscCall(DMPlexGetIsoperiodicFaceSF(dm, &num_face_sfs, NULL));
6724: newDM = hasConstraints || perm || (num_face_sfs > 0) ? PETSC_TRUE : PETSC_FALSE;
6725: PetscCallMPI(MPIU_Allreduce(MPI_IN_PLACE, &newDM, 1, MPI_C_BOOL, MPI_LOR, PetscObjectComm((PetscObject)dm)));
6726: if (!newDM) {
6727: *odm = dm;
6728: PetscFunctionReturn(PETSC_SUCCESS);
6729: }
6730: if (!dm->dmBC) {
6731: PetscSection newSection, gsection;
6732: PetscSF sf, sfNatural;
6733: PetscBool usePerm = dm->ignorePermOutput ? PETSC_FALSE : PETSC_TRUE;
6735: PetscCall(DMClone(dm, &dm->dmBC));
6736: PetscCall(DMCopyDisc(dm, dm->dmBC));
6737: PetscCall(PetscSectionClone(section, &newSection));
6738: PetscCall(DMSetLocalSection(dm->dmBC, newSection));
6739: PetscCall(PetscSectionDestroy(&newSection));
6740: PetscCall(DMGetNaturalSF(dm, &sfNatural));
6741: PetscCall(DMSetNaturalSF(dm->dmBC, sfNatural));
6742: PetscCall(DMGetPointSF(dm->dmBC, &sf));
6743: PetscCall(PetscSectionCreateGlobalSection(section, sf, usePerm, PETSC_TRUE, PETSC_FALSE, &gsection));
6744: PetscCall(DMSetGlobalSection(dm->dmBC, gsection));
6745: PetscCall(PetscSectionDestroy(&gsection));
6746: }
6747: *odm = dm->dmBC;
6748: PetscFunctionReturn(PETSC_SUCCESS);
6749: }
6751: /*@
6752: DMGetOutputSequenceNumber - Retrieve the sequence number/value for output
6754: Input Parameter:
6755: . dm - The original `DM`
6757: Output Parameters:
6758: + num - The output sequence number
6759: - val - The output sequence value
6761: Level: intermediate
6763: Note:
6764: This is intended for output that should appear in sequence, for instance
6765: a set of timesteps in an `PETSCVIEWERHDF5` file, or a set of realizations of a stochastic system.
6767: Developer Note:
6768: The `DM` serves as a convenient place to store the current iteration value. The iteration is not
6769: not directly related to the `DM`.
6771: .seealso: [](ch_dmbase), `DM`, `VecView()`
6772: @*/
6773: PetscErrorCode DMGetOutputSequenceNumber(DM dm, PetscInt *num, PetscReal *val)
6774: {
6775: PetscFunctionBegin;
6777: if (num) {
6778: PetscAssertPointer(num, 2);
6779: *num = dm->outputSequenceNum;
6780: }
6781: if (val) {
6782: PetscAssertPointer(val, 3);
6783: *val = dm->outputSequenceVal;
6784: }
6785: PetscFunctionReturn(PETSC_SUCCESS);
6786: }
6788: /*@
6789: DMSetOutputSequenceNumber - Set the sequence number/value for output
6791: Input Parameters:
6792: + dm - The original `DM`
6793: . num - The output sequence number
6794: - val - The output sequence value
6796: Level: intermediate
6798: Note:
6799: This is intended for output that should appear in sequence, for instance
6800: a set of timesteps in an `PETSCVIEWERHDF5` file, or a set of realizations of a stochastic system.
6802: .seealso: [](ch_dmbase), `DM`, `VecView()`
6803: @*/
6804: PetscErrorCode DMSetOutputSequenceNumber(DM dm, PetscInt num, PetscReal val)
6805: {
6806: PetscFunctionBegin;
6808: dm->outputSequenceNum = num;
6809: dm->outputSequenceVal = val;
6810: PetscFunctionReturn(PETSC_SUCCESS);
6811: }
6813: /*@
6814: DMOutputSequenceLoad - Retrieve the sequence value from a `PetscViewer`
6816: Input Parameters:
6817: + dm - The original `DM`
6818: . viewer - The `PetscViewer` to get it from
6819: . name - The sequence name
6820: - num - The output sequence number
6822: Output Parameter:
6823: . val - The output sequence value
6825: Level: intermediate
6827: Note:
6828: This is intended for output that should appear in sequence, for instance
6829: a set of timesteps in an `PETSCVIEWERHDF5` file, or a set of realizations of a stochastic system.
6831: Developer Note:
6832: It is unclear at the user API level why a `DM` is needed as input
6834: .seealso: [](ch_dmbase), `DM`, `DMGetOutputSequenceNumber()`, `DMSetOutputSequenceNumber()`, `VecView()`
6835: @*/
6836: PetscErrorCode DMOutputSequenceLoad(DM dm, PetscViewer viewer, const char name[], PetscInt num, PetscReal *val)
6837: {
6838: PetscBool ishdf5;
6840: PetscFunctionBegin;
6843: PetscAssertPointer(name, 3);
6844: PetscAssertPointer(val, 5);
6845: PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERHDF5, &ishdf5));
6846: PetscCheck(ishdf5, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Invalid viewer; open viewer with PetscViewerHDF5Open()");
6847: #if PetscDefined(HAVE_HDF5)
6848: PetscScalar value;
6850: PetscCall(DMSequenceLoad_HDF5_Internal(dm, name, num, &value, viewer));
6851: *val = PetscRealPart(value);
6852: #endif
6853: PetscFunctionReturn(PETSC_SUCCESS);
6854: }
6856: /*@
6857: DMGetOutputSequenceLength - Retrieve the number of sequence values from a `PetscViewer`
6859: Input Parameters:
6860: + dm - The original `DM`
6861: . viewer - The `PetscViewer` to get it from
6862: - name - The sequence name
6864: Output Parameter:
6865: . len - The length of the output sequence
6867: Level: intermediate
6869: Note:
6870: This is intended for output that should appear in sequence, for instance
6871: a set of timesteps in an `PETSCVIEWERHDF5` file, or a set of realizations of a stochastic system.
6873: Developer Note:
6874: It is unclear at the user API level why a `DM` is needed as input
6876: .seealso: [](ch_dmbase), `DM`, `DMGetOutputSequenceNumber()`, `DMSetOutputSequenceNumber()`, `VecView()`
6877: @*/
6878: PetscErrorCode DMGetOutputSequenceLength(DM dm, PetscViewer viewer, const char name[], PetscInt *len)
6879: {
6880: PetscBool ishdf5;
6882: PetscFunctionBegin;
6885: PetscAssertPointer(name, 3);
6886: PetscAssertPointer(len, 4);
6887: PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERHDF5, &ishdf5));
6888: PetscCheck(ishdf5, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Invalid viewer; open viewer with PetscViewerHDF5Open()");
6889: #if PetscDefined(HAVE_HDF5)
6890: PetscCall(DMSequenceGetLength_HDF5_Internal(dm, name, len, viewer));
6891: #endif
6892: PetscFunctionReturn(PETSC_SUCCESS);
6893: }
6895: /*@
6896: DMGetUseNatural - Get the flag for creating a mapping to the natural order when a `DM` is (re)distributed in parallel
6898: Not Collective
6900: Input Parameter:
6901: . dm - The `DM`
6903: Output Parameter:
6904: . useNatural - `PETSC_TRUE` to build the mapping to a natural order during distribution
6906: Level: beginner
6908: .seealso: [](ch_dmbase), `DM`, `DMSetUseNatural()`, `DMCreate()`
6909: @*/
6910: PetscErrorCode DMGetUseNatural(DM dm, PetscBool *useNatural)
6911: {
6912: PetscFunctionBegin;
6914: PetscAssertPointer(useNatural, 2);
6915: *useNatural = dm->useNatural;
6916: PetscFunctionReturn(PETSC_SUCCESS);
6917: }
6919: /*@
6920: DMSetUseNatural - Set the flag for creating a mapping to the natural order when a `DM` is (re)distributed in parallel
6922: Collective
6924: Input Parameters:
6925: + dm - The `DM`
6926: - useNatural - `PETSC_TRUE` to build the mapping to a natural order during distribution
6928: Level: beginner
6930: Note:
6931: This also causes the map to be build after `DMCreateSubDM()` and `DMCreateSuperDM()`
6933: .seealso: [](ch_dmbase), `DM`, `DMGetUseNatural()`, `DMCreate()`, `DMPlexDistribute()`, `DMCreateSubDM()`, `DMCreateSuperDM()`
6934: @*/
6935: PetscErrorCode DMSetUseNatural(DM dm, PetscBool useNatural)
6936: {
6937: PetscFunctionBegin;
6940: dm->useNatural = useNatural;
6941: PetscFunctionReturn(PETSC_SUCCESS);
6942: }
6944: /*@
6945: DMCreateLabel - Create a label of the given name if it does not already exist in the `DM`
6947: Not Collective
6949: Input Parameters:
6950: + dm - The `DM` object
6951: - name - The label name
6953: Level: intermediate
6955: .seealso: [](ch_dmbase), `DM`, `DMLabelCreate()`, `DMHasLabel()`, `DMGetLabelValue()`, `DMSetLabelValue()`, `DMGetStratumIS()`
6956: @*/
6957: PetscErrorCode DMCreateLabel(DM dm, const char name[])
6958: {
6959: PetscBool flg;
6960: DMLabel label;
6962: PetscFunctionBegin;
6964: PetscAssertPointer(name, 2);
6965: PetscCall(DMHasLabel(dm, name, &flg));
6966: if (!flg) {
6967: PetscCall(DMLabelCreate(PETSC_COMM_SELF, name, &label));
6968: PetscCall(DMAddLabel(dm, label));
6969: PetscCall(DMLabelDestroy(&label));
6970: }
6971: PetscFunctionReturn(PETSC_SUCCESS);
6972: }
6974: /*@
6975: DMCreateLabelAtIndex - Create a label of the given name at the given index. If it already exists in the `DM`, move it to this index.
6977: Not Collective
6979: Input Parameters:
6980: + dm - The `DM` object
6981: . l - The index for the label
6982: - name - The label name
6984: Level: intermediate
6986: .seealso: [](ch_dmbase), `DM`, `DMCreateLabel()`, `DMLabelCreate()`, `DMHasLabel()`, `DMGetLabelValue()`, `DMSetLabelValue()`, `DMGetStratumIS()`
6987: @*/
6988: PetscErrorCode DMCreateLabelAtIndex(DM dm, PetscInt l, const char name[])
6989: {
6990: DMLabelLink orig, prev = NULL;
6991: DMLabel label;
6992: PetscInt Nl, m;
6993: PetscBool flg, match;
6994: const char *lname;
6996: PetscFunctionBegin;
6998: PetscAssertPointer(name, 3);
6999: PetscCall(DMHasLabel(dm, name, &flg));
7000: if (!flg) {
7001: PetscCall(DMLabelCreate(PETSC_COMM_SELF, name, &label));
7002: PetscCall(DMAddLabel(dm, label));
7003: PetscCall(DMLabelDestroy(&label));
7004: }
7005: PetscCall(DMGetNumLabels(dm, &Nl));
7006: PetscCheck(l < Nl, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Label index %" PetscInt_FMT " must be in [0, %" PetscInt_FMT ")", l, Nl);
7007: for (m = 0, orig = dm->labels; m < Nl; ++m, prev = orig, orig = orig->next) {
7008: PetscCall(PetscObjectGetName((PetscObject)orig->label, &lname));
7009: PetscCall(PetscStrcmp(name, lname, &match));
7010: if (match) break;
7011: }
7012: if (m == l) PetscFunctionReturn(PETSC_SUCCESS);
7013: if (!m) dm->labels = orig->next;
7014: else prev->next = orig->next;
7015: if (!l) {
7016: orig->next = dm->labels;
7017: dm->labels = orig;
7018: } else {
7019: for (m = 0, prev = dm->labels; m < l - 1; ++m, prev = prev->next);
7020: orig->next = prev->next;
7021: prev->next = orig;
7022: }
7023: PetscFunctionReturn(PETSC_SUCCESS);
7024: }
7026: /*@
7027: DMGetLabelValue - Get the value in a `DMLabel` for the given point, with -1 as the default
7029: Not Collective
7031: Input Parameters:
7032: + dm - The `DM` object
7033: . name - The label name
7034: - point - The mesh point
7036: Output Parameter:
7037: . value - The label value for this point, or -1 if the point is not in the label
7039: Level: beginner
7041: .seealso: [](ch_dmbase), `DM`, `DMLabelGetValue()`, `DMSetLabelValue()`, `DMGetStratumIS()`
7042: @*/
7043: PetscErrorCode DMGetLabelValue(DM dm, const char name[], PetscInt point, PetscInt *value)
7044: {
7045: DMLabel label;
7047: PetscFunctionBegin;
7049: PetscAssertPointer(name, 2);
7050: PetscCall(DMGetLabel(dm, name, &label));
7051: PetscCheck(label, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "No label named %s was found", name);
7052: PetscCall(DMLabelGetValue(label, point, value));
7053: PetscFunctionReturn(PETSC_SUCCESS);
7054: }
7056: /*@
7057: DMSetLabelValue - Add a point to a `DMLabel` with given value
7059: Not Collective
7061: Input Parameters:
7062: + dm - The `DM` object
7063: . name - The label name
7064: . point - The mesh point
7065: - value - The label value for this point
7067: Output Parameter:
7069: Level: beginner
7071: .seealso: [](ch_dmbase), `DM`, `DMLabelSetValue()`, `DMGetStratumIS()`, `DMClearLabelValue()`
7072: @*/
7073: PetscErrorCode DMSetLabelValue(DM dm, const char name[], PetscInt point, PetscInt value)
7074: {
7075: DMLabel label;
7077: PetscFunctionBegin;
7079: PetscAssertPointer(name, 2);
7080: PetscCall(DMGetLabel(dm, name, &label));
7081: if (!label) {
7082: PetscCall(DMCreateLabel(dm, name));
7083: PetscCall(DMGetLabel(dm, name, &label));
7084: }
7085: PetscCall(DMLabelSetValue(label, point, value));
7086: PetscFunctionReturn(PETSC_SUCCESS);
7087: }
7089: /*@
7090: DMClearLabelValue - Remove a point from a `DMLabel` with given value
7092: Not Collective
7094: Input Parameters:
7095: + dm - The `DM` object
7096: . name - The label name
7097: . point - The mesh point
7098: - value - The label value for this point
7100: Level: beginner
7102: .seealso: [](ch_dmbase), `DM`, `DMLabelClearValue()`, `DMSetLabelValue()`, `DMGetStratumIS()`
7103: @*/
7104: PetscErrorCode DMClearLabelValue(DM dm, const char name[], PetscInt point, PetscInt value)
7105: {
7106: DMLabel label;
7108: PetscFunctionBegin;
7110: PetscAssertPointer(name, 2);
7111: PetscCall(DMGetLabel(dm, name, &label));
7112: if (!label) PetscFunctionReturn(PETSC_SUCCESS);
7113: PetscCall(DMLabelClearValue(label, point, value));
7114: PetscFunctionReturn(PETSC_SUCCESS);
7115: }
7117: /*@
7118: DMGetLabelSize - Get the value of `DMLabelGetNumValues()` of a `DMLabel` in the `DM`
7120: Not Collective
7122: Input Parameters:
7123: + dm - The `DM` object
7124: - name - The label name
7126: Output Parameter:
7127: . size - The number of different integer ids, or 0 if the label does not exist
7129: Level: beginner
7131: Developer Note:
7132: This should be renamed to something like `DMGetLabelNumValues()` or removed.
7134: .seealso: [](ch_dmbase), `DM`, `DMLabelGetNumValues()`, `DMSetLabelValue()`, `DMGetLabel()`
7135: @*/
7136: PetscErrorCode DMGetLabelSize(DM dm, const char name[], PetscInt *size)
7137: {
7138: DMLabel label;
7140: PetscFunctionBegin;
7142: PetscAssertPointer(name, 2);
7143: PetscAssertPointer(size, 3);
7144: PetscCall(DMGetLabel(dm, name, &label));
7145: *size = 0;
7146: if (!label) PetscFunctionReturn(PETSC_SUCCESS);
7147: PetscCall(DMLabelGetNumValues(label, size));
7148: PetscFunctionReturn(PETSC_SUCCESS);
7149: }
7151: /*@
7152: DMGetLabelIdIS - Get the `DMLabelGetValueIS()` from a `DMLabel` in the `DM`
7154: Not Collective
7156: Input Parameters:
7157: + dm - The `DM` object
7158: - name - The label name
7160: Output Parameter:
7161: . ids - The integer ids, or `NULL` if the label does not exist
7163: Level: beginner
7165: .seealso: [](ch_dmbase), `DM`, `DMLabelGetValueIS()`, `DMGetLabelSize()`
7166: @*/
7167: PetscErrorCode DMGetLabelIdIS(DM dm, const char name[], IS *ids)
7168: {
7169: DMLabel label;
7171: PetscFunctionBegin;
7173: PetscAssertPointer(name, 2);
7174: PetscAssertPointer(ids, 3);
7175: PetscCall(DMGetLabel(dm, name, &label));
7176: *ids = NULL;
7177: if (label) PetscCall(DMLabelGetValueIS(label, ids));
7178: else {
7179: /* returning an empty IS */
7180: PetscCall(ISCreateGeneral(PETSC_COMM_SELF, 0, NULL, PETSC_USE_POINTER, ids));
7181: }
7182: PetscFunctionReturn(PETSC_SUCCESS);
7183: }
7185: /*@
7186: DMGetStratumSize - Get the number of points in a label stratum
7188: Not Collective
7190: Input Parameters:
7191: + dm - The `DM` object
7192: . name - The label name of the stratum
7193: - value - The stratum value
7195: Output Parameter:
7196: . size - The number of points, also called the stratum size
7198: Level: beginner
7200: .seealso: [](ch_dmbase), `DM`, `DMLabelGetStratumSize()`, `DMGetLabelSize()`, `DMGetLabelIds()`
7201: @*/
7202: PetscErrorCode DMGetStratumSize(DM dm, const char name[], PetscInt value, PetscInt *size)
7203: {
7204: DMLabel label;
7206: PetscFunctionBegin;
7208: PetscAssertPointer(name, 2);
7209: PetscAssertPointer(size, 4);
7210: PetscCall(DMGetLabel(dm, name, &label));
7211: *size = 0;
7212: if (!label) PetscFunctionReturn(PETSC_SUCCESS);
7213: PetscCall(DMLabelGetStratumSize(label, value, size));
7214: PetscFunctionReturn(PETSC_SUCCESS);
7215: }
7217: /*@
7218: DMGetStratumIS - Get 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
7227: Output Parameter:
7228: . points - The stratum points, or `NULL` if the label does not exist or does not have that value
7230: Level: beginner
7232: .seealso: [](ch_dmbase), `DM`, `DMLabelGetStratumIS()`, `DMGetStratumSize()`
7233: @*/
7234: PetscErrorCode DMGetStratumIS(DM dm, const char name[], PetscInt value, IS *points)
7235: {
7236: DMLabel label;
7238: PetscFunctionBegin;
7240: PetscAssertPointer(name, 2);
7241: PetscAssertPointer(points, 4);
7242: PetscCall(DMGetLabel(dm, name, &label));
7243: *points = NULL;
7244: if (!label) PetscFunctionReturn(PETSC_SUCCESS);
7245: PetscCall(DMLabelGetStratumIS(label, value, points));
7246: PetscFunctionReturn(PETSC_SUCCESS);
7247: }
7249: /*@
7250: DMSetStratumIS - Set the points in a label stratum
7252: Not Collective
7254: Input Parameters:
7255: + dm - The `DM` object
7256: . name - The label name
7257: . value - The stratum value
7258: - points - The stratum points
7260: Level: beginner
7262: .seealso: [](ch_dmbase), `DM`, `DMLabel`, `DMClearLabelStratum()`, `DMLabelClearStratum()`, `DMLabelSetStratumIS()`, `DMGetStratumSize()`
7263: @*/
7264: PetscErrorCode DMSetStratumIS(DM dm, const char name[], PetscInt value, IS points)
7265: {
7266: DMLabel label;
7268: PetscFunctionBegin;
7270: PetscAssertPointer(name, 2);
7272: PetscCall(DMGetLabel(dm, name, &label));
7273: if (!label) PetscFunctionReturn(PETSC_SUCCESS);
7274: PetscCall(DMLabelSetStratumIS(label, value, points));
7275: PetscFunctionReturn(PETSC_SUCCESS);
7276: }
7278: /*@
7279: DMClearLabelStratum - Remove all points from a stratum from a `DMLabel`
7281: Not Collective
7283: Input Parameters:
7284: + dm - The `DM` object
7285: . name - The label name
7286: - value - The label value for this point
7288: Output Parameter:
7290: Level: beginner
7292: .seealso: [](ch_dmbase), `DM`, `DMLabel`, `DMLabelClearStratum()`, `DMSetLabelValue()`, `DMGetStratumIS()`, `DMClearLabelValue()`
7293: @*/
7294: PetscErrorCode DMClearLabelStratum(DM dm, const char name[], PetscInt value)
7295: {
7296: DMLabel label;
7298: PetscFunctionBegin;
7300: PetscAssertPointer(name, 2);
7301: PetscCall(DMGetLabel(dm, name, &label));
7302: if (!label) PetscFunctionReturn(PETSC_SUCCESS);
7303: PetscCall(DMLabelClearStratum(label, value));
7304: PetscFunctionReturn(PETSC_SUCCESS);
7305: }
7307: /*@
7308: DMGetNumLabels - Return the number of labels defined by on the `DM`
7310: Not Collective
7312: Input Parameter:
7313: . dm - The `DM` object
7315: Output Parameter:
7316: . numLabels - the number of Labels
7318: Level: intermediate
7320: .seealso: [](ch_dmbase), `DM`, `DMLabel`, `DMGetLabelByNum()`, `DMGetLabelName()`, `DMGetLabelValue()`, `DMSetLabelValue()`, `DMGetStratumIS()`
7321: @*/
7322: PetscErrorCode DMGetNumLabels(DM dm, PetscInt *numLabels)
7323: {
7324: DMLabelLink next = dm->labels;
7325: PetscInt n = 0;
7327: PetscFunctionBegin;
7329: PetscAssertPointer(numLabels, 2);
7330: while (next) {
7331: ++n;
7332: next = next->next;
7333: }
7334: *numLabels = n;
7335: PetscFunctionReturn(PETSC_SUCCESS);
7336: }
7338: /*@
7339: DMGetLabelName - Return the name of nth label
7341: Not Collective
7343: Input Parameters:
7344: + dm - The `DM` object
7345: - n - the label number
7347: Output Parameter:
7348: . name - the label name
7350: Level: intermediate
7352: Developer Note:
7353: Some of the functions that appropriate on labels using their number have the suffix ByNum, others do not.
7355: .seealso: [](ch_dmbase), `DM`, `DMLabel`, `DMGetLabelByNum()`, `DMGetLabel()`, `DMGetLabelValue()`, `DMSetLabelValue()`, `DMGetStratumIS()`
7356: @*/
7357: PetscErrorCode DMGetLabelName(DM dm, PetscInt n, const char *name[])
7358: {
7359: DMLabelLink next = dm->labels;
7360: PetscInt l = 0;
7362: PetscFunctionBegin;
7364: PetscAssertPointer(name, 3);
7365: while (next) {
7366: if (l == n) {
7367: PetscCall(PetscObjectGetName((PetscObject)next->label, name));
7368: PetscFunctionReturn(PETSC_SUCCESS);
7369: }
7370: ++l;
7371: next = next->next;
7372: }
7373: SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Label %" PetscInt_FMT " does not exist in this DM", n);
7374: }
7376: /*@
7377: DMHasLabel - Determine whether the `DM` has a label of a given name
7379: Not Collective
7381: Input Parameters:
7382: + dm - The `DM` object
7383: - name - The label name
7385: Output Parameter:
7386: . hasLabel - `PETSC_TRUE` if the label is present
7388: Level: intermediate
7390: .seealso: [](ch_dmbase), `DM`, `DMLabel`, `DMGetLabel()`, `DMGetLabelByNum()`, `DMCreateLabel()`, `DMGetLabelValue()`, `DMSetLabelValue()`, `DMGetStratumIS()`
7391: @*/
7392: PetscErrorCode DMHasLabel(DM dm, const char name[], PetscBool *hasLabel)
7393: {
7394: DMLabelLink next = dm->labels;
7395: const char *lname;
7397: PetscFunctionBegin;
7399: PetscAssertPointer(name, 2);
7400: PetscAssertPointer(hasLabel, 3);
7401: *hasLabel = PETSC_FALSE;
7402: while (next) {
7403: PetscCall(PetscObjectGetName((PetscObject)next->label, &lname));
7404: PetscCall(PetscStrcmp(name, lname, hasLabel));
7405: if (*hasLabel) break;
7406: next = next->next;
7407: }
7408: PetscFunctionReturn(PETSC_SUCCESS);
7409: }
7411: // PetscClangLinter pragma ignore: -fdoc-section-header-unknown
7412: /*@
7413: DMGetLabel - Return the label of a given name, or `NULL`, from a `DM`
7415: Not Collective
7417: Input Parameters:
7418: + dm - The `DM` object
7419: - name - The label name
7421: Output Parameter:
7422: . label - The `DMLabel`, or `NULL` if the label is absent
7424: Default labels in a `DMPLEX`:
7425: + "depth" - Holds the depth (co-dimension) of each mesh point
7426: . "celltype" - Holds the topological type of each cell
7427: . "ghost" - If the DM is distributed with overlap, this marks the cells and faces in the overlap
7428: . "Cell Sets" - Mirrors the cell sets defined by GMsh and ExodusII
7429: . "Face Sets" - Mirrors the face sets defined by GMsh and ExodusII
7430: - "Vertex Sets" - Mirrors the vertex sets defined by GMsh
7432: Level: intermediate
7434: .seealso: [](ch_dmbase), `DM`, `DMLabel`, `DMHasLabel()`, `DMGetLabelByNum()`, `DMAddLabel()`, `DMCreateLabel()`, `DMPlexGetDepthLabel()`, `DMPlexGetCellType()`
7435: @*/
7436: PetscErrorCode DMGetLabel(DM dm, const char name[], DMLabel *label)
7437: {
7438: DMLabelLink next = dm->labels;
7439: PetscBool hasLabel;
7440: const char *lname;
7442: PetscFunctionBegin;
7444: PetscAssertPointer(name, 2);
7445: PetscAssertPointer(label, 3);
7446: *label = NULL;
7447: while (next) {
7448: PetscCall(PetscObjectGetName((PetscObject)next->label, &lname));
7449: PetscCall(PetscStrcmp(name, lname, &hasLabel));
7450: if (hasLabel) {
7451: *label = next->label;
7452: break;
7453: }
7454: next = next->next;
7455: }
7456: PetscFunctionReturn(PETSC_SUCCESS);
7457: }
7459: /*@
7460: DMGetLabelByNum - Return the nth label on a `DM`
7462: Not Collective
7464: Input Parameters:
7465: + dm - The `DM` object
7466: - n - the label number
7468: Output Parameter:
7469: . label - the label
7471: Level: intermediate
7473: .seealso: [](ch_dmbase), `DM`, `DMLabel`, `DMAddLabel()`, `DMGetLabelValue()`, `DMSetLabelValue()`, `DMGetStratumIS()`
7474: @*/
7475: PetscErrorCode DMGetLabelByNum(DM dm, PetscInt n, DMLabel *label)
7476: {
7477: DMLabelLink next = dm->labels;
7478: PetscInt l = 0;
7480: PetscFunctionBegin;
7482: PetscAssertPointer(label, 3);
7483: while (next) {
7484: if (l == n) {
7485: *label = next->label;
7486: PetscFunctionReturn(PETSC_SUCCESS);
7487: }
7488: ++l;
7489: next = next->next;
7490: }
7491: SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Label %" PetscInt_FMT " does not exist in this DM", n);
7492: }
7494: /*@
7495: DMAddLabel - Add the label to this `DM`
7497: Not Collective
7499: Input Parameters:
7500: + dm - The `DM` object
7501: - label - The `DMLabel`
7503: Level: developer
7505: .seealso: [](ch_dmbase), `DM`, `DMLabel`, `DMCreateLabel()`, `DMHasLabel()`, `DMGetLabelValue()`, `DMSetLabelValue()`, `DMGetStratumIS()`
7506: @*/
7507: PetscErrorCode DMAddLabel(DM dm, DMLabel label)
7508: {
7509: DMLabelLink l, *p, tmpLabel;
7510: PetscBool hasLabel;
7511: const char *lname;
7512: PetscBool flg;
7514: PetscFunctionBegin;
7516: PetscCall(PetscObjectGetName((PetscObject)label, &lname));
7517: PetscCall(DMHasLabel(dm, lname, &hasLabel));
7518: PetscCheck(!hasLabel, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Label %s already exists in this DM", lname);
7519: PetscCall(PetscCalloc1(1, &tmpLabel));
7520: tmpLabel->label = label;
7521: tmpLabel->output = PETSC_TRUE;
7522: for (p = &dm->labels; (l = *p); p = &l->next) { }
7523: *p = tmpLabel;
7524: PetscCall(PetscObjectReference((PetscObject)label));
7525: PetscCall(PetscStrcmp(lname, "depth", &flg));
7526: if (flg) dm->depthLabel = label;
7527: PetscCall(PetscStrcmp(lname, "celltype", &flg));
7528: if (flg) dm->celltypeLabel = label;
7529: PetscFunctionReturn(PETSC_SUCCESS);
7530: }
7532: // PetscClangLinter pragma ignore: -fdoc-section-header-unknown
7533: /*@
7534: DMSetLabel - Replaces the label of a given name, or ignores it if the name is not present
7536: Not Collective
7538: Input Parameters:
7539: + dm - The `DM` object
7540: - label - The `DMLabel`, having the same name, to substitute
7542: Default labels in a `DMPLEX`:
7543: + "depth" - Holds the depth (co-dimension) of each mesh point
7544: . "celltype" - Holds the topological type of each cell
7545: . "ghost" - If the DM is distributed with overlap, this marks the cells and faces in the overlap
7546: . "Cell Sets" - Mirrors the cell sets defined by GMsh and ExodusII
7547: . "Face Sets" - Mirrors the face sets defined by GMsh and ExodusII
7548: - "Vertex Sets" - Mirrors the vertex sets defined by GMsh
7550: Level: intermediate
7552: .seealso: [](ch_dmbase), `DM`, `DMLabel`, `DMCreateLabel()`, `DMHasLabel()`, `DMPlexGetDepthLabel()`, `DMPlexGetCellType()`
7553: @*/
7554: PetscErrorCode DMSetLabel(DM dm, DMLabel label)
7555: {
7556: DMLabelLink next = dm->labels;
7557: PetscBool hasLabel, flg;
7558: const char *name, *lname;
7560: PetscFunctionBegin;
7563: PetscCall(PetscObjectGetName((PetscObject)label, &name));
7564: while (next) {
7565: PetscCall(PetscObjectGetName((PetscObject)next->label, &lname));
7566: PetscCall(PetscStrcmp(name, lname, &hasLabel));
7567: if (hasLabel) {
7568: PetscCall(PetscObjectReference((PetscObject)label));
7569: PetscCall(PetscStrcmp(lname, "depth", &flg));
7570: if (flg) dm->depthLabel = label;
7571: PetscCall(PetscStrcmp(lname, "celltype", &flg));
7572: if (flg) dm->celltypeLabel = label;
7573: PetscCall(DMLabelDestroy(&next->label));
7574: next->label = label;
7575: break;
7576: }
7577: next = next->next;
7578: }
7579: PetscFunctionReturn(PETSC_SUCCESS);
7580: }
7582: /*@
7583: DMRemoveLabel - Remove the label given by name from this `DM`
7585: Not Collective
7587: Input Parameters:
7588: + dm - The `DM` object
7589: - name - The label name
7591: Output Parameter:
7592: . label - The `DMLabel`, or `NULL` if the label is absent. Pass in `NULL` to call `DMLabelDestroy()` on the label, otherwise the
7593: caller is responsible for calling `DMLabelDestroy()`.
7595: Level: developer
7597: .seealso: [](ch_dmbase), `DM`, `DMLabel`, `DMCreateLabel()`, `DMHasLabel()`, `DMGetLabel()`, `DMGetLabelValue()`, `DMSetLabelValue()`, `DMLabelDestroy()`, `DMRemoveLabelBySelf()`
7598: @*/
7599: PetscErrorCode DMRemoveLabel(DM dm, const char name[], DMLabel *label)
7600: {
7601: DMLabelLink link, *pnext;
7602: PetscBool hasLabel;
7603: const char *lname;
7605: PetscFunctionBegin;
7607: PetscAssertPointer(name, 2);
7608: if (label) {
7609: PetscAssertPointer(label, 3);
7610: *label = NULL;
7611: }
7612: for (pnext = &dm->labels; (link = *pnext); pnext = &link->next) {
7613: PetscCall(PetscObjectGetName((PetscObject)link->label, &lname));
7614: PetscCall(PetscStrcmp(name, lname, &hasLabel));
7615: if (hasLabel) {
7616: *pnext = link->next; /* Remove from list */
7617: PetscCall(PetscStrcmp(name, "depth", &hasLabel));
7618: if (hasLabel) dm->depthLabel = NULL;
7619: PetscCall(PetscStrcmp(name, "celltype", &hasLabel));
7620: if (hasLabel) dm->celltypeLabel = NULL;
7621: if (label) *label = link->label;
7622: else PetscCall(DMLabelDestroy(&link->label));
7623: PetscCall(PetscFree(link));
7624: break;
7625: }
7626: }
7627: PetscFunctionReturn(PETSC_SUCCESS);
7628: }
7630: /*@
7631: DMRemoveLabelBySelf - Remove the label from this `DM`
7633: Not Collective
7635: Input Parameters:
7636: + dm - The `DM` object
7637: . label - The `DMLabel` to be removed from the `DM`
7638: - failNotFound - Should it fail if the label is not found in the `DM`?
7640: Level: developer
7642: Note:
7643: Only exactly the same instance is removed if found, name match is ignored.
7644: If the `DM` has an exclusive reference to the label, the label gets destroyed and
7645: *label nullified.
7647: .seealso: [](ch_dmbase), `DM`, `DMLabel`, `DMCreateLabel()`, `DMHasLabel()`, `DMGetLabel()`, `DMGetLabelValue()`, `DMSetLabelValue()`, `DMLabelDestroy()`, `DMRemoveLabel()`
7648: @*/
7649: PetscErrorCode DMRemoveLabelBySelf(DM dm, DMLabel *label, PetscBool failNotFound)
7650: {
7651: DMLabelLink link, *pnext;
7652: PetscBool hasLabel = PETSC_FALSE;
7654: PetscFunctionBegin;
7656: PetscAssertPointer(label, 2);
7657: if (!*label && !failNotFound) PetscFunctionReturn(PETSC_SUCCESS);
7660: for (pnext = &dm->labels; (link = *pnext); pnext = &link->next) {
7661: if (*label == link->label) {
7662: hasLabel = PETSC_TRUE;
7663: *pnext = link->next; /* Remove from list */
7664: if (*label == dm->depthLabel) dm->depthLabel = NULL;
7665: if (*label == dm->celltypeLabel) dm->celltypeLabel = NULL;
7666: if (((PetscObject)link->label)->refct < 2) *label = NULL; /* nullify if exclusive reference */
7667: PetscCall(DMLabelDestroy(&link->label));
7668: PetscCall(PetscFree(link));
7669: break;
7670: }
7671: }
7672: PetscCheck(hasLabel || !failNotFound, PetscObjectComm((PetscObject)dm), PETSC_ERR_ARG_WRONG, "Given label not found in DM");
7673: PetscFunctionReturn(PETSC_SUCCESS);
7674: }
7676: /*@
7677: DMGetLabelOutput - Get the output flag for a given label
7679: Not Collective
7681: Input Parameters:
7682: + dm - The `DM` object
7683: - name - The label name
7685: Output Parameter:
7686: . output - The flag for output
7688: Level: developer
7690: .seealso: [](ch_dmbase), `DM`, `DMLabel`, `DMSetLabelOutput()`, `DMCreateLabel()`, `DMHasLabel()`, `DMGetLabelValue()`, `DMSetLabelValue()`, `DMGetStratumIS()`
7691: @*/
7692: PetscErrorCode DMGetLabelOutput(DM dm, const char name[], PetscBool *output)
7693: {
7694: DMLabelLink next = dm->labels;
7695: const char *lname;
7697: PetscFunctionBegin;
7699: PetscAssertPointer(name, 2);
7700: PetscAssertPointer(output, 3);
7701: while (next) {
7702: PetscBool flg;
7704: PetscCall(PetscObjectGetName((PetscObject)next->label, &lname));
7705: PetscCall(PetscStrcmp(name, lname, &flg));
7706: if (flg) {
7707: *output = next->output;
7708: PetscFunctionReturn(PETSC_SUCCESS);
7709: }
7710: next = next->next;
7711: }
7712: SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "No label named %s was present in this dm", name);
7713: }
7715: /*@
7716: DMSetLabelOutput - Set if a given label should be saved to a `PetscViewer` in calls to `DMView()`
7718: Not Collective
7720: Input Parameters:
7721: + dm - The `DM` object
7722: . name - The label name
7723: - output - `PETSC_TRUE` to save the label to the viewer
7725: Level: developer
7727: .seealso: [](ch_dmbase), `DM`, `DMLabel`, `DMGetOutputFlag()`, `DMGetLabelOutput()`, `DMCreateLabel()`, `DMHasLabel()`, `DMGetLabelValue()`, `DMSetLabelValue()`, `DMGetStratumIS()`
7728: @*/
7729: PetscErrorCode DMSetLabelOutput(DM dm, const char name[], PetscBool output)
7730: {
7731: DMLabelLink next = dm->labels;
7732: const char *lname;
7734: PetscFunctionBegin;
7736: PetscAssertPointer(name, 2);
7737: while (next) {
7738: PetscBool flg;
7740: PetscCall(PetscObjectGetName((PetscObject)next->label, &lname));
7741: PetscCall(PetscStrcmp(name, lname, &flg));
7742: if (flg) {
7743: next->output = output;
7744: PetscFunctionReturn(PETSC_SUCCESS);
7745: }
7746: next = next->next;
7747: }
7748: SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "No label named %s was present in this dm", name);
7749: }
7751: /*@
7752: DMCopyLabels - Copy labels from one `DM` mesh to another `DM` with a superset of the points
7754: Collective
7756: Input Parameters:
7757: + dmA - The `DM` object with initial labels
7758: . dmB - The `DM` object to which labels are copied
7759: . mode - Copy labels by pointers (`PETSC_OWN_POINTER`) or duplicate them (`PETSC_COPY_VALUES`)
7760: . all - Copy all labels including "depth", "dim", and "celltype" (`PETSC_TRUE`) which are otherwise ignored (`PETSC_FALSE`)
7761: - emode - How to behave when a `DMLabel` in the source and destination `DM`s with the same name is encountered (see `DMCopyLabelsMode`)
7763: Level: intermediate
7765: Note:
7766: This is typically used when interpolating or otherwise adding to a mesh, or testing.
7768: .seealso: [](ch_dmbase), `DM`, `DMLabel`, `DMAddLabel()`, `DMCopyLabelsMode`
7769: @*/
7770: PetscErrorCode DMCopyLabels(DM dmA, DM dmB, PetscCopyMode mode, PetscBool all, DMCopyLabelsMode emode)
7771: {
7772: DMLabel label, labelNew, labelOld;
7773: const char *name;
7774: PetscBool flg;
7775: DMLabelLink link;
7777: PetscFunctionBegin;
7782: PetscCheck(mode != PETSC_USE_POINTER, PetscObjectComm((PetscObject)dmA), PETSC_ERR_SUP, "PETSC_USE_POINTER not supported for objects");
7783: if (dmA == dmB) PetscFunctionReturn(PETSC_SUCCESS);
7784: for (link = dmA->labels; link; link = link->next) {
7785: label = link->label;
7786: PetscCall(PetscObjectGetName((PetscObject)label, &name));
7787: if (!all) {
7788: PetscCall(PetscStrcmp(name, "depth", &flg));
7789: if (flg) continue;
7790: PetscCall(PetscStrcmp(name, "dim", &flg));
7791: if (flg) continue;
7792: PetscCall(PetscStrcmp(name, "celltype", &flg));
7793: if (flg) continue;
7794: }
7795: PetscCall(DMGetLabel(dmB, name, &labelOld));
7796: if (labelOld) {
7797: switch (emode) {
7798: case DM_COPY_LABELS_KEEP:
7799: continue;
7800: case DM_COPY_LABELS_REPLACE:
7801: PetscCall(DMRemoveLabelBySelf(dmB, &labelOld, PETSC_TRUE));
7802: break;
7803: case DM_COPY_LABELS_FAIL:
7804: SETERRQ(PetscObjectComm((PetscObject)dmA), PETSC_ERR_ARG_OUTOFRANGE, "Label %s already exists in destination DM", name);
7805: default:
7806: SETERRQ(PetscObjectComm((PetscObject)dmA), PETSC_ERR_ARG_OUTOFRANGE, "Unhandled DMCopyLabelsMode %d", (int)emode);
7807: }
7808: }
7809: if (mode == PETSC_COPY_VALUES) PetscCall(DMLabelDuplicate(label, &labelNew));
7810: else labelNew = label;
7811: PetscCall(DMAddLabel(dmB, labelNew));
7812: if (mode == PETSC_COPY_VALUES) PetscCall(DMLabelDestroy(&labelNew));
7813: }
7814: PetscFunctionReturn(PETSC_SUCCESS);
7815: }
7817: /*@
7818: DMCompareLabels - Compare labels between two `DM` objects
7820: Collective; No Fortran Support
7822: Input Parameters:
7823: + dm0 - First `DM` object
7824: - dm1 - Second `DM` object
7826: Output Parameters:
7827: + equal - (Optional) Flag whether labels of `dm0` and `dm1` are the same
7828: - message - (Optional) Message describing the difference, or `NULL` if there is no difference
7830: Level: intermediate
7832: Notes:
7833: The output flag equal will be the same on all processes.
7835: If equal is passed as `NULL` and difference is found, an error is thrown on all processes.
7837: Make sure to pass equal is `NULL` on all processes or none of them.
7839: The output message is set independently on each rank.
7841: message must be freed with `PetscFree()`
7843: If message is passed as `NULL` and a difference is found, the difference description is printed to `stderr` in synchronized manner.
7845: Make sure to pass message as `NULL` on all processes or no processes.
7847: Labels are matched by name. If the number of labels and their names are equal,
7848: `DMLabelCompare()` is used to compare each pair of labels with the same name.
7850: Developer Note:
7851: Cannot automatically generate the Fortran stub because `message` must be freed with `PetscFree()`
7853: .seealso: [](ch_dmbase), `DM`, `DMLabel`, `DMAddLabel()`, `DMCopyLabelsMode`, `DMLabelCompare()`
7854: @*/
7855: PetscErrorCode DMCompareLabels(DM dm0, DM dm1, PetscBool *equal, char *message[]) PeNS
7856: {
7857: PetscInt n;
7858: char msg[PETSC_MAX_PATH_LEN] = "";
7859: PetscBool eq;
7860: MPI_Comm comm;
7861: PetscMPIInt rank;
7863: PetscFunctionBegin;
7866: PetscCheckSameComm(dm0, 1, dm1, 2);
7867: if (equal) PetscAssertPointer(equal, 3);
7868: if (message) PetscAssertPointer(message, 4);
7869: PetscCall(PetscObjectGetComm((PetscObject)dm0, &comm));
7870: PetscCallMPI(MPI_Comm_rank(comm, &rank));
7871: {
7872: PetscInt n1;
7874: PetscCall(DMGetNumLabels(dm0, &n));
7875: PetscCall(DMGetNumLabels(dm1, &n1));
7876: eq = (PetscBool)(n == n1);
7877: if (!eq) PetscCall(PetscSNPrintf(msg, sizeof(msg), "Number of labels in dm0 = %" PetscInt_FMT " != %" PetscInt_FMT " = Number of labels in dm1", n, n1));
7878: PetscCallMPI(MPIU_Allreduce(MPI_IN_PLACE, &eq, 1, MPI_C_BOOL, MPI_LAND, comm));
7879: if (!eq) goto finish;
7880: }
7881: for (PetscInt i = 0; i < n; i++) {
7882: DMLabel l0, l1;
7883: const char *name;
7884: char *msgInner;
7886: /* Ignore label order */
7887: PetscCall(DMGetLabelByNum(dm0, i, &l0));
7888: PetscCall(PetscObjectGetName((PetscObject)l0, &name));
7889: PetscCall(DMGetLabel(dm1, name, &l1));
7890: if (!l1) {
7891: PetscCall(PetscSNPrintf(msg, sizeof(msg), "Label \"%s\" (#%" PetscInt_FMT " in dm0) not found in dm1", name, i));
7892: eq = PETSC_FALSE;
7893: break;
7894: }
7895: PetscCall(DMLabelCompare(comm, l0, l1, &eq, &msgInner));
7896: PetscCall(PetscStrncpy(msg, msgInner, sizeof(msg)));
7897: PetscCall(PetscFree(msgInner));
7898: if (!eq) break;
7899: }
7900: PetscCallMPI(MPIU_Allreduce(MPI_IN_PLACE, &eq, 1, MPI_C_BOOL, MPI_LAND, comm));
7901: finish:
7902: /* If message output arg not set, print to stderr */
7903: if (message) {
7904: *message = NULL;
7905: if (msg[0]) PetscCall(PetscStrallocpy(msg, message));
7906: } else {
7907: if (msg[0]) PetscCall(PetscSynchronizedFPrintf(comm, PETSC_STDERR, "[%d] %s\n", rank, msg));
7908: PetscCall(PetscSynchronizedFlush(comm, PETSC_STDERR));
7909: }
7910: /* If same output arg not ser and labels are not equal, throw error */
7911: if (equal) *equal = eq;
7912: else PetscCheck(eq, comm, PETSC_ERR_ARG_INCOMP, "DMLabels are not the same in dm0 and dm1");
7913: PetscFunctionReturn(PETSC_SUCCESS);
7914: }
7916: PetscErrorCode DMSetLabelValue_Fast(DM dm, DMLabel *label, const char name[], PetscInt point, PetscInt value)
7917: {
7918: PetscFunctionBegin;
7919: PetscAssertPointer(label, 2);
7920: if (!*label) {
7921: PetscCall(DMCreateLabel(dm, name));
7922: PetscCall(DMGetLabel(dm, name, label));
7923: }
7924: PetscCall(DMLabelSetValue(*label, point, value));
7925: PetscFunctionReturn(PETSC_SUCCESS);
7926: }
7928: /*
7929: Many mesh programs, such as Triangle and TetGen, allow only a single label for each mesh point. Therefore, we would
7930: like to encode all label IDs using a single, universal label. We can do this by assigning an integer to every
7931: (label, id) pair in the DM.
7933: However, a mesh point can have multiple labels, so we must separate all these values. We will assign a bit range to
7934: each label.
7935: */
7936: PetscErrorCode DMUniversalLabelCreate(DM dm, DMUniversalLabel *universal)
7937: {
7938: DMUniversalLabel ul;
7939: PetscBool *active;
7940: PetscInt pStart, pEnd, p, Nl, l, m;
7942: PetscFunctionBegin;
7943: PetscCall(PetscMalloc1(1, &ul));
7944: PetscCall(DMLabelCreate(PETSC_COMM_SELF, "universal", &ul->label));
7945: PetscCall(DMGetNumLabels(dm, &Nl));
7946: PetscCall(PetscCalloc1(Nl, &active));
7947: ul->Nl = 0;
7948: for (l = 0; l < Nl; ++l) {
7949: PetscBool isdepth, iscelltype;
7950: const char *name;
7952: PetscCall(DMGetLabelName(dm, l, &name));
7953: PetscCall(PetscStrncmp(name, "depth", 6, &isdepth));
7954: PetscCall(PetscStrncmp(name, "celltype", 9, &iscelltype));
7955: active[l] = !(isdepth || iscelltype) ? PETSC_TRUE : PETSC_FALSE;
7956: if (active[l]) ++ul->Nl;
7957: }
7958: PetscCall(PetscCalloc5(ul->Nl, &ul->names, ul->Nl, &ul->indices, ul->Nl + 1, &ul->offsets, ul->Nl + 1, &ul->bits, ul->Nl, &ul->masks));
7959: ul->Nv = 0;
7960: for (l = 0, m = 0; l < Nl; ++l) {
7961: DMLabel label;
7962: PetscInt nv;
7963: const char *name;
7965: if (!active[l]) continue;
7966: PetscCall(DMGetLabelName(dm, l, &name));
7967: PetscCall(DMGetLabelByNum(dm, l, &label));
7968: PetscCall(DMLabelGetNumValues(label, &nv));
7969: PetscCall(PetscStrallocpy(name, &ul->names[m]));
7970: ul->indices[m] = l;
7971: ul->Nv += nv;
7972: ul->offsets[m + 1] = nv;
7973: ul->bits[m + 1] = PetscCeilReal(PetscLog2Real(nv + 1));
7974: ++m;
7975: }
7976: for (l = 1; l <= ul->Nl; ++l) {
7977: ul->offsets[l] = ul->offsets[l - 1] + ul->offsets[l];
7978: ul->bits[l] = ul->bits[l - 1] + ul->bits[l];
7979: }
7980: for (l = 0; l < ul->Nl; ++l) {
7981: ul->masks[l] = 0;
7982: for (PetscInt b = ul->bits[l]; b < ul->bits[l + 1]; ++b) ul->masks[l] |= 1 << b;
7983: }
7984: PetscCall(PetscMalloc1(ul->Nv, &ul->values));
7985: for (l = 0, m = 0; l < Nl; ++l) {
7986: DMLabel label;
7987: IS valueIS;
7988: const PetscInt *varr;
7989: PetscInt nv;
7991: if (!active[l]) continue;
7992: PetscCall(DMGetLabelByNum(dm, l, &label));
7993: PetscCall(DMLabelGetNumValues(label, &nv));
7994: PetscCall(DMLabelGetValueIS(label, &valueIS));
7995: PetscCall(ISGetIndices(valueIS, &varr));
7996: for (PetscInt v = 0; v < nv; ++v) ul->values[ul->offsets[m] + v] = varr[v];
7997: PetscCall(ISRestoreIndices(valueIS, &varr));
7998: PetscCall(ISDestroy(&valueIS));
7999: PetscCall(PetscSortInt(nv, &ul->values[ul->offsets[m]]));
8000: ++m;
8001: }
8002: PetscCall(DMPlexGetChart(dm, &pStart, &pEnd));
8003: for (p = pStart; p < pEnd; ++p) {
8004: PetscInt uval = 0;
8005: PetscBool marked = PETSC_FALSE;
8007: for (l = 0, m = 0; l < Nl; ++l) {
8008: DMLabel label;
8009: PetscInt val, defval, loc, nv;
8011: if (!active[l]) continue;
8012: PetscCall(DMGetLabelByNum(dm, l, &label));
8013: PetscCall(DMLabelGetValue(label, p, &val));
8014: PetscCall(DMLabelGetDefaultValue(label, &defval));
8015: if (val == defval) {
8016: ++m;
8017: continue;
8018: }
8019: nv = ul->offsets[m + 1] - ul->offsets[m];
8020: marked = PETSC_TRUE;
8021: PetscCall(PetscFindInt(val, nv, &ul->values[ul->offsets[m]], &loc));
8022: PetscCheck(loc >= 0, PETSC_COMM_SELF, PETSC_ERR_PLIB, "Label value %" PetscInt_FMT " not found in compression array", val);
8023: uval += (loc + 1) << ul->bits[m];
8024: ++m;
8025: }
8026: if (marked) PetscCall(DMLabelSetValue(ul->label, p, uval));
8027: }
8028: PetscCall(PetscFree(active));
8029: *universal = ul;
8030: PetscFunctionReturn(PETSC_SUCCESS);
8031: }
8033: PetscErrorCode DMUniversalLabelDestroy(DMUniversalLabel *universal)
8034: {
8035: PetscInt l;
8037: PetscFunctionBegin;
8038: for (l = 0; l < (*universal)->Nl; ++l) PetscCall(PetscFree((*universal)->names[l]));
8039: PetscCall(DMLabelDestroy(&(*universal)->label));
8040: PetscCall(PetscFree5((*universal)->names, (*universal)->indices, (*universal)->offsets, (*universal)->bits, (*universal)->masks));
8041: PetscCall(PetscFree((*universal)->values));
8042: PetscCall(PetscFree(*universal));
8043: *universal = NULL;
8044: PetscFunctionReturn(PETSC_SUCCESS);
8045: }
8047: PetscErrorCode DMUniversalLabelGetLabel(DMUniversalLabel ul, DMLabel *ulabel)
8048: {
8049: PetscFunctionBegin;
8050: PetscAssertPointer(ulabel, 2);
8051: *ulabel = ul->label;
8052: PetscFunctionReturn(PETSC_SUCCESS);
8053: }
8055: PetscErrorCode DMUniversalLabelCreateLabels(DMUniversalLabel ul, PetscBool preserveOrder, DM dm)
8056: {
8057: PetscInt Nl = ul->Nl, l;
8059: PetscFunctionBegin;
8061: for (l = 0; l < Nl; ++l) {
8062: if (preserveOrder) PetscCall(DMCreateLabelAtIndex(dm, ul->indices[l], ul->names[l]));
8063: else PetscCall(DMCreateLabel(dm, ul->names[l]));
8064: }
8065: if (preserveOrder) {
8066: for (l = 0; l < ul->Nl; ++l) {
8067: const char *name;
8068: PetscBool match;
8070: PetscCall(DMGetLabelName(dm, ul->indices[l], &name));
8071: PetscCall(PetscStrcmp(name, ul->names[l], &match));
8072: PetscCheck(match, PetscObjectComm((PetscObject)dm), PETSC_ERR_ARG_WRONG, "Label %" PetscInt_FMT " name %s does not match new name %s", l, name, ul->names[l]);
8073: }
8074: }
8075: PetscFunctionReturn(PETSC_SUCCESS);
8076: }
8078: PetscErrorCode DMUniversalLabelSetLabelValue(DMUniversalLabel ul, DM dm, PetscBool useIndex, PetscInt p, PetscInt value)
8079: {
8080: PetscFunctionBegin;
8081: for (PetscInt l = 0; l < ul->Nl; ++l) {
8082: DMLabel label;
8083: PetscInt lval = (value & ul->masks[l]) >> ul->bits[l];
8085: if (lval) {
8086: if (useIndex) PetscCall(DMGetLabelByNum(dm, ul->indices[l], &label));
8087: else PetscCall(DMGetLabel(dm, ul->names[l], &label));
8088: PetscCall(DMLabelSetValue(label, p, ul->values[ul->offsets[l] + lval - 1]));
8089: }
8090: }
8091: PetscFunctionReturn(PETSC_SUCCESS);
8092: }
8094: /*@
8095: DMGetCoarseDM - Get the coarse `DM`from which this `DM` was obtained by refinement
8097: Not Collective
8099: Input Parameter:
8100: . dm - The `DM` object
8102: Output Parameter:
8103: . cdm - The coarse `DM`
8105: Level: intermediate
8107: .seealso: [](ch_dmbase), `DM`, `DMSetCoarseDM()`, `DMCoarsen()`
8108: @*/
8109: PetscErrorCode DMGetCoarseDM(DM dm, DM *cdm)
8110: {
8111: PetscFunctionBegin;
8113: PetscAssertPointer(cdm, 2);
8114: *cdm = dm->coarseMesh;
8115: PetscFunctionReturn(PETSC_SUCCESS);
8116: }
8118: /*@
8119: DMSetCoarseDM - Set the coarse `DM` from which this `DM` was obtained by refinement
8121: Input Parameters:
8122: + dm - The `DM` object
8123: - cdm - The coarse `DM`
8125: Level: intermediate
8127: Note:
8128: Normally this is set automatically by `DMRefine()`
8130: .seealso: [](ch_dmbase), `DM`, `DMGetCoarseDM()`, `DMCoarsen()`, `DMSetRefine()`, `DMSetFineDM()`
8131: @*/
8132: PetscErrorCode DMSetCoarseDM(DM dm, DM cdm)
8133: {
8134: PetscFunctionBegin;
8137: if (dm == cdm) cdm = NULL;
8138: PetscCall(PetscObjectReference((PetscObject)cdm));
8139: PetscCall(DMDestroy(&dm->coarseMesh));
8140: dm->coarseMesh = cdm;
8141: PetscFunctionReturn(PETSC_SUCCESS);
8142: }
8144: /*@
8145: DMGetFineDM - Get the fine mesh from which this `DM` was obtained by coarsening
8147: Input Parameter:
8148: . dm - The `DM` object
8150: Output Parameter:
8151: . fdm - The fine `DM`
8153: Level: intermediate
8155: .seealso: [](ch_dmbase), `DM`, `DMSetFineDM()`, `DMCoarsen()`, `DMRefine()`
8156: @*/
8157: PetscErrorCode DMGetFineDM(DM dm, DM *fdm)
8158: {
8159: PetscFunctionBegin;
8161: PetscAssertPointer(fdm, 2);
8162: *fdm = dm->fineMesh;
8163: PetscFunctionReturn(PETSC_SUCCESS);
8164: }
8166: /*@
8167: DMSetFineDM - Set the fine mesh from which this was obtained by coarsening
8169: Input Parameters:
8170: + dm - The `DM` object
8171: - fdm - The fine `DM`
8173: Level: developer
8175: Note:
8176: Normally this is set automatically by `DMCoarsen()`
8178: .seealso: [](ch_dmbase), `DM`, `DMGetFineDM()`, `DMCoarsen()`, `DMRefine()`
8179: @*/
8180: PetscErrorCode DMSetFineDM(DM dm, DM fdm)
8181: {
8182: PetscFunctionBegin;
8185: if (dm == fdm) fdm = NULL;
8186: PetscCall(PetscObjectReference((PetscObject)fdm));
8187: PetscCall(DMDestroy(&dm->fineMesh));
8188: dm->fineMesh = fdm;
8189: PetscFunctionReturn(PETSC_SUCCESS);
8190: }
8192: /*@
8193: DMAddBoundary - Add a boundary condition, for a single field, to a model represented by a `DM`
8195: Collective
8197: Input Parameters:
8198: + dm - The `DM`, with a `PetscDS` that matches the problem being constrained
8199: . type - The type of condition, e.g. `DM_BC_ESSENTIAL_ANALYTIC`, `DM_BC_ESSENTIAL_FIELD` (Dirichlet), or `DM_BC_NATURAL` (Neumann)
8200: . name - The BC name
8201: . label - The label defining constrained points
8202: . Nv - The number of `DMLabel` values for constrained points
8203: . values - An array of values for constrained points
8204: . field - The field to constrain
8205: . Nc - The number of constrained field components (0 will constrain all components)
8206: . comps - An array of constrained component numbers
8207: . bcFunc - A pointwise function giving boundary values
8208: . bcFunc_t - A pointwise function giving the time derivative of the boundary values, or `NULL`
8209: - ctx - An optional application context for `bcFunc`
8211: Output Parameter:
8212: . bd - (Optional) Boundary number
8214: Options Database Keys:
8215: + -bc_NAME values - Overrides the boundary ids for boundary named NAME
8216: - -bc_NAME_comp comps - Overrides the boundary components for boundary named NAME
8218: Level: intermediate
8220: Notes:
8221: If the `DM` is of type `DMPLEX` and the field is of type `PetscFE`, then this function completes the label using `DMPlexLabelComplete()`.
8223: Both bcFunc and bcFunc_t will depend on the boundary condition type. If the type if `DM_BC_ESSENTIAL`, then the calling sequence is\:
8224: .vb
8225: void bcFunc(PetscInt dim, PetscReal time, const PetscReal x[], PetscInt Nc, PetscScalar bcval[])
8226: .ve
8228: If the type is `DM_BC_ESSENTIAL_FIELD` or other _FIELD value, then the calling sequence is\:
8230: .vb
8231: void bcFunc(PetscInt dim, PetscInt Nf, PetscInt NfAux,
8232: const PetscInt uOff[], const PetscInt uOff_x[], const PetscScalar u[], const PetscScalar u_t[], const PetscScalar u_x[],
8233: const PetscInt aOff[], const PetscInt aOff_x[], const PetscScalar a[], const PetscScalar a_t[], const PetscScalar a_x[],
8234: PetscReal time, const PetscReal x[], PetscScalar bcval[])
8235: .ve
8236: + dim - the spatial dimension
8237: . Nf - the number of fields
8238: . uOff - the offset into u[] and u_t[] for each field
8239: . uOff_x - the offset into u_x[] for each field
8240: . u - each field evaluated at the current point
8241: . u_t - the time derivative of each field evaluated at the current point
8242: . u_x - the gradient of each field evaluated at the current point
8243: . aOff - the offset into a[] and a_t[] for each auxiliary field
8244: . aOff_x - the offset into a_x[] for each auxiliary field
8245: . a - each auxiliary field evaluated at the current point
8246: . a_t - the time derivative of each auxiliary field evaluated at the current point
8247: . a_x - the gradient of auxiliary each field evaluated at the current point
8248: . t - current time
8249: . x - coordinates of the current point
8250: . numConstants - number of constant parameters
8251: . constants - constant parameters
8252: - bcval - output values at the current point
8254: .seealso: [](ch_dmbase), `DM`, `DSGetBoundary()`, `PetscDSAddBoundary()`
8255: @*/
8256: PetscErrorCode DMAddBoundary(DM dm, DMBoundaryConditionType type, const char name[], DMLabel label, PetscInt Nv, const PetscInt values[], PetscInt field, PetscInt Nc, const PetscInt comps[], PetscVoidFn *bcFunc, PetscVoidFn *bcFunc_t, PetscCtx ctx, PetscInt *bd)
8257: {
8258: PetscDS ds;
8260: PetscFunctionBegin;
8267: PetscCheck(!dm->localSection, PetscObjectComm((PetscObject)dm), PETSC_ERR_ARG_WRONGSTATE, "Cannot add boundary to DM after creating local section");
8268: PetscCall(DMGetDS(dm, &ds));
8269: /* Complete label */
8270: if (label) {
8271: PetscObject obj;
8272: PetscClassId id;
8274: PetscCall(DMGetField(dm, field, NULL, &obj));
8275: PetscCall(PetscObjectGetClassId(obj, &id));
8276: if (id == PETSCFE_CLASSID) {
8277: DM plex;
8279: PetscCall(DMConvert(dm, DMPLEX, &plex));
8280: if (plex) PetscCall(DMPlexLabelComplete(plex, label));
8281: PetscCall(DMDestroy(&plex));
8282: }
8283: }
8284: PetscCall(PetscDSAddBoundary(ds, type, name, label, Nv, values, field, Nc, comps, bcFunc, bcFunc_t, ctx, bd));
8285: PetscFunctionReturn(PETSC_SUCCESS);
8286: }
8288: /* TODO Remove this since now the structures are the same */
8289: static PetscErrorCode DMPopulateBoundary(DM dm)
8290: {
8291: PetscDS ds;
8292: DMBoundary *lastnext;
8293: DSBoundary dsbound;
8295: PetscFunctionBegin;
8296: PetscCall(DMGetDS(dm, &ds));
8297: dsbound = ds->boundary;
8298: if (dm->boundary) {
8299: DMBoundary next = dm->boundary;
8301: /* quick check to see if the PetscDS has changed */
8302: if (next->dsboundary == dsbound) PetscFunctionReturn(PETSC_SUCCESS);
8303: /* the PetscDS has changed: tear down and rebuild */
8304: while (next) {
8305: DMBoundary b = next;
8307: next = b->next;
8308: PetscCall(PetscFree(b));
8309: }
8310: dm->boundary = NULL;
8311: }
8313: lastnext = &dm->boundary;
8314: while (dsbound) {
8315: DMBoundary dmbound;
8317: PetscCall(PetscNew(&dmbound));
8318: dmbound->dsboundary = dsbound;
8319: dmbound->label = dsbound->label;
8320: /* push on the back instead of the front so that it is in the same order as in the PetscDS */
8321: *lastnext = dmbound;
8322: lastnext = &dmbound->next;
8323: dsbound = dsbound->next;
8324: }
8325: PetscFunctionReturn(PETSC_SUCCESS);
8326: }
8328: /*@
8329: DMIsBoundaryPoint - Determine whether a mesh point lies on a `DM` boundary
8331: Not Collective
8333: Input Parameters:
8334: + dm - the `DM` object
8335: - point - the mesh point number
8337: Output Parameter:
8338: . isBd - `PETSC_TRUE` if `point` belongs to any boundary label registered on the `DM`
8340: Level: developer
8342: .seealso: [](ch_dmbase), `DM`, `DMLabel`, `DMAddBoundary()`, `PetscDSGetBoundary()`
8343: @*/
8344: PetscErrorCode DMIsBoundaryPoint(DM dm, PetscInt point, PetscBool *isBd)
8345: {
8346: DMBoundary b;
8348: PetscFunctionBegin;
8350: PetscAssertPointer(isBd, 3);
8351: *isBd = PETSC_FALSE;
8352: PetscCall(DMPopulateBoundary(dm));
8353: b = dm->boundary;
8354: while (b && !*isBd) {
8355: DMLabel label = b->label;
8356: DSBoundary dsb = b->dsboundary;
8358: if (label) {
8359: for (PetscInt i = 0; i < dsb->Nv && !*isBd; ++i) PetscCall(DMLabelStratumHasPoint(label, dsb->values[i], point, isBd));
8360: }
8361: b = b->next;
8362: }
8363: PetscFunctionReturn(PETSC_SUCCESS);
8364: }
8366: /*@
8367: DMHasBound - Determine whether a bound condition was specified
8369: Logically collective
8371: Input Parameter:
8372: . dm - The `DM`, with a `PetscDS` that matches the problem being constrained
8374: Output Parameter:
8375: . hasBound - Flag indicating if a bound condition was specified
8377: Level: intermediate
8379: .seealso: [](ch_dmbase), `DM`, `DSAddBoundary()`, `PetscDSAddBoundary()`
8380: @*/
8381: PetscErrorCode DMHasBound(DM dm, PetscBool *hasBound)
8382: {
8383: PetscDS ds;
8384: PetscInt Nf, numBd;
8386: PetscFunctionBegin;
8387: *hasBound = PETSC_FALSE;
8388: PetscCall(DMGetDS(dm, &ds));
8389: PetscCall(PetscDSGetNumFields(ds, &Nf));
8390: for (PetscInt f = 0; f < Nf; ++f) {
8391: PetscSimplePointFn *lfunc, *ufunc;
8393: PetscCall(PetscDSGetLowerBound(ds, f, &lfunc, NULL));
8394: PetscCall(PetscDSGetUpperBound(ds, f, &ufunc, NULL));
8395: if (lfunc || ufunc) *hasBound = PETSC_TRUE;
8396: }
8398: PetscCall(PetscDSGetNumBoundary(ds, &numBd));
8399: PetscCall(PetscDSUpdateBoundaryLabels(ds, dm));
8400: for (PetscInt b = 0; b < numBd; ++b) {
8401: PetscWeakForm wf;
8402: DMBoundaryConditionType type;
8403: const char *name;
8404: DMLabel label;
8405: PetscInt numids;
8406: const PetscInt *ids;
8407: PetscInt field, Nc;
8408: const PetscInt *comps;
8409: PetscVoidFn *bvfunc;
8410: void *ctx;
8412: PetscCall(PetscDSGetBoundary(ds, b, &wf, &type, &name, &label, &numids, &ids, &field, &Nc, &comps, &bvfunc, NULL, &ctx));
8413: if (type == DM_BC_LOWER_BOUND || type == DM_BC_UPPER_BOUND) *hasBound = PETSC_TRUE;
8414: }
8415: PetscFunctionReturn(PETSC_SUCCESS);
8416: }
8418: /*@
8419: DMProjectFunction - This projects the given function into the function space provided by a `DM`, putting the coefficients in a global vector.
8421: Collective
8423: Input Parameters:
8424: + dm - The `DM`
8425: . time - The time
8426: . funcs - The coordinate functions to evaluate, one per field
8427: . ctxs - Optional array of contexts to pass to each coordinate function. ctxs itself may be null.
8428: - mode - The insertion mode for values
8430: Output Parameter:
8431: . X - vector
8433: Calling sequence of `funcs`:
8434: + dim - The spatial dimension
8435: . time - The time at which to sample
8436: . x - The coordinates
8437: . Nc - The number of components
8438: . u - The output field values
8439: - ctx - optional function context
8441: Level: developer
8443: Developer Notes:
8444: This API is specific to only particular usage of `DM`
8446: The notes need to provide some information about what has to be provided to the `DM` to be able to perform the computation.
8448: .seealso: [](ch_dmbase), `DM`, `DMProjectFunctionLocal()`, `DMProjectFunctionLabel()`, `DMComputeL2Diff()`
8449: @*/
8450: PetscErrorCode DMProjectFunction(DM dm, PetscReal time, PetscErrorCode (**funcs)(PetscInt dim, PetscReal time, const PetscReal x[], PetscInt Nc, PetscScalar *u, PetscCtx ctx), void **ctxs, InsertMode mode, Vec X)
8451: {
8452: Vec localX;
8454: PetscFunctionBegin;
8456: PetscCall(PetscLogEventBegin(DM_ProjectFunction, dm, X, 0, 0));
8457: PetscCall(DMGetLocalVector(dm, &localX));
8458: PetscCall(VecSet(localX, 0.));
8459: PetscCall(DMProjectFunctionLocal(dm, time, funcs, ctxs, mode, localX));
8460: PetscCall(DMLocalToGlobalBegin(dm, localX, mode, X));
8461: PetscCall(DMLocalToGlobalEnd(dm, localX, mode, X));
8462: PetscCall(DMRestoreLocalVector(dm, &localX));
8463: PetscCall(PetscLogEventEnd(DM_ProjectFunction, dm, X, 0, 0));
8464: PetscFunctionReturn(PETSC_SUCCESS);
8465: }
8467: /*@
8468: DMProjectFunctionLocal - This projects the given function into the function space provided by a `DM`, putting the coefficients in a local vector.
8470: Not Collective
8472: Input Parameters:
8473: + dm - The `DM`
8474: . time - The time
8475: . funcs - The coordinate functions to evaluate, one per field
8476: . ctxs - Optional array of contexts to pass to each coordinate function. ctxs itself may be null.
8477: - mode - The insertion mode for values
8479: Output Parameter:
8480: . localX - vector
8482: Calling sequence of `funcs`:
8483: + dim - The spatial dimension
8484: . time - The current timestep
8485: . x - The coordinates
8486: . Nc - The number of components
8487: . u - The output field values
8488: - ctx - optional function context
8490: Level: developer
8492: Developer Notes:
8493: This API is specific to only particular usage of `DM`
8495: The notes need to provide some information about what has to be provided to the `DM` to be able to perform the computation.
8497: .seealso: [](ch_dmbase), `DM`, `DMProjectFunction()`, `DMProjectFunctionLabel()`, `DMComputeL2Diff()`
8498: @*/
8499: PetscErrorCode DMProjectFunctionLocal(DM dm, PetscReal time, PetscErrorCode (**funcs)(PetscInt dim, PetscReal time, const PetscReal x[], PetscInt Nc, PetscScalar *u, PetscCtx ctx), void **ctxs, InsertMode mode, Vec localX)
8500: {
8501: PetscFunctionBegin;
8504: PetscUseTypeMethod(dm, projectfunctionlocal, time, funcs, ctxs, mode, localX);
8505: PetscFunctionReturn(PETSC_SUCCESS);
8506: }
8508: /*@
8509: DMProjectFunctionLabel - This projects the given function into the function space provided by the `DM`, putting the coefficients in a global vector, setting values only for points in the given label.
8511: Collective
8513: Input Parameters:
8514: + dm - The `DM`
8515: . time - The time
8516: . numIds - The number of ids
8517: . ids - The ids
8518: . Nc - The number of components
8519: . comps - The components
8520: . label - The `DMLabel` selecting the portion of the mesh for projection
8521: . funcs - The coordinate functions to evaluate, one per field
8522: . ctxs - Optional array of contexts to pass to each coordinate function. ctxs may be null.
8523: - mode - The insertion mode for values
8525: Output Parameter:
8526: . X - vector
8528: Calling sequence of `funcs`:
8529: + dim - The spatial dimension
8530: . time - The current timestep
8531: . x - The coordinates
8532: . Nc - The number of components
8533: . u - The output field values
8534: - ctx - optional function context
8536: Level: developer
8538: Developer Notes:
8539: This API is specific to only particular usage of `DM`
8541: The notes need to provide some information about what has to be provided to the `DM` to be able to perform the computation.
8543: .seealso: [](ch_dmbase), `DM`, `DMProjectFunction()`, `DMProjectFunctionLocal()`, `DMProjectFunctionLabelLocal()`, `DMComputeL2Diff()`
8544: @*/
8545: PetscErrorCode DMProjectFunctionLabel(DM dm, PetscReal time, DMLabel label, PetscInt numIds, const PetscInt ids[], PetscInt Nc, const PetscInt comps[], PetscErrorCode (**funcs)(PetscInt dim, PetscReal time, const PetscReal x[], PetscInt Nc, PetscScalar *u, PetscCtx ctx), void **ctxs, InsertMode mode, Vec X)
8546: {
8547: Vec localX;
8549: PetscFunctionBegin;
8551: PetscCall(DMGetLocalVector(dm, &localX));
8552: PetscCall(VecSet(localX, 0.));
8553: PetscCall(DMProjectFunctionLabelLocal(dm, time, label, numIds, ids, Nc, comps, funcs, ctxs, mode, localX));
8554: PetscCall(DMLocalToGlobalBegin(dm, localX, mode, X));
8555: PetscCall(DMLocalToGlobalEnd(dm, localX, mode, X));
8556: PetscCall(DMRestoreLocalVector(dm, &localX));
8557: PetscFunctionReturn(PETSC_SUCCESS);
8558: }
8560: /*@
8561: DMProjectFunctionLabelLocal - This projects the given function into the function space provided by the `DM`, putting the coefficients in a local vector, setting values only for points in the given label.
8563: Not Collective
8565: Input Parameters:
8566: + dm - The `DM`
8567: . time - The time
8568: . label - The `DMLabel` selecting the portion of the mesh for projection
8569: . numIds - The number of ids
8570: . ids - The ids
8571: . Nc - The number of components
8572: . comps - The components
8573: . funcs - The coordinate functions to evaluate, one per field
8574: . ctxs - Optional array of contexts to pass to each coordinate function. ctxs itself may be null.
8575: - mode - The insertion mode for values
8577: Output Parameter:
8578: . localX - vector
8580: Calling sequence of `funcs`:
8581: + dim - The spatial dimension
8582: . time - The current time
8583: . x - The coordinates
8584: . Nc - The number of components
8585: . u - The output field values
8586: - ctx - optional function context
8588: Level: developer
8590: Developer Notes:
8591: This API is specific to only particular usage of `DM`
8593: The notes need to provide some information about what has to be provided to the `DM` to be able to perform the computation.
8595: .seealso: [](ch_dmbase), `DM`, `DMProjectFunction()`, `DMProjectFunctionLocal()`, `DMProjectFunctionLabel()`, `DMComputeL2Diff()`
8596: @*/
8597: PetscErrorCode DMProjectFunctionLabelLocal(DM dm, PetscReal time, DMLabel label, PetscInt numIds, const PetscInt ids[], PetscInt Nc, const PetscInt comps[], PetscErrorCode (**funcs)(PetscInt dim, PetscReal time, const PetscReal x[], PetscInt Nc, PetscScalar *u, PetscCtx ctx), void **ctxs, InsertMode mode, Vec localX)
8598: {
8599: PetscFunctionBegin;
8602: PetscUseTypeMethod(dm, projectfunctionlabellocal, time, label, numIds, ids, Nc, comps, funcs, ctxs, mode, localX);
8603: PetscFunctionReturn(PETSC_SUCCESS);
8604: }
8606: /*@
8607: DMProjectFieldLocal - This projects the given function of the input fields into the function space provided by the `DM`, putting the coefficients in a local vector.
8609: Not Collective
8611: Input Parameters:
8612: + dm - The `DM`
8613: . time - The time
8614: . localU - The input field vector; may be `NULL` if projection is defined purely by coordinates
8615: . funcs - The functions to evaluate, one per field
8616: - mode - The insertion mode for values
8618: Output Parameter:
8619: . localX - The output vector
8621: Calling sequence of `funcs`:
8622: + dim - The spatial dimension
8623: . Nf - The number of input fields
8624: . NfAux - The number of input auxiliary fields
8625: . uOff - The offset of each field in u[]
8626: . uOff_x - The offset of each field in u_x[]
8627: . u - The field values at this point in space
8628: . u_t - The field time derivative at this point in space (or `NULL`)
8629: . u_x - The field derivatives at this point in space
8630: . aOff - The offset of each auxiliary field in u[]
8631: . aOff_x - The offset of each auxiliary field in u_x[]
8632: . a - The auxiliary field values at this point in space
8633: . a_t - The auxiliary field time derivative at this point in space (or `NULL`)
8634: . a_x - The auxiliary field derivatives at this point in space
8635: . t - The current time
8636: . x - The coordinates of this point
8637: . numConstants - The number of constants
8638: . constants - The value of each constant
8639: - f - The value of the function at this point in space
8641: Level: intermediate
8643: Note:
8644: There are three different `DM`s that potentially interact in this function. The output `DM`, dm, specifies the layout of the values calculates by funcs.
8645: The input `DM`, attached to U, may be different. For example, you can input the solution over the full domain, but output over a piece of the boundary, or
8646: a subdomain. You can also output a different number of fields than the input, with different discretizations. Last the auxiliary `DM`, attached to the
8647: auxiliary field vector, which is attached to dm, can also be different. It can have a different topology, number of fields, and discretizations.
8649: Developer Notes:
8650: This API is specific to only particular usage of `DM`
8652: The notes need to provide some information about what has to be provided to the `DM` to be able to perform the computation.
8654: .seealso: [](ch_dmbase), `DM`, `DMProjectField()`, `DMProjectFieldLabelLocal()`,
8655: `DMProjectFunction()`, `DMComputeL2Diff()`
8656: @*/
8657: PetscErrorCode DMProjectFieldLocal(DM dm, PetscReal time, Vec localU, void (**funcs)(PetscInt dim, PetscInt Nf, PetscInt NfAux, const PetscInt uOff[], const PetscInt uOff_x[], const PetscScalar u[], const PetscScalar u_t[], const PetscScalar u_x[], const PetscInt aOff[], const PetscInt aOff_x[], const PetscScalar a[], const PetscScalar a_t[], const PetscScalar a_x[], PetscReal t, const PetscReal x[], PetscInt numConstants, const PetscScalar constants[], PetscScalar f[]), InsertMode mode, Vec localX)
8658: {
8659: PetscFunctionBegin;
8663: PetscUseTypeMethod(dm, projectfieldlocal, time, localU, funcs, mode, localX);
8664: PetscFunctionReturn(PETSC_SUCCESS);
8665: }
8667: /*@
8668: DMProjectFieldLabelLocal - This projects the given function of the input fields into the function space provided, putting the coefficients in a local vector, calculating only over the portion of the domain specified by the label.
8670: Not Collective
8672: Input Parameters:
8673: + dm - The `DM`
8674: . time - The time
8675: . label - The `DMLabel` marking the portion of the domain to output
8676: . numIds - The number of label ids to use
8677: . ids - The label ids to use for marking
8678: . Nc - The number of components to set in the output, or `PETSC_DETERMINE` for all components
8679: . comps - The components to set in the output, or `NULL` for all components
8680: . localU - The input field vector
8681: . funcs - The functions to evaluate, one per field
8682: - mode - The insertion mode for values
8684: Output Parameter:
8685: . localX - The output vector
8687: Calling sequence of `funcs`:
8688: + dim - The spatial dimension
8689: . Nf - The number of input fields
8690: . NfAux - The number of input auxiliary fields
8691: . uOff - The offset of each field in u[]
8692: . uOff_x - The offset of each field in u_x[]
8693: . u - The field values at this point in space
8694: . u_t - The field time derivative at this point in space (or `NULL`)
8695: . u_x - The field derivatives at this point in space
8696: . aOff - The offset of each auxiliary field in u[]
8697: . aOff_x - The offset of each auxiliary field in u_x[]
8698: . a - The auxiliary field values at this point in space
8699: . a_t - The auxiliary field time derivative at this point in space (or `NULL`)
8700: . a_x - The auxiliary field derivatives at this point in space
8701: . t - The current time
8702: . x - The coordinates of this point
8703: . numConstants - The number of constants
8704: . constants - The value of each constant
8705: - f - The value of the function at this point in space
8707: Level: intermediate
8709: Note:
8710: There are three different `DM`s that potentially interact in this function. The output `DM`, dm, specifies the layout of the values calculates by funcs.
8711: The input `DM`, attached to localU, may be different. For example, you can input the solution over the full domain, but output over a piece of the boundary, or
8712: a subdomain. You can also output a different number of fields than the input, with different discretizations. Last the auxiliary `DM`, attached to the
8713: auxiliary field vector, which is attached to dm, can also be different. It can have a different topology, number of fields, and discretizations.
8715: Developer Notes:
8716: This API is specific to only particular usage of `DM`
8718: The notes need to provide some information about what has to be provided to the `DM` to be able to perform the computation.
8720: .seealso: [](ch_dmbase), `DM`, `DMProjectField()`, `DMProjectFieldLabel()`, `DMProjectFunction()`, `DMComputeL2Diff()`
8721: @*/
8722: PetscErrorCode DMProjectFieldLabelLocal(DM dm, PetscReal time, DMLabel label, PetscInt numIds, const PetscInt ids[], PetscInt Nc, const PetscInt comps[], Vec localU, void (**funcs)(PetscInt dim, PetscInt Nf, PetscInt NfAux, const PetscInt uOff[], const PetscInt uOff_x[], const PetscScalar u[], const PetscScalar u_t[], const PetscScalar u_x[], const PetscInt aOff[], const PetscInt aOff_x[], const PetscScalar a[], const PetscScalar a_t[], const PetscScalar a_x[], PetscReal t, const PetscReal x[], PetscInt numConstants, const PetscScalar constants[], PetscScalar f[]), InsertMode mode, Vec localX)
8723: {
8724: PetscFunctionBegin;
8728: PetscUseTypeMethod(dm, projectfieldlabellocal, time, label, numIds, ids, Nc, comps, localU, funcs, mode, localX);
8729: PetscFunctionReturn(PETSC_SUCCESS);
8730: }
8732: /*@
8733: DMProjectFieldLabel - This projects the given function of the input fields into the function space provided, putting the coefficients in a global vector, calculating only over the portion of the domain specified by the label.
8735: Not Collective
8737: Input Parameters:
8738: + dm - The `DM`
8739: . time - The time
8740: . label - The `DMLabel` marking the portion of the domain to output
8741: . numIds - The number of label ids to use
8742: . ids - The label ids to use for marking
8743: . Nc - The number of components to set in the output, or `PETSC_DETERMINE` for all components
8744: . comps - The components to set in the output, or `NULL` for all components
8745: . U - The input field vector
8746: . funcs - The functions to evaluate, one per field
8747: - mode - The insertion mode for values
8749: Output Parameter:
8750: . X - The output vector
8752: Calling sequence of `funcs`:
8753: + dim - The spatial dimension
8754: . Nf - The number of input fields
8755: . NfAux - The number of input auxiliary fields
8756: . uOff - The offset of each field in u[]
8757: . uOff_x - The offset of each field in u_x[]
8758: . u - The field values at this point in space
8759: . u_t - The field time derivative at this point in space (or `NULL`)
8760: . u_x - The field derivatives at this point in space
8761: . aOff - The offset of each auxiliary field in u[]
8762: . aOff_x - The offset of each auxiliary field in u_x[]
8763: . a - The auxiliary field values at this point in space
8764: . a_t - The auxiliary field time derivative at this point in space (or `NULL`)
8765: . a_x - The auxiliary field derivatives at this point in space
8766: . t - The current time
8767: . x - The coordinates of this point
8768: . numConstants - The number of constants
8769: . constants - The value of each constant
8770: - f - The value of the function at this point in space
8772: Level: intermediate
8774: Note:
8775: There are three different `DM`s that potentially interact in this function. The output `DM`, dm, specifies the layout of the values calculates by funcs.
8776: The input `DM`, attached to U, may be different. For example, you can input the solution over the full domain, but output over a piece of the boundary, or
8777: a subdomain. You can also output a different number of fields than the input, with different discretizations. Last the auxiliary `DM`, attached to the
8778: auxiliary field vector, which is attached to dm, can also be different. It can have a different topology, number of fields, and discretizations.
8780: Developer Notes:
8781: This API is specific to only particular usage of `DM`
8783: The notes need to provide some information about what has to be provided to the `DM` to be able to perform the computation.
8785: .seealso: [](ch_dmbase), `DM`, `DMProjectField()`, `DMProjectFieldLabelLocal()`, `DMProjectFunction()`, `DMComputeL2Diff()`
8786: @*/
8787: PetscErrorCode DMProjectFieldLabel(DM dm, PetscReal time, DMLabel label, PetscInt numIds, const PetscInt ids[], PetscInt Nc, const PetscInt comps[], Vec U, void (**funcs)(PetscInt dim, PetscInt Nf, PetscInt NfAux, const PetscInt uOff[], const PetscInt uOff_x[], const PetscScalar u[], const PetscScalar u_t[], const PetscScalar u_x[], const PetscInt aOff[], const PetscInt aOff_x[], const PetscScalar a[], const PetscScalar a_t[], const PetscScalar a_x[], PetscReal t, const PetscReal x[], PetscInt numConstants, const PetscScalar constants[], PetscScalar f[]), InsertMode mode, Vec X)
8788: {
8789: DM dmIn;
8790: Vec localU, localX;
8792: PetscFunctionBegin;
8794: PetscCall(VecGetDM(U, &dmIn));
8795: PetscCall(DMGetLocalVector(dmIn, &localU));
8796: PetscCall(DMGetLocalVector(dm, &localX));
8797: PetscCall(VecSet(localX, 0.));
8798: PetscCall(DMGlobalToLocalBegin(dmIn, U, mode, localU));
8799: PetscCall(DMGlobalToLocalEnd(dmIn, U, mode, localU));
8800: PetscCall(DMProjectFieldLabelLocal(dm, time, label, numIds, ids, Nc, comps, localU, funcs, mode, localX));
8801: PetscCall(DMLocalToGlobalBegin(dm, localX, mode, X));
8802: PetscCall(DMLocalToGlobalEnd(dm, localX, mode, X));
8803: PetscCall(DMRestoreLocalVector(dm, &localX));
8804: PetscCall(DMRestoreLocalVector(dmIn, &localU));
8805: PetscFunctionReturn(PETSC_SUCCESS);
8806: }
8808: /*@
8809: DMProjectBdFieldLabelLocal - This projects the given function of the input fields into the function space provided, putting the coefficients in a local vector, calculating only over the portion of the domain boundary specified by the label.
8811: Not Collective
8813: Input Parameters:
8814: + dm - The `DM`
8815: . time - The time
8816: . label - The `DMLabel` marking the portion of the domain boundary to output
8817: . numIds - The number of label ids to use
8818: . ids - The label ids to use for marking
8819: . Nc - The number of components to set in the output, or `PETSC_DETERMINE` for all components
8820: . comps - The components to set in the output, or `NULL` for all components
8821: . localU - The input field vector
8822: . funcs - The functions to evaluate, one per field
8823: - mode - The insertion mode for values
8825: Output Parameter:
8826: . localX - The output vector
8828: Calling sequence of `funcs`:
8829: + dim - The spatial dimension
8830: . Nf - The number of input fields
8831: . NfAux - The number of input auxiliary fields
8832: . uOff - The offset of each field in u[]
8833: . uOff_x - The offset of each field in u_x[]
8834: . u - The field values at this point in space
8835: . u_t - The field time derivative at this point in space (or `NULL`)
8836: . u_x - The field derivatives at this point in space
8837: . aOff - The offset of each auxiliary field in u[]
8838: . aOff_x - The offset of each auxiliary field in u_x[]
8839: . a - The auxiliary field values at this point in space
8840: . a_t - The auxiliary field time derivative at this point in space (or `NULL`)
8841: . a_x - The auxiliary field derivatives at this point in space
8842: . t - The current time
8843: . x - The coordinates of this point
8844: . n - The face normal
8845: . numConstants - The number of constants
8846: . constants - The value of each constant
8847: - f - The value of the function at this point in space
8849: Level: intermediate
8851: Note:
8852: There are three different `DM`s that potentially interact in this function. The output `DM`, dm, specifies the layout of the values calculates by funcs.
8853: The input `DM`, attached to U, may be different. For example, you can input the solution over the full domain, but output over a piece of the boundary, or
8854: a subdomain. You can also output a different number of fields than the input, with different discretizations. Last the auxiliary `DM`, attached to the
8855: auxiliary field vector, which is attached to dm, can also be different. It can have a different topology, number of fields, and discretizations.
8857: Developer Notes:
8858: This API is specific to only particular usage of `DM`
8860: The notes need to provide some information about what has to be provided to the `DM` to be able to perform the computation.
8862: .seealso: [](ch_dmbase), `DM`, `DMProjectField()`, `DMProjectFieldLabelLocal()`, `DMProjectFunction()`, `DMComputeL2Diff()`
8863: @*/
8864: PetscErrorCode DMProjectBdFieldLabelLocal(DM dm, PetscReal time, DMLabel label, PetscInt numIds, const PetscInt ids[], PetscInt Nc, const PetscInt comps[], Vec localU, void (**funcs)(PetscInt dim, PetscInt Nf, PetscInt NfAux, const PetscInt uOff[], const PetscInt uOff_x[], const PetscScalar u[], const PetscScalar u_t[], const PetscScalar u_x[], const PetscInt aOff[], const PetscInt aOff_x[], const PetscScalar a[], const PetscScalar a_t[], const PetscScalar a_x[], PetscReal t, const PetscReal x[], const PetscReal n[], PetscInt numConstants, const PetscScalar constants[], PetscScalar f[]), InsertMode mode, Vec localX)
8865: {
8866: PetscFunctionBegin;
8870: PetscUseTypeMethod(dm, projectbdfieldlabellocal, time, label, numIds, ids, Nc, comps, localU, funcs, mode, localX);
8871: PetscFunctionReturn(PETSC_SUCCESS);
8872: }
8874: /*@
8875: DMComputeL2Diff - This function computes the L_2 difference between a function u and an FEM interpolant solution u_h.
8877: Collective
8879: Input Parameters:
8880: + dm - The `DM`
8881: . time - The time
8882: . funcs - The functions to evaluate for each field component
8883: . ctxs - Optional array of contexts to pass to each function, or `NULL`.
8884: - X - The coefficient vector u_h, a global vector
8886: Output Parameter:
8887: . diff - The diff ||u - u_h||_2
8889: Level: developer
8891: Developer Notes:
8892: This API is specific to only particular usage of `DM`
8894: The notes need to provide some information about what has to be provided to the `DM` to be able to perform the computation.
8896: .seealso: [](ch_dmbase), `DM`, `DMProjectFunction()`, `DMComputeL2FieldDiff()`, `DMComputeL2GradientDiff()`
8897: @*/
8898: PetscErrorCode DMComputeL2Diff(DM dm, PetscReal time, PetscErrorCode (**funcs)(PetscInt, PetscReal, const PetscReal[], PetscInt, PetscScalar *, void *), void **ctxs, Vec X, PetscReal *diff)
8899: {
8900: PetscFunctionBegin;
8903: PetscUseTypeMethod(dm, computel2diff, time, funcs, ctxs, X, diff);
8904: PetscFunctionReturn(PETSC_SUCCESS);
8905: }
8907: /*@
8908: DMComputeL2GradientDiff - This function computes the L_2 difference between the gradient of a function u and an FEM interpolant solution grad u_h.
8910: Collective
8912: Input Parameters:
8913: + dm - The `DM`
8914: . time - The time
8915: . funcs - The gradient functions to evaluate for each field component
8916: . ctxs - Optional array of contexts to pass to each function, or `NULL`.
8917: . X - The coefficient vector u_h, a global vector
8918: - n - The vector to project along
8920: Output Parameter:
8921: . diff - The diff ||(grad u - grad u_h) . n||_2
8923: Level: developer
8925: Developer Notes:
8926: This API is specific to only particular usage of `DM`
8928: The notes need to provide some information about what has to be provided to the `DM` to be able to perform the computation.
8930: .seealso: [](ch_dmbase), `DM`, `DMProjectFunction()`, `DMComputeL2Diff()`, `DMComputeL2FieldDiff()`
8931: @*/
8932: PetscErrorCode DMComputeL2GradientDiff(DM dm, PetscReal time, PetscErrorCode (**funcs)(PetscInt, PetscReal, const PetscReal[], const PetscReal[], PetscInt, PetscScalar *, void *), void **ctxs, Vec X, const PetscReal n[], PetscReal *diff)
8933: {
8934: PetscFunctionBegin;
8937: PetscUseTypeMethod(dm, computel2gradientdiff, time, funcs, ctxs, X, n, diff);
8938: PetscFunctionReturn(PETSC_SUCCESS);
8939: }
8941: /*@
8942: DMComputeL2FieldDiff - This function computes the L_2 difference between a function u and an FEM interpolant solution u_h, separated into field components.
8944: Collective
8946: Input Parameters:
8947: + dm - The `DM`
8948: . time - The time
8949: . funcs - The functions to evaluate for each field component
8950: . ctxs - Optional array of contexts to pass to each function, or `NULL`.
8951: - X - The coefficient vector u_h, a global vector
8953: Output Parameter:
8954: . diff - The array of differences, ||u^f - u^f_h||_2
8956: Level: developer
8958: Developer Notes:
8959: This API is specific to only particular usage of `DM`
8961: The notes need to provide some information about what has to be provided to the `DM` to be able to perform the computation.
8963: .seealso: [](ch_dmbase), `DM`, `DMProjectFunction()`, `DMComputeL2GradientDiff()`
8964: @*/
8965: PetscErrorCode DMComputeL2FieldDiff(DM dm, PetscReal time, PetscErrorCode (**funcs)(PetscInt, PetscReal, const PetscReal[], PetscInt, PetscScalar *, void *), void **ctxs, Vec X, PetscReal diff[])
8966: {
8967: PetscFunctionBegin;
8970: PetscUseTypeMethod(dm, computel2fielddiff, time, funcs, ctxs, X, diff);
8971: PetscFunctionReturn(PETSC_SUCCESS);
8972: }
8974: /*@
8975: DMGetNeighbors - Gets an array containing the MPI ranks of all the processes neighbors
8977: Not Collective
8979: Input Parameter:
8980: . dm - The `DM`
8982: Output Parameters:
8983: + nranks - the number of neighbours
8984: - ranks - the neighbors ranks
8986: Level: beginner
8988: Note:
8989: Do not free the array, it is freed when the `DM` is destroyed.
8991: .seealso: [](ch_dmbase), `DM`, `DMDAGetNeighbors()`, `PetscSFGetRootRanks()`
8992: @*/
8993: PetscErrorCode DMGetNeighbors(DM dm, PetscInt *nranks, const PetscMPIInt *ranks[])
8994: {
8995: PetscFunctionBegin;
8997: PetscUseTypeMethod(dm, getneighbors, nranks, ranks);
8998: PetscFunctionReturn(PETSC_SUCCESS);
8999: }
9001: #include <petsc/private/matimpl.h>
9003: /*
9004: Converts the input vector to a ghosted vector and then calls the standard coloring code.
9005: This must be a different function because it requires DM which is not defined in the Mat library
9006: */
9007: static PetscErrorCode MatFDColoringApply_AIJDM(Mat J, MatFDColoring coloring, Vec x1, void *sctx)
9008: {
9009: PetscFunctionBegin;
9010: if (coloring->ctype == IS_COLORING_LOCAL) {
9011: Vec x1local;
9012: DM dm;
9013: PetscCall(MatGetDM(J, &dm));
9014: PetscCheck(dm, PetscObjectComm((PetscObject)J), PETSC_ERR_ARG_INCOMP, "IS_COLORING_LOCAL requires a DM");
9015: PetscCall(DMGetLocalVector(dm, &x1local));
9016: PetscCall(DMGlobalToLocalBegin(dm, x1, INSERT_VALUES, x1local));
9017: PetscCall(DMGlobalToLocalEnd(dm, x1, INSERT_VALUES, x1local));
9018: x1 = x1local;
9019: }
9020: PetscCall(MatFDColoringApply_AIJ(J, coloring, x1, sctx));
9021: if (coloring->ctype == IS_COLORING_LOCAL) {
9022: DM dm;
9023: PetscCall(MatGetDM(J, &dm));
9024: PetscCall(DMRestoreLocalVector(dm, &x1));
9025: }
9026: PetscFunctionReturn(PETSC_SUCCESS);
9027: }
9029: /*@
9030: MatFDColoringUseDM - allows a `MatFDColoring` object to use the `DM` associated with the matrix to compute a `IS_COLORING_LOCAL` coloring
9032: Input Parameters:
9033: + coloring - The matrix to get the `DM` from
9034: - fdcoloring - the `MatFDColoring` object
9036: Level: advanced
9038: Developer Note:
9039: This routine exists because the PETSc `Mat` library does not know about the `DM` objects
9041: .seealso: [](ch_dmbase), `DM`, `MatFDColoring`, `MatFDColoringCreate()`, `ISColoringType`
9042: @*/
9043: PetscErrorCode MatFDColoringUseDM(Mat coloring, MatFDColoring fdcoloring)
9044: {
9045: PetscFunctionBegin;
9046: coloring->ops->fdcoloringapply = MatFDColoringApply_AIJDM;
9047: PetscFunctionReturn(PETSC_SUCCESS);
9048: }
9050: /*@
9051: DMGetCompatibility - determine if two `DM`s are compatible
9053: Collective
9055: Input Parameters:
9056: + dm1 - the first `DM`
9057: - dm2 - the second `DM`
9059: Output Parameters:
9060: + compatible - whether or not the two `DM`s are compatible
9061: - set - whether or not the compatible value was actually determined and set
9063: Level: advanced
9065: Notes:
9066: Two `DM`s are deemed compatible if they represent the same parallel decomposition
9067: of the same topology. This implies that the section (field data) on one
9068: "makes sense" with respect to the topology and parallel decomposition of the other.
9069: Loosely speaking, compatible `DM`s represent the same domain and parallel
9070: decomposition, but hold different data.
9072: Typically, one would confirm compatibility if intending to simultaneously iterate
9073: over a pair of vectors obtained from different `DM`s.
9075: For example, two `DMDA` objects are compatible if they have the same local
9076: and global sizes and the same stencil width. They can have different numbers
9077: of degrees of freedom per node. Thus, one could use the node numbering from
9078: either `DM` in bounds for a loop over vectors derived from either `DM`.
9080: Consider the operation of summing data living on a 2-dof `DMDA` to data living
9081: on a 1-dof `DMDA`, which should be compatible, as in the following snippet.
9082: .vb
9083: ...
9084: PetscCall(DMGetCompatibility(da1,da2,&compatible,&set));
9085: if (set && compatible) {
9086: PetscCall(DMDAVecGetArrayDOF(da1,vec1,&arr1));
9087: PetscCall(DMDAVecGetArrayDOF(da2,vec2,&arr2));
9088: PetscCall(DMDAGetCorners(da1,&x,&y,NULL,&m,&n,NULL));
9089: for (j=y; j<y+n; ++j) {
9090: for (i=x; i<x+m, ++i) {
9091: arr1[j][i][0] = arr2[j][i][0] + arr2[j][i][1];
9092: }
9093: }
9094: PetscCall(DMDAVecRestoreArrayDOF(da1,vec1,&arr1));
9095: PetscCall(DMDAVecRestoreArrayDOF(da2,vec2,&arr2));
9096: } else {
9097: SETERRQ(PetscObjectComm((PetscObject)da1,PETSC_ERR_ARG_INCOMP,"DMDA objects incompatible");
9098: }
9099: ...
9100: .ve
9102: Checking compatibility might be expensive for a given implementation of `DM`,
9103: or might be impossible to unambiguously confirm or deny. For this reason,
9104: this function may decline to determine compatibility, and hence users should
9105: always check the "set" output parameter.
9107: A `DM` is always compatible with itself.
9109: In the current implementation, `DM`s which live on "unequal" communicators
9110: (MPI_UNEQUAL in the terminology of MPI_Comm_compare()) are always deemed
9111: incompatible.
9113: This function is labeled "Collective," as information about all subdomains
9114: is required on each rank. However, in `DM` implementations which store all this
9115: information locally, this function may be merely "Logically Collective".
9117: Developer Note:
9118: Compatibility is assumed to be a symmetric concept; `DM` A is compatible with `DM` B
9119: iff B is compatible with A. Thus, this function checks the implementations
9120: of both dm and dmc (if they are of different types), attempting to determine
9121: compatibility. It is left to `DM` implementers to ensure that symmetry is
9122: preserved. The simplest way to do this is, when implementing type-specific
9123: logic for this function, is to check for existing logic in the implementation
9124: of other `DM` types and let *set = PETSC_FALSE if found.
9126: .seealso: [](ch_dmbase), `DM`, `DMDACreateCompatibleDMDA()`, `DMStagCreateCompatibleDMStag()`
9127: @*/
9128: PetscErrorCode DMGetCompatibility(DM dm1, DM dm2, PetscBool *compatible, PetscBool *set)
9129: {
9130: PetscMPIInt compareResult;
9131: DMType type, type2;
9132: PetscBool sameType;
9134: PetscFunctionBegin;
9138: /* Declare a DM compatible with itself */
9139: if (dm1 == dm2) {
9140: *set = PETSC_TRUE;
9141: *compatible = PETSC_TRUE;
9142: PetscFunctionReturn(PETSC_SUCCESS);
9143: }
9145: /* Declare a DM incompatible with a DM that lives on an "unequal"
9146: communicator. Note that this does not preclude compatibility with
9147: DMs living on "congruent" or "similar" communicators, but this must be
9148: determined by the implementation-specific logic */
9149: PetscCallMPI(MPI_Comm_compare(PetscObjectComm((PetscObject)dm1), PetscObjectComm((PetscObject)dm2), &compareResult));
9150: if (compareResult == MPI_UNEQUAL) {
9151: *set = PETSC_TRUE;
9152: *compatible = PETSC_FALSE;
9153: PetscFunctionReturn(PETSC_SUCCESS);
9154: }
9156: /* Pass to the implementation-specific routine, if one exists. */
9157: if (dm1->ops->getcompatibility) {
9158: PetscUseTypeMethod(dm1, getcompatibility, dm2, compatible, set);
9159: if (*set) PetscFunctionReturn(PETSC_SUCCESS);
9160: }
9162: /* If dm1 and dm2 are of different types, then attempt to check compatibility
9163: with an implementation of this function from dm2 */
9164: PetscCall(DMGetType(dm1, &type));
9165: PetscCall(DMGetType(dm2, &type2));
9166: PetscCall(PetscStrcmp(type, type2, &sameType));
9167: if (!sameType && dm2->ops->getcompatibility) {
9168: PetscUseTypeMethod(dm2, getcompatibility, dm1, compatible, set); /* Note argument order */
9169: } else {
9170: *set = PETSC_FALSE;
9171: }
9172: PetscFunctionReturn(PETSC_SUCCESS);
9173: }
9175: /*@
9176: DMMonitorSet - Sets an additional monitor function that is to be used after a solve to monitor discretization performance.
9178: Logically Collective
9180: Input Parameters:
9181: + dm - the `DM`
9182: . f - the monitor function
9183: . mctx - [optional] context for private data for the monitor routine (use `NULL` if no context is desired)
9184: - monitordestroy - [optional] routine that frees monitor context (may be `NULL`), see `PetscCtxDestroyFn` for the calling sequence
9186: Options Database Key:
9187: . -dm_monitor_cancel - cancels all monitors that have been hardwired into a code by calls to `DMMonitorSet()`, but
9188: does not cancel those set via the options database.
9190: Level: intermediate
9192: Note:
9193: Several different monitoring routines may be set by calling
9194: `DMMonitorSet()` multiple times or with `DMMonitorSetFromOptions()`; all will be called in the
9195: order in which they were set.
9197: Fortran Note:
9198: Only a single monitor function can be set for each `DM` object
9200: Developer Note:
9201: This API has a generic name but seems specific to a very particular aspect of the use of `DM`
9203: .seealso: [](ch_dmbase), `DM`, `DMMonitorCancel()`, `DMMonitorSetFromOptions()`, `DMMonitor()`, `PetscCtxDestroyFn`
9204: @*/
9205: PetscErrorCode DMMonitorSet(DM dm, PetscErrorCode (*f)(DM, void *), void *mctx, PetscCtxDestroyFn *monitordestroy)
9206: {
9207: PetscFunctionBegin;
9209: for (PetscInt m = 0; m < dm->numbermonitors; ++m) {
9210: PetscBool identical;
9212: PetscCall(PetscMonitorCompare((PetscErrorCode (*)(void))(PetscVoidFn *)f, mctx, monitordestroy, (PetscErrorCode (*)(void))(PetscVoidFn *)dm->monitor[m], dm->monitorcontext[m], dm->monitordestroy[m], &identical));
9213: if (identical) PetscFunctionReturn(PETSC_SUCCESS);
9214: }
9215: PetscCheck(dm->numbermonitors < MAXDMMONITORS, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Too many monitors set");
9216: dm->monitor[dm->numbermonitors] = f;
9217: dm->monitordestroy[dm->numbermonitors] = monitordestroy;
9218: dm->monitorcontext[dm->numbermonitors++] = mctx;
9219: PetscFunctionReturn(PETSC_SUCCESS);
9220: }
9222: /*@
9223: DMMonitorCancel - Clears all the monitor functions for a `DM` object.
9225: Logically Collective
9227: Input Parameter:
9228: . dm - the DM
9230: Options Database Key:
9231: . -dm_monitor_cancel - cancels all monitors that have been hardwired
9232: into a code by calls to `DMonitorSet()`, but does not cancel those
9233: set via the options database
9235: Level: intermediate
9237: Note:
9238: There is no way to clear one specific monitor from a `DM` object.
9240: .seealso: [](ch_dmbase), `DM`, `DMMonitorSet()`, `DMMonitorSetFromOptions()`, `DMMonitor()`
9241: @*/
9242: PetscErrorCode DMMonitorCancel(DM dm)
9243: {
9244: PetscFunctionBegin;
9246: for (PetscInt m = 0; m < dm->numbermonitors; ++m) {
9247: if (dm->monitordestroy[m]) PetscCall((*dm->monitordestroy[m])(&dm->monitorcontext[m]));
9248: }
9249: dm->numbermonitors = 0;
9250: PetscFunctionReturn(PETSC_SUCCESS);
9251: }
9253: /*@
9254: DMMonitorSetFromOptions - Sets a monitor function and viewer appropriate for the type indicated by the user
9256: Collective
9258: Input Parameters:
9259: + dm - `DM` object you wish to monitor
9260: . name - the monitor type one is seeking
9261: . help - message indicating what monitoring is done
9262: . manual - manual page for the monitor
9263: . monitor - the monitor function, this must use a `PetscViewerFormat` as its context
9264: - monitorsetup - a function that is called once ONLY if the user selected this monitor that may set additional features of the `DM` or `PetscViewer` objects
9266: Output Parameter:
9267: . flg - Flag set if the monitor was created
9269: Calling sequence of `monitor`:
9270: + dm - the `DM` to be monitored
9271: - ctx - monitor context
9273: Calling sequence of `monitorsetup`:
9274: + dm - the `DM` to be monitored
9275: - vf - the `PetscViewer` and format to be used by the monitor
9277: Level: developer
9279: .seealso: [](ch_dmbase), `DM`, `PetscOptionsCreateViewer()`, `PetscOptionsGetReal()`, `PetscOptionsHasName()`, `PetscOptionsGetString()`,
9280: `PetscOptionsGetIntArray()`, `PetscOptionsGetRealArray()`, `PetscOptionsBool()`,
9281: `PetscOptionsInt()`, `PetscOptionsString()`, `PetscOptionsReal()`,
9282: `PetscOptionsName()`, `PetscOptionsBegin()`, `PetscOptionsEnd()`, `PetscOptionsHeadBegin()`,
9283: `PetscOptionsStringArray()`, `PetscOptionsRealArray()`, `PetscOptionsScalar()`,
9284: `PetscOptionsBoolGroupBegin()`, `PetscOptionsBoolGroup()`, `PetscOptionsBoolGroupEnd()`,
9285: `PetscOptionsFList()`, `PetscOptionsEList()`, `DMMonitor()`, `DMMonitorSet()`
9286: @*/
9287: PetscErrorCode DMMonitorSetFromOptions(DM dm, const char name[], const char help[], const char manual[], PetscErrorCode (*monitor)(DM dm, PetscCtx ctx), PetscErrorCode (*monitorsetup)(DM dm, PetscViewerAndFormat *vf), PetscBool *flg)
9288: {
9289: PetscViewer viewer;
9290: PetscViewerFormat format;
9292: PetscFunctionBegin;
9294: PetscCall(PetscOptionsCreateViewer(PetscObjectComm((PetscObject)dm), ((PetscObject)dm)->options, ((PetscObject)dm)->prefix, name, &viewer, &format, flg));
9295: if (*flg) {
9296: PetscViewerAndFormat *vf;
9298: PetscCall(PetscViewerAndFormatCreate(viewer, format, &vf));
9299: PetscCall(PetscViewerDestroy(&viewer));
9300: if (monitorsetup) PetscCall((*monitorsetup)(dm, vf));
9301: PetscCall(DMMonitorSet(dm, monitor, vf, (PetscCtxDestroyFn *)PetscViewerAndFormatDestroy));
9302: }
9303: PetscFunctionReturn(PETSC_SUCCESS);
9304: }
9306: /*@
9307: DMMonitor - runs the user provided monitor routines, if they exist
9309: Collective
9311: Input Parameter:
9312: . dm - The `DM`
9314: Level: developer
9316: Developer Note:
9317: Note should indicate when during the life of the `DM` the monitor is run. It appears to be
9318: related to the discretization process seems rather specialized since some `DM` have no
9319: concept of discretization.
9321: .seealso: [](ch_dmbase), `DM`, `DMMonitorSet()`, `DMMonitorSetFromOptions()`
9322: @*/
9323: PetscErrorCode DMMonitor(DM dm)
9324: {
9325: PetscFunctionBegin;
9326: if (!dm) PetscFunctionReturn(PETSC_SUCCESS);
9328: for (PetscInt m = 0; m < dm->numbermonitors; ++m) PetscCall((*dm->monitor[m])(dm, dm->monitorcontext[m]));
9329: PetscFunctionReturn(PETSC_SUCCESS);
9330: }
9332: /*@
9333: DMComputeError - Computes the error assuming the user has provided the exact solution functions
9335: Collective
9337: Input Parameters:
9338: + dm - The `DM`
9339: - sol - The solution vector
9341: Input/Output Parameter:
9342: . errors - An array of length Nf, the number of fields, or `NULL` for no output; on output
9343: contains the error in each field
9345: Output Parameter:
9346: . errorVec - A vector to hold the cellwise error (may be `NULL`)
9348: Level: developer
9350: Note:
9351: The exact solutions come from the `PetscDS` object, and the time comes from `DMGetOutputSequenceNumber()`.
9353: .seealso: [](ch_dmbase), `DM`, `DMMonitorSet()`, `DMGetRegionNumDS()`, `PetscDSGetExactSolution()`, `DMGetOutputSequenceNumber()`
9354: @*/
9355: PetscErrorCode DMComputeError(DM dm, Vec sol, PetscReal errors[], Vec *errorVec)
9356: {
9357: PetscErrorCode (**exactSol)(PetscInt, PetscReal, const PetscReal[], PetscInt, PetscScalar[], void *);
9358: void **ctxs;
9359: PetscReal time;
9360: PetscInt Nf, f, Nds, s;
9362: PetscFunctionBegin;
9363: PetscCall(DMGetNumFields(dm, &Nf));
9364: PetscCall(PetscCalloc2(Nf, &exactSol, Nf, &ctxs));
9365: PetscCall(DMGetNumDS(dm, &Nds));
9366: for (s = 0; s < Nds; ++s) {
9367: PetscDS ds;
9368: DMLabel label;
9369: IS fieldIS;
9370: const PetscInt *fields;
9371: PetscInt dsNf;
9373: PetscCall(DMGetRegionNumDS(dm, s, &label, &fieldIS, &ds, NULL));
9374: PetscCall(PetscDSGetNumFields(ds, &dsNf));
9375: if (fieldIS) PetscCall(ISGetIndices(fieldIS, &fields));
9376: for (f = 0; f < dsNf; ++f) {
9377: const PetscInt field = fields[f];
9378: PetscCall(PetscDSGetExactSolution(ds, field, &exactSol[field], &ctxs[field]));
9379: }
9380: if (fieldIS) PetscCall(ISRestoreIndices(fieldIS, &fields));
9381: }
9382: for (f = 0; f < Nf; ++f) PetscCheck(exactSol[f], PetscObjectComm((PetscObject)dm), PETSC_ERR_ARG_WRONG, "DS must contain exact solution functions in order to calculate error, missing for field %" PetscInt_FMT, f);
9383: PetscCall(DMGetOutputSequenceNumber(dm, NULL, &time));
9384: if (errors) PetscCall(DMComputeL2FieldDiff(dm, time, exactSol, ctxs, sol, errors));
9385: if (errorVec) {
9386: DM edm;
9387: DMPolytopeType ct;
9388: PetscBool simplex;
9389: PetscInt dim, cStart, Nf;
9391: PetscCall(DMClone(dm, &edm));
9392: PetscCall(DMGetDimension(edm, &dim));
9393: PetscCall(DMPlexGetHeightStratum(dm, 0, &cStart, NULL));
9394: PetscCall(DMPlexGetCellType(dm, cStart, &ct));
9395: simplex = DMPolytopeTypeGetNumVertices(ct) == DMPolytopeTypeGetDim(ct) + 1 ? PETSC_TRUE : PETSC_FALSE;
9396: PetscCall(DMGetNumFields(dm, &Nf));
9397: for (f = 0; f < Nf; ++f) {
9398: PetscFE fe, efe;
9399: PetscQuadrature q;
9400: const char *name;
9402: PetscCall(DMGetField(dm, f, NULL, (PetscObject *)&fe));
9403: PetscCall(PetscFECreateLagrange(PETSC_COMM_SELF, dim, Nf, simplex, 0, PETSC_DETERMINE, &efe));
9404: PetscCall(PetscObjectGetName((PetscObject)fe, &name));
9405: PetscCall(PetscObjectSetName((PetscObject)efe, name));
9406: PetscCall(PetscFEGetQuadrature(fe, &q));
9407: PetscCall(PetscFESetQuadrature(efe, q));
9408: PetscCall(DMSetField(edm, f, NULL, (PetscObject)efe));
9409: PetscCall(PetscFEDestroy(&efe));
9410: }
9411: PetscCall(DMCreateDS(edm));
9413: PetscCall(DMCreateGlobalVector(edm, errorVec));
9414: PetscCall(PetscObjectSetName((PetscObject)*errorVec, "Error"));
9415: PetscCall(DMPlexComputeL2DiffVec(dm, time, exactSol, ctxs, sol, *errorVec));
9416: PetscCall(DMDestroy(&edm));
9417: }
9418: PetscCall(PetscFree2(exactSol, ctxs));
9419: PetscFunctionReturn(PETSC_SUCCESS);
9420: }
9422: /*@
9423: DMGetNumAuxiliaryVec - Get the number of auxiliary vectors associated with this `DM`
9425: Not Collective
9427: Input Parameter:
9428: . dm - The `DM`
9430: Output Parameter:
9431: . numAux - The number of auxiliary data vectors
9433: Level: advanced
9435: .seealso: [](ch_dmbase), `DM`, `DMClearAuxiliaryVec()`, `DMSetAuxiliaryVec()`, `DMGetAuxiliaryLabels()`, `DMGetAuxiliaryVec()`
9436: @*/
9437: PetscErrorCode DMGetNumAuxiliaryVec(DM dm, PetscInt *numAux)
9438: {
9439: PetscFunctionBegin;
9441: PetscCall(PetscHMapAuxGetSize(dm->auxData, numAux));
9442: PetscFunctionReturn(PETSC_SUCCESS);
9443: }
9445: /*@
9446: DMGetAuxiliaryVec - Get the auxiliary vector for region specified by the given label and value, and equation part
9448: Not Collective
9450: Input Parameters:
9451: + dm - The `DM`
9452: . label - The `DMLabel`
9453: . value - The label value indicating the region
9454: - part - The equation part, or 0 if unused
9456: Output Parameter:
9457: . aux - The `Vec` holding auxiliary field data
9459: Level: advanced
9461: Note:
9462: If no auxiliary vector is found for this (label, value), (`NULL`, 0, 0) is checked as well.
9464: .seealso: [](ch_dmbase), `DM`, `DMClearAuxiliaryVec()`, `DMSetAuxiliaryVec()`, `DMGetNumAuxiliaryVec()`, `DMGetAuxiliaryLabels()`
9465: @*/
9466: PetscErrorCode DMGetAuxiliaryVec(DM dm, DMLabel label, PetscInt value, PetscInt part, Vec *aux)
9467: {
9468: PetscHashAuxKey key, wild = {NULL, 0, 0};
9469: PetscBool has;
9471: PetscFunctionBegin;
9474: key.label = label;
9475: key.value = value;
9476: key.part = part;
9477: PetscCall(PetscHMapAuxHas(dm->auxData, key, &has));
9478: if (has) PetscCall(PetscHMapAuxGet(dm->auxData, key, aux));
9479: else PetscCall(PetscHMapAuxGet(dm->auxData, wild, aux));
9480: PetscFunctionReturn(PETSC_SUCCESS);
9481: }
9483: /*@
9484: DMSetAuxiliaryVec - Set an auxiliary vector for region specified by the given label and value, and equation part
9486: Not Collective because auxiliary vectors are not parallel
9488: Input Parameters:
9489: + dm - The `DM`
9490: . label - The `DMLabel`
9491: . value - The label value indicating the region
9492: . part - The equation part, or 0 if unused
9493: - aux - The `Vec` holding auxiliary field data
9495: Level: advanced
9497: .seealso: [](ch_dmbase), `DM`, `DMClearAuxiliaryVec()`, `DMGetAuxiliaryVec()`, `DMGetAuxiliaryLabels()`, `DMCopyAuxiliaryVec()`
9498: @*/
9499: PetscErrorCode DMSetAuxiliaryVec(DM dm, DMLabel label, PetscInt value, PetscInt part, Vec aux)
9500: {
9501: Vec old;
9502: PetscHashAuxKey key;
9504: PetscFunctionBegin;
9507: key.label = label;
9508: key.value = value;
9509: key.part = part;
9510: PetscCall(PetscHMapAuxGet(dm->auxData, key, &old));
9511: PetscCall(PetscObjectReference((PetscObject)aux));
9512: if (!aux) PetscCall(PetscHMapAuxDel(dm->auxData, key));
9513: else PetscCall(PetscHMapAuxSet(dm->auxData, key, aux));
9514: PetscCall(VecDestroy(&old));
9515: PetscFunctionReturn(PETSC_SUCCESS);
9516: }
9518: /*@
9519: DMGetAuxiliaryLabels - Get the labels, values, and parts for all auxiliary vectors in this `DM`
9521: Not Collective
9523: Input Parameter:
9524: . dm - The `DM`
9526: Output Parameters:
9527: + labels - The `DMLabel`s for each `Vec`
9528: . values - The label values for each `Vec`
9529: - parts - The equation parts for each `Vec`
9531: Level: advanced
9533: Note:
9534: The arrays passed in must be at least as large as `DMGetNumAuxiliaryVec()`.
9536: .seealso: [](ch_dmbase), `DM`, `DMClearAuxiliaryVec()`, `DMGetNumAuxiliaryVec()`, `DMGetAuxiliaryVec()`, `DMSetAuxiliaryVec()`, `DMCopyAuxiliaryVec()`
9537: @*/
9538: PetscErrorCode DMGetAuxiliaryLabels(DM dm, DMLabel labels[], PetscInt values[], PetscInt parts[])
9539: {
9540: PetscHashAuxKey *keys;
9541: PetscInt n, i, off = 0;
9543: PetscFunctionBegin;
9545: PetscAssertPointer(labels, 2);
9546: PetscAssertPointer(values, 3);
9547: PetscAssertPointer(parts, 4);
9548: PetscCall(DMGetNumAuxiliaryVec(dm, &n));
9549: PetscCall(PetscMalloc1(n, &keys));
9550: PetscCall(PetscHMapAuxGetKeys(dm->auxData, &off, keys));
9551: for (i = 0; i < n; ++i) {
9552: labels[i] = keys[i].label;
9553: values[i] = keys[i].value;
9554: parts[i] = keys[i].part;
9555: }
9556: PetscCall(PetscFree(keys));
9557: PetscFunctionReturn(PETSC_SUCCESS);
9558: }
9560: /*@
9561: DMCopyAuxiliaryVec - Copy the auxiliary vector data on a `DM` to a new `DM`
9563: Not Collective
9565: Input Parameter:
9566: . dm - The `DM`
9568: Output Parameter:
9569: . dmNew - The new `DM`, now with the same auxiliary data
9571: Level: advanced
9573: Note:
9574: This is a shallow copy of the auxiliary vectors
9576: .seealso: [](ch_dmbase), `DM`, `DMClearAuxiliaryVec()`, `DMGetNumAuxiliaryVec()`, `DMGetAuxiliaryVec()`, `DMSetAuxiliaryVec()`
9577: @*/
9578: PetscErrorCode DMCopyAuxiliaryVec(DM dm, DM dmNew)
9579: {
9580: PetscFunctionBegin;
9583: if (dm == dmNew) PetscFunctionReturn(PETSC_SUCCESS);
9584: PetscCall(DMClearAuxiliaryVec(dmNew));
9586: PetscCall(PetscHMapAuxDestroy(&dmNew->auxData));
9587: PetscCall(PetscHMapAuxDuplicate(dm->auxData, &dmNew->auxData));
9588: {
9589: Vec *auxData;
9590: PetscInt n, i, off = 0;
9592: PetscCall(PetscHMapAuxGetSize(dmNew->auxData, &n));
9593: PetscCall(PetscMalloc1(n, &auxData));
9594: PetscCall(PetscHMapAuxGetVals(dmNew->auxData, &off, auxData));
9595: for (i = 0; i < n; ++i) PetscCall(PetscObjectReference((PetscObject)auxData[i]));
9596: PetscCall(PetscFree(auxData));
9597: }
9598: PetscFunctionReturn(PETSC_SUCCESS);
9599: }
9601: /*@
9602: DMClearAuxiliaryVec - Destroys the auxiliary vector information and creates a new empty one
9604: Not Collective
9606: Input Parameter:
9607: . dm - The `DM`
9609: Level: advanced
9611: .seealso: [](ch_dmbase), `DM`, `DMCopyAuxiliaryVec()`, `DMGetNumAuxiliaryVec()`, `DMGetAuxiliaryVec()`, `DMSetAuxiliaryVec()`
9612: @*/
9613: PetscErrorCode DMClearAuxiliaryVec(DM dm)
9614: {
9615: Vec *auxData;
9616: PetscInt n, i, off = 0;
9618: PetscFunctionBegin;
9619: PetscCall(PetscHMapAuxGetSize(dm->auxData, &n));
9620: PetscCall(PetscMalloc1(n, &auxData));
9621: PetscCall(PetscHMapAuxGetVals(dm->auxData, &off, auxData));
9622: for (i = 0; i < n; ++i) PetscCall(VecDestroy(&auxData[i]));
9623: PetscCall(PetscFree(auxData));
9624: PetscCall(PetscHMapAuxDestroy(&dm->auxData));
9625: PetscCall(PetscHMapAuxCreate(&dm->auxData));
9626: PetscFunctionReturn(PETSC_SUCCESS);
9627: }
9629: /*@
9630: DMPolytopeMatchOrientation - Determine an orientation (transformation) that takes the source face arrangement to the target face arrangement
9632: Not Collective
9634: Input Parameters:
9635: + ct - The `DMPolytopeType`
9636: . sourceCone - The source arrangement of faces
9637: - targetCone - The target arrangement of faces
9639: Output Parameters:
9640: + ornt - The orientation (transformation) which will take the source arrangement to the target arrangement
9641: - found - Flag indicating that a suitable orientation was found
9643: Level: advanced
9645: Note:
9646: An arrangement is a face order combined with an orientation for each face
9648: Each orientation (transformation) is labeled with an integer from negative `DMPolytopeTypeGetNumArrangements(ct)`/2 to `DMPolytopeTypeGetNumArrangements(ct)`/2
9649: that labels each arrangement (face ordering plus orientation for each face).
9651: See `DMPolytopeMatchVertexOrientation()` to find a new vertex orientation that takes the source vertex arrangement to the target vertex arrangement
9653: .seealso: [](ch_dmbase), `DM`, `DMPolytopeGetOrientation()`, `DMPolytopeMatchVertexOrientation()`, `DMPolytopeGetVertexOrientation()`
9654: @*/
9655: PetscErrorCode DMPolytopeMatchOrientation(DMPolytopeType ct, const PetscInt sourceCone[], const PetscInt targetCone[], PetscInt *ornt, PetscBool *found)
9656: {
9657: const PetscInt cS = DMPolytopeTypeGetConeSize(ct);
9658: const PetscInt nO = DMPolytopeTypeGetNumArrangements(ct) / 2;
9659: PetscInt o, c;
9661: PetscFunctionBegin;
9662: if (!nO) {
9663: *ornt = 0;
9664: *found = PETSC_TRUE;
9665: PetscFunctionReturn(PETSC_SUCCESS);
9666: }
9667: for (o = -nO; o < nO; ++o) {
9668: const PetscInt *arr = DMPolytopeTypeGetArrangement(ct, o);
9670: for (c = 0; c < cS; ++c)
9671: if (sourceCone[arr[c * 2]] != targetCone[c]) break;
9672: if (c == cS) {
9673: *ornt = o;
9674: break;
9675: }
9676: }
9677: *found = o == nO ? PETSC_FALSE : PETSC_TRUE;
9678: PetscFunctionReturn(PETSC_SUCCESS);
9679: }
9681: /*@
9682: DMPolytopeGetOrientation - Determine an orientation (transformation) that takes the source face arrangement to the target face arrangement
9684: Not Collective
9686: Input Parameters:
9687: + ct - The `DMPolytopeType`
9688: . sourceCone - The source arrangement of faces
9689: - targetCone - The target arrangement of faces
9691: Output Parameter:
9692: . ornt - The orientation (transformation) which will take the source arrangement to the target arrangement
9694: Level: advanced
9696: Note:
9697: This function is the same as `DMPolytopeMatchOrientation()` except it will generate an error if no suitable orientation can be found.
9699: Developer Note:
9700: It is unclear why this function needs to exist since one can simply call `DMPolytopeMatchOrientation()` and error if none is found
9702: .seealso: [](ch_dmbase), `DM`, `DMPolytopeType`, `DMPolytopeMatchOrientation()`, `DMPolytopeGetVertexOrientation()`, `DMPolytopeMatchVertexOrientation()`
9703: @*/
9704: PetscErrorCode DMPolytopeGetOrientation(DMPolytopeType ct, const PetscInt sourceCone[], const PetscInt targetCone[], PetscInt *ornt)
9705: {
9706: PetscBool found;
9708: PetscFunctionBegin;
9709: PetscCall(DMPolytopeMatchOrientation(ct, sourceCone, targetCone, ornt, &found));
9710: PetscCheck(found, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Could not find orientation for %s", DMPolytopeTypes[ct]);
9711: PetscFunctionReturn(PETSC_SUCCESS);
9712: }
9714: /*@
9715: DMPolytopeMatchVertexOrientation - Determine an orientation (transformation) that takes the source vertex arrangement to the target vertex arrangement
9717: Not Collective
9719: Input Parameters:
9720: + ct - The `DMPolytopeType`
9721: . sourceVert - The source arrangement of vertices
9722: - targetVert - The target arrangement of vertices
9724: Output Parameters:
9725: + ornt - The orientation (transformation) which will take the source arrangement to the target arrangement
9726: - found - Flag indicating that a suitable orientation was found
9728: Level: advanced
9730: Notes:
9731: An arrangement is a vertex order
9733: Each orientation (transformation) is labeled with an integer from negative `DMPolytopeTypeGetNumArrangements(ct)`/2 to `DMPolytopeTypeGetNumArrangements(ct)`/2
9734: that labels each arrangement (vertex ordering).
9736: See `DMPolytopeMatchOrientation()` to find a new face orientation that takes the source face arrangement to the target face arrangement
9738: .seealso: [](ch_dmbase), `DM`, `DMPolytopeType`, `DMPolytopeGetOrientation()`, `DMPolytopeMatchOrientation()`, `DMPolytopeTypeGetNumVertices()`, `DMPolytopeTypeGetVertexArrangement()`
9739: @*/
9740: PetscErrorCode DMPolytopeMatchVertexOrientation(DMPolytopeType ct, const PetscInt sourceVert[], const PetscInt targetVert[], PetscInt *ornt, PetscBool *found)
9741: {
9742: const PetscInt cS = DMPolytopeTypeGetNumVertices(ct);
9743: const PetscInt nO = DMPolytopeTypeGetNumArrangements(ct) / 2;
9744: PetscInt o, c;
9746: PetscFunctionBegin;
9747: if (!nO) {
9748: *ornt = 0;
9749: *found = PETSC_TRUE;
9750: PetscFunctionReturn(PETSC_SUCCESS);
9751: }
9752: for (o = -nO; o < nO; ++o) {
9753: const PetscInt *arr = DMPolytopeTypeGetVertexArrangement(ct, o);
9755: for (c = 0; c < cS; ++c)
9756: if (sourceVert[arr[c]] != targetVert[c]) break;
9757: if (c == cS) {
9758: *ornt = o;
9759: break;
9760: }
9761: }
9762: *found = o == nO ? PETSC_FALSE : PETSC_TRUE;
9763: PetscFunctionReturn(PETSC_SUCCESS);
9764: }
9766: /*@
9767: DMPolytopeGetVertexOrientation - Determine an orientation (transformation) that takes the source vertex arrangement to the target vertex arrangement
9769: Not Collective
9771: Input Parameters:
9772: + ct - The `DMPolytopeType`
9773: . sourceCone - The source arrangement of vertices
9774: - targetCone - The target arrangement of vertices
9776: Output Parameter:
9777: . ornt - The orientation (transformation) which will take the source arrangement to the target arrangement
9779: Level: advanced
9781: Note:
9782: This function is the same as `DMPolytopeMatchVertexOrientation()` except it errors if not orientation is possible.
9784: Developer Note:
9785: It is unclear why this function needs to exist since one can simply call `DMPolytopeMatchVertexOrientation()` and error if none is found
9787: .seealso: [](ch_dmbase), `DM`, `DMPolytopeType`, `DMPolytopeMatchVertexOrientation()`, `DMPolytopeGetOrientation()`
9788: @*/
9789: PetscErrorCode DMPolytopeGetVertexOrientation(DMPolytopeType ct, const PetscInt sourceCone[], const PetscInt targetCone[], PetscInt *ornt)
9790: {
9791: PetscBool found;
9793: PetscFunctionBegin;
9794: PetscCall(DMPolytopeMatchVertexOrientation(ct, sourceCone, targetCone, ornt, &found));
9795: PetscCheck(found, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Could not find orientation for %s", DMPolytopeTypes[ct]);
9796: PetscFunctionReturn(PETSC_SUCCESS);
9797: }
9799: /*@
9800: DMPolytopeInCellTest - Check whether a point lies inside the reference cell of given type
9802: Not Collective
9804: Input Parameters:
9805: + ct - The `DMPolytopeType`
9806: - point - Coordinates of the point
9808: Output Parameter:
9809: . inside - Flag indicating whether the point is inside the reference cell of given type
9811: Level: advanced
9813: .seealso: [](ch_dmbase), `DM`, `DMPolytopeType`, `DMLocatePoints()`
9814: @*/
9815: PetscErrorCode DMPolytopeInCellTest(DMPolytopeType ct, const PetscReal point[], PetscBool *inside)
9816: {
9817: PetscReal sum = 0.0;
9819: PetscFunctionBegin;
9820: *inside = PETSC_TRUE;
9821: switch (ct) {
9822: case DM_POLYTOPE_TRIANGLE:
9823: case DM_POLYTOPE_TETRAHEDRON:
9824: for (PetscInt d = 0; d < DMPolytopeTypeGetDim(ct); ++d) {
9825: if (point[d] < -1.0) {
9826: *inside = PETSC_FALSE;
9827: break;
9828: }
9829: sum += point[d];
9830: }
9831: if (sum > PETSC_SMALL) {
9832: *inside = PETSC_FALSE;
9833: break;
9834: }
9835: break;
9836: case DM_POLYTOPE_QUADRILATERAL:
9837: case DM_POLYTOPE_HEXAHEDRON:
9838: for (PetscInt d = 0; d < DMPolytopeTypeGetDim(ct); ++d)
9839: if (PetscAbsReal(point[d]) > 1. + PETSC_SMALL) {
9840: *inside = PETSC_FALSE;
9841: break;
9842: }
9843: break;
9844: default:
9845: SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Unsupported polytope type %s", DMPolytopeTypes[ct]);
9846: }
9847: PetscFunctionReturn(PETSC_SUCCESS);
9848: }
9850: /*@
9851: DMReorderSectionSetDefault - Set flag indicating whether the local section should be reordered by default
9853: Logically collective
9855: Input Parameters:
9856: + dm - The DM
9857: - reorder - Flag for reordering
9859: Level: intermediate
9861: .seealso: `DMReorderSectionGetDefault()`
9862: @*/
9863: PetscErrorCode DMReorderSectionSetDefault(DM dm, DMReorderDefaultFlag reorder)
9864: {
9865: PetscFunctionBegin;
9867: PetscTryMethod(dm, "DMReorderSectionSetDefault_C", (DM, DMReorderDefaultFlag), (dm, reorder));
9868: PetscFunctionReturn(PETSC_SUCCESS);
9869: }
9871: /*@
9872: DMReorderSectionGetDefault - Get flag indicating whether the local section should be reordered by default
9874: Not collective
9876: Input Parameter:
9877: . dm - The DM
9879: Output Parameter:
9880: . reorder - Flag for reordering
9882: Level: intermediate
9884: .seealso: `DMReorderSetDefault()`
9885: @*/
9886: PetscErrorCode DMReorderSectionGetDefault(DM dm, DMReorderDefaultFlag *reorder)
9887: {
9888: PetscFunctionBegin;
9890: PetscAssertPointer(reorder, 2);
9891: *reorder = DM_REORDER_DEFAULT_NOTSET;
9892: PetscTryMethod(dm, "DMReorderSectionGetDefault_C", (DM, DMReorderDefaultFlag *), (dm, reorder));
9893: PetscFunctionReturn(PETSC_SUCCESS);
9894: }
9896: /*@
9897: DMReorderSectionSetType - Set the type of local section reordering
9899: Logically collective
9901: Input Parameters:
9902: + dm - The DM
9903: - reorder - The reordering method
9905: Level: intermediate
9907: .seealso: `DMReorderSectionGetType()`, `DMReorderSectionSetDefault()`
9908: @*/
9909: PetscErrorCode DMReorderSectionSetType(DM dm, MatOrderingType reorder)
9910: {
9911: PetscFunctionBegin;
9913: PetscTryMethod(dm, "DMReorderSectionSetType_C", (DM, MatOrderingType), (dm, reorder));
9914: PetscFunctionReturn(PETSC_SUCCESS);
9915: }
9917: /*@
9918: DMReorderSectionGetType - Get the reordering type for the local section
9920: Not collective
9922: Input Parameter:
9923: . dm - The DM
9925: Output Parameter:
9926: . reorder - The reordering method
9928: Level: intermediate
9930: .seealso: `DMReorderSetDefault()`, `DMReorderSectionGetDefault()`
9931: @*/
9932: PetscErrorCode DMReorderSectionGetType(DM dm, MatOrderingType *reorder)
9933: {
9934: PetscFunctionBegin;
9936: PetscAssertPointer(reorder, 2);
9937: *reorder = NULL;
9938: PetscTryMethod(dm, "DMReorderSectionGetType_C", (DM, MatOrderingType *), (dm, reorder));
9939: PetscFunctionReturn(PETSC_SUCCESS);
9940: }