Actual source code: dm.c
1: #include <petscvec.h>
2: #include <petsc/private/dmimpl.h>
3: #include <petsc/private/dmlabelimpl.h>
4: #include <petsc/private/petscdsimpl.h>
5: #include <petscdmplex.h>
6: #include <petscdmceed.h>
7: #include <petscdmfield.h>
8: #include <petscsf.h>
9: #include <petscds.h>
11: #ifdef PETSC_HAVE_LIBCEED
12: #include <petscfeceed.h>
13: #endif
15: PetscClassId DM_CLASSID;
16: PetscClassId DMLABEL_CLASSID;
17: PetscLogEvent DM_Convert, DM_GlobalToLocal, DM_LocalToGlobal, DM_LocalToLocal, DM_LocatePoints, DM_Coarsen, DM_Refine, DM_CreateInterpolation, DM_CreateRestriction, DM_CreateInjection, DM_CreateMatrix, DM_CreateMassMatrix, DM_Load, DM_View, DM_AdaptInterpolator, DM_ProjectFunction;
19: const char *const DMBoundaryTypes[] = {"NONE", "GHOSTED", "MIRROR", "PERIODIC", "TWIST", "DMBoundaryType", "DM_BOUNDARY_", NULL};
20: const char *const DMBoundaryConditionTypes[] = {"INVALID", "ESSENTIAL", "NATURAL", "INVALID", "LOWER_BOUND", "ESSENTIAL_FIELD", "NATURAL_FIELD", "INVALID", "UPPER_BOUND", "ESSENTIAL_BD_FIELD", "NATURAL_RIEMANN", "DMBoundaryConditionType",
21: "DM_BC_", NULL};
22: const char *const DMBlockingTypes[] = {"TOPOLOGICAL_POINT", "FIELD_NODE", "DMBlockingType", "DM_BLOCKING_", NULL};
23: const char *const DMPolytopeTypes[] =
24: {"vertex", "segment", "tensor_segment", "triangle", "quadrilateral", "tensor_quad", "tetrahedron", "hexahedron", "triangular_prism", "tensor_triangular_prism", "tensor_quadrilateral_prism", "pyramid", "FV_ghost_cell", "interior_ghost_cell",
25: "unknown", "unknown_cell", "unknown_face", "invalid", "DMPolytopeType", "DM_POLYTOPE_", NULL};
26: const char *const DMCopyLabelsModes[] = {"replace", "keep", "fail", "DMCopyLabelsMode", "DM_COPY_LABELS_", NULL};
28: /*@
29: DMCreate - Creates an empty `DM` object. `DM`s are the abstract objects in PETSc that mediate between meshes and discretizations and the
30: algebraic solvers, time integrators, and optimization algorithms in PETSc.
32: Collective
34: Input Parameter:
35: . comm - The communicator for the `DM` object
37: Output Parameter:
38: . dm - The `DM` object
40: Level: beginner
42: Notes:
43: See `DMType` for a brief summary of available `DM`.
45: The type must then be set with `DMSetType()`. If you never call `DMSetType()` it will generate an
46: error when you try to use the `dm`.
48: `DM` is an orphan initialism or orphan acronym, the letters have no meaning and never did.
50: .seealso: [](ch_dmbase), `DM`, `DMSetType()`, `DMType`, `DMDACreate()`, `DMDA`, `DMSLICED`, `DMCOMPOSITE`, `DMPLEX`, `DMMOAB`, `DMNETWORK`
51: @*/
52: PetscErrorCode DMCreate(MPI_Comm comm, DM *dm)
53: {
54: DM v;
55: PetscDS ds;
57: PetscFunctionBegin;
58: PetscAssertPointer(dm, 2);
60: PetscCall(DMInitializePackage());
61: PetscCall(PetscHeaderCreate(v, DM_CLASSID, "DM", "Distribution Manager", "DM", comm, DMDestroy, DMView));
62: ((PetscObject)v)->non_cyclic_references = &DMCountNonCyclicReferences;
63: v->setupcalled = PETSC_FALSE;
64: v->setfromoptionscalled = PETSC_FALSE;
65: v->ltogmap = NULL;
66: v->bind_below = 0;
67: v->bs = 1;
68: v->coloringtype = IS_COLORING_GLOBAL;
69: PetscCall(PetscSFCreate(comm, &v->sf));
70: PetscCall(PetscSFCreate(comm, &v->sectionSF));
71: v->labels = NULL;
72: v->adjacency[0] = PETSC_FALSE;
73: v->adjacency[1] = PETSC_TRUE;
74: v->depthLabel = NULL;
75: v->celltypeLabel = NULL;
76: v->localSection = NULL;
77: v->globalSection = NULL;
78: v->defaultConstraint.section = NULL;
79: v->defaultConstraint.mat = NULL;
80: v->defaultConstraint.bias = NULL;
81: v->coordinates[0].dim = PETSC_DEFAULT;
82: v->coordinates[1].dim = PETSC_DEFAULT;
83: v->sparseLocalize = PETSC_TRUE;
84: v->dim = PETSC_DETERMINE;
85: PetscCall(PetscDSCreate(PETSC_COMM_SELF, &ds));
86: PetscCall(DMSetRegionDS(v, NULL, NULL, ds, NULL));
87: PetscCall(PetscDSDestroy(&ds));
88: PetscCall(PetscHMapAuxCreate(&v->auxData));
89: v->dmBC = NULL;
90: v->coarseMesh = NULL;
91: v->outputSequenceNum = -1;
92: v->outputSequenceVal = 0.0;
93: PetscCall(DMSetVecType(v, VECSTANDARD));
94: PetscCall(DMSetMatType(v, MATAIJ));
96: *dm = v;
97: PetscFunctionReturn(PETSC_SUCCESS);
98: }
100: /*@
101: DMClone - Creates a `DM` object with the same topology as the original.
103: Collective
105: Input Parameter:
106: . dm - The original `DM` object
108: Output Parameter:
109: . newdm - The new `DM` object
111: Level: beginner
113: Notes:
114: For some `DM` implementations this is a shallow clone, the result of which may share (reference counted) information with its parent. For example,
115: `DMClone()` applied to a `DMPLEX` object will result in a new `DMPLEX` that shares the topology with the original `DMPLEX`. It does not
116: share the `PetscSection` of the original `DM`.
118: The clone is considered set up if the original has been set up.
120: Use `DMConvert()` for a general way to create new `DM` from a given `DM`
122: .seealso: [](ch_dmbase), `DM`, `DMDestroy()`, `DMCreate()`, `DMSetType()`, `DMSetLocalSection()`, `DMSetGlobalSection()`, `DMPLEX`, `DMConvert()`
123: @*/
124: PetscErrorCode DMClone(DM dm, DM *newdm)
125: {
126: PetscSF sf;
127: Vec coords;
128: void *ctx;
129: MatOrderingType otype;
130: DMReorderDefaultFlag flg;
131: PetscInt dim, cdim, i;
132: PetscBool sparse;
134: PetscFunctionBegin;
136: PetscAssertPointer(newdm, 2);
137: PetscCall(DMCreate(PetscObjectComm((PetscObject)dm), newdm));
138: PetscCall(DMCopyLabels(dm, *newdm, PETSC_COPY_VALUES, PETSC_TRUE, DM_COPY_LABELS_FAIL));
139: (*newdm)->leveldown = dm->leveldown;
140: (*newdm)->levelup = dm->levelup;
141: (*newdm)->prealloc_only = dm->prealloc_only;
142: (*newdm)->prealloc_skip = dm->prealloc_skip;
143: PetscCall(PetscFree((*newdm)->vectype));
144: PetscCall(PetscStrallocpy(dm->vectype, (char **)&(*newdm)->vectype));
145: PetscCall(PetscFree((*newdm)->mattype));
146: PetscCall(PetscStrallocpy(dm->mattype, (char **)&(*newdm)->mattype));
147: PetscCall(DMGetDimension(dm, &dim));
148: PetscCall(DMSetDimension(*newdm, dim));
149: PetscTryTypeMethod(dm, clone, newdm);
150: (*newdm)->setupcalled = dm->setupcalled;
151: PetscCall(DMGetPointSF(dm, &sf));
152: PetscCall(DMSetPointSF(*newdm, sf));
153: PetscCall(DMGetApplicationContext(dm, &ctx));
154: PetscCall(DMSetApplicationContext(*newdm, ctx));
155: PetscCall(DMReorderSectionGetDefault(dm, &flg));
156: PetscCall(DMReorderSectionSetDefault(*newdm, flg));
157: PetscCall(DMReorderSectionGetType(dm, &otype));
158: PetscCall(DMReorderSectionSetType(*newdm, otype));
159: for (i = 0; i < 2; ++i) {
160: if (dm->coordinates[i].dm) {
161: DM ncdm;
162: PetscSection cs;
163: PetscInt pEnd = -1, pEndMax = -1;
165: PetscCall(DMGetLocalSection(dm->coordinates[i].dm, &cs));
166: if (cs) PetscCall(PetscSectionGetChart(cs, NULL, &pEnd));
167: PetscCallMPI(MPIU_Allreduce(&pEnd, &pEndMax, 1, MPIU_INT, MPI_MAX, PetscObjectComm((PetscObject)dm)));
168: if (pEndMax >= 0) {
169: PetscCall(DMClone(dm->coordinates[i].dm, &ncdm));
170: PetscCall(DMCopyDisc(dm->coordinates[i].dm, ncdm));
171: PetscCall(DMSetLocalSection(ncdm, cs));
172: if (dm->coordinates[i].dm->periodic.setup) {
173: ncdm->periodic.setup = dm->coordinates[i].dm->periodic.setup;
174: PetscCall(ncdm->periodic.setup(ncdm));
175: }
176: if (i) PetscCall(DMSetCellCoordinateDM(*newdm, ncdm));
177: else PetscCall(DMSetCoordinateDM(*newdm, ncdm));
178: PetscCall(DMDestroy(&ncdm));
179: }
180: }
181: }
182: PetscCall(DMGetCoordinateDim(dm, &cdim));
183: PetscCall(DMSetCoordinateDim(*newdm, cdim));
184: PetscCall(DMGetCoordinatesLocal(dm, &coords));
185: if (coords) {
186: PetscCall(DMSetCoordinatesLocal(*newdm, coords));
187: } else {
188: PetscCall(DMGetCoordinates(dm, &coords));
189: if (coords) PetscCall(DMSetCoordinates(*newdm, coords));
190: }
191: PetscCall(DMGetSparseLocalize(dm, &sparse));
192: PetscCall(DMSetSparseLocalize(*newdm, sparse));
193: PetscCall(DMGetCellCoordinatesLocal(dm, &coords));
194: if (coords) {
195: PetscCall(DMSetCellCoordinatesLocal(*newdm, coords));
196: } else {
197: PetscCall(DMGetCellCoordinates(dm, &coords));
198: if (coords) PetscCall(DMSetCellCoordinates(*newdm, coords));
199: }
200: {
201: const PetscReal *maxCell, *Lstart, *L;
203: PetscCall(DMGetPeriodicity(dm, &maxCell, &Lstart, &L));
204: PetscCall(DMSetPeriodicity(*newdm, maxCell, Lstart, L));
205: }
206: {
207: PetscBool useCone, useClosure;
209: PetscCall(DMGetAdjacency(dm, PETSC_DEFAULT, &useCone, &useClosure));
210: PetscCall(DMSetAdjacency(*newdm, PETSC_DEFAULT, useCone, useClosure));
211: }
212: PetscFunctionReturn(PETSC_SUCCESS);
213: }
215: /*@
216: DMSetVecType - Sets the type of vector to be created with `DMCreateLocalVector()` and `DMCreateGlobalVector()`
218: Logically Collective
220: Input Parameters:
221: + dm - initial distributed array
222: - ctype - the vector type, for example `VECSTANDARD`, `VECCUDA`, or `VECVIENNACL`
224: Options Database Key:
225: . -dm_vec_type ctype - the type of vector to create
227: Level: intermediate
229: .seealso: [](ch_dmbase), `DM`, `DMCreate()`, `DMDestroy()`, `DMDAInterpolationType`, `VecType`, `DMGetVecType()`, `DMSetMatType()`, `DMGetMatType()`,
230: `VECSTANDARD`, `VECCUDA`, `VECVIENNACL`, `DMCreateLocalVector()`, `DMCreateGlobalVector()`
231: @*/
232: PetscErrorCode DMSetVecType(DM dm, VecType ctype)
233: {
234: char *tmp;
236: PetscFunctionBegin;
238: PetscAssertPointer(ctype, 2);
239: tmp = (char *)dm->vectype;
240: PetscCall(PetscStrallocpy(ctype, (char **)&dm->vectype));
241: PetscCall(PetscFree(tmp));
242: PetscFunctionReturn(PETSC_SUCCESS);
243: }
245: /*@
246: DMGetVecType - Gets the type of vector created with `DMCreateLocalVector()` and `DMCreateGlobalVector()`
248: Logically Collective
250: Input Parameter:
251: . da - initial distributed array
253: Output Parameter:
254: . ctype - the vector type
256: Level: intermediate
258: .seealso: [](ch_dmbase), `DM`, `DMCreate()`, `DMDestroy()`, `DMDAInterpolationType`, `VecType`, `DMSetMatType()`, `DMGetMatType()`, `DMSetVecType()`
259: @*/
260: PetscErrorCode DMGetVecType(DM da, VecType *ctype)
261: {
262: PetscFunctionBegin;
264: *ctype = da->vectype;
265: PetscFunctionReturn(PETSC_SUCCESS);
266: }
268: /*@
269: VecGetDM - Gets the `DM` defining the data layout of the vector
271: Not Collective
273: Input Parameter:
274: . v - The `Vec`
276: Output Parameter:
277: . dm - The `DM`
279: Level: intermediate
281: Note:
282: A `Vec` may not have a `DM` associated with it.
284: .seealso: [](ch_dmbase), `DM`, `VecSetDM()`, `DMGetLocalVector()`, `DMGetGlobalVector()`, `DMSetVecType()`
285: @*/
286: PetscErrorCode VecGetDM(Vec v, DM *dm)
287: {
288: PetscFunctionBegin;
290: PetscAssertPointer(dm, 2);
291: PetscCall(PetscObjectQuery((PetscObject)v, "__PETSc_dm", (PetscObject *)dm));
292: PetscFunctionReturn(PETSC_SUCCESS);
293: }
295: /*@
296: VecSetDM - Sets the `DM` defining the data layout of the vector.
298: Not Collective
300: Input Parameters:
301: + v - The `Vec`
302: - dm - The `DM`
304: Level: developer
306: Notes:
307: This is rarely used, generally one uses `DMGetLocalVector()` or `DMGetGlobalVector()` to create a vector associated with a given `DM`
309: This is NOT the same as `DMCreateGlobalVector()` since it does not change the view methods or perform other customization, but merely sets the `DM` member.
311: .seealso: [](ch_dmbase), `DM`, `VecGetDM()`, `DMGetLocalVector()`, `DMGetGlobalVector()`, `DMSetVecType()`
312: @*/
313: PetscErrorCode VecSetDM(Vec v, DM dm)
314: {
315: PetscFunctionBegin;
318: PetscCall(PetscObjectCompose((PetscObject)v, "__PETSc_dm", (PetscObject)dm));
319: PetscFunctionReturn(PETSC_SUCCESS);
320: }
322: /*@
323: DMSetISColoringType - Sets the type of coloring, `IS_COLORING_GLOBAL` or `IS_COLORING_LOCAL` that is created by the `DM`
325: Logically Collective
327: Input Parameters:
328: + dm - the `DM` context
329: - ctype - the matrix type
331: Options Database Key:
332: . -dm_is_coloring_type (global|local) - see `ISColoringType`
334: Level: intermediate
336: .seealso: [](ch_dmbase), `DM`, `DMDACreate1d()`, `DMDACreate2d()`, `DMDACreate3d()`, `DMCreateMatrix()`, `DMCreateMassMatrix()`, `DMSetMatrixPreallocateOnly()`, `MatType`, `DMGetMatType()`,
337: `DMGetISColoringType()`, `ISColoringType`, `IS_COLORING_GLOBAL`, `IS_COLORING_LOCAL`
338: @*/
339: PetscErrorCode DMSetISColoringType(DM dm, ISColoringType ctype)
340: {
341: PetscFunctionBegin;
343: dm->coloringtype = ctype;
344: PetscFunctionReturn(PETSC_SUCCESS);
345: }
347: /*@
348: DMGetISColoringType - Gets the type of coloring, `IS_COLORING_GLOBAL` or `IS_COLORING_LOCAL` that is created by the `DM`
350: Logically Collective
352: Input Parameter:
353: . dm - the `DM` context
355: Output Parameter:
356: . ctype - the matrix type
358: Level: intermediate
360: .seealso: [](ch_dmbase), `DM`, `DMDACreate1d()`, `DMDACreate2d()`, `DMDACreate3d()`, `DMCreateMatrix()`, `DMCreateMassMatrix()`, `DMSetMatrixPreallocateOnly()`, `MatType`, `DMGetMatType()`,
361: `ISColoringType`, `IS_COLORING_GLOBAL`, `IS_COLORING_LOCAL`
362: @*/
363: PetscErrorCode DMGetISColoringType(DM dm, ISColoringType *ctype)
364: {
365: PetscFunctionBegin;
367: *ctype = dm->coloringtype;
368: PetscFunctionReturn(PETSC_SUCCESS);
369: }
371: /*@
372: DMSetMatType - Sets the type of matrix created with `DMCreateMatrix()`
374: Logically Collective
376: Input Parameters:
377: + dm - the `DM` context
378: - ctype - the matrix type, for example `MATMPIAIJ`
380: Options Database Key:
381: . -dm_mat_type ctype - the type of the matrix to create, see `MatType`
383: Level: intermediate
385: .seealso: [](ch_dmbase), `DM`, `MatType`, `DMDACreate1d()`, `DMDACreate2d()`, `DMDACreate3d()`, `DMCreateMatrix()`, `DMCreateMassMatrix()`, `DMSetMatrixPreallocateOnly()`, `DMGetMatType()`, `DMCreateGlobalVector()`, `DMCreateLocalVector()`
386: @*/
387: PetscErrorCode DMSetMatType(DM dm, MatType ctype)
388: {
389: char *tmp;
391: PetscFunctionBegin;
393: PetscAssertPointer(ctype, 2);
394: tmp = (char *)dm->mattype;
395: PetscCall(PetscStrallocpy(ctype, (char **)&dm->mattype));
396: PetscCall(PetscFree(tmp));
397: PetscFunctionReturn(PETSC_SUCCESS);
398: }
400: /*@
401: DMGetMatType - Gets the type of matrix that would be created with `DMCreateMatrix()`
403: Logically Collective
405: Input Parameter:
406: . dm - the `DM` context
408: Output Parameter:
409: . ctype - the matrix type
411: Level: intermediate
413: .seealso: [](ch_dmbase), `DM`, `DMDACreate1d()`, `DMDACreate2d()`, `DMDACreate3d()`, `DMCreateMatrix()`, `DMCreateMassMatrix()`, `DMSetMatrixPreallocateOnly()`, `MatType`, `DMSetMatType()`
414: @*/
415: PetscErrorCode DMGetMatType(DM dm, MatType *ctype)
416: {
417: PetscFunctionBegin;
419: *ctype = dm->mattype;
420: PetscFunctionReturn(PETSC_SUCCESS);
421: }
423: /*@
424: MatGetDM - Gets the `DM` defining the data layout of the matrix
426: Not Collective
428: Input Parameter:
429: . A - The `Mat`
431: Output Parameter:
432: . dm - The `DM`
434: Level: intermediate
436: Note:
437: A matrix may not have a `DM` associated with it
439: Developer Note:
440: Since the `Mat` class doesn't know about the `DM` class the `DM` object is associated with the `Mat` through a `PetscObjectCompose()` operation
442: .seealso: [](ch_dmbase), `DM`, `MatSetDM()`, `DMCreateMatrix()`, `DMSetMatType()`
443: @*/
444: PetscErrorCode MatGetDM(Mat A, DM *dm)
445: {
446: PetscFunctionBegin;
448: PetscAssertPointer(dm, 2);
449: PetscCall(PetscObjectQuery((PetscObject)A, "__PETSc_dm", (PetscObject *)dm));
450: PetscFunctionReturn(PETSC_SUCCESS);
451: }
453: /*@
454: MatSetDM - Sets the `DM` defining the data layout of the matrix
456: Not Collective
458: Input Parameters:
459: + A - The `Mat`
460: - dm - The `DM`
462: Level: developer
464: Note:
465: This is rarely used in practice, rather `DMCreateMatrix()` is used to create a matrix associated with a particular `DM`
467: Developer Note:
468: Since the `Mat` class doesn't know about the `DM` class the `DM` object is associated with
469: the `Mat` through a `PetscObjectCompose()` operation
471: .seealso: [](ch_dmbase), `DM`, `MatGetDM()`, `DMCreateMatrix()`, `DMSetMatType()`
472: @*/
473: PetscErrorCode MatSetDM(Mat A, DM dm)
474: {
475: PetscFunctionBegin;
478: PetscCall(PetscObjectCompose((PetscObject)A, "__PETSc_dm", (PetscObject)dm));
479: PetscFunctionReturn(PETSC_SUCCESS);
480: }
482: /*@
483: DMSetOptionsPrefix - Sets the prefix prepended to all option names when searching through the options database
485: Logically Collective
487: Input Parameters:
488: + dm - the `DM` context
489: - prefix - the prefix to prepend
491: Level: advanced
493: Note:
494: A hyphen (-) must NOT be given at the beginning of the prefix name.
495: The first character of all runtime options is AUTOMATICALLY the hyphen.
497: .seealso: [](ch_dmbase), `DM`, `PetscObjectSetOptionsPrefix()`, `DMSetFromOptions()`
498: @*/
499: PetscErrorCode DMSetOptionsPrefix(DM dm, const char prefix[])
500: {
501: PetscFunctionBegin;
503: PetscCall(PetscObjectSetOptionsPrefix((PetscObject)dm, prefix));
504: if (dm->sf) PetscCall(PetscObjectSetOptionsPrefix((PetscObject)dm->sf, prefix));
505: if (dm->sectionSF) PetscCall(PetscObjectSetOptionsPrefix((PetscObject)dm->sectionSF, prefix));
506: PetscFunctionReturn(PETSC_SUCCESS);
507: }
509: /*@
510: DMAppendOptionsPrefix - Appends an additional string to an already existing prefix used for searching for
511: `DM` options in the options database.
513: Logically Collective
515: Input Parameters:
516: + dm - the `DM` context
517: - prefix - the string to append to the current prefix
519: Level: advanced
521: Note:
522: If the `DM` does not currently have an options prefix then this value is used alone as the prefix as if `DMSetOptionsPrefix()` had been called.
523: A hyphen (-) must NOT be given at the beginning of the prefix name.
524: The first character of all runtime options is AUTOMATICALLY the hyphen.
526: .seealso: [](ch_dmbase), `DM`, `DMSetOptionsPrefix()`, `DMGetOptionsPrefix()`, `PetscObjectAppendOptionsPrefix()`, `DMSetFromOptions()`
527: @*/
528: PetscErrorCode DMAppendOptionsPrefix(DM dm, const char prefix[])
529: {
530: PetscFunctionBegin;
532: PetscCall(PetscObjectAppendOptionsPrefix((PetscObject)dm, prefix));
533: PetscFunctionReturn(PETSC_SUCCESS);
534: }
536: /*@
537: DMGetOptionsPrefix - Gets the prefix used for searching for all
538: DM options in the options database.
540: Not Collective
542: Input Parameter:
543: . dm - the `DM` context
545: Output Parameter:
546: . prefix - pointer to the prefix string used is returned
548: Level: advanced
550: .seealso: [](ch_dmbase), `DM`, `DMSetOptionsPrefix()`, `DMAppendOptionsPrefix()`, `DMSetFromOptions()`
551: @*/
552: PetscErrorCode DMGetOptionsPrefix(DM dm, const char *prefix[])
553: {
554: PetscFunctionBegin;
556: PetscCall(PetscObjectGetOptionsPrefix((PetscObject)dm, prefix));
557: PetscFunctionReturn(PETSC_SUCCESS);
558: }
560: static PetscErrorCode DMCountNonCyclicReferences_Internal(DM dm, PetscBool recurseCoarse, PetscBool recurseFine, PetscInt *ncrefct)
561: {
562: PetscInt refct = ((PetscObject)dm)->refct;
564: PetscFunctionBegin;
565: *ncrefct = 0;
566: if (dm->coarseMesh && dm->coarseMesh->fineMesh == dm) {
567: refct--;
568: if (recurseCoarse) {
569: PetscInt coarseCount;
571: PetscCall(DMCountNonCyclicReferences_Internal(dm->coarseMesh, PETSC_TRUE, PETSC_FALSE, &coarseCount));
572: refct += coarseCount;
573: }
574: }
575: if (dm->fineMesh && dm->fineMesh->coarseMesh == dm) {
576: refct--;
577: if (recurseFine) {
578: PetscInt fineCount;
580: PetscCall(DMCountNonCyclicReferences_Internal(dm->fineMesh, PETSC_FALSE, PETSC_TRUE, &fineCount));
581: refct += fineCount;
582: }
583: }
584: *ncrefct = refct;
585: PetscFunctionReturn(PETSC_SUCCESS);
586: }
588: /* Generic wrapper for DMCountNonCyclicReferences_Internal() */
589: PetscErrorCode DMCountNonCyclicReferences(PetscObject dm, PetscInt *ncrefct)
590: {
591: PetscFunctionBegin;
592: PetscCall(DMCountNonCyclicReferences_Internal((DM)dm, PETSC_TRUE, PETSC_TRUE, ncrefct));
593: PetscFunctionReturn(PETSC_SUCCESS);
594: }
596: PetscErrorCode DMDestroyLabelLinkList_Internal(DM dm)
597: {
598: DMLabelLink next = dm->labels;
600: PetscFunctionBegin;
601: /* destroy the labels */
602: while (next) {
603: DMLabelLink tmp = next->next;
605: if (next->label == dm->depthLabel) dm->depthLabel = NULL;
606: if (next->label == dm->celltypeLabel) dm->celltypeLabel = NULL;
607: PetscCall(DMLabelDestroy(&next->label));
608: PetscCall(PetscFree(next));
609: next = tmp;
610: }
611: dm->labels = NULL;
612: PetscFunctionReturn(PETSC_SUCCESS);
613: }
615: PetscErrorCode DMDestroyCoordinates_Internal(DMCoordinates *c)
616: {
617: PetscFunctionBegin;
618: c->dim = PETSC_DEFAULT;
619: PetscCall(DMDestroy(&c->dm));
620: PetscCall(VecDestroy(&c->x));
621: PetscCall(VecDestroy(&c->xl));
622: PetscCall(DMFieldDestroy(&c->field));
623: PetscFunctionReturn(PETSC_SUCCESS);
624: }
626: /*@
627: DMDestroy - Destroys a `DM`.
629: Collective
631: Input Parameter:
632: . dm - the `DM` object to destroy
634: Level: developer
636: .seealso: [](ch_dmbase), `DM`, `DMCreate()`, `DMType`, `DMSetType()`, `DMView()`, `DMCreateGlobalVector()`, `DMCreateInterpolation()`, `DMCreateColoring()`, `DMCreateMatrix()`
637: @*/
638: PetscErrorCode DMDestroy(DM *dm)
639: {
640: PetscInt cnt;
642: PetscFunctionBegin;
643: if (!*dm) PetscFunctionReturn(PETSC_SUCCESS);
646: /* count all non-cyclic references in the doubly-linked list of coarse<->fine meshes */
647: PetscCall(DMCountNonCyclicReferences_Internal(*dm, PETSC_TRUE, PETSC_TRUE, &cnt));
648: --((PetscObject)*dm)->refct;
649: if (--cnt > 0) {
650: *dm = NULL;
651: PetscFunctionReturn(PETSC_SUCCESS);
652: }
653: if (((PetscObject)*dm)->refct < 0) PetscFunctionReturn(PETSC_SUCCESS);
654: ((PetscObject)*dm)->refct = 0;
656: PetscCall(DMClearGlobalVectors(*dm));
657: PetscCall(DMClearLocalVectors(*dm));
658: PetscCall(DMClearNamedGlobalVectors(*dm));
659: PetscCall(DMClearNamedLocalVectors(*dm));
661: /* Destroy the list of hooks */
662: {
663: DMCoarsenHookLink link, next;
664: for (link = (*dm)->coarsenhook; link; link = next) {
665: next = link->next;
666: PetscCall(PetscFree(link));
667: }
668: (*dm)->coarsenhook = NULL;
669: }
670: {
671: DMRefineHookLink link, next;
672: for (link = (*dm)->refinehook; link; link = next) {
673: next = link->next;
674: PetscCall(PetscFree(link));
675: }
676: (*dm)->refinehook = NULL;
677: }
678: {
679: DMSubDomainHookLink link, next;
680: for (link = (*dm)->subdomainhook; link; link = next) {
681: next = link->next;
682: PetscCall(PetscFree(link));
683: }
684: (*dm)->subdomainhook = NULL;
685: }
686: {
687: DMGlobalToLocalHookLink link, next;
688: for (link = (*dm)->gtolhook; link; link = next) {
689: next = link->next;
690: PetscCall(PetscFree(link));
691: }
692: (*dm)->gtolhook = NULL;
693: }
694: {
695: DMLocalToGlobalHookLink link, next;
696: for (link = (*dm)->ltoghook; link; link = next) {
697: next = link->next;
698: PetscCall(PetscFree(link));
699: }
700: (*dm)->ltoghook = NULL;
701: }
702: /* Destroy the work arrays */
703: {
704: DMWorkLink link, next;
705: PetscCheck(!(*dm)->workout, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Work array still checked out %p %p", (void *)(*dm)->workout, (*dm)->workout->mem);
706: for (link = (*dm)->workin; link; link = next) {
707: next = link->next;
708: PetscCall(PetscFree(link->mem));
709: PetscCall(PetscFree(link));
710: }
711: (*dm)->workin = NULL;
712: }
713: /* destroy the labels */
714: PetscCall(DMDestroyLabelLinkList_Internal(*dm));
715: /* destroy the fields */
716: PetscCall(DMClearFields(*dm));
717: /* destroy the boundaries */
718: {
719: DMBoundary next = (*dm)->boundary;
720: while (next) {
721: DMBoundary b = next;
723: next = b->next;
724: PetscCall(PetscFree(b));
725: }
726: }
728: PetscCall(PetscObjectDestroy(&(*dm)->dmksp));
729: PetscCall(PetscObjectDestroy(&(*dm)->dmsnes));
730: PetscCall(PetscObjectDestroy(&(*dm)->dmts));
732: if ((*dm)->ctx && (*dm)->ctxdestroy) PetscCall((*(*dm)->ctxdestroy)(&(*dm)->ctx));
733: PetscCall(MatFDColoringDestroy(&(*dm)->fd));
734: PetscCall(ISLocalToGlobalMappingDestroy(&(*dm)->ltogmap));
735: PetscCall(PetscFree((*dm)->vectype));
736: PetscCall(PetscFree((*dm)->mattype));
738: PetscCall(PetscSectionDestroy(&(*dm)->localSection));
739: PetscCall(PetscSectionDestroy(&(*dm)->globalSection));
740: PetscCall(PetscFree((*dm)->reorderSectionType));
741: PetscCall(PetscLayoutDestroy(&(*dm)->map));
742: PetscCall(PetscSectionDestroy(&(*dm)->defaultConstraint.section));
743: PetscCall(MatDestroy(&(*dm)->defaultConstraint.mat));
744: PetscCall(PetscSFDestroy(&(*dm)->sf));
745: PetscCall(PetscSFDestroy(&(*dm)->sectionSF));
746: PetscCall(PetscSFDestroy(&(*dm)->sfNatural));
747: PetscCall(PetscObjectDereference((PetscObject)(*dm)->sfMigration));
748: PetscCall(DMClearAuxiliaryVec(*dm));
749: PetscCall(PetscHMapAuxDestroy(&(*dm)->auxData));
750: if ((*dm)->coarseMesh && (*dm)->coarseMesh->fineMesh == *dm) PetscCall(DMSetFineDM((*dm)->coarseMesh, NULL));
752: PetscCall(DMDestroy(&(*dm)->coarseMesh));
753: if ((*dm)->fineMesh && (*dm)->fineMesh->coarseMesh == *dm) PetscCall(DMSetCoarseDM((*dm)->fineMesh, NULL));
754: PetscCall(DMDestroy(&(*dm)->fineMesh));
755: PetscCall(PetscFree((*dm)->Lstart));
756: PetscCall(PetscFree((*dm)->L));
757: PetscCall(PetscFree((*dm)->maxCell));
758: PetscCall(PetscFree2((*dm)->nullspaceConstructors, (*dm)->nearnullspaceConstructors));
759: PetscCall(DMDestroyCoordinates_Internal(&(*dm)->coordinates[0]));
760: PetscCall(DMDestroyCoordinates_Internal(&(*dm)->coordinates[1]));
761: if ((*dm)->transformDestroy) PetscCall((*(*dm)->transformDestroy)(*dm, (*dm)->transformCtx));
762: PetscCall(DMDestroy(&(*dm)->transformDM));
763: PetscCall(VecDestroy(&(*dm)->transform));
764: for (PetscInt i = 0; i < (*dm)->periodic.num_affines; i++) {
765: PetscCall(VecScatterDestroy(&(*dm)->periodic.affine_to_local[i]));
766: PetscCall(VecDestroy(&(*dm)->periodic.affine[i]));
767: }
768: if ((*dm)->periodic.num_affines > 0) PetscCall(PetscFree2((*dm)->periodic.affine_to_local, (*dm)->periodic.affine));
770: PetscCall(DMClearDS(*dm));
771: PetscCall(DMDestroy(&(*dm)->dmBC));
772: /* if memory was published with SAWs then destroy it */
773: PetscCall(PetscObjectSAWsViewOff((PetscObject)*dm));
775: PetscTryTypeMethod(*dm, destroy);
776: PetscCall(DMMonitorCancel(*dm));
777: PetscCall(DMCeedDestroy(&(*dm)->dmceed));
778: #ifdef PETSC_HAVE_LIBCEED
779: PetscCallCEED(CeedElemRestrictionDestroy(&(*dm)->ceedERestrict));
780: PetscCallCEED(CeedDestroy(&(*dm)->ceed));
781: #endif
782: /* We do not destroy (*dm)->data here so that we can reference count backend objects */
783: PetscCall(PetscHeaderDestroy(dm));
784: PetscFunctionReturn(PETSC_SUCCESS);
785: }
787: /*@
788: DMSetUp - sets up the data structures inside a `DM` object
790: Collective
792: Input Parameter:
793: . dm - the `DM` object to setup
795: Level: intermediate
797: Note:
798: This is usually called after various parameter setting operations and `DMSetFromOptions()` are called on the `DM`
800: .seealso: [](ch_dmbase), `DM`, `DMCreate()`, `DMSetType()`, `DMView()`, `DMCreateGlobalVector()`, `DMCreateInterpolation()`, `DMCreateColoring()`, `DMCreateMatrix()`
801: @*/
802: PetscErrorCode DMSetUp(DM dm)
803: {
804: PetscFunctionBegin;
806: if (dm->setupcalled) PetscFunctionReturn(PETSC_SUCCESS);
807: PetscTryTypeMethod(dm, setup);
808: dm->setupcalled = PETSC_TRUE;
809: PetscFunctionReturn(PETSC_SUCCESS);
810: }
812: /*@
813: DMSetFromOptions - sets parameters in a `DM` from the options database
815: Collective
817: Input Parameter:
818: . dm - the `DM` object to set options for
820: Options Database Keys:
821: + -dm_preallocate_only (true|false) - Only preallocate the matrix for `DMCreateMatrix()` and `DMCreateMassMatrix()`, but do not fill it with zeros
822: . -dm_vec_type type - type of vector to create inside `DM`
823: . -dm_mat_type type - type of matrix to create inside `DM`
824: . -dm_is_coloring_type (global|local) - see `ISColoringType`
825: . -dm_bind_below n - bind (force execution on CPU) for `Vec` and `Mat` objects with local size (number of vector entries or matrix rows) below n; currently only supported for `DMDA`
826: . -dm_plex_option_phases ph0_, ph1_, ... - List of prefixes for option processing phases
827: . -dm_plex_filename str - File containing a mesh
828: . -dm_plex_boundary_filename str - File containing a mesh boundary
829: . -dm_plex_name str - Name of the mesh in the file
830: . -dm_plex_shape shape - The domain shape, such as `BOX`, `SPHERE`, etc.
831: . -dm_plex_cell ct - Cell shape
832: . -dm_plex_reference_cell_domain (true|false) - Use a reference cell domain
833: . -dm_plex_dim dim - Set the topological dimension
834: . -dm_plex_simplex (true|false) - `PETSC_TRUE` for simplex elements, `PETSC_FALSE` for tensor elements
835: . -dm_plex_interpolate (true|false) - `PETSC_TRUE` turns on topological interpolation (creating edges and faces)
836: . -dm_plex_orient (true|false) - `PETSC_TRUE` turns on topological orientation (flipping edges and faces)
837: . -dm_plex_scale sc - Scale factor for mesh coordinates
838: . -dm_coord_remap (true|false) - Map coordinates using a function
839: . -dm_plex_coordinate_dim dim - Change the coordinate dimension of a mesh (usually given with cdm_ prefix)
840: . -dm_coord_map mapname - Select a builtin coordinate map
841: . -dm_coord_map_params p0,p1,p2,... - Set coordinate mapping parameters
842: . -dm_plex_box_faces m,n,p - Number of faces along each dimension
843: . -dm_plex_box_lower x,y,z - Specify lower-left-bottom coordinates for the box
844: . -dm_plex_box_upper x,y,z - Specify upper-right-top coordinates for the box
845: . -dm_plex_box_bd bx,by,bz - Specify the `DMBoundaryType` for each direction
846: . -dm_plex_sphere_radius r - The sphere radius
847: . -dm_plex_ball_radius r - Radius of the ball
848: . -dm_plex_cylinder_bd bz - Boundary type in the z direction
849: . -dm_plex_cylinder_num_wedges n - Number of wedges around the cylinder
850: . -dm_plex_reorder order - Reorder the mesh using the specified algorithm
851: . -dm_refine_pre n - The number of refinements before distribution
852: . -dm_refine_uniform_pre (true|false) - Flag for uniform refinement before distribution
853: . -dm_refine_volume_limit_pre v - The maximum cell volume after refinement before distribution
854: . -dm_refine n - The number of refinements after distribution
855: . -dm_extrude l - Activate extrusion and specify the number of layers to extrude
856: . -dm_plex_save_transform (true|false) - Save the `DMPlexTransform` that produced this mesh
857: . -dm_plex_transform_extrude_thickness t - The total thickness of extruded layers
858: . -dm_plex_transform_extrude_use_tensor (true|false) - Use tensor cells when extruding
859: . -dm_plex_transform_extrude_symmetric (true|false) - Extrude layers symmetrically about the surface
860: . -dm_plex_transform_extrude_normal n0,...,nd - Specify the extrusion direction
861: . -dm_plex_transform_extrude_thicknesses t0,...,tl - Specify thickness of each layer
862: . -dm_plex_create_fv_ghost_cells - Flag to create finite volume ghost cells on the boundary
863: . -dm_plex_fv_ghost_cells_label name - Label name for ghost cells boundary
864: . -dm_distribute (true|false) - Flag to redistribute a mesh among processes
865: . -dm_distribute_overlap n - The size of the overlap halo
866: . -dm_plex_adj_cone (true|false) - Set adjacency direction
867: . -dm_plex_adj_closure (true|false) - Set adjacency size
868: . -dm_plex_use_ceed (true|false) - Use LibCEED as the FEM backend
869: . -dm_plex_check_symmetry (true|false) - Check that the adjacency information in the mesh is symmetric - `DMPlexCheckSymmetry()`
870: . -dm_plex_check_skeleton (true|false) - Check that each cell has the correct number of vertices (only for homogeneous simplex or tensor meshes) - `DMPlexCheckSkeleton()`
871: . -dm_plex_check_faces (true|false) - Check that the faces of each cell give a vertex order this is consistent with what we expect from the cell type - `DMPlexCheckFaces()`
872: . -dm_plex_check_geometry (true|false) - Check that cells have positive volume - `DMPlexCheckGeometry()`
873: . -dm_plex_check_pointsf (true|false) - Check some necessary conditions for `PointSF` - `DMPlexCheckPointSF()`
874: . -dm_plex_check_interface_cones (true|false) - Check points on inter-partition interfaces have conforming order of cone points - `DMPlexCheckInterfaceCones()`
875: - -dm_plex_check_all (true|false) - Perform all the checks above
877: Level: intermediate
879: Note:
880: For some `DMType` such as `DMDA` this cannot be called after `DMSetUp()` has been called.
882: .seealso: [](ch_dmbase), `DM`, `DMView()`, `DMCreateGlobalVector()`, `DMCreateInterpolation()`, `DMCreateColoring()`, `DMCreateMatrix()`,
883: `DMPlexCheckSymmetry()`, `DMPlexCheckSkeleton()`, `DMPlexCheckFaces()`, `DMPlexCheckGeometry()`, `DMPlexCheckPointSF()`, `DMPlexCheckInterfaceCones()`,
884: `DMSetOptionsPrefix()`, `DMType`, `DMPLEX`, `DMDA`, `DMSetUp()`
885: @*/
886: PetscErrorCode DMSetFromOptions(DM dm)
887: {
888: char typeName[256];
889: PetscBool flg;
891: PetscFunctionBegin;
893: dm->setfromoptionscalled = PETSC_TRUE;
894: if (dm->sf) PetscCall(PetscSFSetFromOptions(dm->sf));
895: if (dm->sectionSF) PetscCall(PetscSFSetFromOptions(dm->sectionSF));
896: if (dm->coordinates[0].dm) PetscCall(DMSetFromOptions(dm->coordinates[0].dm));
897: PetscObjectOptionsBegin((PetscObject)dm);
898: PetscCall(PetscOptionsBool("-dm_preallocate_only", "only preallocate matrix, but do not set column indices", "DMSetMatrixPreallocateOnly", dm->prealloc_only, &dm->prealloc_only, NULL));
899: PetscCall(PetscOptionsFList("-dm_vec_type", "Vector type used for created vectors", "DMSetVecType", VecList, dm->vectype, typeName, 256, &flg));
900: if (flg) PetscCall(DMSetVecType(dm, typeName));
901: PetscCall(PetscOptionsFList("-dm_mat_type", "Matrix type used for created matrices", "DMSetMatType", MatList, dm->mattype ? dm->mattype : typeName, typeName, sizeof(typeName), &flg));
902: if (flg) PetscCall(DMSetMatType(dm, typeName));
903: PetscCall(PetscOptionsEnum("-dm_blocking_type", "Topological point or field node blocking", "DMSetBlockingType", DMBlockingTypes, (PetscEnum)dm->blocking_type, (PetscEnum *)&dm->blocking_type, NULL));
904: PetscCall(PetscOptionsEnum("-dm_is_coloring_type", "Global or local coloring of Jacobian", "DMSetISColoringType", ISColoringTypes, (PetscEnum)dm->coloringtype, (PetscEnum *)&dm->coloringtype, NULL));
905: PetscCall(PetscOptionsInt("-dm_bind_below", "Set the size threshold (in entries) below which the Vec is bound to the CPU", "VecBindToCPU", dm->bind_below, &dm->bind_below, &flg));
906: PetscCall(PetscOptionsBool("-dm_ignore_perm_output", "Ignore the local section permutation on output", "DMGetOutputDM", dm->ignorePermOutput, &dm->ignorePermOutput, NULL));
907: PetscTryTypeMethod(dm, setfromoptions, PetscOptionsObject);
908: /* process any options handlers added with PetscObjectAddOptionsHandler() */
909: PetscCall(PetscObjectProcessOptionsHandlers((PetscObject)dm, PetscOptionsObject));
910: PetscOptionsEnd();
911: PetscFunctionReturn(PETSC_SUCCESS);
912: }
914: /*@
915: DMViewFromOptions - View a `DM` in a particular way based on a request in the options database
917: Collective
919: Input Parameters:
920: + dm - the `DM` object
921: . obj - optional object that provides the prefix for the options database (if `NULL` then the prefix in `obj` is used)
922: - name - option string that is used to activate viewing
924: Options Database Key:
925: . -name [viewertype][:...] - option name and values. See `PetscObjectViewFromOptions()` for the possible arguments
927: Level: intermediate
929: .seealso: [](ch_dmbase), `DM`, `DMView()`, `PetscObjectViewFromOptions()`, `DMCreate()`
930: @*/
931: PetscErrorCode DMViewFromOptions(DM dm, PeOp PetscObject obj, const char name[])
932: {
933: PetscFunctionBegin;
935: PetscCall(PetscObjectViewFromOptions((PetscObject)dm, obj, name));
936: PetscFunctionReturn(PETSC_SUCCESS);
937: }
939: /*@
940: DMView - Views a `DM`. Depending on the `PetscViewer` and its `PetscViewerFormat` it may print some ASCII information about the `DM` to the screen or a file or
941: save the `DM` in a binary file to be loaded later or create a visualization of the `DM`
943: Collective
945: Input Parameters:
946: + dm - the `DM` object to view
947: - v - the viewer
949: Options Database Keys:
950: + -view_pyvista_warp f - Warps the mesh by the active scalar with factor f
951: . -view_pyvista_clip xl,xu,yl,yu,zl,zu - Defines the clipping box
952: . -dm_view_draw_line_color color - Specify the X-window color for cell borders
953: . -dm_view_draw_cell_color color - Specify the X-window color for cells
954: - -dm_view_draw_affine (true|false) - Flag to ignore high-order edges
956: Level: beginner
958: Notes:
960: `PetscViewer` = `PETSCVIEWERHDF5` i.e. HDF5 format can be used with `PETSC_VIEWER_HDF5_PETSC` as the `PetscViewerFormat` to save multiple `DMPLEX`
961: meshes in a single HDF5 file. This in turn requires one to name the `DMPLEX` object with `PetscObjectSetName()`
962: before saving it with `DMView()` and before loading it with `DMLoad()` for identification of the mesh object.
964: `PetscViewer` = `PETSCVIEWEREXODUSII` i.e. ExodusII format assumes that element blocks (mapped to "Cell sets" labels)
965: consists of sequentially numbered cells.
967: If `dm` has been distributed, only the part of the `DM` on MPI rank 0 (including "ghost" cells and vertices) will be written.
969: Only TRI, TET, QUAD, and HEX cells are supported in ExodusII.
971: `DMPLEX` only represents geometry while most post-processing software expect that a mesh also provides information on the discretization space. This function assumes that the file represents Lagrange finite elements of order 1 or 2.
972: The order of the mesh shall be set using `PetscViewerExodusIISetOrder()`
974: Variable names can be set and queried using `PetscViewerExodusII[Set/Get][Nodal/Zonal]VariableNames[s]`.
976: .seealso: [](ch_dmbase), `DM`, `PetscViewer`, `PetscViewerFormat`, `PetscViewerSetFormat()`, `DMDestroy()`, `DMCreateGlobalVector()`, `DMCreateInterpolation()`, `DMCreateColoring()`, `DMCreateMatrix()`, `DMCreateMassMatrix()`, `DMLoad()`, `PetscObjectSetName()`
977: @*/
978: PetscErrorCode DMView(DM dm, PetscViewer v)
979: {
980: PetscBool isbinary;
981: PetscMPIInt size;
982: PetscViewerFormat format;
984: PetscFunctionBegin;
986: if (!v) PetscCall(PetscViewerASCIIGetStdout(PetscObjectComm((PetscObject)dm), &v));
988: /* Ideally, we would like to have this test on.
989: However, it currently breaks socket viz via GLVis.
990: During DMView(parallel_mesh,glvis_viewer), each
991: process opens a sequential ASCII socket to visualize
992: the local mesh, and PetscObjectView(dm,local_socket)
993: is internally called inside VecView_GLVis, incurring
994: in an error here */
995: /* PetscCheckSameComm(dm,1,v,2); */
996: PetscCall(PetscViewerCheckWritable(v));
998: PetscCall(PetscLogEventBegin(DM_View, v, 0, 0, 0));
999: PetscCall(PetscViewerGetFormat(v, &format));
1000: PetscCallMPI(MPI_Comm_size(PetscObjectComm((PetscObject)dm), &size));
1001: if (size == 1 && format == PETSC_VIEWER_LOAD_BALANCE) PetscFunctionReturn(PETSC_SUCCESS);
1002: PetscCall(PetscObjectPrintClassNamePrefixType((PetscObject)dm, v));
1003: PetscCall(PetscObjectTypeCompare((PetscObject)v, PETSCVIEWERBINARY, &isbinary));
1004: if (isbinary) {
1005: PetscInt classid = DM_FILE_CLASSID;
1006: char type[256];
1008: PetscCall(PetscViewerBinaryWrite(v, &classid, 1, PETSC_INT));
1009: PetscCall(PetscStrncpy(type, ((PetscObject)dm)->type_name, sizeof(type)));
1010: PetscCall(PetscViewerBinaryWrite(v, type, 256, PETSC_CHAR));
1011: }
1012: PetscTryTypeMethod(dm, view, v);
1013: PetscCall(PetscLogEventEnd(DM_View, v, 0, 0, 0));
1014: PetscFunctionReturn(PETSC_SUCCESS);
1015: }
1017: /*@
1018: DMCreateGlobalVector - Creates a global vector from a `DM` object. A global vector is a parallel vector that has no duplicate values shared between MPI ranks,
1019: that is it has no ghost locations.
1021: Collective
1023: Input Parameter:
1024: . dm - the `DM` object
1026: Output Parameter:
1027: . vec - the global vector
1029: Level: beginner
1031: Note:
1032: PETSc `Vec` always have all zero entries when created with `DMCreateGlobalVector()` until routines such as `VecSet()` or `VecSetValues()`
1033: are used to change the values. There is no reason to call `VecZeroEntries()` after creation.
1035: .seealso: [](ch_dmbase), `DM`, `Vec`, `DMCreateLocalVector()`, `DMGetGlobalVector()`, `DMDestroy()`, `DMView()`, `DMCreateInterpolation()`, `DMCreateColoring()`, `DMCreateMatrix()`,
1036: `DMGlobalToLocalBegin()`, `DMGlobalToLocalEnd()`
1037: @*/
1038: PetscErrorCode DMCreateGlobalVector(DM dm, Vec *vec)
1039: {
1040: PetscFunctionBegin;
1042: PetscAssertPointer(vec, 2);
1043: PetscUseTypeMethod(dm, createglobalvector, vec);
1044: if (PetscDefined(USE_DEBUG)) {
1045: DM vdm;
1047: PetscCall(VecGetDM(*vec, &vdm));
1048: PetscCheck(vdm, PETSC_COMM_SELF, PETSC_ERR_PLIB, "DM type '%s' did not attach the DM to the vector", ((PetscObject)dm)->type_name);
1049: }
1050: PetscFunctionReturn(PETSC_SUCCESS);
1051: }
1053: /*@
1054: DMCreateLocalVector - Creates a local vector from a `DM` object.
1056: Not Collective
1058: Input Parameter:
1059: . dm - the `DM` object
1061: Output Parameter:
1062: . vec - the local vector
1064: Level: beginner
1066: Notes:
1067: A local vector usually has ghost locations that contain values that are owned by different MPI ranks. A global vector has no ghost locations.
1069: PETSc `Vec` always have all zero entries when created with `DMCreateLocalVector()` until routines such as `VecSet()` or `VecSetValues()`
1070: are used to change the values. There is no reason to call `VecZeroEntries()` after creation.
1072: .seealso: [](ch_dmbase), `DM`, `Vec`, `DMCreateGlobalVector()`, `DMGetLocalVector()`, `DMDestroy()`, `DMView()`, `DMCreateInterpolation()`, `DMCreateColoring()`, `DMCreateMatrix()`,
1073: `DMGlobalToLocalBegin()`, `DMGlobalToLocalEnd()`
1074: @*/
1075: PetscErrorCode DMCreateLocalVector(DM dm, Vec *vec)
1076: {
1077: PetscFunctionBegin;
1079: PetscAssertPointer(vec, 2);
1080: PetscUseTypeMethod(dm, createlocalvector, vec);
1081: if (PetscDefined(USE_DEBUG)) {
1082: DM vdm;
1084: PetscCall(VecGetDM(*vec, &vdm));
1085: PetscCheck(vdm, PETSC_COMM_SELF, PETSC_ERR_LIB, "DM type '%s' did not attach the DM to the vector", ((PetscObject)dm)->type_name);
1086: }
1087: PetscFunctionReturn(PETSC_SUCCESS);
1088: }
1090: /*@
1091: DMGetLocalToGlobalMapping - Accesses the local-to-global mapping in a `DM`.
1093: Collective
1095: Input Parameter:
1096: . dm - the `DM` that provides the mapping
1098: Output Parameter:
1099: . ltog - the mapping
1101: Level: advanced
1103: Notes:
1104: The global to local mapping allows one to set values into the global vector or matrix using `VecSetValuesLocal()` and `MatSetValuesLocal()`
1106: Vectors obtained with `DMCreateGlobalVector()` and matrices obtained with `DMCreateMatrix()` already contain the global mapping so you do
1107: need to use this function with those objects.
1109: This mapping can then be used by `VecSetLocalToGlobalMapping()` or `MatSetLocalToGlobalMapping()`.
1111: .seealso: [](ch_dmbase), `DM`, `DMCreateLocalVector()`, `DMCreateGlobalVector()`, `VecSetLocalToGlobalMapping()`, `MatSetLocalToGlobalMapping()`,
1112: `DMCreateMatrix()`
1113: @*/
1114: PetscErrorCode DMGetLocalToGlobalMapping(DM dm, ISLocalToGlobalMapping *ltog)
1115: {
1116: PetscInt bs = -1, bsLocal[2], bsMinMax[2];
1118: PetscFunctionBegin;
1120: PetscAssertPointer(ltog, 2);
1121: if (!dm->ltogmap) {
1122: PetscSection section, sectionGlobal;
1124: PetscCall(DMGetLocalSection(dm, §ion));
1125: if (section) {
1126: const PetscInt *cdofs;
1127: PetscInt *ltog;
1128: PetscInt pStart, pEnd, n, p, k, l;
1130: PetscCall(DMGetGlobalSection(dm, §ionGlobal));
1131: PetscCall(PetscSectionGetChart(section, &pStart, &pEnd));
1132: PetscCall(PetscSectionGetStorageSize(section, &n));
1133: PetscCall(PetscMalloc1(n, <og)); /* We want the local+overlap size */
1134: for (p = pStart, l = 0; p < pEnd; ++p) {
1135: PetscInt bdof, cdof, dof, off, c, cind;
1137: /* Should probably use constrained dofs */
1138: PetscCall(PetscSectionGetDof(section, p, &dof));
1139: PetscCall(PetscSectionGetConstraintDof(section, p, &cdof));
1140: PetscCall(PetscSectionGetConstraintIndices(section, p, &cdofs));
1141: PetscCall(PetscSectionGetOffset(sectionGlobal, p, &off));
1142: /* If you have dofs, and constraints, and they are unequal, we set the blocksize to 1 */
1143: bdof = cdof && (dof - cdof) ? 1 : dof;
1144: if (dof) bs = bs < 0 ? bdof : PetscGCD(bs, bdof);
1146: for (c = 0, cind = 0; c < dof; ++c, ++l) {
1147: if (cind < cdof && c == cdofs[cind]) {
1148: ltog[l] = off < 0 ? off - c : -(off + c + 1);
1149: cind++;
1150: } else {
1151: ltog[l] = (off < 0 ? -(off + 1) : off) + c - cind;
1152: }
1153: }
1154: }
1155: /* Must have same blocksize on all procs (some might have no points) */
1156: bsLocal[0] = bs < 0 ? PETSC_INT_MAX : bs;
1157: bsLocal[1] = bs;
1158: PetscCall(PetscGlobalMinMaxInt(PetscObjectComm((PetscObject)dm), bsLocal, bsMinMax));
1159: if (bsMinMax[0] != bsMinMax[1]) bs = 1;
1160: else bs = bsMinMax[0];
1161: bs = bs < 0 ? 1 : bs;
1162: /* Must reduce indices by blocksize */
1163: if (bs > 1) {
1164: for (l = 0, k = 0; l < n; l += bs, ++k) {
1165: // Integer division of negative values truncates toward zero(!), not toward negative infinity
1166: ltog[k] = ltog[l] >= 0 ? ltog[l] / bs : -(-(ltog[l] + 1) / bs + 1);
1167: }
1168: n /= bs;
1169: }
1170: PetscCall(ISLocalToGlobalMappingCreate(PetscObjectComm((PetscObject)dm), bs, n, ltog, PETSC_OWN_POINTER, &dm->ltogmap));
1171: } else PetscUseTypeMethod(dm, getlocaltoglobalmapping);
1172: }
1173: *ltog = dm->ltogmap;
1174: PetscFunctionReturn(PETSC_SUCCESS);
1175: }
1177: /*@
1178: DMGetBlockSize - Gets the inherent block size associated with a `DM`
1180: Not Collective
1182: Input Parameter:
1183: . dm - the `DM` with block structure
1185: Output Parameter:
1186: . bs - the block size, 1 implies no exploitable block structure
1188: Level: intermediate
1190: Notes:
1191: This might be the number of degrees of freedom at each grid point for a structured grid.
1193: Complex `DM` that represent multiphysics or staggered grids or mixed-methods do not generally have a single inherent block size, but
1194: rather different locations in the vectors may have a different block size.
1196: .seealso: [](ch_dmbase), `DM`, `ISCreateBlock()`, `VecSetBlockSize()`, `MatSetBlockSize()`, `DMGetLocalToGlobalMapping()`
1197: @*/
1198: PetscErrorCode DMGetBlockSize(DM dm, PetscInt *bs)
1199: {
1200: PetscFunctionBegin;
1202: PetscAssertPointer(bs, 2);
1203: PetscCheck(dm->bs >= 1, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "DM does not have enough information to provide a block size yet");
1204: *bs = dm->bs;
1205: PetscFunctionReturn(PETSC_SUCCESS);
1206: }
1208: /*@
1209: DMCreateInterpolation - Gets the interpolation matrix between two `DM` objects. The resulting matrix map degrees of freedom in the vector obtained by
1210: `DMCreateGlobalVector()` on the coarse `DM` to similar vectors on the fine grid `DM`.
1212: Collective
1214: Input Parameters:
1215: + dmc - the `DM` object
1216: - dmf - the second, finer `DM` object
1218: Output Parameters:
1219: + mat - the interpolation
1220: - vec - the scaling (optional, pass `NULL` if not needed), see `DMCreateInterpolationScale()`
1222: Level: developer
1224: Notes:
1225: For `DMDA` objects this only works for "uniform refinement", that is the refined mesh was obtained `DMRefine()` or the coarse mesh was obtained by
1226: DMCoarsen(). The coordinates set into the `DMDA` are completely ignored in computing the interpolation.
1228: For `DMDA` objects you can use this interpolation (more precisely the interpolation from the `DMGetCoordinateDM()`) to interpolate the mesh coordinate
1229: vectors EXCEPT in the periodic case where it does not make sense since the coordinate vectors are not periodic.
1231: .seealso: [](ch_dmbase), `DM`, `DMDestroy()`, `DMView()`, `DMCreateGlobalVector()`, `DMCreateColoring()`, `DMCreateMatrix()`, `DMCreateMassMatrix()`, `DMRefine()`, `DMCoarsen()`, `DMCreateRestriction()`, `DMCreateInterpolationScale()`
1232: @*/
1233: PetscErrorCode DMCreateInterpolation(DM dmc, DM dmf, Mat *mat, Vec *vec)
1234: {
1235: PetscFunctionBegin;
1238: PetscAssertPointer(mat, 3);
1239: PetscCall(PetscLogEventBegin(DM_CreateInterpolation, dmc, dmf, 0, 0));
1240: PetscUseTypeMethod(dmc, createinterpolation, dmf, mat, vec);
1241: PetscCall(PetscLogEventEnd(DM_CreateInterpolation, dmc, dmf, 0, 0));
1242: PetscFunctionReturn(PETSC_SUCCESS);
1243: }
1245: /*@
1246: DMCreateInterpolationScale - Forms L = 1/(R*1) where 1 is the vector of all ones, and R is
1247: the transpose of the interpolation between the `DM`.
1249: Input Parameters:
1250: + dac - `DM` that defines a coarse mesh
1251: . daf - `DM` that defines a fine mesh
1252: - mat - the restriction (or interpolation operator) from fine to coarse
1254: Output Parameter:
1255: . scale - the scaled vector
1257: Level: advanced
1259: Note:
1260: xcoarse = diag(L)*R*xfine preserves scale and is thus suitable for state (versus residual)
1261: restriction. In other words xcoarse is the coarse representation of xfine.
1263: Developer Note:
1264: If the fine-scale `DMDA` has the -dm_bind_below option set to true, then `DMCreateInterpolationScale()` calls `MatSetBindingPropagates()`
1265: on the restriction/interpolation operator to set the bindingpropagates flag to true.
1267: .seealso: [](ch_dmbase), `DM`, `MatRestrict()`, `MatInterpolate()`, `DMCreateInterpolation()`, `DMCreateRestriction()`, `DMCreateGlobalVector()`
1268: @*/
1269: PetscErrorCode DMCreateInterpolationScale(DM dac, DM daf, Mat mat, Vec *scale)
1270: {
1271: Vec fine;
1272: PetscScalar one = 1.0;
1273: #if defined(PETSC_HAVE_CUDA)
1274: PetscBool bindingpropagates, isbound;
1275: #endif
1277: PetscFunctionBegin;
1278: PetscCall(DMCreateGlobalVector(daf, &fine));
1279: PetscCall(DMCreateGlobalVector(dac, scale));
1280: PetscCall(VecSet(fine, one));
1281: #if defined(PETSC_HAVE_CUDA)
1282: /* If the 'fine' Vec is bound to the CPU, it makes sense to bind 'mat' as well.
1283: * Note that we only do this for the CUDA case, right now, but if we add support for MatMultTranspose() via ViennaCL,
1284: * we'll need to do it for that case, too.*/
1285: PetscCall(VecGetBindingPropagates(fine, &bindingpropagates));
1286: if (bindingpropagates) {
1287: PetscCall(MatSetBindingPropagates(mat, PETSC_TRUE));
1288: PetscCall(VecBoundToCPU(fine, &isbound));
1289: PetscCall(MatBindToCPU(mat, isbound));
1290: }
1291: #endif
1292: PetscCall(MatRestrict(mat, fine, *scale));
1293: PetscCall(VecDestroy(&fine));
1294: PetscCall(VecReciprocal(*scale));
1295: PetscFunctionReturn(PETSC_SUCCESS);
1296: }
1298: /*@
1299: DMCreateRestriction - Gets restriction matrix between two `DM` objects. The resulting matrix map degrees of freedom in the vector obtained by
1300: `DMCreateGlobalVector()` on the fine `DM` to similar vectors on the coarse grid `DM`.
1302: Collective
1304: Input Parameters:
1305: + dmc - the `DM` object
1306: - dmf - the second, finer `DM` object
1308: Output Parameter:
1309: . mat - the restriction
1311: Level: developer
1313: Note:
1314: This only works for `DMSTAG`. For many situations either the transpose of the operator obtained with `DMCreateInterpolation()` or that
1315: matrix multiplied by the vector obtained with `DMCreateInterpolationScale()` provides the desired object.
1317: .seealso: [](ch_dmbase), `DM`, `DMRestrict()`, `DMInterpolate()`, `DMDestroy()`, `DMView()`, `DMCreateGlobalVector()`, `DMCreateColoring()`, `DMCreateMatrix()`, `DMCreateMassMatrix()`, `DMRefine()`, `DMCoarsen()`, `DMCreateInterpolation()`
1318: @*/
1319: PetscErrorCode DMCreateRestriction(DM dmc, DM dmf, Mat *mat)
1320: {
1321: PetscFunctionBegin;
1324: PetscAssertPointer(mat, 3);
1325: PetscCall(PetscLogEventBegin(DM_CreateRestriction, dmc, dmf, 0, 0));
1326: PetscUseTypeMethod(dmc, createrestriction, dmf, mat);
1327: PetscCall(PetscLogEventEnd(DM_CreateRestriction, dmc, dmf, 0, 0));
1328: PetscFunctionReturn(PETSC_SUCCESS);
1329: }
1331: /*@
1332: DMCreateInjection - Gets injection matrix between two `DM` objects.
1334: Collective
1336: Input Parameters:
1337: + dac - the `DM` object
1338: - daf - the second, finer `DM` object
1340: Output Parameter:
1341: . mat - the injection
1343: Level: developer
1345: Notes:
1346: This is an operator that applied to a vector obtained with `DMCreateGlobalVector()` on the
1347: fine grid maps the values to a vector on the vector on the coarse `DM` by simply selecting
1348: the values on the coarse grid points. This compares to the operator obtained by
1349: `DMCreateRestriction()` or the transpose of the operator obtained by
1350: `DMCreateInterpolation()` that uses a "local weighted average" of the values around the
1351: coarse grid point as the coarse grid value.
1353: For `DMDA` objects this only works for "uniform refinement", that is the refined mesh was obtained `DMRefine()` or the coarse mesh was obtained by
1354: `DMCoarsen()`. The coordinates set into the `DMDA` are completely ignored in computing the injection.
1356: .seealso: [](ch_dmbase), `DM`, `DMDestroy()`, `DMView()`, `DMCreateGlobalVector()`, `DMCreateColoring()`, `DMCreateMatrix()`, `DMCreateMassMatrix()`, `DMCreateInterpolation()`,
1357: `DMCreateRestriction()`, `MatRestrict()`, `MatInterpolate()`
1358: @*/
1359: PetscErrorCode DMCreateInjection(DM dac, DM daf, Mat *mat)
1360: {
1361: PetscFunctionBegin;
1364: PetscAssertPointer(mat, 3);
1365: PetscCall(PetscLogEventBegin(DM_CreateInjection, dac, daf, 0, 0));
1366: PetscUseTypeMethod(dac, createinjection, daf, mat);
1367: PetscCall(PetscLogEventEnd(DM_CreateInjection, dac, daf, 0, 0));
1368: PetscFunctionReturn(PETSC_SUCCESS);
1369: }
1371: /*@
1372: 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
1373: a Galerkin finite element model on the `DM`
1375: Collective
1377: Input Parameters:
1378: + dmc - the target `DM` object
1379: - dmf - the source `DM` object, can be `NULL`
1381: Output Parameter:
1382: . mat - the mass matrix
1384: Level: developer
1386: Notes:
1387: For `DMPLEX` the finite element model for the `DM` must have been already provided.
1389: 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()`
1391: .seealso: [](ch_dmbase), `DM`, `DMCreateMassMatrixLumped()`, `DMCreateMatrix()`, `DMRefine()`, `DMCoarsen()`, `DMCreateRestriction()`, `DMCreateInterpolation()`, `DMCreateInjection()`
1392: @*/
1393: PetscErrorCode DMCreateMassMatrix(DM dmc, DM dmf, Mat *mat)
1394: {
1395: PetscFunctionBegin;
1397: if (!dmf) dmf = dmc;
1399: PetscAssertPointer(mat, 3);
1400: PetscCall(PetscLogEventBegin(DM_CreateMassMatrix, dmc, dmf, 0, 0));
1401: PetscUseTypeMethod(dmc, createmassmatrix, dmf, mat);
1402: PetscCall(PetscLogEventEnd(DM_CreateMassMatrix, dmc, dmf, 0, 0));
1403: PetscFunctionReturn(PETSC_SUCCESS);
1404: }
1406: /*@
1407: DMCreateMassMatrixLumped - Gets the lumped mass matrix for a given `DM`
1409: Collective
1411: Input Parameter:
1412: . dm - the `DM` object
1414: Output Parameters:
1415: + llm - the local lumped mass matrix, which is a diagonal matrix, represented as a vector
1416: - lm - the global lumped mass matrix, which is a diagonal matrix, represented as a vector
1418: Level: developer
1420: Note:
1421: See `DMCreateMassMatrix()` for how to create the non-lumped version of the mass matrix.
1423: .seealso: [](ch_dmbase), `DM`, `DMCreateMassMatrix()`, `DMCreateMatrix()`, `DMRefine()`, `DMCoarsen()`, `DMCreateRestriction()`, `DMCreateInterpolation()`, `DMCreateInjection()`
1424: @*/
1425: PetscErrorCode DMCreateMassMatrixLumped(DM dm, Vec *llm, Vec *lm)
1426: {
1427: PetscFunctionBegin;
1429: if (llm) PetscAssertPointer(llm, 2);
1430: if (lm) PetscAssertPointer(lm, 3);
1431: if (llm || lm) PetscUseTypeMethod(dm, createmassmatrixlumped, llm, lm);
1432: PetscFunctionReturn(PETSC_SUCCESS);
1433: }
1435: /*@
1436: 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`
1438: Collective
1440: Input Parameters:
1441: + dmc - the target `DM` object
1442: - dmf - the source `DM` object, can be `NULL`
1444: Output Parameter:
1445: . mat - the gradient matrix
1447: Level: developer
1449: Notes:
1450: For `DMPLEX` the finite element model for the `DM` must have been already provided.
1452: .seealso: [](ch_dmbase), `DM`, `DMCreateMassMatrix()`, `DMCreateMassMatrixLumped()`, `DMCreateMatrix()`, `DMRefine()`, `DMCoarsen()`, `DMCreateRestriction()`, `DMCreateInterpolation()`, `DMCreateInjection()`
1453: @*/
1454: PetscErrorCode DMCreateGradientMatrix(DM dmc, DM dmf, Mat *mat)
1455: {
1456: PetscFunctionBegin;
1458: if (!dmf) dmf = dmc;
1460: PetscAssertPointer(mat, 3);
1461: PetscUseTypeMethod(dmc, creategradientmatrix, dmf, mat);
1462: PetscFunctionReturn(PETSC_SUCCESS);
1463: }
1465: /*@
1466: DMCreateColoring - Gets coloring of a graph associated with the `DM`. Often the graph represents the operator matrix associated with the discretization
1467: of a PDE on the `DM`.
1469: Collective
1471: Input Parameters:
1472: + dm - the `DM` object
1473: - ctype - `IS_COLORING_LOCAL` or `IS_COLORING_GLOBAL`
1475: Output Parameter:
1476: . coloring - the coloring
1478: Level: developer
1480: Notes:
1481: 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
1482: matrix comes from (what this function provides). In general using the mesh produces a more optimal coloring (fewer colors).
1484: This produces a coloring with the distance of 2, see `MatSetColoringDistance()` which can be used for efficiently computing Jacobians with `MatFDColoringCreate()`
1485: 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,
1486: otherwise an error will be generated.
1488: .seealso: [](ch_dmbase), `DM`, `ISColoring`, `DMDestroy()`, `DMView()`, `DMCreateGlobalVector()`, `DMCreateInterpolation()`, `DMCreateMatrix()`, `DMCreateMassMatrix()`, `DMSetMatType()`, `MatColoring`, `MatFDColoringCreate()`
1489: @*/
1490: PetscErrorCode DMCreateColoring(DM dm, ISColoringType ctype, ISColoring *coloring)
1491: {
1492: PetscFunctionBegin;
1494: PetscAssertPointer(coloring, 3);
1495: PetscUseTypeMethod(dm, getcoloring, ctype, coloring);
1496: PetscFunctionReturn(PETSC_SUCCESS);
1497: }
1499: /*@
1500: DMCreateMatrix - Creates a matrix of appropriate size and nonzero structure for a `DM`. The matrix is most commonly used to store the Jacobian
1501: of a discrete PDE operator.
1503: Collective
1505: Input Parameter:
1506: . dm - the `DM` object
1508: Output Parameter:
1509: . mat - the matrix
1511: Options Database Key:
1512: . -dm_preallocate_only (true|false) - Only preallocate the matrix for `DMCreateMatrix()` and `DMCreateMassMatrix()`, but do not fill its nonzero structure
1514: Level: beginner
1516: Notes:
1517: This properly preallocates the number of nonzeros in the sparse matrix so you
1518: do not need to do it yourself.
1520: By default it also sets the nonzero structure and puts in the zero entries. To prevent setting
1521: the nonzero pattern call `DMSetMatrixPreallocateOnly()`
1523: For `DMDA`, when you call `MatView()` on this matrix it is displayed using the global natural ordering, NOT in the ordering used
1524: internally by PETSc.
1526: For `DMDA`, in general it is easiest to use `MatSetValuesStencil()` or `MatSetValuesLocal()` to put values into the matrix because
1527: `MatSetValues()` requires the indices for the global numbering for the `DMDA` which is complic`ated to compute
1529: .seealso: [](ch_dmbase), `DM`, `DMDestroy()`, `DMView()`, `DMCreateGlobalVector()`, `DMCreateInterpolation()`, `DMSetMatType()`, `DMCreateMassMatrix()`
1530: @*/
1531: PetscErrorCode DMCreateMatrix(DM dm, Mat *mat)
1532: {
1533: PetscFunctionBegin;
1535: PetscAssertPointer(mat, 2);
1536: PetscCall(MatInitializePackage());
1537: PetscCall(PetscLogEventBegin(DM_CreateMatrix, 0, 0, 0, 0));
1538: PetscUseTypeMethod(dm, creatematrix, mat);
1539: if (PetscDefined(USE_DEBUG)) {
1540: DM mdm;
1542: PetscCall(MatGetDM(*mat, &mdm));
1543: PetscCheck(mdm, PETSC_COMM_SELF, PETSC_ERR_PLIB, "DM type '%s' did not attach the DM to the matrix", ((PetscObject)dm)->type_name);
1544: }
1545: /* Handle nullspace and near nullspace */
1546: if (dm->Nf) {
1547: MatNullSpace nullSpace;
1548: PetscInt Nf;
1550: PetscCall(DMGetNumFields(dm, &Nf));
1551: for (PetscInt f = 0; f < Nf; ++f) {
1552: if (dm->nullspaceConstructors && dm->nullspaceConstructors[f]) {
1553: PetscCall((*dm->nullspaceConstructors[f])(dm, f, f, &nullSpace));
1554: PetscCall(MatSetNullSpace(*mat, nullSpace));
1555: PetscCall(MatNullSpaceDestroy(&nullSpace));
1556: break;
1557: }
1558: }
1559: for (PetscInt f = 0; f < Nf; ++f) {
1560: if (dm->nearnullspaceConstructors && dm->nearnullspaceConstructors[f]) {
1561: PetscCall((*dm->nearnullspaceConstructors[f])(dm, f, f, &nullSpace));
1562: PetscCall(MatSetNearNullSpace(*mat, nullSpace));
1563: PetscCall(MatNullSpaceDestroy(&nullSpace));
1564: }
1565: }
1566: }
1567: PetscCall(PetscLogEventEnd(DM_CreateMatrix, 0, 0, 0, 0));
1568: PetscFunctionReturn(PETSC_SUCCESS);
1569: }
1571: /*@
1572: DMSetMatrixPreallocateSkip - When `DMCreateMatrix()` is called the matrix sizes and
1573: `ISLocalToGlobalMapping` will be properly set, but the data structures to store values in the
1574: matrices will not be preallocated.
1576: Logically Collective
1578: Input Parameters:
1579: + dm - the `DM`
1580: - skip - `PETSC_TRUE` to skip preallocation
1582: Level: developer
1584: Note:
1585: This is most useful to reduce initialization costs when `MatSetPreallocationCOO()` and
1586: `MatSetValuesCOO()` will be used.
1588: .seealso: [](ch_dmbase), `DM`, `DMCreateMatrix()`, `DMSetMatrixStructureOnly()`, `DMSetMatrixPreallocateOnly()`
1589: @*/
1590: PetscErrorCode DMSetMatrixPreallocateSkip(DM dm, PetscBool skip)
1591: {
1592: PetscFunctionBegin;
1594: dm->prealloc_skip = skip;
1595: PetscFunctionReturn(PETSC_SUCCESS);
1596: }
1598: /*@
1599: DMSetMatrixPreallocateOnly - When `DMCreateMatrix()` is called the matrix will be properly
1600: preallocated but the nonzero structure and zero values will not be set.
1602: Logically Collective
1604: Input Parameters:
1605: + dm - the `DM`
1606: - only - `PETSC_TRUE` if only want preallocation
1608: Options Database Key:
1609: . -dm_preallocate_only - Only preallocate the matrix for `DMCreateMatrix()`, `DMCreateMassMatrix()`, but do not fill it with zeros
1611: Level: developer
1613: .seealso: [](ch_dmbase), `DM`, `DMCreateMatrix()`, `DMCreateMassMatrix()`, `DMSetMatrixStructureOnly()`, `DMSetMatrixPreallocateSkip()`
1614: @*/
1615: PetscErrorCode DMSetMatrixPreallocateOnly(DM dm, PetscBool only)
1616: {
1617: PetscFunctionBegin;
1619: dm->prealloc_only = only;
1620: PetscFunctionReturn(PETSC_SUCCESS);
1621: }
1623: /*@
1624: DMSetMatrixStructureOnly - When `DMCreateMatrix()` is called, the matrix nonzero structure will be created
1625: but the array for numerical values will not be allocated.
1627: Logically Collective
1629: Input Parameters:
1630: + dm - the `DM`
1631: - only - `PETSC_TRUE` if you only want matrix nonzero structure
1633: Level: developer
1635: .seealso: [](ch_dmbase), `DM`, `DMCreateMatrix()`, `DMSetMatrixPreallocateOnly()`, `DMSetMatrixPreallocateSkip()`
1636: @*/
1637: PetscErrorCode DMSetMatrixStructureOnly(DM dm, PetscBool only)
1638: {
1639: PetscFunctionBegin;
1641: dm->structure_only = only;
1642: PetscFunctionReturn(PETSC_SUCCESS);
1643: }
1645: /*@
1646: DMSetBlockingType - set the blocking granularity to be used for variable block size `DMCreateMatrix()` is called
1648: Logically Collective
1650: Input Parameters:
1651: + dm - the `DM`
1652: - btype - block by topological point or field node
1654: Options Database Key:
1655: . -dm_blocking_type (topological_point|field_node) - use topological point blocking or field node blocking
1657: Level: advanced
1659: .seealso: [](ch_dmbase), `DM`, `DMCreateMatrix()`, `MatSetVariableBlockSizes()`
1660: @*/
1661: PetscErrorCode DMSetBlockingType(DM dm, DMBlockingType btype)
1662: {
1663: PetscFunctionBegin;
1665: dm->blocking_type = btype;
1666: PetscFunctionReturn(PETSC_SUCCESS);
1667: }
1669: /*@
1670: DMGetBlockingType - get the blocking granularity to be used for variable block size `DMCreateMatrix()` is called
1672: Not Collective
1674: Input Parameter:
1675: . dm - the `DM`
1677: Output Parameter:
1678: . btype - block by topological point or field node
1680: Level: advanced
1682: .seealso: [](ch_dmbase), `DM`, `DMCreateMatrix()`, `MatSetVariableBlockSizes()`
1683: @*/
1684: PetscErrorCode DMGetBlockingType(DM dm, DMBlockingType *btype)
1685: {
1686: PetscFunctionBegin;
1688: PetscAssertPointer(btype, 2);
1689: *btype = dm->blocking_type;
1690: PetscFunctionReturn(PETSC_SUCCESS);
1691: }
1693: /*@C
1694: DMGetWorkArray - Gets a work array guaranteed to be at least the input size, restore with `DMRestoreWorkArray()`
1696: Not Collective
1698: Input Parameters:
1699: + dm - the `DM` object
1700: . count - The minimum size
1701: - dtype - MPI data type, often `MPIU_REAL`, `MPIU_SCALAR`, or `MPIU_INT`)
1703: Output Parameter:
1704: . mem - the work array
1706: Level: developer
1708: Notes:
1709: A `DM` may stash the array between instantiations so using this routine may be more efficient than calling `PetscMalloc()`
1711: The array may contain nonzero values
1713: .seealso: [](ch_dmbase), `DM`, `DMDestroy()`, `DMCreate()`, `DMRestoreWorkArray()`, `PetscMalloc()`
1714: @*/
1715: PetscErrorCode DMGetWorkArray(DM dm, PetscInt count, MPI_Datatype dtype, void *mem)
1716: {
1717: DMWorkLink link;
1718: PetscMPIInt dsize;
1720: PetscFunctionBegin;
1722: PetscAssertPointer(mem, 4);
1723: if (!count) {
1724: *(void **)mem = NULL;
1725: PetscFunctionReturn(PETSC_SUCCESS);
1726: }
1727: if (dm->workin) {
1728: link = dm->workin;
1729: dm->workin = dm->workin->next;
1730: } else {
1731: PetscCall(PetscNew(&link));
1732: }
1733: /* Avoid MPI_Type_size for most used datatypes
1734: Get size directly */
1735: if (dtype == MPIU_INT) dsize = sizeof(PetscInt);
1736: else if (dtype == MPIU_REAL) dsize = sizeof(PetscReal);
1737: #if defined(PETSC_USE_64BIT_INDICES)
1738: else if (dtype == MPI_INT) dsize = sizeof(int);
1739: #endif
1740: #if defined(PETSC_USE_COMPLEX)
1741: else if (dtype == MPIU_SCALAR) dsize = sizeof(PetscScalar);
1742: #endif
1743: else PetscCallMPI(MPI_Type_size(dtype, &dsize));
1745: if (((size_t)dsize * count) > link->bytes) {
1746: PetscCall(PetscFree(link->mem));
1747: PetscCall(PetscMalloc(dsize * count, &link->mem));
1748: link->bytes = dsize * count;
1749: }
1750: link->next = dm->workout;
1751: dm->workout = link;
1752: *(void **)mem = link->mem;
1753: PetscFunctionReturn(PETSC_SUCCESS);
1754: }
1756: /*@C
1757: DMRestoreWorkArray - Restores a work array obtained with `DMCreateWorkArray()`
1759: Not Collective
1761: Input Parameters:
1762: + dm - the `DM` object
1763: . count - The minimum size
1764: - dtype - MPI data type, often `MPIU_REAL`, `MPIU_SCALAR`, `MPIU_INT`
1766: Output Parameter:
1767: . mem - the work array
1769: Level: developer
1771: Developer Note:
1772: count and dtype are ignored, they are only needed for `DMGetWorkArray()`
1774: .seealso: [](ch_dmbase), `DM`, `DMDestroy()`, `DMCreate()`, `DMGetWorkArray()`
1775: @*/
1776: PetscErrorCode DMRestoreWorkArray(DM dm, PetscInt count, MPI_Datatype dtype, void *mem)
1777: {
1778: DMWorkLink *p, link;
1780: PetscFunctionBegin;
1781: PetscAssertPointer(mem, 4);
1782: (void)count;
1783: (void)dtype;
1784: if (!*(void **)mem) PetscFunctionReturn(PETSC_SUCCESS);
1785: for (p = &dm->workout; (link = *p); p = &link->next) {
1786: if (link->mem == *(void **)mem) {
1787: *p = link->next;
1788: link->next = dm->workin;
1789: dm->workin = link;
1790: *(void **)mem = NULL;
1791: PetscFunctionReturn(PETSC_SUCCESS);
1792: }
1793: }
1794: SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Array was not checked out");
1795: }
1797: /*@C
1798: DMSetNullSpaceConstructor - Provide a callback function which constructs the nullspace for a given field, defined with `DMAddField()`, when function spaces
1799: are joined or split, such as in `DMCreateSubDM()`
1801: Logically Collective; No Fortran Support
1803: Input Parameters:
1804: + dm - The `DM`
1805: . field - The field number for the nullspace
1806: - nullsp - A callback to create the nullspace
1808: Calling sequence of `nullsp`:
1809: + dm - The present `DM`
1810: . origField - The field number given above, in the original `DM`
1811: . field - The field number in dm
1812: - nullSpace - The nullspace for the given field
1814: Level: intermediate
1816: .seealso: [](ch_dmbase), `DM`, `DMAddField()`, `DMGetNullSpaceConstructor()`, `DMSetNearNullSpaceConstructor()`, `DMGetNearNullSpaceConstructor()`, `DMCreateSubDM()`, `DMCreateSuperDM()`
1817: @*/
1818: PetscErrorCode DMSetNullSpaceConstructor(DM dm, PetscInt field, PetscErrorCode (*nullsp)(DM dm, PetscInt origField, PetscInt field, MatNullSpace *nullSpace))
1819: {
1820: PetscFunctionBegin;
1822: PetscCheck(field < dm->Nf, PetscObjectComm((PetscObject)dm), PETSC_ERR_ARG_OUTOFRANGE, "Cannot handle %" PetscInt_FMT " >= %" PetscInt_FMT " fields", field, dm->Nf);
1823: PetscCheck(dm->nullspaceConstructors, PetscObjectComm((PetscObject)dm), PETSC_ERR_ARG_WRONG, "Must call DMCreateDS() to setup nullspaces");
1824: dm->nullspaceConstructors[field] = nullsp;
1825: PetscFunctionReturn(PETSC_SUCCESS);
1826: }
1828: /*@C
1829: DMGetNullSpaceConstructor - Return the callback function which constructs the nullspace for a given field, defined with `DMAddField()`
1831: Not Collective; No Fortran Support
1833: Input Parameters:
1834: + dm - The `DM`
1835: - field - The field number for the nullspace
1837: Output Parameter:
1838: . nullsp - A callback to create the nullspace
1840: Calling sequence of `nullsp`:
1841: + dm - The present DM
1842: . origField - The field number given above, in the original DM
1843: . field - The field number in dm
1844: - nullSpace - The nullspace for the given field
1846: Level: intermediate
1848: .seealso: [](ch_dmbase), `DM`, `DMAddField()`, `DMGetField()`, `DMSetNullSpaceConstructor()`, `DMSetNearNullSpaceConstructor()`, `DMGetNearNullSpaceConstructor()`, `DMCreateSubDM()`, `DMCreateSuperDM()`
1849: @*/
1850: PetscErrorCode DMGetNullSpaceConstructor(DM dm, PetscInt field, PetscErrorCode (**nullsp)(DM dm, PetscInt origField, PetscInt field, MatNullSpace *nullSpace))
1851: {
1852: PetscFunctionBegin;
1854: PetscAssertPointer(nullsp, 3);
1855: PetscCheck(field < dm->Nf, PetscObjectComm((PetscObject)dm), PETSC_ERR_ARG_OUTOFRANGE, "Cannot handle %" PetscInt_FMT " >= %" PetscInt_FMT " fields", field, dm->Nf);
1856: PetscCheck(dm->nullspaceConstructors, PetscObjectComm((PetscObject)dm), PETSC_ERR_ARG_WRONG, "Must call DMCreateDS() to setup nullspaces");
1857: *nullsp = dm->nullspaceConstructors[field];
1858: PetscFunctionReturn(PETSC_SUCCESS);
1859: }
1861: /*@C
1862: DMSetNearNullSpaceConstructor - Provide a callback function which constructs the near-nullspace for a given field, defined with `DMAddField()`
1864: Logically Collective; No Fortran Support
1866: Input Parameters:
1867: + dm - The `DM`
1868: . field - The field number for the nullspace
1869: - nullsp - A callback to create the near-nullspace
1871: Calling sequence of `nullsp`:
1872: + dm - The present `DM`
1873: . origField - The field number given above, in the original `DM`
1874: . field - The field number in dm
1875: - nullSpace - The nullspace for the given field
1877: Level: intermediate
1879: .seealso: [](ch_dmbase), `DM`, `DMAddField()`, `DMGetNearNullSpaceConstructor()`, `DMSetNullSpaceConstructor()`, `DMGetNullSpaceConstructor()`, `DMCreateSubDM()`, `DMCreateSuperDM()`,
1880: `MatNullSpace`
1881: @*/
1882: PetscErrorCode DMSetNearNullSpaceConstructor(DM dm, PetscInt field, PetscErrorCode (*nullsp)(DM dm, PetscInt origField, PetscInt field, MatNullSpace *nullSpace))
1883: {
1884: PetscFunctionBegin;
1886: PetscCheck(field < dm->Nf, PetscObjectComm((PetscObject)dm), PETSC_ERR_ARG_OUTOFRANGE, "Cannot handle %" PetscInt_FMT " >= %" PetscInt_FMT " fields", field, dm->Nf);
1887: PetscCheck(dm->nearnullspaceConstructors, PetscObjectComm((PetscObject)dm), PETSC_ERR_ARG_WRONG, "Must call DMCreateDS() to setup nullspaces");
1888: dm->nearnullspaceConstructors[field] = nullsp;
1889: PetscFunctionReturn(PETSC_SUCCESS);
1890: }
1892: /*@C
1893: DMGetNearNullSpaceConstructor - Return the callback function which constructs the near-nullspace for a given field, defined with `DMAddField()`
1895: Not Collective; No Fortran Support
1897: Input Parameters:
1898: + dm - The `DM`
1899: - field - The field number for the nullspace
1901: Output Parameter:
1902: . nullsp - A callback to create the near-nullspace
1904: Calling sequence of `nullsp`:
1905: + dm - The present `DM`
1906: . origField - The field number given above, in the original `DM`
1907: . field - The field number in dm
1908: - nullSpace - The nullspace for the given field
1910: Level: intermediate
1912: .seealso: [](ch_dmbase), `DM`, `DMAddField()`, `DMGetField()`, `DMSetNearNullSpaceConstructor()`, `DMSetNullSpaceConstructor()`, `DMGetNullSpaceConstructor()`, `DMCreateSubDM()`,
1913: `MatNullSpace`, `DMCreateSuperDM()`
1914: @*/
1915: PetscErrorCode DMGetNearNullSpaceConstructor(DM dm, PetscInt field, PetscErrorCode (**nullsp)(DM dm, PetscInt origField, PetscInt field, MatNullSpace *nullSpace))
1916: {
1917: PetscFunctionBegin;
1919: PetscAssertPointer(nullsp, 3);
1920: PetscCheck(field < dm->Nf, PetscObjectComm((PetscObject)dm), PETSC_ERR_ARG_OUTOFRANGE, "Cannot handle %" PetscInt_FMT " >= %" PetscInt_FMT " fields", field, dm->Nf);
1921: PetscCheck(dm->nearnullspaceConstructors, PetscObjectComm((PetscObject)dm), PETSC_ERR_ARG_WRONG, "Must call DMCreateDS() to setup nullspaces");
1922: *nullsp = dm->nearnullspaceConstructors[field];
1923: PetscFunctionReturn(PETSC_SUCCESS);
1924: }
1926: /*@C
1927: DMCreateFieldIS - Creates a set of `IS` objects with the global indices of dofs for each field defined with `DMAddField()`
1929: Not Collective; No Fortran Support
1931: Input Parameter:
1932: . dm - the `DM` object
1934: Output Parameters:
1935: + numFields - The number of fields (or `NULL` if not requested)
1936: . fieldNames - The name of each field (or `NULL` if not requested)
1937: - fields - The global indices for each field (or `NULL` if not requested)
1939: Level: intermediate
1941: Note:
1942: The user is responsible for freeing all requested arrays. In particular, every entry of `fieldNames` should be freed with
1943: `PetscFree()`, every entry of `fields` should be destroyed with `ISDestroy()`, and both arrays should be freed with
1944: `PetscFree()`.
1946: Developer Note:
1947: It is not clear why both this function and `DMCreateFieldDecomposition()` exist. Having two seems redundant and confusing. This function should
1948: likely be removed.
1950: .seealso: [](ch_dmbase), `DM`, `DMAddField()`, `DMGetField()`, `DMDestroy()`, `DMView()`, `DMCreateInterpolation()`, `DMCreateColoring()`, `DMCreateMatrix()`,
1951: `DMCreateFieldDecomposition()`
1952: @*/
1953: PetscErrorCode DMCreateFieldIS(DM dm, PetscInt *numFields, char ***fieldNames, IS *fields[])
1954: {
1955: PetscSection section, sectionGlobal;
1957: PetscFunctionBegin;
1959: if (numFields) {
1960: PetscAssertPointer(numFields, 2);
1961: *numFields = 0;
1962: }
1963: if (fieldNames) {
1964: PetscAssertPointer(fieldNames, 3);
1965: *fieldNames = NULL;
1966: }
1967: if (fields) {
1968: PetscAssertPointer(fields, 4);
1969: *fields = NULL;
1970: }
1971: PetscCall(DMGetLocalSection(dm, §ion));
1972: if (section) {
1973: PetscInt *fieldSizes, *fieldNc, **fieldIndices;
1974: PetscInt nF, f, pStart, pEnd, p;
1976: PetscCall(DMGetGlobalSection(dm, §ionGlobal));
1977: PetscCall(PetscSectionGetNumFields(section, &nF));
1978: PetscCall(PetscMalloc3(nF, &fieldSizes, nF, &fieldNc, nF, &fieldIndices));
1979: PetscCall(PetscSectionGetChart(sectionGlobal, &pStart, &pEnd));
1980: for (f = 0; f < nF; ++f) {
1981: fieldSizes[f] = 0;
1982: PetscCall(PetscSectionGetFieldComponents(section, f, &fieldNc[f]));
1983: }
1984: for (p = pStart; p < pEnd; ++p) {
1985: PetscInt gdof;
1987: PetscCall(PetscSectionGetDof(sectionGlobal, p, &gdof));
1988: if (gdof > 0) {
1989: for (f = 0; f < nF; ++f) {
1990: PetscInt fdof, fcdof, fpdof;
1992: PetscCall(PetscSectionGetFieldDof(section, p, f, &fdof));
1993: PetscCall(PetscSectionGetFieldConstraintDof(section, p, f, &fcdof));
1994: fpdof = fdof - fcdof;
1995: if (fpdof && fpdof != fieldNc[f]) {
1996: /* Layout does not admit a pointwise block size */
1997: fieldNc[f] = 1;
1998: }
1999: fieldSizes[f] += fpdof;
2000: }
2001: }
2002: }
2003: for (f = 0; f < nF; ++f) {
2004: PetscCall(PetscMalloc1(fieldSizes[f], &fieldIndices[f]));
2005: fieldSizes[f] = 0;
2006: }
2007: for (p = pStart; p < pEnd; ++p) {
2008: PetscInt gdof, goff;
2010: PetscCall(PetscSectionGetDof(sectionGlobal, p, &gdof));
2011: if (gdof > 0) {
2012: PetscCall(PetscSectionGetOffset(sectionGlobal, p, &goff));
2013: for (f = 0; f < nF; ++f) {
2014: PetscInt fdof, fcdof, fc;
2016: PetscCall(PetscSectionGetFieldDof(section, p, f, &fdof));
2017: PetscCall(PetscSectionGetFieldConstraintDof(section, p, f, &fcdof));
2018: for (fc = 0; fc < fdof - fcdof; ++fc, ++fieldSizes[f]) fieldIndices[f][fieldSizes[f]] = goff++;
2019: }
2020: }
2021: }
2022: if (numFields) *numFields = nF;
2023: if (fieldNames) {
2024: PetscCall(PetscMalloc1(nF, fieldNames));
2025: for (f = 0; f < nF; ++f) {
2026: const char *fieldName;
2028: PetscCall(PetscSectionGetFieldName(section, f, &fieldName));
2029: PetscCall(PetscStrallocpy(fieldName, &(*fieldNames)[f]));
2030: }
2031: }
2032: if (fields) {
2033: PetscCall(PetscMalloc1(nF, fields));
2034: for (f = 0; f < nF; ++f) {
2035: PetscInt bs, in[2], out[2];
2037: PetscCall(ISCreateGeneral(PetscObjectComm((PetscObject)dm), fieldSizes[f], fieldIndices[f], PETSC_OWN_POINTER, &(*fields)[f]));
2038: in[0] = -fieldNc[f];
2039: in[1] = fieldNc[f];
2040: PetscCallMPI(MPIU_Allreduce(in, out, 2, MPIU_INT, MPI_MAX, PetscObjectComm((PetscObject)dm)));
2041: bs = (-out[0] == out[1]) ? out[1] : 1;
2042: PetscCall(ISSetBlockSize((*fields)[f], bs));
2043: }
2044: }
2045: PetscCall(PetscFree3(fieldSizes, fieldNc, fieldIndices));
2046: } else PetscTryTypeMethod(dm, createfieldis, numFields, fieldNames, fields);
2047: PetscFunctionReturn(PETSC_SUCCESS);
2048: }
2050: /*@C
2051: DMCreateFieldDecomposition - Returns a list of `IS` objects defining a decomposition of a problem into subproblems
2052: corresponding to different fields.
2054: Not Collective; No Fortran Support
2056: Input Parameter:
2057: . dm - the `DM` object
2059: Output Parameters:
2060: + len - The number of fields (or `NULL` if not requested)
2061: . namelist - The name for each field (or `NULL` if not requested)
2062: . islist - The global indices for each field (or `NULL` if not requested)
2063: - dmlist - The `DM`s for each field subproblem (or `NULL`, if not requested; if `NULL` is returned, no `DM`s are defined)
2065: Level: intermediate
2067: Notes:
2068: Each `IS` contains the global indices of the dofs of the corresponding field, defined by
2069: `DMAddField()`. The optional list of `DM`s define the `DM` for each subproblem.
2071: The same as `DMCreateFieldIS()` but also returns a `DM` for each field.
2073: The user is responsible for freeing all requested arrays. In particular, every entry of `namelist` should be freed with
2074: `PetscFree()`, every entry of `islist` should be destroyed with `ISDestroy()`, every entry of `dmlist` should be destroyed with `DMDestroy()`,
2075: and all of the arrays should be freed with `PetscFree()`.
2077: Fortran Notes:
2078: Use the declarations
2079: .vb
2080: character(80), pointer :: namelist(:)
2081: IS, pointer :: islist(:)
2082: DM, pointer :: dmlist(:)
2083: .ve
2085: `namelist` must be provided, `islist` may be `PETSC_NULL_IS_POINTER` and `dmlist` may be `PETSC_NULL_DM_POINTER`
2087: Use `DMDestroyFieldDecomposition()` to free the returned objects
2089: Developer Notes:
2090: It is not clear why this function and `DMCreateFieldIS()` exist. Having two seems redundant and confusing.
2092: Unlike `DMRefine()`, `DMCoarsen()`, and `DMCreateDomainDecomposition()` this provides no mechanism to provide hooks that are called after the
2093: decomposition is computed.
2095: .seealso: [](ch_dmbase), `DM`, `DMAddField()`, `DMCreateFieldIS()`, `DMCreateSubDM()`, `DMCreateDomainDecomposition()`, `DMDestroy()`, `DMView()`, `DMCreateInterpolation()`, `DMCreateColoring()`, `DMCreateMatrix()`, `DMCreateMassMatrix()`, `DMRefine()`, `DMCoarsen()`
2096: @*/
2097: PetscErrorCode DMCreateFieldDecomposition(DM dm, PetscInt *len, char ***namelist, IS *islist[], DM *dmlist[])
2098: {
2099: PetscFunctionBegin;
2101: if (len) {
2102: PetscAssertPointer(len, 2);
2103: *len = 0;
2104: }
2105: if (namelist) {
2106: PetscAssertPointer(namelist, 3);
2107: *namelist = NULL;
2108: }
2109: if (islist) {
2110: PetscAssertPointer(islist, 4);
2111: *islist = NULL;
2112: }
2113: if (dmlist) {
2114: PetscAssertPointer(dmlist, 5);
2115: *dmlist = NULL;
2116: }
2117: /*
2118: Is it a good idea to apply the following check across all impls?
2119: Perhaps some impls can have a well-defined decomposition before DMSetUp?
2120: This, however, follows the general principle that accessors are not well-behaved until the object is set up.
2121: */
2122: PetscCheck(dm->setupcalled, PetscObjectComm((PetscObject)dm), PETSC_ERR_ARG_WRONGSTATE, "Decomposition defined only after DMSetUp");
2123: if (!dm->ops->createfielddecomposition) {
2124: PetscSection section;
2125: PetscInt numFields;
2127: PetscCall(DMGetLocalSection(dm, §ion));
2128: if (section) PetscCall(PetscSectionGetNumFields(section, &numFields));
2129: if (section && numFields && dm->ops->createsubdm) {
2130: if (len) *len = numFields;
2131: if (namelist) PetscCall(PetscMalloc1(numFields, namelist));
2132: if (islist) PetscCall(PetscMalloc1(numFields, islist));
2133: if (dmlist) PetscCall(PetscMalloc1(numFields, dmlist));
2134: for (PetscInt f = 0; f < numFields; ++f) {
2135: const char *fieldName;
2137: PetscCall(DMCreateSubDM(dm, 1, &f, islist ? &(*islist)[f] : NULL, dmlist ? &(*dmlist)[f] : NULL));
2138: if (namelist) {
2139: PetscCall(PetscSectionGetFieldName(section, f, &fieldName));
2140: PetscCall(PetscStrallocpy(fieldName, &(*namelist)[f]));
2141: }
2142: }
2143: } else {
2144: PetscCall(DMCreateFieldIS(dm, len, namelist, islist));
2145: /* By default there are no DMs associated with subproblems. */
2146: if (dmlist) *dmlist = NULL;
2147: }
2148: } else PetscUseTypeMethod(dm, createfielddecomposition, len, namelist, islist, dmlist);
2149: PetscFunctionReturn(PETSC_SUCCESS);
2150: }
2152: /*@
2153: DMCreateSubDM - Returns an `IS` and `DM` encapsulating a subproblem defined by the fields passed in.
2154: The fields are defined by `DMCreateFieldIS()`.
2156: Not collective
2158: Input Parameters:
2159: + dm - The `DM` object
2160: . numFields - The number of fields to select
2161: - fields - The field numbers of the selected fields
2163: Output Parameters:
2164: + is - The global indices for all the degrees of freedom in the new sub `DM`, use `NULL` if not needed
2165: - subdm - The `DM` for the subproblem, use `NULL` if not needed
2167: Level: intermediate
2169: Note:
2170: You need to call `DMPlexSetMigrationSF()` on the original `DM` if you want the Global-To-Natural map to be automatically constructed
2172: .seealso: [](ch_dmbase), `DM`, `DMCreateFieldIS()`, `DMCreateFieldDecomposition()`, `DMAddField()`, `DMCreateSuperDM()`, `IS`, `VecISCopy()`, `DMPlexSetMigrationSF()`, `DMDestroy()`, `DMView()`, `DMCreateInterpolation()`, `DMCreateColoring()`, `DMCreateMatrix()`, `DMCreateMassMatrix()`
2173: @*/
2174: PetscErrorCode DMCreateSubDM(DM dm, PetscInt numFields, const PetscInt fields[], IS *is, DM *subdm)
2175: {
2176: PetscFunctionBegin;
2178: PetscAssertPointer(fields, 3);
2179: if (is) PetscAssertPointer(is, 4);
2180: if (subdm) PetscAssertPointer(subdm, 5);
2181: PetscUseTypeMethod(dm, createsubdm, numFields, fields, is, subdm);
2182: PetscFunctionReturn(PETSC_SUCCESS);
2183: }
2185: /*@C
2186: DMCreateSuperDM - Returns an arrays of `IS` and a single `DM` encapsulating a superproblem defined by multiple `DM`s passed in.
2188: Not collective
2190: Input Parameters:
2191: + dms - The `DM` objects
2192: - n - The number of `DM`s
2194: Output Parameters:
2195: + is - The global indices for each of subproblem within the super `DM`, or `NULL`, its length is `n`
2196: - superdm - The `DM` for the superproblem
2198: Level: intermediate
2200: Note:
2201: You need to call `DMPlexSetMigrationSF()` on the original `DM` if you want the Global-To-Natural map to be automatically constructed
2203: .seealso: [](ch_dmbase), `DM`, `DMCreateSubDM()`, `DMPlexSetMigrationSF()`, `DMDestroy()`, `DMView()`, `DMCreateInterpolation()`, `DMCreateColoring()`, `DMCreateMatrix()`, `DMCreateMassMatrix()`, `DMCreateFieldIS()`, `DMCreateDomainDecomposition()`
2204: @*/
2205: PetscErrorCode DMCreateSuperDM(DM dms[], PetscInt n, IS *is[], DM *superdm)
2206: {
2207: PetscFunctionBegin;
2208: PetscAssertPointer(dms, 1);
2210: if (is) PetscAssertPointer(is, 3);
2211: PetscAssertPointer(superdm, 4);
2212: PetscCheck(n >= 0, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Number of DMs must be nonnegative: %" PetscInt_FMT, n);
2213: if (n) {
2214: DM dm = dms[0];
2215: PetscCheck(dm->ops->createsuperdm, PetscObjectComm((PetscObject)dm), PETSC_ERR_SUP, "No method createsuperdm for DM of type %s", ((PetscObject)dm)->type_name);
2216: PetscCall((*dm->ops->createsuperdm)(dms, n, is, superdm));
2217: }
2218: PetscFunctionReturn(PETSC_SUCCESS);
2219: }
2221: /*@C
2222: DMCreateDomainDecomposition - Returns lists of `IS` objects defining a decomposition of a
2223: problem into subproblems corresponding to restrictions to pairs of nested subdomains.
2225: Not Collective
2227: Input Parameter:
2228: . dm - the `DM` object
2230: Output Parameters:
2231: + n - The number of subproblems in the domain decomposition (or `NULL` if not requested), also the length of the four arrays below
2232: . namelist - The name for each subdomain (or `NULL` if not requested)
2233: . innerislist - The global indices for each inner subdomain (or `NULL`, if not requested)
2234: . outerislist - The global indices for each outer subdomain (or `NULL`, if not requested)
2235: - dmlist - The `DM`s for each subdomain subproblem (or `NULL`, if not requested; if `NULL` is returned, no `DM`s are defined)
2237: Level: intermediate
2239: Notes:
2240: Each `IS` contains the global indices of the dofs of the corresponding subdomains with in the
2241: dofs of the original `DM`. The inner subdomains conceptually define a nonoverlapping
2242: covering, while outer subdomains can overlap.
2244: The optional list of `DM`s define a `DM` for each subproblem.
2246: The user is responsible for freeing all requested arrays. In particular, every entry of `namelist` should be freed with
2247: `PetscFree()`, every entry of `innerislist` and `outerislist` should be destroyed with `ISDestroy()`, every entry of `dmlist` should be destroyed with `DMDestroy()`,
2248: and all of the arrays should be freed with `PetscFree()`.
2250: Developer Notes:
2251: The `dmlist` is for the inner subdomains or the outer subdomains or all subdomains?
2253: The names are inconsistent, the hooks use `DMSubDomainHook` which is nothing like `DMCreateDomainDecomposition()` while `DMRefineHook` is used for `DMRefine()`.
2255: .seealso: [](ch_dmbase), `DM`, `DMCreateFieldDecomposition()`, `DMDestroy()`, `DMCreateDomainDecompositionScatters()`, `DMView()`, `DMCreateInterpolation()`,
2256: `DMSubDomainHookAdd()`, `DMSubDomainHookRemove()`, `DMCreateColoring()`, `DMCreateMatrix()`, `DMCreateMassMatrix()`, `DMRefine()`, `DMCoarsen()`
2257: @*/
2258: PetscErrorCode DMCreateDomainDecomposition(DM dm, PetscInt *n, char **namelist[], IS *innerislist[], IS *outerislist[], DM *dmlist[])
2259: {
2260: DMSubDomainHookLink link;
2261: PetscInt l;
2263: PetscFunctionBegin;
2265: if (n) {
2266: PetscAssertPointer(n, 2);
2267: *n = 0;
2268: }
2269: if (namelist) {
2270: PetscAssertPointer(namelist, 3);
2271: *namelist = NULL;
2272: }
2273: if (innerislist) {
2274: PetscAssertPointer(innerislist, 4);
2275: *innerislist = NULL;
2276: }
2277: if (outerislist) {
2278: PetscAssertPointer(outerislist, 5);
2279: *outerislist = NULL;
2280: }
2281: if (dmlist) {
2282: PetscAssertPointer(dmlist, 6);
2283: *dmlist = NULL;
2284: }
2285: /*
2286: Is it a good idea to apply the following check across all impls?
2287: Perhaps some impls can have a well-defined decomposition before DMSetUp?
2288: This, however, follows the general principle that accessors are not well-behaved until the object is set up.
2289: */
2290: PetscCheck(dm->setupcalled, PetscObjectComm((PetscObject)dm), PETSC_ERR_ARG_WRONGSTATE, "Decomposition defined only after DMSetUp");
2291: if (dm->ops->createdomaindecomposition) {
2292: PetscUseTypeMethod(dm, createdomaindecomposition, &l, namelist, innerislist, outerislist, dmlist);
2293: /* copy subdomain hooks and context over to the subdomain DMs */
2294: if (dmlist && *dmlist) {
2295: for (PetscInt i = 0; i < l; i++) {
2296: for (link = dm->subdomainhook; link; link = link->next) {
2297: if (link->ddhook) PetscCall((*link->ddhook)(dm, (*dmlist)[i], link->ctx));
2298: }
2299: if (dm->ctx) (*dmlist)[i]->ctx = dm->ctx;
2300: }
2301: }
2302: if (n) *n = l;
2303: }
2304: PetscFunctionReturn(PETSC_SUCCESS);
2305: }
2307: /*@C
2308: DMCreateDomainDecompositionScatters - Returns scatters to the subdomain vectors from the global vector for subdomains created with
2309: `DMCreateDomainDecomposition()`
2311: Not Collective
2313: Input Parameters:
2314: + dm - the `DM` object
2315: . n - the number of subdomains
2316: - subdms - the local subdomains
2318: Output Parameters:
2319: + iscat - scatter from global vector to nonoverlapping global vector entries on subdomain
2320: . oscat - scatter from global vector to overlapping global vector entries on subdomain
2321: - gscat - scatter from global vector to local vector on subdomain (fills in ghosts)
2323: Level: developer
2325: Note:
2326: This is an alternative to the `iis` and `ois` arguments in `DMCreateDomainDecomposition()` that allow for the solution
2327: of general nonlinear problems with overlapping subdomain methods. While merely having index sets that enable subsets
2328: of the residual equations to be created is fine for linear problems, nonlinear problems require local assembly of
2329: solution and residual data.
2331: Developer Note:
2332: Can the `subdms` input be anything or are they exactly the `DM` obtained from
2333: `DMCreateDomainDecomposition()`?
2335: .seealso: [](ch_dmbase), `DM`, `DMCreateDomainDecomposition()`, `DMDestroy()`, `DMView()`, `DMCreateInterpolation()`, `DMCreateColoring()`, `DMCreateMatrix()`, `DMCreateMassMatrix()`, `DMCreateFieldIS()`
2336: @*/
2337: PetscErrorCode DMCreateDomainDecompositionScatters(DM dm, PetscInt n, DM subdms[], VecScatter *iscat[], VecScatter *oscat[], VecScatter *gscat[])
2338: {
2339: PetscFunctionBegin;
2341: PetscAssertPointer(subdms, 3);
2342: PetscUseTypeMethod(dm, createddscatters, n, subdms, iscat, oscat, gscat);
2343: PetscFunctionReturn(PETSC_SUCCESS);
2344: }
2346: /*@
2347: DMRefine - Refines a `DM` object using a standard nonadaptive refinement of the underlying mesh
2349: Collective
2351: Input Parameters:
2352: + dm - the `DM` object
2353: - comm - the communicator to contain the new `DM` object (or `MPI_COMM_NULL`)
2355: Output Parameter:
2356: . dmf - the refined `DM`, or `NULL`
2358: Options Database Key:
2359: . -dm_plex_cell_refiner strategy - chooses the refinement strategy, e.g. regular, tohex
2361: Level: developer
2363: Note:
2364: If no refinement was done, the return value is `NULL`
2366: .seealso: [](ch_dmbase), `DM`, `DMCoarsen()`, `DMDestroy()`, `DMView()`, `DMCreateGlobalVector()`, `DMCreateInterpolation()`, `DMCreateDomainDecomposition()`,
2367: `DMRefineHookAdd()`, `DMRefineHookRemove()`
2368: @*/
2369: PetscErrorCode DMRefine(DM dm, MPI_Comm comm, DM *dmf)
2370: {
2371: DMRefineHookLink link;
2373: PetscFunctionBegin;
2375: PetscCall(PetscLogEventBegin(DM_Refine, dm, 0, 0, 0));
2376: PetscUseTypeMethod(dm, refine, comm, dmf);
2377: if (*dmf) {
2378: (*dmf)->ops->creatematrix = dm->ops->creatematrix;
2380: PetscCall(PetscObjectCopyFortranFunctionPointers((PetscObject)dm, (PetscObject)*dmf));
2382: (*dmf)->ctx = dm->ctx;
2383: (*dmf)->leveldown = dm->leveldown;
2384: (*dmf)->levelup = dm->levelup + 1;
2386: PetscCall(DMSetMatType(*dmf, dm->mattype));
2387: for (link = dm->refinehook; link; link = link->next) {
2388: if (link->refinehook) PetscCall((*link->refinehook)(dm, *dmf, link->ctx));
2389: }
2390: }
2391: PetscCall(PetscLogEventEnd(DM_Refine, dm, 0, 0, 0));
2392: PetscFunctionReturn(PETSC_SUCCESS);
2393: }
2395: /*@C
2396: DMRefineHookAdd - adds a callback to be run when interpolating a nonlinear problem to a finer grid
2398: Logically Collective; No Fortran Support
2400: Input Parameters:
2401: + coarse - `DM` on which to run a hook when interpolating to a finer level
2402: . refinehook - function to run when setting up the finer level
2403: . interphook - function to run to update data on finer levels (once per `SNESSolve()`)
2404: - ctx - [optional] context for provide data for the hooks (may be `NULL`)
2406: Calling sequence of `refinehook`:
2407: + coarse - coarse level `DM`
2408: . fine - fine level `DM` to interpolate problem to
2409: - ctx - optional function context
2411: Calling sequence of `interphook`:
2412: + coarse - coarse level `DM`
2413: . interp - matrix interpolating a coarse-level solution to the finer grid
2414: . fine - fine level `DM` to update
2415: - ctx - optional function context
2417: Level: advanced
2419: Notes:
2420: This function is only needed if auxiliary data that is attached to the `DM`s via, for example, `PetscObjectCompose()`, needs to be
2421: passed to fine grids while grid sequencing.
2423: The actual interpolation is done when `DMInterpolate()` is called.
2425: If this function is called multiple times, the hooks will be run in the order they are added.
2427: .seealso: [](ch_dmbase), `DM`, `DMCoarsenHookAdd()`, `DMInterpolate()`, `SNESFASGetInterpolation()`, `SNESFASGetInjection()`, `PetscObjectCompose()`, `PetscContainerCreate()`
2428: @*/
2429: PetscErrorCode DMRefineHookAdd(DM coarse, PetscErrorCode (*refinehook)(DM coarse, DM fine, PetscCtx ctx), PetscErrorCode (*interphook)(DM coarse, Mat interp, DM fine, PetscCtx ctx), PetscCtx ctx)
2430: {
2431: DMRefineHookLink link, *p;
2433: PetscFunctionBegin;
2435: for (p = &coarse->refinehook; *p; p = &(*p)->next) { /* Scan to the end of the current list of hooks */
2436: if ((*p)->refinehook == refinehook && (*p)->interphook == interphook && (*p)->ctx == ctx) PetscFunctionReturn(PETSC_SUCCESS);
2437: }
2438: PetscCall(PetscNew(&link));
2439: link->refinehook = refinehook;
2440: link->interphook = interphook;
2441: link->ctx = ctx;
2442: link->next = NULL;
2443: *p = link;
2444: PetscFunctionReturn(PETSC_SUCCESS);
2445: }
2447: /*@C
2448: DMRefineHookRemove - remove a callback from the list of hooks, that have been set with `DMRefineHookAdd()`, to be run when interpolating
2449: a nonlinear problem to a finer grid
2451: Logically Collective; No Fortran Support
2453: Input Parameters:
2454: + coarse - the `DM` on which to run a hook when restricting to a coarser level
2455: . refinehook - function to run when setting up a finer level
2456: . interphook - function to run to update data on finer levels
2457: - ctx - [optional] application context for provide data for the hooks (may be `NULL`)
2459: Calling sequence of refinehook:
2460: + coarse - the coarse `DM`
2461: . fine - the fine `DM`
2462: - ctx - context for the function
2464: Calling sequence of interphook:
2465: + coarse - the coarse `DM`
2466: . interp - the interpolation `Mat` from coarse to fine
2467: . fine - the fine `DM`
2468: - ctx - context for the function
2470: Level: advanced
2472: Note:
2473: This function does nothing if the hook is not in the list.
2475: .seealso: [](ch_dmbase), `DM`, `DMRefineHookAdd()`, `DMCoarsenHookRemove()`, `DMInterpolate()`, `SNESFASGetInterpolation()`, `SNESFASGetInjection()`, `PetscObjectCompose()`, `PetscContainerCreate()`
2476: @*/
2477: PetscErrorCode DMRefineHookRemove(DM coarse, PetscErrorCode (*refinehook)(DM coarse, DM fine, PetscCtx ctx), PetscErrorCode (*interphook)(DM coarse, Mat interp, DM fine, PetscCtx ctx), PetscCtx ctx)
2478: {
2479: DMRefineHookLink link, *p;
2481: PetscFunctionBegin;
2483: for (p = &coarse->refinehook; *p; p = &(*p)->next) { /* Search the list of current hooks */
2484: if ((*p)->refinehook == refinehook && (*p)->interphook == interphook && (*p)->ctx == ctx) {
2485: link = *p;
2486: *p = link->next;
2487: PetscCall(PetscFree(link));
2488: break;
2489: }
2490: }
2491: PetscFunctionReturn(PETSC_SUCCESS);
2492: }
2494: /*@
2495: DMInterpolate - interpolates user-defined problem data attached to a `DM` to a finer `DM` by running hooks registered by `DMRefineHookAdd()`
2497: Collective if any hooks are
2499: Input Parameters:
2500: + coarse - coarser `DM` to use as a base
2501: . interp - interpolation matrix, apply using `MatInterpolate()`
2502: - fine - finer `DM` to update
2504: Level: developer
2506: Developer Note:
2507: This routine is called `DMInterpolate()` while the hook is called `DMRefineHookAdd()`. It would be better to have an
2508: an API with consistent terminology.
2510: .seealso: [](ch_dmbase), `DM`, `DMRefineHookAdd()`, `MatInterpolate()`
2511: @*/
2512: PetscErrorCode DMInterpolate(DM coarse, Mat interp, DM fine)
2513: {
2514: DMRefineHookLink link;
2516: PetscFunctionBegin;
2517: for (link = fine->refinehook; link; link = link->next) {
2518: if (link->interphook) PetscCall((*link->interphook)(coarse, interp, fine, link->ctx));
2519: }
2520: PetscFunctionReturn(PETSC_SUCCESS);
2521: }
2523: /*@
2524: DMInterpolateSolution - Interpolates a solution from a coarse mesh to a fine mesh.
2526: Collective
2528: Input Parameters:
2529: + coarse - coarse `DM`
2530: . fine - fine `DM`
2531: . interp - (optional) the matrix computed by `DMCreateInterpolation()`. Implementations may not need this, but if it
2532: is available it can avoid some recomputation. If it is provided, `MatInterpolate()` will be used if
2533: the coarse `DM` does not have a specialized implementation.
2534: - coarseSol - solution on the coarse mesh
2536: Output Parameter:
2537: . fineSol - the interpolation of coarseSol to the fine mesh
2539: Level: developer
2541: Note:
2542: This function exists because the interpolation of a solution vector between meshes is not always a linear
2543: map. For example, if a boundary value problem has an inhomogeneous Dirichlet boundary condition that is compressed
2544: out of the solution vector. Or if interpolation is inherently a nonlinear operation, such as a method using
2545: slope-limiting reconstruction.
2547: Developer Note:
2548: This doesn't just interpolate "solutions" so its API name is questionable.
2550: .seealso: [](ch_dmbase), `DM`, `DMInterpolate()`, `DMCreateInterpolation()`
2551: @*/
2552: PetscErrorCode DMInterpolateSolution(DM coarse, DM fine, Mat interp, Vec coarseSol, Vec fineSol)
2553: {
2554: PetscErrorCode (*interpsol)(DM, DM, Mat, Vec, Vec) = NULL;
2556: PetscFunctionBegin;
2562: PetscCall(PetscObjectQueryFunction((PetscObject)coarse, "DMInterpolateSolution_C", &interpsol));
2563: if (interpsol) {
2564: PetscCall((*interpsol)(coarse, fine, interp, coarseSol, fineSol));
2565: } else if (interp) {
2566: PetscCall(MatInterpolate(interp, coarseSol, fineSol));
2567: } else SETERRQ(PetscObjectComm((PetscObject)coarse), PETSC_ERR_SUP, "DM %s does not implement DMInterpolateSolution()", ((PetscObject)coarse)->type_name);
2568: PetscFunctionReturn(PETSC_SUCCESS);
2569: }
2571: /*@
2572: DMGetRefineLevel - Gets the number of refinements that have generated this `DM` from some initial `DM`.
2574: Not Collective
2576: Input Parameter:
2577: . dm - the `DM` object
2579: Output Parameter:
2580: . level - number of refinements
2582: Level: developer
2584: Note:
2585: This can be used, by example, to set the number of coarser levels associated with this `DM` for a multigrid solver.
2587: .seealso: [](ch_dmbase), `DM`, `DMRefine()`, `DMCoarsen()`, `DMGetCoarsenLevel()`, `DMDestroy()`, `DMView()`, `DMCreateGlobalVector()`, `DMCreateInterpolation()`
2588: @*/
2589: PetscErrorCode DMGetRefineLevel(DM dm, PetscInt *level)
2590: {
2591: PetscFunctionBegin;
2593: *level = dm->levelup;
2594: PetscFunctionReturn(PETSC_SUCCESS);
2595: }
2597: /*@
2598: DMSetRefineLevel - Sets the number of refinements that have generated this `DM`.
2600: Not Collective
2602: Input Parameters:
2603: + dm - the `DM` object
2604: - level - number of refinements
2606: Level: advanced
2608: Notes:
2609: This value is used by `PCMG` to determine how many multigrid levels to use
2611: The values are usually set automatically by the process that is causing the refinements of an initial `DM` by calling this routine.
2613: .seealso: [](ch_dmbase), `DM`, `DMGetRefineLevel()`, `DMCoarsen()`, `DMGetCoarsenLevel()`, `DMDestroy()`, `DMView()`, `DMCreateGlobalVector()`, `DMCreateInterpolation()`
2614: @*/
2615: PetscErrorCode DMSetRefineLevel(DM dm, PetscInt level)
2616: {
2617: PetscFunctionBegin;
2619: dm->levelup = level;
2620: PetscFunctionReturn(PETSC_SUCCESS);
2621: }
2623: /*@
2624: DMExtrude - Extrude a `DM` object from a surface
2626: Collective
2628: Input Parameters:
2629: + dm - the `DM` object
2630: - layers - the number of extruded cell layers
2632: Output Parameter:
2633: . dme - the extruded `DM`, or `NULL`
2635: Level: developer
2637: Note:
2638: If no extrusion was done, the return value is `NULL`
2640: .seealso: [](ch_dmbase), `DM`, `DMRefine()`, `DMCoarsen()`, `DMDestroy()`, `DMView()`, `DMCreateGlobalVector()`
2641: @*/
2642: PetscErrorCode DMExtrude(DM dm, PetscInt layers, DM *dme)
2643: {
2644: PetscFunctionBegin;
2646: PetscUseTypeMethod(dm, extrude, layers, dme);
2647: if (*dme) {
2648: (*dme)->ops->creatematrix = dm->ops->creatematrix;
2649: PetscCall(PetscObjectCopyFortranFunctionPointers((PetscObject)dm, (PetscObject)*dme));
2650: (*dme)->ctx = dm->ctx;
2651: PetscCall(DMSetMatType(*dme, dm->mattype));
2652: }
2653: PetscFunctionReturn(PETSC_SUCCESS);
2654: }
2656: PetscErrorCode DMGetBasisTransformDM_Internal(DM dm, DM *tdm)
2657: {
2658: PetscFunctionBegin;
2660: PetscAssertPointer(tdm, 2);
2661: *tdm = dm->transformDM;
2662: PetscFunctionReturn(PETSC_SUCCESS);
2663: }
2665: PetscErrorCode DMGetBasisTransformVec_Internal(DM dm, Vec *tv)
2666: {
2667: PetscFunctionBegin;
2669: PetscAssertPointer(tv, 2);
2670: *tv = dm->transform;
2671: PetscFunctionReturn(PETSC_SUCCESS);
2672: }
2674: /*@
2675: DMHasBasisTransform - Whether the `DM` employs a basis transformation from functions in global vectors to functions in local vectors
2677: Input Parameter:
2678: . dm - The `DM`
2680: Output Parameter:
2681: . flg - `PETSC_TRUE` if a basis transformation should be done
2683: Level: developer
2685: .seealso: [](ch_dmbase), `DM`, `DMPlexGlobalToLocalBasis()`, `DMPlexLocalToGlobalBasis()`, `DMPlexCreateBasisRotation()`
2686: @*/
2687: PetscErrorCode DMHasBasisTransform(DM dm, PetscBool *flg)
2688: {
2689: Vec tv;
2691: PetscFunctionBegin;
2693: PetscAssertPointer(flg, 2);
2694: PetscCall(DMGetBasisTransformVec_Internal(dm, &tv));
2695: *flg = tv ? PETSC_TRUE : PETSC_FALSE;
2696: PetscFunctionReturn(PETSC_SUCCESS);
2697: }
2699: PetscErrorCode DMConstructBasisTransform_Internal(DM dm)
2700: {
2701: PetscSection s, ts;
2702: PetscScalar *ta;
2703: PetscInt cdim, pStart, pEnd, p, Nf, f, Nc, dof;
2705: PetscFunctionBegin;
2706: PetscCall(DMGetCoordinateDim(dm, &cdim));
2707: PetscCall(DMGetLocalSection(dm, &s));
2708: PetscCall(PetscSectionGetChart(s, &pStart, &pEnd));
2709: PetscCall(PetscSectionGetNumFields(s, &Nf));
2710: PetscCall(DMClone(dm, &dm->transformDM));
2711: PetscCall(DMGetLocalSection(dm->transformDM, &ts));
2712: PetscCall(PetscSectionSetNumFields(ts, Nf));
2713: PetscCall(PetscSectionSetChart(ts, pStart, pEnd));
2714: for (f = 0; f < Nf; ++f) {
2715: PetscCall(PetscSectionGetFieldComponents(s, f, &Nc));
2716: /* We could start to label fields by their transformation properties */
2717: if (Nc != cdim) continue;
2718: for (p = pStart; p < pEnd; ++p) {
2719: PetscCall(PetscSectionGetFieldDof(s, p, f, &dof));
2720: if (!dof) continue;
2721: PetscCall(PetscSectionSetFieldDof(ts, p, f, PetscSqr(cdim)));
2722: PetscCall(PetscSectionAddDof(ts, p, PetscSqr(cdim)));
2723: }
2724: }
2725: PetscCall(PetscSectionSetUp(ts));
2726: PetscCall(DMCreateLocalVector(dm->transformDM, &dm->transform));
2727: PetscCall(VecGetArray(dm->transform, &ta));
2728: for (p = pStart; p < pEnd; ++p) {
2729: for (f = 0; f < Nf; ++f) {
2730: PetscCall(PetscSectionGetFieldDof(ts, p, f, &dof));
2731: if (dof) {
2732: PetscReal x[3] = {0.0, 0.0, 0.0};
2733: PetscScalar *tva;
2734: const PetscScalar *A;
2736: /* TODO Get quadrature point for this dual basis vector for coordinate */
2737: PetscCall((*dm->transformGetMatrix)(dm, x, PETSC_TRUE, &A, dm->transformCtx));
2738: PetscCall(DMPlexPointLocalFieldRef(dm->transformDM, p, f, ta, (void *)&tva));
2739: PetscCall(PetscArraycpy(tva, A, PetscSqr(cdim)));
2740: }
2741: }
2742: }
2743: PetscCall(VecRestoreArray(dm->transform, &ta));
2744: PetscFunctionReturn(PETSC_SUCCESS);
2745: }
2747: PetscErrorCode DMCopyTransform(DM dm, DM newdm)
2748: {
2749: PetscFunctionBegin;
2752: newdm->transformCtx = dm->transformCtx;
2753: newdm->transformSetUp = dm->transformSetUp;
2754: newdm->transformDestroy = NULL;
2755: newdm->transformGetMatrix = dm->transformGetMatrix;
2756: if (newdm->transformSetUp) PetscCall(DMConstructBasisTransform_Internal(newdm));
2757: PetscFunctionReturn(PETSC_SUCCESS);
2758: }
2760: /*@C
2761: DMGlobalToLocalHookAdd - adds a callback to be run when `DMGlobalToLocal()` is called
2763: Logically Collective
2765: Input Parameters:
2766: + dm - the `DM`
2767: . beginhook - function to run at the beginning of `DMGlobalToLocalBegin()`
2768: . endhook - function to run after `DMGlobalToLocalEnd()` has completed
2769: - ctx - [optional] context for provide data for the hooks (may be `NULL`)
2771: Calling sequence of `beginhook`:
2772: + dm - global `DM`
2773: . g - global vector
2774: . mode - mode
2775: . l - local vector
2776: - ctx - optional function context
2778: Calling sequence of `endhook`:
2779: + dm - global `DM`
2780: . g - global vector
2781: . mode - mode
2782: . l - local vector
2783: - ctx - optional function context
2785: Level: advanced
2787: Note:
2788: 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.
2790: .seealso: [](ch_dmbase), `DM`, `DMGlobalToLocal()`, `DMRefineHookAdd()`, `SNESFASGetInterpolation()`, `SNESFASGetInjection()`, `PetscObjectCompose()`, `PetscContainerCreate()`
2791: @*/
2792: 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)
2793: {
2794: DMGlobalToLocalHookLink link, *p;
2796: PetscFunctionBegin;
2798: for (p = &dm->gtolhook; *p; p = &(*p)->next) { } /* Scan to the end of the current list of hooks */
2799: PetscCall(PetscNew(&link));
2800: link->beginhook = beginhook;
2801: link->endhook = endhook;
2802: link->ctx = ctx;
2803: link->next = NULL;
2804: *p = link;
2805: PetscFunctionReturn(PETSC_SUCCESS);
2806: }
2808: static PetscErrorCode DMGlobalToLocalHook_Constraints(DM dm, Vec g, InsertMode mode, Vec l, PetscCtx ctx)
2809: {
2810: Mat cMat;
2811: Vec cVec, cBias;
2812: PetscSection section, cSec;
2813: PetscInt pStart, pEnd, p, dof;
2815: PetscFunctionBegin;
2816: (void)g;
2817: (void)ctx;
2819: PetscCall(DMGetDefaultConstraints(dm, &cSec, &cMat, &cBias));
2820: if (cMat && (mode == INSERT_VALUES || mode == INSERT_ALL_VALUES || mode == INSERT_BC_VALUES)) {
2821: PetscInt nRows;
2823: PetscCall(MatGetSize(cMat, &nRows, NULL));
2824: if (nRows <= 0) PetscFunctionReturn(PETSC_SUCCESS);
2825: PetscCall(DMGetLocalSection(dm, §ion));
2826: PetscCall(MatCreateVecs(cMat, NULL, &cVec));
2827: PetscCall(MatMult(cMat, l, cVec));
2828: if (cBias) PetscCall(VecAXPY(cVec, 1., cBias));
2829: PetscCall(PetscSectionGetChart(cSec, &pStart, &pEnd));
2830: for (p = pStart; p < pEnd; p++) {
2831: PetscCall(PetscSectionGetDof(cSec, p, &dof));
2832: if (dof) {
2833: PetscScalar *vals;
2834: PetscCall(VecGetValuesSection(cVec, cSec, p, &vals));
2835: PetscCall(VecSetValuesSection(l, section, p, vals, INSERT_ALL_VALUES));
2836: }
2837: }
2838: PetscCall(VecDestroy(&cVec));
2839: }
2840: PetscFunctionReturn(PETSC_SUCCESS);
2841: }
2843: /*@
2844: DMGlobalToLocal - update local vectors from global vector
2846: Neighbor-wise Collective
2848: Input Parameters:
2849: + dm - the `DM` object
2850: . g - the global vector
2851: . mode - `INSERT_VALUES` or `ADD_VALUES`
2852: - l - the local vector
2854: Level: beginner
2856: Notes:
2857: The communication involved in this update can be overlapped with computation by instead using
2858: `DMGlobalToLocalBegin()` and `DMGlobalToLocalEnd()`.
2860: `DMGlobalToLocalHookAdd()` may be used to provide additional operations that are performed during the update process.
2862: .seealso: [](ch_dmbase), `DM`, `DMGlobalToLocalHookAdd()`, `DMCoarsen()`, `DMDestroy()`, `DMView()`, `DMCreateGlobalVector()`, `DMCreateInterpolation()`,
2863: `DMLocalToGlobalBegin()`, `DMLocalToGlobal()`, `DMLocalToGlobalEnd()`,
2864: `DMGlobalToLocalBegin()`, `DMGlobalToLocalEnd()`
2865: @*/
2866: PetscErrorCode DMGlobalToLocal(DM dm, Vec g, InsertMode mode, Vec l)
2867: {
2868: PetscFunctionBegin;
2869: PetscCall(DMGlobalToLocalBegin(dm, g, mode, l));
2870: PetscCall(DMGlobalToLocalEnd(dm, g, mode, l));
2871: PetscFunctionReturn(PETSC_SUCCESS);
2872: }
2874: /*@
2875: DMGlobalToLocalBegin - Begins updating local vectors from global vector
2877: Neighbor-wise Collective
2879: Input Parameters:
2880: + dm - the `DM` object
2881: . g - the global vector
2882: . mode - `INSERT_VALUES` or `ADD_VALUES`
2883: - l - the local vector
2885: Level: intermediate
2887: Notes:
2888: The operation is completed with `DMGlobalToLocalEnd()`
2890: One can perform local computations between the `DMGlobalToLocalBegin()` and `DMGlobalToLocalEnd()` to overlap communication and computation
2892: `DMGlobalToLocal()` is a short form of `DMGlobalToLocalBegin()` and `DMGlobalToLocalEnd()`
2894: `DMGlobalToLocalHookAdd()` may be used to provide additional operations that are performed during the update process.
2896: .seealso: [](ch_dmbase), `DM`, `DMCoarsen()`, `DMDestroy()`, `DMView()`, `DMCreateGlobalVector()`, `DMCreateInterpolation()`, `DMGlobalToLocal()`, `DMGlobalToLocalEnd()`, `DMLocalToGlobalBegin()`, `DMLocalToGlobal()`, `DMLocalToGlobalEnd()`
2897: @*/
2898: PetscErrorCode DMGlobalToLocalBegin(DM dm, Vec g, InsertMode mode, Vec l)
2899: {
2900: PetscSF sf;
2901: DMGlobalToLocalHookLink link;
2903: PetscFunctionBegin;
2905: for (link = dm->gtolhook; link; link = link->next) {
2906: if (link->beginhook) PetscCall((*link->beginhook)(dm, g, mode, l, link->ctx));
2907: }
2908: PetscCall(DMGetSectionSF(dm, &sf));
2909: if (sf) {
2910: const PetscScalar *gArray;
2911: PetscScalar *lArray;
2912: PetscMemType lmtype, gmtype;
2914: PetscCheck(mode != ADD_VALUES, PetscObjectComm((PetscObject)dm), PETSC_ERR_ARG_OUTOFRANGE, "Invalid insertion mode %d", (int)mode);
2915: PetscCall(VecGetArrayAndMemType(l, &lArray, &lmtype));
2916: PetscCall(VecGetArrayReadAndMemType(g, &gArray, &gmtype));
2917: PetscCall(PetscSFBcastWithMemTypeBegin(sf, MPIU_SCALAR, gmtype, gArray, lmtype, lArray, MPI_REPLACE));
2918: PetscCall(VecRestoreArrayAndMemType(l, &lArray));
2919: PetscCall(VecRestoreArrayReadAndMemType(g, &gArray));
2920: } else {
2921: PetscUseTypeMethod(dm, globaltolocalbegin, g, mode == INSERT_ALL_VALUES ? INSERT_VALUES : (mode == ADD_ALL_VALUES ? ADD_VALUES : mode), l);
2922: }
2923: PetscFunctionReturn(PETSC_SUCCESS);
2924: }
2926: /*@
2927: DMGlobalToLocalEnd - Ends updating local vectors from global vector
2929: Neighbor-wise Collective
2931: Input Parameters:
2932: + dm - the `DM` object
2933: . g - the global vector
2934: . mode - `INSERT_VALUES` or `ADD_VALUES`
2935: - l - the local vector
2937: Level: intermediate
2939: Note:
2940: See `DMGlobalToLocalBegin()` for details.
2942: .seealso: [](ch_dmbase), `DM`, `DMCoarsen()`, `DMDestroy()`, `DMView()`, `DMCreateGlobalVector()`, `DMCreateInterpolation()`, `DMGlobalToLocal()`, `DMLocalToGlobalBegin()`, `DMLocalToGlobal()`, `DMLocalToGlobalEnd()`
2943: @*/
2944: PetscErrorCode DMGlobalToLocalEnd(DM dm, Vec g, InsertMode mode, Vec l)
2945: {
2946: PetscSF sf;
2947: const PetscScalar *gArray;
2948: PetscScalar *lArray;
2949: PetscBool transform;
2950: DMGlobalToLocalHookLink link;
2951: PetscMemType lmtype, gmtype;
2953: PetscFunctionBegin;
2955: PetscCall(DMGetSectionSF(dm, &sf));
2956: PetscCall(DMHasBasisTransform(dm, &transform));
2957: if (sf) {
2958: PetscCheck(mode != ADD_VALUES, PetscObjectComm((PetscObject)dm), PETSC_ERR_ARG_OUTOFRANGE, "Invalid insertion mode %d", (int)mode);
2960: PetscCall(VecGetArrayAndMemType(l, &lArray, &lmtype));
2961: PetscCall(VecGetArrayReadAndMemType(g, &gArray, &gmtype));
2962: PetscCall(PetscSFBcastEnd(sf, MPIU_SCALAR, gArray, lArray, MPI_REPLACE));
2963: PetscCall(VecRestoreArrayAndMemType(l, &lArray));
2964: PetscCall(VecRestoreArrayReadAndMemType(g, &gArray));
2965: if (transform) PetscCall(DMPlexGlobalToLocalBasis(dm, l));
2966: } else {
2967: PetscUseTypeMethod(dm, globaltolocalend, g, mode == INSERT_ALL_VALUES ? INSERT_VALUES : (mode == ADD_ALL_VALUES ? ADD_VALUES : mode), l);
2968: }
2969: PetscCall(DMGlobalToLocalHook_Constraints(dm, g, mode, l, NULL));
2970: for (link = dm->gtolhook; link; link = link->next) {
2971: if (link->endhook) PetscCall((*link->endhook)(dm, g, mode, l, link->ctx));
2972: }
2973: PetscFunctionReturn(PETSC_SUCCESS);
2974: }
2976: /*@C
2977: DMLocalToGlobalHookAdd - adds a callback to be run when a local to global is called
2979: Logically Collective
2981: Input Parameters:
2982: + dm - the `DM`
2983: . beginhook - function to run at the beginning of `DMLocalToGlobalBegin()`
2984: . endhook - function to run after `DMLocalToGlobalEnd()` has completed
2985: - ctx - [optional] context for provide data for the hooks (may be `NULL`)
2987: Calling sequence of `beginhook`:
2988: + global - global `DM`
2989: . l - local vector
2990: . mode - mode
2991: . g - global vector
2992: - ctx - optional function context
2994: Calling sequence of `endhook`:
2995: + global - global `DM`
2996: . l - local vector
2997: . mode - mode
2998: . g - global vector
2999: - ctx - optional function context
3001: Level: advanced
3003: .seealso: [](ch_dmbase), `DM`, `DMLocalToGlobal()`, `DMRefineHookAdd()`, `DMGlobalToLocalHookAdd()`, `SNESFASGetInterpolation()`, `SNESFASGetInjection()`, `PetscObjectCompose()`, `PetscContainerCreate()`
3004: @*/
3005: 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)
3006: {
3007: DMLocalToGlobalHookLink link, *p;
3009: PetscFunctionBegin;
3011: for (p = &dm->ltoghook; *p; p = &(*p)->next) { } /* Scan to the end of the current list of hooks */
3012: PetscCall(PetscNew(&link));
3013: link->beginhook = beginhook;
3014: link->endhook = endhook;
3015: link->ctx = ctx;
3016: link->next = NULL;
3017: *p = link;
3018: PetscFunctionReturn(PETSC_SUCCESS);
3019: }
3021: static PetscErrorCode DMLocalToGlobalHook_Constraints(DM dm, Vec l, InsertMode mode, Vec g, PetscCtx ctx)
3022: {
3023: PetscFunctionBegin;
3024: (void)g;
3025: (void)ctx;
3027: if (mode == ADD_VALUES || mode == ADD_ALL_VALUES || mode == ADD_BC_VALUES) {
3028: Mat cMat;
3029: Vec cVec;
3030: PetscInt nRows;
3031: PetscSection section, cSec;
3032: PetscInt pStart, pEnd, p, dof;
3034: PetscCall(DMGetDefaultConstraints(dm, &cSec, &cMat, NULL));
3035: if (!cMat) PetscFunctionReturn(PETSC_SUCCESS);
3037: PetscCall(MatGetSize(cMat, &nRows, NULL));
3038: if (nRows <= 0) PetscFunctionReturn(PETSC_SUCCESS);
3039: PetscCall(DMGetLocalSection(dm, §ion));
3040: PetscCall(MatCreateVecs(cMat, NULL, &cVec));
3041: PetscCall(PetscSectionGetChart(cSec, &pStart, &pEnd));
3042: for (p = pStart; p < pEnd; p++) {
3043: PetscCall(PetscSectionGetDof(cSec, p, &dof));
3044: if (dof) {
3045: PetscInt d;
3046: PetscScalar *vals;
3047: PetscCall(VecGetValuesSection(l, section, p, &vals));
3048: PetscCall(VecSetValuesSection(cVec, cSec, p, vals, mode));
3049: /* for this to be the true transpose, we have to zero the values that
3050: * we just extracted */
3051: for (d = 0; d < dof; d++) vals[d] = 0.;
3052: }
3053: }
3054: PetscCall(MatMultTransposeAdd(cMat, cVec, l, l));
3055: PetscCall(VecDestroy(&cVec));
3056: }
3057: PetscFunctionReturn(PETSC_SUCCESS);
3058: }
3059: /*@
3060: DMLocalToGlobal - updates global vectors from local vectors
3062: Neighbor-wise Collective
3064: Input Parameters:
3065: + dm - the `DM` object
3066: . l - the local vector
3067: . 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.
3068: - g - the global vector
3070: Level: beginner
3072: Notes:
3073: The communication involved in this update can be overlapped with computation by using
3074: `DMLocalToGlobalBegin()` and `DMLocalToGlobalEnd()`.
3076: In the `ADD_VALUES` case you normally would zero the receiving vector before beginning this operation.
3078: `INSERT_VALUES` is not supported for `DMDA`; in that case simply compute the values directly into a global vector instead of a local one.
3080: Use `DMLocalToGlobalHookAdd()` to add additional operations that are performed on the data during the update process
3082: .seealso: [](ch_dmbase), `DM`, `DMLocalToGlobalBegin()`, `DMLocalToGlobalEnd()`, `DMCoarsen()`, `DMDestroy()`, `DMView()`, `DMCreateGlobalVector()`, `DMCreateInterpolation()`, `DMGlobalToLocal()`, `DMGlobalToLocalEnd()`, `DMGlobalToLocalBegin()`, `DMLocalToGlobalHookAdd()`, `DMGlobaToLocallHookAdd()`
3083: @*/
3084: PetscErrorCode DMLocalToGlobal(DM dm, Vec l, InsertMode mode, Vec g)
3085: {
3086: PetscFunctionBegin;
3087: PetscCall(DMLocalToGlobalBegin(dm, l, mode, g));
3088: PetscCall(DMLocalToGlobalEnd(dm, l, mode, g));
3089: PetscFunctionReturn(PETSC_SUCCESS);
3090: }
3092: /*@
3093: DMLocalToGlobalBegin - begins updating global vectors from local vectors
3095: Neighbor-wise Collective
3097: Input Parameters:
3098: + dm - the `DM` object
3099: . l - the local vector
3100: . 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.
3101: - g - the global vector
3103: Level: intermediate
3105: Notes:
3106: In the `ADD_VALUES` case you normally would zero the receiving vector before beginning this operation.
3108: `INSERT_VALUES is` not supported for `DMDA`, in that case simply compute the values directly into a global vector instead of a local one.
3110: Use `DMLocalToGlobalEnd()` to complete the communication process.
3112: `DMLocalToGlobal()` is a short form of `DMLocalToGlobalBegin()` and `DMLocalToGlobalEnd()`
3114: `DMLocalToGlobalHookAdd()` may be used to provide additional operations that are performed during the update process.
3116: .seealso: [](ch_dmbase), `DM`, `DMLocalToGlobal()`, `DMLocalToGlobalEnd()`, `DMCoarsen()`, `DMDestroy()`, `DMView()`, `DMCreateGlobalVector()`, `DMCreateInterpolation()`, `DMGlobalToLocal()`, `DMGlobalToLocalEnd()`, `DMGlobalToLocalBegin()`
3117: @*/
3118: PetscErrorCode DMLocalToGlobalBegin(DM dm, Vec l, InsertMode mode, Vec g)
3119: {
3120: PetscSF sf;
3121: PetscSection s, gs;
3122: DMLocalToGlobalHookLink link;
3123: Vec tmpl;
3124: const PetscScalar *lArray;
3125: PetscScalar *gArray;
3126: PetscBool isInsert, transform, l_inplace = PETSC_FALSE, g_inplace = PETSC_FALSE;
3127: PetscMemType lmtype = PETSC_MEMTYPE_HOST, gmtype = PETSC_MEMTYPE_HOST;
3129: PetscFunctionBegin;
3131: for (link = dm->ltoghook; link; link = link->next) {
3132: if (link->beginhook) PetscCall((*link->beginhook)(dm, l, mode, g, link->ctx));
3133: }
3134: PetscCall(DMLocalToGlobalHook_Constraints(dm, l, mode, g, NULL));
3135: PetscCall(DMGetSectionSF(dm, &sf));
3136: PetscCall(DMGetLocalSection(dm, &s));
3137: switch (mode) {
3138: case INSERT_VALUES:
3139: case INSERT_ALL_VALUES:
3140: case INSERT_BC_VALUES:
3141: isInsert = PETSC_TRUE;
3142: break;
3143: case ADD_VALUES:
3144: case ADD_ALL_VALUES:
3145: case ADD_BC_VALUES:
3146: isInsert = PETSC_FALSE;
3147: break;
3148: default:
3149: SETERRQ(PetscObjectComm((PetscObject)dm), PETSC_ERR_ARG_OUTOFRANGE, "Invalid insertion mode %d", mode);
3150: }
3151: if ((sf && !isInsert) || (s && isInsert)) {
3152: PetscCall(DMHasBasisTransform(dm, &transform));
3153: if (transform) {
3154: PetscCall(DMGetNamedLocalVector(dm, "__petsc_dm_transform_local_copy", &tmpl));
3155: PetscCall(VecCopy(l, tmpl));
3156: PetscCall(DMPlexLocalToGlobalBasis(dm, tmpl));
3157: PetscCall(VecGetArrayRead(tmpl, &lArray));
3158: } else if (isInsert) {
3159: PetscCall(VecGetArrayRead(l, &lArray));
3160: } else {
3161: PetscCall(VecGetArrayReadAndMemType(l, &lArray, &lmtype));
3162: l_inplace = PETSC_TRUE;
3163: }
3164: if (s && isInsert) {
3165: PetscCall(VecGetArray(g, &gArray));
3166: } else {
3167: PetscCall(VecGetArrayAndMemType(g, &gArray, &gmtype));
3168: g_inplace = PETSC_TRUE;
3169: }
3170: if (sf && !isInsert) {
3171: PetscCall(PetscSFReduceWithMemTypeBegin(sf, MPIU_SCALAR, lmtype, lArray, gmtype, gArray, MPIU_SUM));
3172: } else if (s && isInsert) {
3173: PetscInt gStart, pStart, pEnd, p;
3175: PetscCall(DMGetGlobalSection(dm, &gs));
3176: PetscCall(PetscSectionGetChart(s, &pStart, &pEnd));
3177: PetscCall(VecGetOwnershipRange(g, &gStart, NULL));
3178: for (p = pStart; p < pEnd; ++p) {
3179: PetscInt dof, gdof, cdof, gcdof, off, goff, d, e;
3181: PetscCall(PetscSectionGetDof(s, p, &dof));
3182: PetscCall(PetscSectionGetDof(gs, p, &gdof));
3183: PetscCall(PetscSectionGetConstraintDof(s, p, &cdof));
3184: PetscCall(PetscSectionGetConstraintDof(gs, p, &gcdof));
3185: PetscCall(PetscSectionGetOffset(s, p, &off));
3186: PetscCall(PetscSectionGetOffset(gs, p, &goff));
3187: /* Ignore off-process data and points with no global data */
3188: if (!gdof || goff < 0) continue;
3189: 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);
3190: /* If no constraints are enforced in the global vector */
3191: if (!gcdof) {
3192: for (d = 0; d < dof; ++d) gArray[goff - gStart + d] = lArray[off + d];
3193: /* If constraints are enforced in the global vector */
3194: } else if (cdof == gcdof) {
3195: const PetscInt *cdofs;
3196: PetscInt cind = 0;
3198: PetscCall(PetscSectionGetConstraintIndices(s, p, &cdofs));
3199: for (d = 0, e = 0; d < dof; ++d) {
3200: if ((cind < cdof) && (d == cdofs[cind])) {
3201: ++cind;
3202: continue;
3203: }
3204: gArray[goff - gStart + e++] = lArray[off + d];
3205: }
3206: } 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);
3207: }
3208: }
3209: if (g_inplace) {
3210: PetscCall(VecRestoreArrayAndMemType(g, &gArray));
3211: } else {
3212: PetscCall(VecRestoreArray(g, &gArray));
3213: }
3214: if (transform) {
3215: PetscCall(VecRestoreArrayRead(tmpl, &lArray));
3216: PetscCall(DMRestoreNamedLocalVector(dm, "__petsc_dm_transform_local_copy", &tmpl));
3217: } else if (l_inplace) {
3218: PetscCall(VecRestoreArrayReadAndMemType(l, &lArray));
3219: } else {
3220: PetscCall(VecRestoreArrayRead(l, &lArray));
3221: }
3222: } else {
3223: PetscUseTypeMethod(dm, localtoglobalbegin, l, mode == INSERT_ALL_VALUES ? INSERT_VALUES : (mode == ADD_ALL_VALUES ? ADD_VALUES : mode), g);
3224: }
3225: PetscFunctionReturn(PETSC_SUCCESS);
3226: }
3228: /*@
3229: DMLocalToGlobalEnd - updates global vectors from local vectors
3231: Neighbor-wise Collective
3233: Input Parameters:
3234: + dm - the `DM` object
3235: . l - the local vector
3236: . mode - `INSERT_VALUES` or `ADD_VALUES`
3237: - g - the global vector
3239: Level: intermediate
3241: Note:
3242: See `DMLocalToGlobalBegin()` for full details
3244: .seealso: [](ch_dmbase), `DM`, `DMLocalToGlobalBegin()`, `DMCoarsen()`, `DMDestroy()`, `DMView()`, `DMCreateGlobalVector()`, `DMCreateInterpolation()`, `DMGlobalToLocalEnd()`
3245: @*/
3246: PetscErrorCode DMLocalToGlobalEnd(DM dm, Vec l, InsertMode mode, Vec g)
3247: {
3248: PetscSF sf;
3249: PetscSection s;
3250: DMLocalToGlobalHookLink link;
3251: PetscBool isInsert, transform;
3253: PetscFunctionBegin;
3255: PetscCall(DMGetSectionSF(dm, &sf));
3256: PetscCall(DMGetLocalSection(dm, &s));
3257: switch (mode) {
3258: case INSERT_VALUES:
3259: case INSERT_ALL_VALUES:
3260: isInsert = PETSC_TRUE;
3261: break;
3262: case ADD_VALUES:
3263: case ADD_ALL_VALUES:
3264: isInsert = PETSC_FALSE;
3265: break;
3266: default:
3267: SETERRQ(PetscObjectComm((PetscObject)dm), PETSC_ERR_ARG_OUTOFRANGE, "Invalid insertion mode %d", mode);
3268: }
3269: if (sf && !isInsert) {
3270: const PetscScalar *lArray;
3271: PetscScalar *gArray;
3272: Vec tmpl;
3274: PetscCall(DMHasBasisTransform(dm, &transform));
3275: if (transform) {
3276: PetscCall(DMGetNamedLocalVector(dm, "__petsc_dm_transform_local_copy", &tmpl));
3277: PetscCall(VecGetArrayRead(tmpl, &lArray));
3278: } else {
3279: PetscCall(VecGetArrayReadAndMemType(l, &lArray, NULL));
3280: }
3281: PetscCall(VecGetArrayAndMemType(g, &gArray, NULL));
3282: PetscCall(PetscSFReduceEnd(sf, MPIU_SCALAR, lArray, gArray, MPIU_SUM));
3283: if (transform) {
3284: PetscCall(VecRestoreArrayRead(tmpl, &lArray));
3285: PetscCall(DMRestoreNamedLocalVector(dm, "__petsc_dm_transform_local_copy", &tmpl));
3286: } else {
3287: PetscCall(VecRestoreArrayReadAndMemType(l, &lArray));
3288: }
3289: PetscCall(VecRestoreArrayAndMemType(g, &gArray));
3290: } else if (s && isInsert) {
3291: } else {
3292: PetscUseTypeMethod(dm, localtoglobalend, l, mode == INSERT_ALL_VALUES ? INSERT_VALUES : (mode == ADD_ALL_VALUES ? ADD_VALUES : mode), g);
3293: }
3294: for (link = dm->ltoghook; link; link = link->next) {
3295: if (link->endhook) PetscCall((*link->endhook)(dm, g, mode, l, link->ctx));
3296: }
3297: PetscFunctionReturn(PETSC_SUCCESS);
3298: }
3300: /*@
3301: DMLocalToLocalBegin - Begins the process of mapping values from a local vector (that include
3302: ghost points that contain irrelevant values) to another local vector where the ghost points
3303: in the second are set correctly from values on other MPI ranks.
3305: Neighbor-wise Collective
3307: Input Parameters:
3308: + dm - the `DM` object
3309: . g - the original local vector
3310: - mode - one of `INSERT_VALUES` or `ADD_VALUES`
3312: Output Parameter:
3313: . l - the local vector with correct ghost values
3315: Level: intermediate
3317: Note:
3318: Must be followed by `DMLocalToLocalEnd()`.
3320: .seealso: [](ch_dmbase), `DM`, `DMLocalToLocalEnd()`, `DMCoarsen()`, `DMDestroy()`, `DMView()`, `DMCreateLocalVector()`, `DMCreateGlobalVector()`, `DMCreateInterpolation()`, `DMGlobalToLocalEnd()`, `DMLocalToGlobalBegin()`
3321: @*/
3322: PetscErrorCode DMLocalToLocalBegin(DM dm, Vec g, InsertMode mode, Vec l)
3323: {
3324: PetscFunctionBegin;
3328: PetscUseTypeMethod(dm, localtolocalbegin, g, mode == INSERT_ALL_VALUES ? INSERT_VALUES : (mode == ADD_ALL_VALUES ? ADD_VALUES : mode), l);
3329: PetscFunctionReturn(PETSC_SUCCESS);
3330: }
3332: /*@
3333: DMLocalToLocalEnd - Maps from a local vector to another local vector where the ghost
3334: points in the second are set correctly. Must be preceded by `DMLocalToLocalBegin()`.
3336: Neighbor-wise Collective
3338: Input Parameters:
3339: + dm - the `DM` object
3340: . g - the original local vector
3341: - mode - one of `INSERT_VALUES` or `ADD_VALUES`
3343: Output Parameter:
3344: . l - the local vector with correct ghost values
3346: Level: intermediate
3348: .seealso: [](ch_dmbase), `DM`, `DMLocalToLocalBegin()`, `DMCoarsen()`, `DMDestroy()`, `DMView()`, `DMCreateLocalVector()`, `DMCreateGlobalVector()`, `DMCreateInterpolation()`, `DMGlobalToLocalEnd()`, `DMLocalToGlobalBegin()`
3349: @*/
3350: PetscErrorCode DMLocalToLocalEnd(DM dm, Vec g, InsertMode mode, Vec l)
3351: {
3352: PetscFunctionBegin;
3356: PetscUseTypeMethod(dm, localtolocalend, g, mode == INSERT_ALL_VALUES ? INSERT_VALUES : (mode == ADD_ALL_VALUES ? ADD_VALUES : mode), l);
3357: PetscFunctionReturn(PETSC_SUCCESS);
3358: }
3360: /*@
3361: DMCoarsen - Coarsens a `DM` object using a standard, non-adaptive coarsening of the underlying mesh
3363: Collective
3365: Input Parameters:
3366: + dm - the `DM` object
3367: - comm - the communicator to contain the new `DM` object (or `MPI_COMM_NULL`)
3369: Output Parameter:
3370: . dmc - the coarsened `DM`
3372: Level: developer
3374: .seealso: [](ch_dmbase), `DM`, `DMRefine()`, `DMDestroy()`, `DMView()`, `DMCreateGlobalVector()`, `DMCreateInterpolation()`, `DMCreateDomainDecomposition()`,
3375: `DMCoarsenHookAdd()`, `DMCoarsenHookRemove()`
3376: @*/
3377: PetscErrorCode DMCoarsen(DM dm, MPI_Comm comm, DM *dmc)
3378: {
3379: DMCoarsenHookLink link;
3381: PetscFunctionBegin;
3383: PetscCall(PetscLogEventBegin(DM_Coarsen, dm, 0, 0, 0));
3384: PetscUseTypeMethod(dm, coarsen, comm, dmc);
3385: if (*dmc) {
3386: (*dmc)->bind_below = dm->bind_below; /* Propagate this from parent DM; otherwise -dm_bind_below will be useless for multigrid cases. */
3387: PetscCall(DMSetCoarseDM(dm, *dmc));
3388: (*dmc)->ops->creatematrix = dm->ops->creatematrix;
3389: PetscCall(PetscObjectCopyFortranFunctionPointers((PetscObject)dm, (PetscObject)*dmc));
3390: (*dmc)->ctx = dm->ctx;
3391: (*dmc)->levelup = dm->levelup;
3392: (*dmc)->leveldown = dm->leveldown + 1;
3393: PetscCall(DMSetMatType(*dmc, dm->mattype));
3394: for (link = dm->coarsenhook; link; link = link->next) {
3395: if (link->coarsenhook) PetscCall((*link->coarsenhook)(dm, *dmc, link->ctx));
3396: }
3397: }
3398: PetscCall(PetscLogEventEnd(DM_Coarsen, dm, 0, 0, 0));
3399: PetscCheck(*dmc, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "NULL coarse mesh produced");
3400: PetscFunctionReturn(PETSC_SUCCESS);
3401: }
3403: /*@C
3404: DMCoarsenHookAdd - adds a callback to be run when restricting a nonlinear problem to the coarse grid
3406: Logically Collective; No Fortran Support
3408: Input Parameters:
3409: + fine - `DM` on which to run a hook when restricting to a coarser level
3410: . coarsenhook - function to run when setting up a coarser level
3411: . restricthook - function to run to update data on coarser levels (called once per `SNESSolve()`)
3412: - ctx - [optional] application context for provide data for the hooks (may be `NULL`)
3414: Calling sequence of `coarsenhook`:
3415: + fine - fine level `DM`
3416: . coarse - coarse level `DM` to restrict problem to
3417: - ctx - optional application function context
3419: Calling sequence of `restricthook`:
3420: + fine - fine level `DM`
3421: . mrestrict - matrix restricting a fine-level solution to the coarse grid, usually the transpose of the interpolation
3422: . rscale - scaling vector for restriction
3423: . inject - matrix restricting by injection
3424: . coarse - coarse level DM to update
3425: - ctx - optional application function context
3427: Level: advanced
3429: Notes:
3430: 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`.
3432: If this function is called multiple times, the hooks will be run in the order they are added.
3434: In order to compose with nonlinear preconditioning without duplicating storage, the hook should be implemented to
3435: extract the finest level information from its context (instead of from the `SNES`).
3437: The hooks are automatically called by `DMRestrict()`
3439: .seealso: [](ch_dmbase), `DM`, `DMCoarsenHookRemove()`, `DMRefineHookAdd()`, `SNESFASGetInterpolation()`, `SNESFASGetInjection()`, `PetscObjectCompose()`, `PetscContainerCreate()`
3440: @*/
3441: 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)
3442: {
3443: DMCoarsenHookLink link, *p;
3445: PetscFunctionBegin;
3447: for (p = &fine->coarsenhook; *p; p = &(*p)->next) { /* Scan to the end of the current list of hooks */
3448: if ((*p)->coarsenhook == coarsenhook && (*p)->restricthook == restricthook && (*p)->ctx == ctx) PetscFunctionReturn(PETSC_SUCCESS);
3449: }
3450: PetscCall(PetscNew(&link));
3451: link->coarsenhook = coarsenhook;
3452: link->restricthook = restricthook;
3453: link->ctx = ctx;
3454: link->next = NULL;
3455: *p = link;
3456: PetscFunctionReturn(PETSC_SUCCESS);
3457: }
3459: /*@C
3460: DMCoarsenHookRemove - remove a callback set with `DMCoarsenHookAdd()`
3462: Logically Collective; No Fortran Support
3464: Input Parameters:
3465: + fine - `DM` on which to run a hook when restricting to a coarser level
3466: . coarsenhook - function to run when setting up a coarser level
3467: . restricthook - function to run to update data on coarser levels
3468: - ctx - [optional] application context for provide data for the hooks (may be `NULL`)
3470: Calling sequence of `coarsenhook`:
3471: + fine - fine level `DM`
3472: . coarse - coarse level `DM` to restrict problem to
3473: - ctx - optional application function context
3475: Calling sequence of `restricthook`:
3476: + fine - fine level `DM`
3477: . rstrict - matrix restricting a fine-level solution to the coarse grid, usually the transpose of the interpolation
3478: . rscale - scaling vector for restriction
3479: . inject - matrix restricting by injection
3480: . coarse - coarse level DM to update
3481: - ctx - optional application function context
3483: Level: advanced
3485: Notes:
3486: This function does nothing if the `coarsenhook` is not in the list.
3488: See `DMCoarsenHookAdd()` for the calling sequence of `coarsenhook` and `restricthook`
3490: .seealso: [](ch_dmbase), `DM`, `DMCoarsenHookAdd()`, `DMRefineHookAdd()`, `SNESFASGetInterpolation()`, `SNESFASGetInjection()`, `PetscObjectCompose()`, `PetscContainerCreate()`
3491: @*/
3492: 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)
3493: {
3494: DMCoarsenHookLink link, *p;
3496: PetscFunctionBegin;
3498: for (p = &fine->coarsenhook; *p; p = &(*p)->next) { /* Search the list of current hooks */
3499: if ((*p)->coarsenhook == coarsenhook && (*p)->restricthook == restricthook && (*p)->ctx == ctx) {
3500: link = *p;
3501: *p = link->next;
3502: PetscCall(PetscFree(link));
3503: break;
3504: }
3505: }
3506: PetscFunctionReturn(PETSC_SUCCESS);
3507: }
3509: /*@
3510: DMRestrict - restricts user-defined problem data to a coarser `DM` by running hooks registered by `DMCoarsenHookAdd()`
3512: Collective if any hooks are
3514: Input Parameters:
3515: + fine - finer `DM` from which the data is obtained
3516: . restrct - restriction matrix, apply using `MatRestrict()`, usually the transpose of the interpolation
3517: . rscale - scaling vector for restriction
3518: . inject - injection matrix, also use `MatRestrict()`
3519: - coarse - coarser `DM` to update
3521: Level: developer
3523: Developer Note:
3524: Though this routine is called `DMRestrict()` the hooks are added with `DMCoarsenHookAdd()`, a consistent terminology would be better
3526: .seealso: [](ch_dmbase), `DM`, `DMCoarsenHookAdd()`, `MatRestrict()`, `DMInterpolate()`, `DMRefineHookAdd()`
3527: @*/
3528: PetscErrorCode DMRestrict(DM fine, Mat restrct, Vec rscale, Mat inject, DM coarse)
3529: {
3530: DMCoarsenHookLink link;
3532: PetscFunctionBegin;
3533: for (link = fine->coarsenhook; link; link = link->next) {
3534: if (link->restricthook) PetscCall((*link->restricthook)(fine, restrct, rscale, inject, coarse, link->ctx));
3535: }
3536: PetscFunctionReturn(PETSC_SUCCESS);
3537: }
3539: /*@C
3540: DMSubDomainHookAdd - adds a callback to be run when restricting a problem to subdomain `DM`s with `DMCreateDomainDecomposition()`
3542: Logically Collective; No Fortran Support
3544: Input Parameters:
3545: + global - global `DM`
3546: . ddhook - function to run to pass data to the decomposition `DM` upon its creation
3547: . restricthook - function to run to update data on block solve (at the beginning of the block solve)
3548: - ctx - [optional] application context for provide data for the hooks (may be `NULL`)
3550: Calling sequence of `ddhook`:
3551: + global - global `DM`
3552: . block - subdomain `DM`
3553: - ctx - optional application function context
3555: Calling sequence of `restricthook`:
3556: + global - global `DM`
3557: . out - scatter to the outer (with ghost and overlap points) sub vector
3558: . in - scatter to sub vector values only owned locally
3559: . block - subdomain `DM`
3560: - ctx - optional application function context
3562: Level: advanced
3564: Notes:
3565: This function can be used if auxiliary data needs to be set up on subdomain `DM`s.
3567: If this function is called multiple times, the hooks will be run in the order they are added.
3569: In order to compose with nonlinear preconditioning without duplicating storage, the hook should be implemented to
3570: extract the global information from its context (instead of from the `SNES`).
3572: Developer Note:
3573: It is unclear what "block solve" means within the definition of `restricthook`
3575: .seealso: [](ch_dmbase), `DM`, `DMSubDomainHookRemove()`, `DMRefineHookAdd()`, `SNESFASGetInterpolation()`, `SNESFASGetInjection()`, `PetscObjectCompose()`, `PetscContainerCreate()`, `DMCreateDomainDecomposition()`
3576: @*/
3577: 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)
3578: {
3579: DMSubDomainHookLink link, *p;
3581: PetscFunctionBegin;
3583: for (p = &global->subdomainhook; *p; p = &(*p)->next) { /* Scan to the end of the current list of hooks */
3584: if ((*p)->ddhook == ddhook && (*p)->restricthook == restricthook && (*p)->ctx == ctx) PetscFunctionReturn(PETSC_SUCCESS);
3585: }
3586: PetscCall(PetscNew(&link));
3587: link->restricthook = restricthook;
3588: link->ddhook = ddhook;
3589: link->ctx = ctx;
3590: link->next = NULL;
3591: *p = link;
3592: PetscFunctionReturn(PETSC_SUCCESS);
3593: }
3595: /*@C
3596: DMSubDomainHookRemove - remove a callback from the list to be run when restricting a problem to subdomain `DM`s with `DMCreateDomainDecomposition()`
3598: Logically Collective; No Fortran Support
3600: Input Parameters:
3601: + global - global `DM`
3602: . ddhook - function to run to pass data to the decomposition `DM` upon its creation
3603: . restricthook - function to run to update data on block solve (at the beginning of the block solve)
3604: - ctx - [optional] application context for provide data for the hooks (may be `NULL`)
3606: Calling sequence of `ddhook`:
3607: + dm - global `DM`
3608: . block - subdomain `DM`
3609: - ctx - optional application function context
3611: Calling sequence of `restricthook`:
3612: + dm - global `DM`
3613: . oscatter - scatter to the outer (with ghost and overlap points) sub vector
3614: . gscatter - scatter to sub vector values only owned locally
3615: . block - subdomain `DM`
3616: - ctx - optional application function context
3618: Level: advanced
3620: .seealso: [](ch_dmbase), `DM`, `DMSubDomainHookAdd()`, `SNESFASGetInterpolation()`, `SNESFASGetInjection()`, `PetscObjectCompose()`, `PetscContainerCreate()`,
3621: `DMCreateDomainDecomposition()`
3622: @*/
3623: 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)
3624: {
3625: DMSubDomainHookLink link, *p;
3627: PetscFunctionBegin;
3629: for (p = &global->subdomainhook; *p; p = &(*p)->next) { /* Search the list of current hooks */
3630: if ((*p)->ddhook == ddhook && (*p)->restricthook == restricthook && (*p)->ctx == ctx) {
3631: link = *p;
3632: *p = link->next;
3633: PetscCall(PetscFree(link));
3634: break;
3635: }
3636: }
3637: PetscFunctionReturn(PETSC_SUCCESS);
3638: }
3640: /*@
3641: DMSubDomainRestrict - restricts user-defined problem data to a subdomain `DM` by running hooks registered by `DMSubDomainHookAdd()`
3643: Collective if any hooks are
3645: Input Parameters:
3646: + global - The global `DM` to use as a base
3647: . oscatter - The scatter from domain global vector filling subdomain global vector with overlap
3648: . gscatter - The scatter from domain global vector filling subdomain local vector with ghosts
3649: - subdm - The subdomain `DM` to update
3651: Level: developer
3653: .seealso: [](ch_dmbase), `DM`, `DMCoarsenHookAdd()`, `MatRestrict()`, `DMCreateDomainDecomposition()`
3654: @*/
3655: PetscErrorCode DMSubDomainRestrict(DM global, VecScatter oscatter, VecScatter gscatter, DM subdm)
3656: {
3657: DMSubDomainHookLink link;
3659: PetscFunctionBegin;
3660: for (link = global->subdomainhook; link; link = link->next) {
3661: if (link->restricthook) PetscCall((*link->restricthook)(global, oscatter, gscatter, subdm, link->ctx));
3662: }
3663: PetscFunctionReturn(PETSC_SUCCESS);
3664: }
3666: /*@
3667: DMGetCoarsenLevel - Gets the number of coarsenings that have generated this `DM`.
3669: Not Collective
3671: Input Parameter:
3672: . dm - the `DM` object
3674: Output Parameter:
3675: . level - number of coarsenings
3677: Level: developer
3679: .seealso: [](ch_dmbase), `DM`, `DMCoarsen()`, `DMSetCoarsenLevel()`, `DMGetRefineLevel()`, `DMDestroy()`, `DMView()`, `DMCreateGlobalVector()`, `DMCreateInterpolation()`
3680: @*/
3681: PetscErrorCode DMGetCoarsenLevel(DM dm, PetscInt *level)
3682: {
3683: PetscFunctionBegin;
3685: PetscAssertPointer(level, 2);
3686: *level = dm->leveldown;
3687: PetscFunctionReturn(PETSC_SUCCESS);
3688: }
3690: /*@
3691: DMSetCoarsenLevel - Sets the number of coarsenings that have generated this `DM`.
3693: Collective
3695: Input Parameters:
3696: + dm - the `DM` object
3697: - level - number of coarsenings
3699: Level: developer
3701: Note:
3702: This is rarely used directly, the information is automatically set when a `DM` is created with `DMCoarsen()`
3704: .seealso: [](ch_dmbase), `DM`, `DMCoarsen()`, `DMGetCoarsenLevel()`, `DMGetRefineLevel()`, `DMDestroy()`, `DMView()`, `DMCreateGlobalVector()`, `DMCreateInterpolation()`
3705: @*/
3706: PetscErrorCode DMSetCoarsenLevel(DM dm, PetscInt level)
3707: {
3708: PetscFunctionBegin;
3710: dm->leveldown = level;
3711: PetscFunctionReturn(PETSC_SUCCESS);
3712: }
3714: /*@
3715: DMRefineHierarchy - Refines a `DM` object, all levels at once
3717: Collective
3719: Input Parameters:
3720: + dm - the `DM` object
3721: - nlevels - the number of levels of refinement
3723: Output Parameter:
3724: . dmf - the refined `DM` hierarchy
3726: Level: developer
3728: .seealso: [](ch_dmbase), `DM`, `DMCoarsen()`, `DMCoarsenHierarchy()`, `DMDestroy()`, `DMView()`, `DMCreateGlobalVector()`, `DMCreateInterpolation()`
3729: @*/
3730: PetscErrorCode DMRefineHierarchy(DM dm, PetscInt nlevels, DM dmf[])
3731: {
3732: PetscFunctionBegin;
3734: PetscCheck(nlevels >= 0, PetscObjectComm((PetscObject)dm), PETSC_ERR_ARG_OUTOFRANGE, "nlevels cannot be negative");
3735: if (nlevels == 0) PetscFunctionReturn(PETSC_SUCCESS);
3736: PetscAssertPointer(dmf, 3);
3737: if (dm->ops->refine && !dm->ops->refinehierarchy) {
3738: PetscCall(DMRefine(dm, PetscObjectComm((PetscObject)dm), &dmf[0]));
3739: for (PetscInt i = 1; i < nlevels; i++) PetscCall(DMRefine(dmf[i - 1], PetscObjectComm((PetscObject)dm), &dmf[i]));
3740: } else PetscUseTypeMethod(dm, refinehierarchy, nlevels, dmf);
3741: PetscFunctionReturn(PETSC_SUCCESS);
3742: }
3744: /*@
3745: DMCoarsenHierarchy - Coarsens a `DM` object, all levels at once
3747: Collective
3749: Input Parameters:
3750: + dm - the `DM` object
3751: - nlevels - the number of levels of coarsening
3753: Output Parameter:
3754: . dmc - the coarsened `DM` hierarchy
3756: Level: developer
3758: .seealso: [](ch_dmbase), `DM`, `DMCoarsen()`, `DMRefineHierarchy()`, `DMDestroy()`, `DMView()`, `DMCreateGlobalVector()`, `DMCreateInterpolation()`
3759: @*/
3760: PetscErrorCode DMCoarsenHierarchy(DM dm, PetscInt nlevels, DM dmc[])
3761: {
3762: PetscFunctionBegin;
3764: PetscCheck(nlevels >= 0, PetscObjectComm((PetscObject)dm), PETSC_ERR_ARG_OUTOFRANGE, "nlevels cannot be negative");
3765: if (nlevels == 0) PetscFunctionReturn(PETSC_SUCCESS);
3766: PetscAssertPointer(dmc, 3);
3767: if (dm->ops->coarsen && !dm->ops->coarsenhierarchy) {
3768: PetscCall(DMCoarsen(dm, PetscObjectComm((PetscObject)dm), &dmc[0]));
3769: for (PetscInt i = 1; i < nlevels; i++) PetscCall(DMCoarsen(dmc[i - 1], PetscObjectComm((PetscObject)dm), &dmc[i]));
3770: } else PetscUseTypeMethod(dm, coarsenhierarchy, nlevels, dmc);
3771: PetscFunctionReturn(PETSC_SUCCESS);
3772: }
3774: /*@C
3775: DMSetApplicationContextDestroy - Sets a user function that will be called to destroy the application context when the `DM` is destroyed
3777: Logically Collective if the function is collective
3779: Input Parameters:
3780: + dm - the `DM` object
3781: - destroy - the destroy function, see `PetscCtxDestroyFn` for the calling sequence
3783: Level: intermediate
3785: .seealso: [](ch_dmbase), `DM`, `DMSetApplicationContext()`, `DMView()`, `DMCreateGlobalVector()`, `DMCreateInterpolation()`, `DMCreateColoring()`, `DMCreateMatrix()`, `DMCreateMassMatrix()`,
3786: `DMGetApplicationContext()`, `PetscCtxDestroyFn`
3787: @*/
3788: PetscErrorCode DMSetApplicationContextDestroy(DM dm, PetscCtxDestroyFn *destroy)
3789: {
3790: PetscFunctionBegin;
3792: dm->ctxdestroy = destroy;
3793: PetscFunctionReturn(PETSC_SUCCESS);
3794: }
3796: /*@
3797: DMSetApplicationContext - Set a user context into a `DM` object
3799: Not Collective
3801: Input Parameters:
3802: + dm - the `DM` object
3803: - ctx - the user context
3805: Level: intermediate
3807: Note:
3808: A user context is a way to pass problem specific information that is accessible whenever the `DM` is available
3809: In a multilevel solver, the user context is shared by all the `DM` in the hierarchy; it is thus not advisable
3810: to store objects that represent discretized quantities inside the context.
3812: Fortran Notes:
3813: This only works when the context is a Fortran derived type or a `PetscObject`. Declare `ctx` with
3814: .vb
3815: type(tUsertype), pointer :: ctx
3816: .ve
3818: .seealso: [](ch_dmbase), `DM`, `DMGetApplicationContext()`, `DMView()`, `DMCreateGlobalVector()`, `DMCreateInterpolation()`, `DMCreateColoring()`, `DMCreateMatrix()`, `DMCreateMassMatrix()`
3819: @*/
3820: PetscErrorCode DMSetApplicationContext(DM dm, PetscCtx ctx)
3821: {
3822: PetscFunctionBegin;
3824: dm->ctx = ctx;
3825: PetscFunctionReturn(PETSC_SUCCESS);
3826: }
3828: /*@
3829: DMGetApplicationContext - Gets a user context from a `DM` object provided with `DMSetApplicationContext()`
3831: Not Collective
3833: Input Parameter:
3834: . dm - the `DM` object
3836: Output Parameter:
3837: . ctx - a pointer to the user context
3839: Level: intermediate
3841: Note:
3842: A user context is a way to pass problem specific information that is accessible whenever the `DM` is available
3844: Fortran Notes:
3845: 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
3846: function that tells the Fortran compiler the derived data type that is returned as the `ctx` argument. For example,
3847: .vb
3848: Interface DMGetApplicationContext
3849: Subroutine DMGetApplicationContext(dm,ctx,ierr)
3850: #include <petsc/finclude/petscdm.h>
3851: use petscdm
3852: DM dm
3853: type(tUsertype), pointer :: ctx
3854: PetscErrorCode ierr
3855: End Subroutine
3856: End Interface DMGetApplicationContext
3857: .ve
3859: The prototype for `ctx` must be
3860: .vb
3861: type(tUsertype), pointer :: ctx
3862: .ve
3864: .seealso: [](ch_dmbase), `DM`, `DMView()`, `DMCreateGlobalVector()`, `DMCreateInterpolation()`, `DMCreateColoring()`, `DMCreateMatrix()`, `DMCreateMassMatrix()`
3865: @*/
3866: PetscErrorCode DMGetApplicationContext(DM dm, PetscCtxRt ctx)
3867: {
3868: PetscFunctionBegin;
3870: *(void **)ctx = dm->ctx;
3871: PetscFunctionReturn(PETSC_SUCCESS);
3872: }
3874: /*@C
3875: DMSetVariableBounds - sets a function to compute the lower and upper bound vectors for `SNESVI`.
3877: Logically Collective
3879: Input Parameters:
3880: + dm - the `DM` object
3881: - f - the function that computes variable bounds used by `SNESVI` (use `NULL` to cancel a previous function that was set)
3883: Calling sequence of f:
3884: + dm - the `DM`
3885: . lower - the vector to hold the lower bounds
3886: - upper - the vector to hold the upper bounds
3888: Level: intermediate
3890: Developer Note:
3891: Should be called `DMSetComputeVIBounds()` or something similar
3893: .seealso: [](ch_dmbase), `DM`, `DMComputeVariableBounds()`, `DMHasVariableBounds()`, `DMView()`, `DMCreateGlobalVector()`, `DMCreateInterpolation()`, `DMCreateColoring()`, `DMCreateMatrix()`, `DMCreateMassMatrix()`, `DMGetApplicationContext()`,
3894: `DMSetJacobian()`
3895: @*/
3896: PetscErrorCode DMSetVariableBounds(DM dm, PetscErrorCode (*f)(DM dm, Vec lower, Vec upper))
3897: {
3898: PetscFunctionBegin;
3900: dm->ops->computevariablebounds = f;
3901: PetscFunctionReturn(PETSC_SUCCESS);
3902: }
3904: /*@
3905: DMHasVariableBounds - does the `DM` object have a variable bounds function?
3907: Not Collective
3909: Input Parameter:
3910: . dm - the `DM` object to destroy
3912: Output Parameter:
3913: . flg - `PETSC_TRUE` if the variable bounds function exists
3915: Level: developer
3917: .seealso: [](ch_dmbase), `DM`, `DMComputeVariableBounds()`, `DMView()`, `DMCreateGlobalVector()`, `DMCreateInterpolation()`, `DMCreateColoring()`, `DMCreateMatrix()`, `DMCreateMassMatrix()`, `DMGetApplicationContext()`
3918: @*/
3919: PetscErrorCode DMHasVariableBounds(DM dm, PetscBool *flg)
3920: {
3921: PetscFunctionBegin;
3923: PetscAssertPointer(flg, 2);
3924: *flg = (dm->ops->computevariablebounds) ? PETSC_TRUE : PETSC_FALSE;
3925: PetscFunctionReturn(PETSC_SUCCESS);
3926: }
3928: /*@
3929: DMComputeVariableBounds - compute variable bounds used by `SNESVI`.
3931: Logically Collective
3933: Input Parameter:
3934: . dm - the `DM` object
3936: Output Parameters:
3937: + xl - lower bound
3938: - xu - upper bound
3940: Level: advanced
3942: Note:
3943: This is generally not called by users. It calls the function provided by the user with DMSetVariableBounds()
3945: .seealso: [](ch_dmbase), `DM`, `DMHasVariableBounds()`, `DMView()`, `DMCreateGlobalVector()`, `DMCreateInterpolation()`, `DMCreateColoring()`, `DMCreateMatrix()`, `DMCreateMassMatrix()`, `DMGetApplicationContext()`
3946: @*/
3947: PetscErrorCode DMComputeVariableBounds(DM dm, Vec xl, Vec xu)
3948: {
3949: PetscFunctionBegin;
3953: PetscUseTypeMethod(dm, computevariablebounds, xl, xu);
3954: PetscFunctionReturn(PETSC_SUCCESS);
3955: }
3957: /*@
3958: DMHasColoring - does the `DM` object have a method of providing a coloring?
3960: Not Collective
3962: Input Parameter:
3963: . dm - the DM object
3965: Output Parameter:
3966: . flg - `PETSC_TRUE` if the `DM` has facilities for `DMCreateColoring()`.
3968: Level: developer
3970: .seealso: [](ch_dmbase), `DM`, `DMCreateColoring()`
3971: @*/
3972: PetscErrorCode DMHasColoring(DM dm, PetscBool *flg)
3973: {
3974: PetscFunctionBegin;
3976: PetscAssertPointer(flg, 2);
3977: *flg = (dm->ops->getcoloring) ? PETSC_TRUE : PETSC_FALSE;
3978: PetscFunctionReturn(PETSC_SUCCESS);
3979: }
3981: /*@
3982: DMHasCreateRestriction - does the `DM` object have a method of providing a restriction?
3984: Not Collective
3986: Input Parameter:
3987: . dm - the `DM` object
3989: Output Parameter:
3990: . flg - `PETSC_TRUE` if the `DM` has facilities for `DMCreateRestriction()`.
3992: Level: developer
3994: .seealso: [](ch_dmbase), `DM`, `DMCreateRestriction()`, `DMHasCreateInterpolation()`, `DMHasCreateInjection()`
3995: @*/
3996: PetscErrorCode DMHasCreateRestriction(DM dm, PetscBool *flg)
3997: {
3998: PetscFunctionBegin;
4000: PetscAssertPointer(flg, 2);
4001: *flg = (dm->ops->createrestriction) ? PETSC_TRUE : PETSC_FALSE;
4002: PetscFunctionReturn(PETSC_SUCCESS);
4003: }
4005: /*@
4006: DMHasCreateInjection - does the `DM` object have a method of providing an injection?
4008: Not Collective
4010: Input Parameter:
4011: . dm - the `DM` object
4013: Output Parameter:
4014: . flg - `PETSC_TRUE` if the `DM` has facilities for `DMCreateInjection()`.
4016: Level: developer
4018: .seealso: [](ch_dmbase), `DM`, `DMCreateInjection()`, `DMHasCreateRestriction()`, `DMHasCreateInterpolation()`
4019: @*/
4020: PetscErrorCode DMHasCreateInjection(DM dm, PetscBool *flg)
4021: {
4022: PetscFunctionBegin;
4024: PetscAssertPointer(flg, 2);
4025: if (dm->ops->hascreateinjection) PetscUseTypeMethod(dm, hascreateinjection, flg);
4026: else *flg = (dm->ops->createinjection) ? PETSC_TRUE : PETSC_FALSE;
4027: PetscFunctionReturn(PETSC_SUCCESS);
4028: }
4030: PetscFunctionList DMList = NULL;
4031: PetscBool DMRegisterAllCalled = PETSC_FALSE;
4033: /*@
4034: DMSetType - Builds a `DM`, for a particular `DM` implementation.
4036: Collective
4038: Input Parameters:
4039: + dm - The `DM` object
4040: - method - The name of the `DMType`, for example `DMDA`, `DMPLEX`
4042: Options Database Key:
4043: . -dm_type type - Sets the `DM` type; use -help for a list of available types
4045: Level: intermediate
4047: Note:
4048: Of the `DM` is constructed by directly calling a function to construct a particular `DM`, for example, `DMDACreate2d()` or `DMPlexCreateBoxMesh()`
4050: .seealso: [](ch_dmbase), `DM`, `DMType`, `DMDA`, `DMPLEX`, `DMGetType()`, `DMCreate()`, `DMDACreate2d()`
4051: @*/
4052: PetscErrorCode DMSetType(DM dm, DMType method)
4053: {
4054: PetscErrorCode (*r)(DM);
4055: PetscBool match;
4057: PetscFunctionBegin;
4059: PetscCall(PetscObjectTypeCompare((PetscObject)dm, method, &match));
4060: if (match) PetscFunctionReturn(PETSC_SUCCESS);
4062: PetscCall(DMRegisterAll());
4063: PetscCall(PetscFunctionListFind(DMList, method, &r));
4064: PetscCheck(r, PetscObjectComm((PetscObject)dm), PETSC_ERR_ARG_UNKNOWN_TYPE, "Unknown DM type: %s", method);
4066: PetscTryTypeMethod(dm, destroy);
4067: PetscCall(PetscMemzero(dm->ops, sizeof(*dm->ops)));
4068: PetscCall(PetscObjectChangeTypeName((PetscObject)dm, method));
4069: PetscCall((*r)(dm));
4070: PetscFunctionReturn(PETSC_SUCCESS);
4071: }
4073: /*@
4074: DMGetType - Gets the `DM` type name (as a string) from the `DM`.
4076: Not Collective
4078: Input Parameter:
4079: . dm - The `DM`
4081: Output Parameter:
4082: . type - The `DMType` name
4084: Level: intermediate
4086: Note:
4087: `type` should not be retained for later use as it will be an invalid pointer if the `DMType` of `dm` is changed.
4089: .seealso: [](ch_dmbase), `DM`, `DMType`, `DMDA`, `DMPLEX`, `DMSetType()`, `DMCreate()`, `PetscObjectTypeCompare()`, `PetscObjectTypeCompareAny()`
4090: @*/
4091: PetscErrorCode DMGetType(DM dm, DMType *type)
4092: {
4093: PetscFunctionBegin;
4095: PetscAssertPointer(type, 2);
4096: PetscCall(DMRegisterAll());
4097: *type = ((PetscObject)dm)->type_name;
4098: PetscFunctionReturn(PETSC_SUCCESS);
4099: }
4101: /*@
4102: DMConvert - Converts a `DM` to another `DM`, either of the same or different type.
4104: Collective
4106: Input Parameters:
4107: + dm - the `DM`
4108: - newtype - new `DM` type (use "same" for the same type)
4110: Output Parameter:
4111: . M - pointer to new `DM`
4113: Level: intermediate
4115: Note:
4116: Cannot be used to convert a sequential `DM` to a parallel or a parallel to sequential,
4117: the MPI communicator of the generated `DM` is always the same as the communicator
4118: of the input `DM`.
4120: .seealso: [](ch_dmbase), `DM`, `DMSetType()`, `DMCreate()`, `DMClone()`
4121: @*/
4122: PetscErrorCode DMConvert(DM dm, DMType newtype, DM *M)
4123: {
4124: DM B;
4125: char convname[256];
4126: PetscBool sametype /*, issame */;
4128: PetscFunctionBegin;
4131: PetscAssertPointer(M, 3);
4132: PetscCall(PetscObjectTypeCompare((PetscObject)dm, newtype, &sametype));
4133: /* PetscCall(PetscStrcmp(newtype, "same", &issame)); */
4134: if (sametype) {
4135: *M = dm;
4136: PetscCall(PetscObjectReference((PetscObject)dm));
4137: PetscFunctionReturn(PETSC_SUCCESS);
4138: } else {
4139: PetscErrorCode (*conv)(DM, DMType, DM *) = NULL;
4141: /*
4142: Order of precedence:
4143: 1) See if a specialized converter is known to the current DM.
4144: 2) See if a specialized converter is known to the desired DM class.
4145: 3) See if a good general converter is registered for the desired class
4146: 4) See if a good general converter is known for the current matrix.
4147: 5) Use a really basic converter.
4148: */
4150: /* 1) See if a specialized converter is known to the current DM and the desired class */
4151: PetscCall(PetscStrncpy(convname, "DMConvert_", sizeof(convname)));
4152: PetscCall(PetscStrlcat(convname, ((PetscObject)dm)->type_name, sizeof(convname)));
4153: PetscCall(PetscStrlcat(convname, "_", sizeof(convname)));
4154: PetscCall(PetscStrlcat(convname, newtype, sizeof(convname)));
4155: PetscCall(PetscStrlcat(convname, "_C", sizeof(convname)));
4156: PetscCall(PetscObjectQueryFunction((PetscObject)dm, convname, &conv));
4157: if (conv) goto foundconv;
4159: /* 2) See if a specialized converter is known to the desired DM class. */
4160: PetscCall(DMCreate(PetscObjectComm((PetscObject)dm), &B));
4161: PetscCall(DMSetType(B, newtype));
4162: PetscCall(PetscStrncpy(convname, "DMConvert_", sizeof(convname)));
4163: PetscCall(PetscStrlcat(convname, ((PetscObject)dm)->type_name, sizeof(convname)));
4164: PetscCall(PetscStrlcat(convname, "_", sizeof(convname)));
4165: PetscCall(PetscStrlcat(convname, newtype, sizeof(convname)));
4166: PetscCall(PetscStrlcat(convname, "_C", sizeof(convname)));
4167: PetscCall(PetscObjectQueryFunction((PetscObject)B, convname, &conv));
4168: if (conv) {
4169: PetscCall(DMDestroy(&B));
4170: goto foundconv;
4171: }
4173: #if 0
4174: /* 3) See if a good general converter is registered for the desired class */
4175: conv = B->ops->convertfrom;
4176: PetscCall(DMDestroy(&B));
4177: if (conv) goto foundconv;
4179: /* 4) See if a good general converter is known for the current matrix */
4180: if (dm->ops->convert) conv = dm->ops->convert;
4181: if (conv) goto foundconv;
4182: #endif
4184: /* 5) Use a really basic converter. */
4185: SETERRQ(PetscObjectComm((PetscObject)dm), PETSC_ERR_SUP, "No conversion possible between DM types %s and %s", ((PetscObject)dm)->type_name, newtype);
4187: foundconv:
4188: PetscCall(PetscLogEventBegin(DM_Convert, dm, 0, 0, 0));
4189: PetscCall((*conv)(dm, newtype, M));
4190: /* Things that are independent of DM type: We should consult DMClone() here */
4191: {
4192: const PetscReal *maxCell, *Lstart, *L;
4194: PetscCall(DMGetPeriodicity(dm, &maxCell, &Lstart, &L));
4195: PetscCall(DMSetPeriodicity(*M, maxCell, Lstart, L));
4196: (*M)->prealloc_only = dm->prealloc_only;
4197: PetscCall(PetscFree((*M)->vectype));
4198: PetscCall(PetscStrallocpy(dm->vectype, (char **)&(*M)->vectype));
4199: PetscCall(PetscFree((*M)->mattype));
4200: PetscCall(PetscStrallocpy(dm->mattype, (char **)&(*M)->mattype));
4201: }
4202: PetscCall(PetscLogEventEnd(DM_Convert, dm, 0, 0, 0));
4203: }
4204: PetscCall(PetscObjectStateIncrease((PetscObject)*M));
4205: PetscFunctionReturn(PETSC_SUCCESS);
4206: }
4208: /*@C
4209: DMRegister - Adds a new `DM` type implementation
4211: Not Collective, No Fortran Support
4213: Input Parameters:
4214: + sname - The name of a new user-defined creation routine
4215: - function - The creation routine itself
4217: Calling sequence of function:
4218: . dm - the new `DM` that is being created
4220: Level: advanced
4222: Note:
4223: `DMRegister()` may be called multiple times to add several user-defined `DM`s
4225: Example Usage:
4226: .vb
4227: DMRegister("my_da", MyDMCreate);
4228: .ve
4230: Then, your `DM` type can be chosen with the procedural interface via
4231: .vb
4232: DMCreate(MPI_Comm, DM *);
4233: DMSetType(DM,"my_da");
4234: .ve
4235: or at runtime via the option
4236: .vb
4237: -da_type my_da
4238: .ve
4240: .seealso: [](ch_dmbase), `DM`, `DMType`, `DMSetType()`, `DMRegisterAll()`, `DMRegisterDestroy()`
4241: @*/
4242: PetscErrorCode DMRegister(const char sname[], PetscErrorCode (*function)(DM dm))
4243: {
4244: PetscFunctionBegin;
4245: PetscCall(DMInitializePackage());
4246: PetscCall(PetscFunctionListAdd(&DMList, sname, function));
4247: PetscFunctionReturn(PETSC_SUCCESS);
4248: }
4250: /*@
4251: DMLoad - Loads a DM that has been stored in binary with `DMView()`.
4253: Collective
4255: Input Parameters:
4256: + newdm - the newly loaded `DM`, this needs to have been created with `DMCreate()` or
4257: some related function before a call to `DMLoad()`.
4258: - viewer - binary file viewer, obtained from `PetscViewerBinaryOpen()` or
4259: `PETSCVIEWERHDF5` file viewer, obtained from `PetscViewerHDF5Open()`
4261: Level: intermediate
4263: Notes:
4264: The type is determined by the data in the file, any type set into the DM before this call is ignored.
4266: Using `PETSCVIEWERHDF5` type with `PETSC_VIEWER_HDF5_PETSC` format, one can save multiple `DMPLEX`
4267: meshes in a single HDF5 file. This in turn requires one to name the `DMPLEX` object with `PetscObjectSetName()`
4268: before saving it with `DMView()` and before loading it with `DMLoad()` for identification of the mesh object.
4270: .seealso: [](ch_dmbase), `DM`, `PetscViewerBinaryOpen()`, `DMView()`, `MatLoad()`, `VecLoad()`
4271: @*/
4272: PetscErrorCode DMLoad(DM newdm, PetscViewer viewer)
4273: {
4274: PetscBool isbinary, ishdf5;
4276: PetscFunctionBegin;
4279: PetscCall(PetscViewerCheckReadable(viewer));
4280: PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERBINARY, &isbinary));
4281: PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERHDF5, &ishdf5));
4282: PetscCall(PetscLogEventBegin(DM_Load, viewer, 0, 0, 0));
4283: if (isbinary) {
4284: PetscInt classid;
4285: char type[256];
4287: PetscCall(PetscViewerBinaryRead(viewer, &classid, 1, NULL, PETSC_INT));
4288: PetscCheck(classid == DM_FILE_CLASSID, PetscObjectComm((PetscObject)newdm), PETSC_ERR_ARG_WRONG, "Not DM next in file, classid found %" PetscInt_FMT, classid);
4289: PetscCall(PetscViewerBinaryRead(viewer, type, 256, NULL, PETSC_CHAR));
4290: PetscCall(DMSetType(newdm, type));
4291: PetscTryTypeMethod(newdm, load, viewer);
4292: } else if (ishdf5) {
4293: PetscTryTypeMethod(newdm, load, viewer);
4294: } else SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Invalid viewer; open viewer with PetscViewerBinaryOpen() or PetscViewerHDF5Open()");
4295: PetscCall(PetscLogEventEnd(DM_Load, viewer, 0, 0, 0));
4296: PetscFunctionReturn(PETSC_SUCCESS);
4297: }
4299: /* FEM Support */
4301: PetscErrorCode DMPrintCellIndices(PetscInt c, const char name[], PetscInt len, const PetscInt x[])
4302: {
4303: PetscInt f;
4305: PetscFunctionBegin;
4306: PetscCall(PetscPrintf(PETSC_COMM_SELF, "Cell %" PetscInt_FMT " Element %s\n", c, name));
4307: for (f = 0; f < len; ++f) PetscCall(PetscPrintf(PETSC_COMM_SELF, " | %" PetscInt_FMT " |\n", x[f]));
4308: PetscFunctionReturn(PETSC_SUCCESS);
4309: }
4311: PetscErrorCode DMPrintCellVector(PetscInt c, const char name[], PetscInt len, const PetscScalar x[])
4312: {
4313: PetscInt f;
4315: PetscFunctionBegin;
4316: PetscCall(PetscPrintf(PETSC_COMM_SELF, "Cell %" PetscInt_FMT " Element %s\n", c, name));
4317: for (f = 0; f < len; ++f) PetscCall(PetscPrintf(PETSC_COMM_SELF, " | %g |\n", (double)PetscRealPart(x[f])));
4318: PetscFunctionReturn(PETSC_SUCCESS);
4319: }
4321: PetscErrorCode DMPrintCellVectorReal(PetscInt c, const char name[], PetscInt len, const PetscReal x[])
4322: {
4323: PetscFunctionBegin;
4324: PetscCall(PetscPrintf(PETSC_COMM_SELF, "Cell %" PetscInt_FMT " Element %s\n", c, name));
4325: for (PetscInt f = 0; f < len; ++f) PetscCall(PetscPrintf(PETSC_COMM_SELF, " | %g |\n", (double)x[f]));
4326: PetscFunctionReturn(PETSC_SUCCESS);
4327: }
4329: PetscErrorCode DMPrintCellMatrix(PetscInt c, const char name[], PetscInt rows, PetscInt cols, const PetscScalar A[])
4330: {
4331: PetscFunctionBegin;
4332: PetscCall(PetscPrintf(PETSC_COMM_SELF, "Cell %" PetscInt_FMT " Element %s\n", c, name));
4333: for (PetscInt f = 0; f < rows; ++f) {
4334: PetscCall(PetscPrintf(PETSC_COMM_SELF, " |"));
4335: for (PetscInt g = 0; g < cols; ++g) PetscCall(PetscPrintf(PETSC_COMM_SELF, " % 9.5g", (double)PetscRealPart(A[f * cols + g])));
4336: PetscCall(PetscPrintf(PETSC_COMM_SELF, " |\n"));
4337: }
4338: PetscFunctionReturn(PETSC_SUCCESS);
4339: }
4341: PetscErrorCode DMPrintLocalVec(DM dm, const char name[], PetscReal tol, Vec X)
4342: {
4343: PetscInt localSize, bs;
4344: PetscMPIInt size;
4345: Vec x, xglob;
4346: const PetscScalar *xarray;
4348: PetscFunctionBegin;
4349: PetscCallMPI(MPI_Comm_size(PetscObjectComm((PetscObject)dm), &size));
4350: PetscCall(VecDuplicate(X, &x));
4351: PetscCall(VecCopy(X, x));
4352: PetscCall(VecFilter(x, tol));
4353: PetscCall(PetscPrintf(PetscObjectComm((PetscObject)dm), "%s:\n", name));
4354: if (size > 1) {
4355: PetscCall(VecGetLocalSize(x, &localSize));
4356: PetscCall(VecGetArrayRead(x, &xarray));
4357: PetscCall(VecGetBlockSize(x, &bs));
4358: PetscCall(VecCreateMPIWithArray(PetscObjectComm((PetscObject)dm), bs, localSize, PETSC_DETERMINE, xarray, &xglob));
4359: } else {
4360: xglob = x;
4361: }
4362: PetscCall(VecView(xglob, PETSC_VIEWER_STDOUT_(PetscObjectComm((PetscObject)dm))));
4363: if (size > 1) {
4364: PetscCall(VecDestroy(&xglob));
4365: PetscCall(VecRestoreArrayRead(x, &xarray));
4366: }
4367: PetscCall(VecDestroy(&x));
4368: PetscFunctionReturn(PETSC_SUCCESS);
4369: }
4371: PetscErrorCode DMViewDSFromOptions_Internal(DM dm, const char opt[])
4372: {
4373: PetscObject obj = (PetscObject)dm;
4374: PetscViewer viewer;
4375: PetscViewerFormat format;
4376: PetscBool flg;
4378: PetscFunctionBegin;
4379: PetscCall(PetscOptionsCreateViewer(PetscObjectComm(obj), obj->options, obj->prefix, opt, &viewer, &format, &flg));
4380: if (flg) {
4381: PetscCall(PetscViewerPushFormat(viewer, format));
4382: for (PetscInt d = 0; d < dm->Nds; ++d) PetscCall(PetscDSView(dm->probs[d].ds, viewer));
4383: PetscCall(PetscViewerFlush(viewer));
4384: PetscCall(PetscViewerPopFormat(viewer));
4385: PetscCall(PetscViewerDestroy(&viewer));
4386: }
4387: PetscFunctionReturn(PETSC_SUCCESS);
4388: }
4390: PetscErrorCode DMViewSectionFromOptions_Internal(DM dm, const char opt[])
4391: {
4392: PetscObject obj = (PetscObject)dm;
4393: PetscViewer viewer;
4394: PetscViewerFormat format;
4395: PetscBool flg;
4397: PetscFunctionBegin;
4398: PetscCall(PetscOptionsCreateViewer(PetscObjectComm(obj), obj->options, obj->prefix, opt, &viewer, &format, &flg));
4399: if (flg) {
4400: PetscCall(PetscViewerPushFormat(viewer, format));
4401: if (dm->localSection) PetscCall(PetscSectionView(dm->localSection, viewer));
4402: PetscCall(PetscViewerFlush(viewer));
4403: PetscCall(PetscViewerPopFormat(viewer));
4404: PetscCall(PetscViewerDestroy(&viewer));
4405: }
4406: PetscFunctionReturn(PETSC_SUCCESS);
4407: }
4409: /*@
4410: DMGetLocalSection - Get the `PetscSection` encoding the local data layout for the `DM`.
4412: Input Parameter:
4413: . dm - The `DM`
4415: Output Parameter:
4416: . section - The `PetscSection`
4418: Options Database Key:
4419: . -dm_petscsection_view - View the section created by the `DM`
4421: Level: intermediate
4423: Note:
4424: This gets a borrowed reference, so the user should not destroy this `PetscSection`.
4426: .seealso: [](ch_dmbase), `DM`, `DMSetLocalSection()`, `DMGetGlobalSection()`
4427: @*/
4428: PetscErrorCode DMGetLocalSection(DM dm, PetscSection *section)
4429: {
4430: PetscFunctionBegin;
4432: PetscAssertPointer(section, 2);
4433: if (!dm->localSection && dm->ops->createlocalsection) {
4434: if (dm->setfromoptionscalled) {
4435: for (PetscInt d = 0; d < dm->Nds; ++d) PetscCall(PetscDSSetFromOptions(dm->probs[d].ds));
4436: PetscCall(DMViewDSFromOptions_Internal(dm, "-dm_petscds_view"));
4437: }
4438: PetscUseTypeMethod(dm, createlocalsection);
4439: if (dm->localSection) PetscCall(PetscObjectViewFromOptions((PetscObject)dm->localSection, NULL, "-dm_petscsection_view"));
4440: }
4441: *section = dm->localSection;
4442: PetscFunctionReturn(PETSC_SUCCESS);
4443: }
4445: /*@
4446: DMSetLocalSection - Set the `PetscSection` encoding the local data layout for the `DM`.
4448: Input Parameters:
4449: + dm - The `DM`
4450: - section - The `PetscSection`
4452: Level: intermediate
4454: Note:
4455: Any existing Section will be destroyed
4457: .seealso: [](ch_dmbase), `DM`, `PetscSection`, `DMGetLocalSection()`, `DMSetGlobalSection()`
4458: @*/
4459: PetscErrorCode DMSetLocalSection(DM dm, PetscSection section)
4460: {
4461: PetscInt numFields = 0;
4463: PetscFunctionBegin;
4466: PetscCall(PetscObjectReference((PetscObject)section));
4467: PetscCall(PetscSectionDestroy(&dm->localSection));
4468: dm->localSection = section;
4469: if (section) PetscCall(PetscSectionGetNumFields(dm->localSection, &numFields));
4470: if (numFields) {
4471: PetscCall(DMSetNumFields(dm, numFields));
4472: for (PetscInt f = 0; f < numFields; ++f) {
4473: PetscObject disc;
4474: const char *name;
4476: PetscCall(PetscSectionGetFieldName(dm->localSection, f, &name));
4477: PetscCall(DMGetField(dm, f, NULL, &disc));
4478: PetscCall(PetscObjectSetName(disc, name));
4479: }
4480: }
4481: /* The global section and the SectionSF will be rebuilt
4482: in the next call to DMGetGlobalSection() and DMGetSectionSF(). */
4483: PetscCall(PetscSectionDestroy(&dm->globalSection));
4484: PetscCall(PetscSFDestroy(&dm->sectionSF));
4485: PetscCall(PetscSFCreate(PetscObjectComm((PetscObject)dm), &dm->sectionSF));
4487: /* Clear scratch vectors */
4488: PetscCall(DMClearGlobalVectors(dm));
4489: PetscCall(DMClearLocalVectors(dm));
4490: PetscCall(DMClearNamedGlobalVectors(dm));
4491: PetscCall(DMClearNamedLocalVectors(dm));
4492: PetscFunctionReturn(PETSC_SUCCESS);
4493: }
4495: /*@C
4496: DMCreateSectionPermutation - Create a permutation of the `PetscSection` chart and optionally a block structure.
4498: Input Parameter:
4499: . dm - The `DM`
4501: Output Parameters:
4502: + perm - A permutation of the mesh points in the chart
4503: - blockStarts - A high bit is set for the point that begins every block, or `NULL` for default blocking
4505: Level: developer
4507: .seealso: [](ch_dmbase), `DM`, `PetscSection`, `DMGetLocalSection()`, `DMGetGlobalSection()`
4508: @*/
4509: PetscErrorCode DMCreateSectionPermutation(DM dm, IS *perm, PetscBT *blockStarts)
4510: {
4511: PetscFunctionBegin;
4512: *perm = NULL;
4513: *blockStarts = NULL;
4514: PetscTryTypeMethod(dm, createsectionpermutation, perm, blockStarts);
4515: PetscFunctionReturn(PETSC_SUCCESS);
4516: }
4518: /*@
4519: DMGetDefaultConstraints - Get the `PetscSection` and `Mat` that specify the local constraint interpolation. See `DMSetDefaultConstraints()` for a description of the purpose of constraint interpolation.
4521: not Collective
4523: Input Parameter:
4524: . dm - The `DM`
4526: Output Parameters:
4527: + section - The `PetscSection` describing the range of the constraint matrix: relates rows of the constraint matrix to dofs of the default section. Returns `NULL` if there are no local constraints.
4528: . mat - The `Mat` that interpolates local constraints: its width should be the layout size of the default section. Returns `NULL` if there are no local constraints.
4529: - bias - Vector containing bias to be added to constrained dofs
4531: Level: advanced
4533: Note:
4534: This gets borrowed references, so the user should not destroy the `PetscSection`, `Mat`, or `Vec`.
4536: .seealso: [](ch_dmbase), `DM`, `DMSetDefaultConstraints()`
4537: @*/
4538: PetscErrorCode DMGetDefaultConstraints(DM dm, PetscSection *section, Mat *mat, Vec *bias)
4539: {
4540: PetscFunctionBegin;
4542: if (!dm->defaultConstraint.section && !dm->defaultConstraint.mat && dm->ops->createdefaultconstraints) PetscUseTypeMethod(dm, createdefaultconstraints);
4543: if (section) *section = dm->defaultConstraint.section;
4544: if (mat) *mat = dm->defaultConstraint.mat;
4545: if (bias) *bias = dm->defaultConstraint.bias;
4546: PetscFunctionReturn(PETSC_SUCCESS);
4547: }
4549: /*@
4550: DMSetDefaultConstraints - Set the `PetscSection` and `Mat` that specify the local constraint interpolation.
4552: Collective
4554: Input Parameters:
4555: + dm - The `DM`
4556: . section - The `PetscSection` describing the range of the constraint matrix: relates rows of the constraint matrix to dofs of the default section. Must have a local communicator (`PETSC_COMM_SELF` or derivative).
4557: . mat - The `Mat` that interpolates local constraints: its width should be the layout size of the default section: `NULL` indicates no constraints. Must have a local communicator (`PETSC_COMM_SELF` or derivative).
4558: - bias - A bias vector to be added to constrained values in the local vector. `NULL` indicates no bias. Must have a local communicator (`PETSC_COMM_SELF` or derivative).
4560: Level: advanced
4562: Notes:
4563: If a constraint matrix is specified, then it is applied during `DMGlobalToLocalEnd()` when mode is `INSERT_VALUES`, `INSERT_BC_VALUES`, or `INSERT_ALL_VALUES`. Without a constraint matrix, the local vector l returned by `DMGlobalToLocalEnd()` contains values that have been scattered from a global vector without modification; with a constraint matrix A, l is modified by computing c = A * l + bias, l[s[i]] = c[i], where the scatter s is defined by the `PetscSection` returned by `DMGetDefaultConstraints()`.
4565: If a constraint matrix is specified, then its adjoint is applied during `DMLocalToGlobalBegin()` when mode is `ADD_VALUES`, `ADD_BC_VALUES`, or `ADD_ALL_VALUES`. Without a constraint matrix, the local vector l is accumulated into a global vector without modification; with a constraint matrix A, l is first modified by computing c[i] = l[s[i]], l[s[i]] = 0, l = l + A'*c, which is the adjoint of the operation described above. Any bias, if specified, is ignored when accumulating.
4567: This increments the references of the `PetscSection`, `Mat`, and `Vec`, so they user can destroy them.
4569: .seealso: [](ch_dmbase), `DM`, `DMGetDefaultConstraints()`
4570: @*/
4571: PetscErrorCode DMSetDefaultConstraints(DM dm, PetscSection section, Mat mat, Vec bias)
4572: {
4573: PetscMPIInt result;
4575: PetscFunctionBegin;
4577: if (section) {
4579: PetscCallMPI(MPI_Comm_compare(PETSC_COMM_SELF, PetscObjectComm((PetscObject)section), &result));
4580: PetscCheck(result == MPI_CONGRUENT || result == MPI_IDENT, PETSC_COMM_SELF, PETSC_ERR_ARG_NOTSAMECOMM, "constraint section must have local communicator");
4581: }
4582: if (mat) {
4584: PetscCallMPI(MPI_Comm_compare(PETSC_COMM_SELF, PetscObjectComm((PetscObject)mat), &result));
4585: PetscCheck(result == MPI_CONGRUENT || result == MPI_IDENT, PETSC_COMM_SELF, PETSC_ERR_ARG_NOTSAMECOMM, "constraint matrix must have local communicator");
4586: }
4587: if (bias) {
4589: PetscCallMPI(MPI_Comm_compare(PETSC_COMM_SELF, PetscObjectComm((PetscObject)bias), &result));
4590: PetscCheck(result == MPI_CONGRUENT || result == MPI_IDENT, PETSC_COMM_SELF, PETSC_ERR_ARG_NOTSAMECOMM, "constraint bias must have local communicator");
4591: }
4592: PetscCall(PetscObjectReference((PetscObject)section));
4593: PetscCall(PetscSectionDestroy(&dm->defaultConstraint.section));
4594: dm->defaultConstraint.section = section;
4595: PetscCall(PetscObjectReference((PetscObject)mat));
4596: PetscCall(MatDestroy(&dm->defaultConstraint.mat));
4597: dm->defaultConstraint.mat = mat;
4598: PetscCall(PetscObjectReference((PetscObject)bias));
4599: PetscCall(VecDestroy(&dm->defaultConstraint.bias));
4600: dm->defaultConstraint.bias = bias;
4601: PetscFunctionReturn(PETSC_SUCCESS);
4602: }
4604: #if defined(PETSC_USE_DEBUG)
4605: /*
4606: DMDefaultSectionCheckConsistency - Check the consistentcy of the global and local sections. Generates and error if they are not consistent.
4608: Input Parameters:
4609: + dm - The `DM`
4610: . localSection - `PetscSection` describing the local data layout
4611: - globalSection - `PetscSection` describing the global data layout
4613: Level: intermediate
4615: .seealso: [](ch_dmbase), `DM`, `DMGetSectionSF()`, `DMSetSectionSF()`
4616: */
4617: static PetscErrorCode DMDefaultSectionCheckConsistency_Internal(DM dm, PetscSection localSection, PetscSection globalSection)
4618: {
4619: MPI_Comm comm;
4620: PetscLayout layout;
4621: const PetscInt *ranges;
4622: PetscInt pStart, pEnd, p, nroots;
4623: PetscMPIInt size, rank;
4624: PetscBool valid = PETSC_TRUE, gvalid;
4626: PetscFunctionBegin;
4627: PetscCall(PetscObjectGetComm((PetscObject)dm, &comm));
4629: PetscCallMPI(MPI_Comm_size(comm, &size));
4630: PetscCallMPI(MPI_Comm_rank(comm, &rank));
4631: PetscCall(PetscSectionGetChart(globalSection, &pStart, &pEnd));
4632: PetscCall(PetscSectionGetConstrainedStorageSize(globalSection, &nroots));
4633: PetscCall(PetscLayoutCreate(comm, &layout));
4634: PetscCall(PetscLayoutSetBlockSize(layout, 1));
4635: PetscCall(PetscLayoutSetLocalSize(layout, nroots));
4636: PetscCall(PetscLayoutSetUp(layout));
4637: PetscCall(PetscLayoutGetRanges(layout, &ranges));
4638: for (p = pStart; p < pEnd; ++p) {
4639: PetscInt dof, cdof, off, gdof, gcdof, goff, gsize, d;
4641: PetscCall(PetscSectionGetDof(localSection, p, &dof));
4642: PetscCall(PetscSectionGetOffset(localSection, p, &off));
4643: PetscCall(PetscSectionGetConstraintDof(localSection, p, &cdof));
4644: PetscCall(PetscSectionGetDof(globalSection, p, &gdof));
4645: PetscCall(PetscSectionGetConstraintDof(globalSection, p, &gcdof));
4646: PetscCall(PetscSectionGetOffset(globalSection, p, &goff));
4647: if (!gdof) continue; /* Censored point */
4648: if ((gdof < 0 ? -(gdof + 1) : gdof) != dof) {
4649: PetscCall(PetscSynchronizedPrintf(comm, "[%d]Global dof %" PetscInt_FMT " for point %" PetscInt_FMT " not equal to local dof %" PetscInt_FMT "\n", rank, gdof, p, dof));
4650: valid = PETSC_FALSE;
4651: }
4652: if (gcdof && (gcdof != cdof)) {
4653: PetscCall(PetscSynchronizedPrintf(comm, "[%d]Global constraints %" PetscInt_FMT " for point %" PetscInt_FMT " not equal to local constraints %" PetscInt_FMT "\n", rank, gcdof, p, cdof));
4654: valid = PETSC_FALSE;
4655: }
4656: if (gdof < 0) {
4657: gsize = gdof < 0 ? -(gdof + 1) - gcdof : gdof - gcdof;
4658: for (d = 0; d < gsize; ++d) {
4659: PetscInt offset = -(goff + 1) + d, r;
4661: PetscCall(PetscFindInt(offset, size + 1, ranges, &r));
4662: if (r < 0) r = -(r + 2);
4663: if ((r < 0) || (r >= size)) {
4664: PetscCall(PetscSynchronizedPrintf(comm, "[%d]Point %" PetscInt_FMT " mapped to invalid process %" PetscInt_FMT " (%" PetscInt_FMT ", %" PetscInt_FMT ")\n", rank, p, r, gdof, goff));
4665: valid = PETSC_FALSE;
4666: break;
4667: }
4668: }
4669: }
4670: }
4671: PetscCall(PetscLayoutDestroy(&layout));
4672: PetscCall(PetscSynchronizedFlush(comm, NULL));
4673: PetscCallMPI(MPIU_Allreduce(&valid, &gvalid, 1, MPI_C_BOOL, MPI_LAND, comm));
4674: if (!gvalid) {
4675: PetscCall(DMView(dm, NULL));
4676: SETERRQ(comm, PETSC_ERR_ARG_WRONG, "Inconsistent local and global sections");
4677: }
4678: PetscFunctionReturn(PETSC_SUCCESS);
4679: }
4680: #endif
4682: PetscErrorCode DMGetIsoperiodicPointSF_Internal(DM dm, PetscSF *sf)
4683: {
4684: PetscErrorCode (*f)(DM, PetscSF *);
4686: PetscFunctionBegin;
4688: PetscAssertPointer(sf, 2);
4689: PetscCall(PetscObjectQueryFunction((PetscObject)dm, "DMGetIsoperiodicPointSF_C", &f));
4690: if (f) PetscCall(f(dm, sf));
4691: else *sf = dm->sf;
4692: PetscFunctionReturn(PETSC_SUCCESS);
4693: }
4695: /*@
4696: DMGetGlobalSection - Get the `PetscSection` encoding the global data layout for the `DM`.
4698: Collective
4700: Input Parameter:
4701: . dm - The `DM`
4703: Output Parameter:
4704: . section - The `PetscSection`
4706: Level: intermediate
4708: Note:
4709: This gets a borrowed reference, so the user should not destroy this `PetscSection`.
4711: .seealso: [](ch_dmbase), `DM`, `DMSetLocalSection()`, `DMGetLocalSection()`
4712: @*/
4713: PetscErrorCode DMGetGlobalSection(DM dm, PetscSection *section)
4714: {
4715: PetscFunctionBegin;
4717: PetscAssertPointer(section, 2);
4718: if (!dm->globalSection) {
4719: PetscSection s;
4720: PetscSF sf;
4722: PetscCall(DMGetLocalSection(dm, &s));
4723: PetscCheck(s, PetscObjectComm((PetscObject)dm), PETSC_ERR_ARG_WRONGSTATE, "DM must have a default PetscSection in order to create a global PetscSection");
4724: PetscCheck(dm->sf, PetscObjectComm((PetscObject)dm), PETSC_ERR_ARG_WRONGSTATE, "DM must have a point PetscSF in order to create a global PetscSection");
4725: PetscCall(DMGetIsoperiodicPointSF_Internal(dm, &sf));
4726: PetscCall(PetscSectionCreateGlobalSection(s, sf, PETSC_TRUE, PETSC_FALSE, PETSC_FALSE, &dm->globalSection));
4727: PetscCall(PetscLayoutDestroy(&dm->map));
4728: PetscCall(PetscSectionGetValueLayout(PetscObjectComm((PetscObject)dm), dm->globalSection, &dm->map));
4729: PetscCall(PetscSectionViewFromOptions(dm->globalSection, NULL, "-global_section_view"));
4730: }
4731: *section = dm->globalSection;
4732: PetscFunctionReturn(PETSC_SUCCESS);
4733: }
4735: /*@
4736: DMSetGlobalSection - Set the `PetscSection` encoding the global data layout for the `DM`.
4738: Input Parameters:
4739: + dm - The `DM`
4740: - section - The PetscSection, or `NULL`
4742: Level: intermediate
4744: Note:
4745: Any existing `PetscSection` will be destroyed
4747: .seealso: [](ch_dmbase), `DM`, `DMGetGlobalSection()`, `DMSetLocalSection()`
4748: @*/
4749: PetscErrorCode DMSetGlobalSection(DM dm, PetscSection section)
4750: {
4751: PetscFunctionBegin;
4754: PetscCall(PetscObjectReference((PetscObject)section));
4755: PetscCall(PetscSectionDestroy(&dm->globalSection));
4756: dm->globalSection = section;
4757: #if defined(PETSC_USE_DEBUG)
4758: if (section) PetscCall(DMDefaultSectionCheckConsistency_Internal(dm, dm->localSection, section));
4759: #endif
4760: /* Clear global scratch vectors and sectionSF */
4761: PetscCall(PetscSFDestroy(&dm->sectionSF));
4762: PetscCall(PetscSFCreate(PetscObjectComm((PetscObject)dm), &dm->sectionSF));
4763: PetscCall(DMClearGlobalVectors(dm));
4764: PetscCall(DMClearNamedGlobalVectors(dm));
4765: PetscFunctionReturn(PETSC_SUCCESS);
4766: }
4768: /*@
4769: DMGetSectionSF - Get the `PetscSF` encoding the parallel dof overlap for the `DM`. If it has not been set,
4770: it is created from the default `PetscSection` layouts in the `DM`.
4772: Input Parameter:
4773: . dm - The `DM`
4775: Output Parameter:
4776: . sf - The `PetscSF`
4778: Level: intermediate
4780: Note:
4781: This gets a borrowed reference, so the user should not destroy this `PetscSF`.
4783: .seealso: [](ch_dmbase), `DM`, `DMSetSectionSF()`, `DMCreateSectionSF()`
4784: @*/
4785: PetscErrorCode DMGetSectionSF(DM dm, PetscSF *sf)
4786: {
4787: PetscInt nroots;
4789: PetscFunctionBegin;
4791: PetscAssertPointer(sf, 2);
4792: if (!dm->sectionSF) PetscCall(PetscSFCreate(PetscObjectComm((PetscObject)dm), &dm->sectionSF));
4793: PetscCall(PetscSFGetGraph(dm->sectionSF, &nroots, NULL, NULL, NULL));
4794: if (nroots < 0) {
4795: PetscSection section, gSection;
4797: PetscCall(DMGetLocalSection(dm, §ion));
4798: if (section) {
4799: PetscCall(DMGetGlobalSection(dm, &gSection));
4800: PetscCall(DMCreateSectionSF(dm, section, gSection));
4801: } else {
4802: *sf = NULL;
4803: PetscFunctionReturn(PETSC_SUCCESS);
4804: }
4805: }
4806: *sf = dm->sectionSF;
4807: PetscFunctionReturn(PETSC_SUCCESS);
4808: }
4810: /*@
4811: DMSetSectionSF - Set the `PetscSF` encoding the parallel dof overlap for the `DM`
4813: Input Parameters:
4814: + dm - The `DM`
4815: - sf - The `PetscSF`
4817: Level: intermediate
4819: Note:
4820: Any previous `PetscSF` is destroyed
4822: .seealso: [](ch_dmbase), `DM`, `DMGetSectionSF()`, `DMCreateSectionSF()`
4823: @*/
4824: PetscErrorCode DMSetSectionSF(DM dm, PetscSF sf)
4825: {
4826: PetscFunctionBegin;
4829: PetscCall(PetscObjectReference((PetscObject)sf));
4830: PetscCall(PetscSFDestroy(&dm->sectionSF));
4831: dm->sectionSF = sf;
4832: PetscFunctionReturn(PETSC_SUCCESS);
4833: }
4835: /*@
4836: DMCreateSectionSF - Create the `PetscSF` encoding the parallel dof overlap for the `DM` based upon the `PetscSection`s
4837: describing the data layout.
4839: Input Parameters:
4840: + dm - The `DM`
4841: . localSection - `PetscSection` describing the local data layout
4842: - globalSection - `PetscSection` describing the global data layout
4844: Level: developer
4846: Note:
4847: One usually uses `DMGetSectionSF()` to obtain the `PetscSF`
4849: Developer Note:
4850: Since this routine has for arguments the two sections from the `DM` and puts the resulting `PetscSF`
4851: directly into the `DM`, perhaps this function should not take the local and global sections as
4852: input and should just obtain them from the `DM`? Plus PETSc creation functions return the thing
4853: they create, this returns nothing
4855: .seealso: [](ch_dmbase), `DM`, `DMGetSectionSF()`, `DMSetSectionSF()`, `DMGetLocalSection()`, `DMGetGlobalSection()`
4856: @*/
4857: PetscErrorCode DMCreateSectionSF(DM dm, PetscSection localSection, PetscSection globalSection)
4858: {
4859: PetscFunctionBegin;
4861: PetscCall(PetscSFSetGraphSection(dm->sectionSF, localSection, globalSection));
4862: PetscFunctionReturn(PETSC_SUCCESS);
4863: }
4865: /*@
4866: DMGetPointSF - Get the `PetscSF` encoding the parallel section point overlap for the `DM`.
4868: Not collective but the resulting `PetscSF` is collective
4870: Input Parameter:
4871: . dm - The `DM`
4873: Output Parameter:
4874: . sf - The `PetscSF`
4876: Level: intermediate
4878: Note:
4879: This gets a borrowed reference, so the user should not destroy this `PetscSF`.
4881: .seealso: [](ch_dmbase), `DM`, `DMSetPointSF()`, `DMGetSectionSF()`, `DMSetSectionSF()`, `DMCreateSectionSF()`
4882: @*/
4883: PetscErrorCode DMGetPointSF(DM dm, PetscSF *sf)
4884: {
4885: PetscFunctionBegin;
4887: PetscAssertPointer(sf, 2);
4888: *sf = dm->sf;
4889: PetscFunctionReturn(PETSC_SUCCESS);
4890: }
4892: /*@
4893: DMSetPointSF - Set the `PetscSF` encoding the parallel section point overlap for the `DM`.
4895: Collective
4897: Input Parameters:
4898: + dm - The `DM`
4899: - sf - The `PetscSF`
4901: Level: intermediate
4903: .seealso: [](ch_dmbase), `DM`, `DMGetPointSF()`, `DMGetSectionSF()`, `DMSetSectionSF()`, `DMCreateSectionSF()`
4904: @*/
4905: PetscErrorCode DMSetPointSF(DM dm, PetscSF sf)
4906: {
4907: PetscFunctionBegin;
4910: PetscCall(PetscObjectReference((PetscObject)sf));
4911: PetscCall(PetscSFDestroy(&dm->sf));
4912: dm->sf = sf;
4913: PetscFunctionReturn(PETSC_SUCCESS);
4914: }
4916: /*@
4917: DMGetNaturalSF - Get the `PetscSF` encoding the map back to the original mesh ordering
4919: Input Parameter:
4920: . dm - The `DM`
4922: Output Parameter:
4923: . sf - The `PetscSF`
4925: Level: intermediate
4927: Note:
4928: This gets a borrowed reference, so the user should not destroy this `PetscSF`.
4930: .seealso: [](ch_dmbase), `DM`, `DMSetNaturalSF()`, `DMSetUseNatural()`, `DMGetUseNatural()`, `DMPlexCreateGlobalToNaturalSF()`, `DMPlexDistribute()`
4931: @*/
4932: PetscErrorCode DMGetNaturalSF(DM dm, PetscSF *sf)
4933: {
4934: PetscFunctionBegin;
4936: PetscAssertPointer(sf, 2);
4937: *sf = dm->sfNatural;
4938: PetscFunctionReturn(PETSC_SUCCESS);
4939: }
4941: /*@
4942: DMSetNaturalSF - Set the PetscSF encoding the map back to the original mesh ordering
4944: Input Parameters:
4945: + dm - The DM
4946: - sf - The PetscSF
4948: Level: intermediate
4950: .seealso: [](ch_dmbase), `DM`, `DMGetNaturalSF()`, `DMSetUseNatural()`, `DMGetUseNatural()`, `DMPlexCreateGlobalToNaturalSF()`, `DMPlexDistribute()`
4951: @*/
4952: PetscErrorCode DMSetNaturalSF(DM dm, PetscSF sf)
4953: {
4954: PetscFunctionBegin;
4957: PetscCall(PetscObjectReference((PetscObject)sf));
4958: PetscCall(PetscSFDestroy(&dm->sfNatural));
4959: dm->sfNatural = sf;
4960: PetscFunctionReturn(PETSC_SUCCESS);
4961: }
4963: static PetscErrorCode DMSetDefaultAdjacency_Private(DM dm, PetscInt f, PetscObject disc)
4964: {
4965: PetscClassId id;
4967: PetscFunctionBegin;
4968: PetscCall(PetscObjectGetClassId(disc, &id));
4969: if (id == PETSCFE_CLASSID) PetscCall(DMSetAdjacency(dm, f, PETSC_FALSE, PETSC_TRUE));
4970: else if (id == PETSCFV_CLASSID) PetscCall(DMSetAdjacency(dm, f, PETSC_TRUE, PETSC_FALSE));
4971: else PetscCall(DMSetAdjacency(dm, f, PETSC_FALSE, PETSC_TRUE));
4972: PetscFunctionReturn(PETSC_SUCCESS);
4973: }
4975: static PetscErrorCode DMFieldEnlarge_Static(DM dm, PetscInt NfNew)
4976: {
4977: RegionField *tmpr;
4978: PetscInt Nf = dm->Nf, f;
4980: PetscFunctionBegin;
4981: if (Nf >= NfNew) PetscFunctionReturn(PETSC_SUCCESS);
4982: PetscCall(PetscMalloc1(NfNew, &tmpr));
4983: for (f = 0; f < Nf; ++f) tmpr[f] = dm->fields[f];
4984: for (f = Nf; f < NfNew; ++f) {
4985: tmpr[f].disc = NULL;
4986: tmpr[f].label = NULL;
4987: tmpr[f].avoidTensor = PETSC_FALSE;
4988: }
4989: PetscCall(PetscFree(dm->fields));
4990: dm->Nf = NfNew;
4991: dm->fields = tmpr;
4992: PetscFunctionReturn(PETSC_SUCCESS);
4993: }
4995: /*@
4996: DMClearFields - Remove all fields from the `DM`
4998: Logically Collective
5000: Input Parameter:
5001: . dm - The `DM`
5003: Level: intermediate
5005: .seealso: [](ch_dmbase), `DM`, `DMGetNumFields()`, `DMSetNumFields()`, `DMSetField()`
5006: @*/
5007: PetscErrorCode DMClearFields(DM dm)
5008: {
5009: PetscInt f;
5011: PetscFunctionBegin;
5013: if (!dm->fields) PetscFunctionReturn(PETSC_SUCCESS); // DMDA does not use fields field in DM
5014: for (f = 0; f < dm->Nf; ++f) {
5015: PetscCall(PetscObjectDestroy(&dm->fields[f].disc));
5016: PetscCall(DMLabelDestroy(&dm->fields[f].label));
5017: }
5018: PetscCall(PetscFree(dm->fields));
5019: dm->fields = NULL;
5020: dm->Nf = 0;
5021: PetscFunctionReturn(PETSC_SUCCESS);
5022: }
5024: /*@
5025: DMGetNumFields - Get the number of fields in the `DM`
5027: Not Collective
5029: Input Parameter:
5030: . dm - The `DM`
5032: Output Parameter:
5033: . numFields - The number of fields
5035: Level: intermediate
5037: .seealso: [](ch_dmbase), `DM`, `DMSetNumFields()`, `DMSetField()`
5038: @*/
5039: PetscErrorCode DMGetNumFields(DM dm, PetscInt *numFields)
5040: {
5041: PetscFunctionBegin;
5043: PetscAssertPointer(numFields, 2);
5044: *numFields = dm->Nf;
5045: PetscFunctionReturn(PETSC_SUCCESS);
5046: }
5048: /*@
5049: DMSetNumFields - Set the number of fields in the `DM`
5051: Logically Collective
5053: Input Parameters:
5054: + dm - The `DM`
5055: - numFields - The number of fields
5057: Level: intermediate
5059: .seealso: [](ch_dmbase), `DM`, `DMGetNumFields()`, `DMSetField()`
5060: @*/
5061: PetscErrorCode DMSetNumFields(DM dm, PetscInt numFields)
5062: {
5063: PetscInt Nf;
5065: PetscFunctionBegin;
5067: PetscCall(DMGetNumFields(dm, &Nf));
5068: for (PetscInt f = Nf; f < numFields; ++f) {
5069: PetscContainer obj;
5071: PetscCall(PetscContainerCreate(PetscObjectComm((PetscObject)dm), &obj));
5072: PetscCall(DMAddField(dm, NULL, (PetscObject)obj));
5073: PetscCall(PetscContainerDestroy(&obj));
5074: }
5075: PetscFunctionReturn(PETSC_SUCCESS);
5076: }
5078: /*@
5079: DMGetField - Return the `DMLabel` and discretization object for a given `DM` field
5081: Not Collective
5083: Input Parameters:
5084: + dm - The `DM`
5085: - f - The field number
5087: Output Parameters:
5088: + label - The label indicating the support of the field, or `NULL` for the entire mesh (pass in `NULL` if not needed)
5089: - disc - The discretization object (pass in `NULL` if not needed)
5091: Level: intermediate
5093: .seealso: [](ch_dmbase), `DM`, `DMAddField()`, `DMSetField()`
5094: @*/
5095: PetscErrorCode DMGetField(DM dm, PetscInt f, DMLabel *label, PetscObject *disc)
5096: {
5097: PetscFunctionBegin;
5099: PetscAssertPointer(disc, 4);
5100: PetscCheck((f >= 0) && (f < dm->Nf), PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Field number %" PetscInt_FMT " must be in [0, %" PetscInt_FMT ")", f, dm->Nf);
5101: if (!dm->fields) {
5102: if (label) *label = NULL;
5103: if (disc) *disc = NULL;
5104: } else { // some DM such as DMDA do not have dm->fields
5105: if (label) *label = dm->fields[f].label;
5106: if (disc) *disc = dm->fields[f].disc;
5107: }
5108: PetscFunctionReturn(PETSC_SUCCESS);
5109: }
5111: /* Does not clear the DS */
5112: PetscErrorCode DMSetField_Internal(DM dm, PetscInt f, DMLabel label, PetscObject disc)
5113: {
5114: PetscFunctionBegin;
5115: PetscCall(DMFieldEnlarge_Static(dm, f + 1));
5116: PetscCall(DMLabelDestroy(&dm->fields[f].label));
5117: PetscCall(PetscObjectDestroy(&dm->fields[f].disc));
5118: dm->fields[f].label = label;
5119: dm->fields[f].disc = disc;
5120: PetscCall(PetscObjectReference((PetscObject)label));
5121: PetscCall(PetscObjectReference(disc));
5122: PetscFunctionReturn(PETSC_SUCCESS);
5123: }
5125: /*@
5126: DMSetField - Set the discretization object for a given `DM` field. Usually one would call `DMAddField()` which automatically handles
5127: the field numbering.
5129: Logically Collective
5131: Input Parameters:
5132: + dm - The `DM`
5133: . f - The field number
5134: . label - The label indicating the support of the field, or `NULL` for the entire mesh
5135: - disc - The discretization object
5137: Level: intermediate
5139: .seealso: [](ch_dmbase), `DM`, `DMAddField()`, `DMGetField()`
5140: @*/
5141: PetscErrorCode DMSetField(DM dm, PetscInt f, DMLabel label, PetscObject disc)
5142: {
5143: PetscFunctionBegin;
5147: PetscCheck(f >= 0, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Field number %" PetscInt_FMT " must be non-negative", f);
5148: PetscCall(DMSetField_Internal(dm, f, label, disc));
5149: PetscCall(DMSetDefaultAdjacency_Private(dm, f, disc));
5150: PetscCall(DMClearDS(dm));
5151: PetscFunctionReturn(PETSC_SUCCESS);
5152: }
5154: /*@
5155: DMAddField - Add a field to a `DM` object. A field is a function space defined by of a set of discretization points (geometric entities)
5156: and a discretization object that defines the function space associated with those points.
5158: Logically Collective
5160: Input Parameters:
5161: + dm - The `DM`
5162: . label - The label indicating the support of the field, or `NULL` for the entire mesh
5163: - disc - The discretization object
5165: Level: intermediate
5167: Notes:
5168: The label already exists or will be added to the `DM` with `DMSetLabel()`.
5170: For example, a piecewise continuous pressure field can be defined by coefficients at the cell centers of a mesh and piecewise constant functions
5171: within each cell. Thus a specific function in the space is defined by the combination of a `Vec` containing the coefficients, a `DM` defining the
5172: geometry entities, a `DMLabel` indicating a subset of those geometric entities, and a discretization object, such as a `PetscFE`.
5174: Fortran Note:
5175: Use the argument `PetscObjectCast(disc)` as the second argument
5177: .seealso: [](ch_dmbase), `DM`, `DMSetLabel()`, `DMSetField()`, `DMGetField()`, `PetscFE`
5178: @*/
5179: PetscErrorCode DMAddField(DM dm, DMLabel label, PetscObject disc)
5180: {
5181: PetscInt Nf = dm->Nf;
5183: PetscFunctionBegin;
5187: PetscCall(DMFieldEnlarge_Static(dm, Nf + 1));
5188: dm->fields[Nf].label = label;
5189: dm->fields[Nf].disc = disc;
5190: PetscCall(PetscObjectReference((PetscObject)label));
5191: PetscCall(PetscObjectReference(disc));
5192: PetscCall(DMSetDefaultAdjacency_Private(dm, Nf, disc));
5193: PetscCall(DMClearDS(dm));
5194: PetscFunctionReturn(PETSC_SUCCESS);
5195: }
5197: /*@
5198: DMSetFieldAvoidTensor - Set flag to avoid defining the field on tensor cells
5200: Logically Collective
5202: Input Parameters:
5203: + dm - The `DM`
5204: . f - The field index
5205: - avoidTensor - `PETSC_TRUE` to skip defining the field on tensor cells
5207: Level: intermediate
5209: .seealso: [](ch_dmbase), `DM`, `DMGetFieldAvoidTensor()`, `DMSetField()`, `DMGetField()`
5210: @*/
5211: PetscErrorCode DMSetFieldAvoidTensor(DM dm, PetscInt f, PetscBool avoidTensor)
5212: {
5213: PetscFunctionBegin;
5214: PetscCheck((f >= 0) && (f < dm->Nf), PetscObjectComm((PetscObject)dm), PETSC_ERR_ARG_OUTOFRANGE, "Field %" PetscInt_FMT " is not in [0, %" PetscInt_FMT ")", f, dm->Nf);
5215: dm->fields[f].avoidTensor = avoidTensor;
5216: PetscFunctionReturn(PETSC_SUCCESS);
5217: }
5219: /*@
5220: DMGetFieldAvoidTensor - Get flag to avoid defining the field on tensor cells
5222: Not Collective
5224: Input Parameters:
5225: + dm - The `DM`
5226: - f - The field index
5228: Output Parameter:
5229: . avoidTensor - The flag to avoid defining the field on tensor cells
5231: Level: intermediate
5233: .seealso: [](ch_dmbase), `DM`, `DMAddField()`, `DMSetField()`, `DMGetField()`, `DMSetFieldAvoidTensor()`
5234: @*/
5235: PetscErrorCode DMGetFieldAvoidTensor(DM dm, PetscInt f, PetscBool *avoidTensor)
5236: {
5237: PetscFunctionBegin;
5238: PetscCheck((f >= 0) && (f < dm->Nf), PetscObjectComm((PetscObject)dm), PETSC_ERR_ARG_OUTOFRANGE, "Field %" PetscInt_FMT " is not in [0, %" PetscInt_FMT ")", f, dm->Nf);
5239: *avoidTensor = dm->fields[f].avoidTensor;
5240: PetscFunctionReturn(PETSC_SUCCESS);
5241: }
5243: /*@
5244: DMCopyFields - Copy the discretizations for the `DM` into another `DM`
5246: Collective
5248: Input Parameters:
5249: + dm - The `DM`
5250: . minDegree - Minimum degree for a discretization, or `PETSC_DETERMINE` for no limit
5251: - maxDegree - Maximum degree for a discretization, or `PETSC_DETERMINE` for no limit
5253: Output Parameter:
5254: . newdm - The `DM`
5256: Level: advanced
5258: .seealso: [](ch_dmbase), `DM`, `DMGetField()`, `DMSetField()`, `DMAddField()`, `DMCopyDS()`, `DMGetDS()`, `DMGetCellDS()`
5259: @*/
5260: PetscErrorCode DMCopyFields(DM dm, PetscInt minDegree, PetscInt maxDegree, DM newdm)
5261: {
5262: PetscInt Nf;
5264: PetscFunctionBegin;
5265: if (dm == newdm) PetscFunctionReturn(PETSC_SUCCESS);
5266: PetscCall(DMGetNumFields(dm, &Nf));
5267: PetscCall(DMClearFields(newdm));
5268: for (PetscInt f = 0; f < Nf; ++f) {
5269: DMLabel label;
5270: PetscObject field;
5271: PetscClassId id;
5272: PetscBool useCone, useClosure;
5274: PetscCall(DMGetField(dm, f, &label, &field));
5275: PetscCall(PetscObjectGetClassId(field, &id));
5276: if (id == PETSCFE_CLASSID) {
5277: PetscFE newfe;
5279: PetscCall(PetscFELimitDegree((PetscFE)field, minDegree, maxDegree, &newfe));
5280: PetscCall(DMSetField(newdm, f, label, (PetscObject)newfe));
5281: PetscCall(PetscFEDestroy(&newfe));
5282: } else {
5283: PetscCall(DMSetField(newdm, f, label, field));
5284: }
5285: PetscCall(DMGetAdjacency(dm, f, &useCone, &useClosure));
5286: PetscCall(DMSetAdjacency(newdm, f, useCone, useClosure));
5287: }
5288: // Create nullspace constructor slots
5289: if (dm->nullspaceConstructors) {
5290: PetscCall(PetscFree2(newdm->nullspaceConstructors, newdm->nearnullspaceConstructors));
5291: PetscCall(PetscCalloc2(Nf, &newdm->nullspaceConstructors, Nf, &newdm->nearnullspaceConstructors));
5292: }
5293: PetscFunctionReturn(PETSC_SUCCESS);
5294: }
5296: /*@
5297: DMGetAdjacency - Returns the flags for determining variable influence
5299: Not Collective
5301: Input Parameters:
5302: + dm - The `DM` object
5303: - f - The field number, or `PETSC_DEFAULT` for the default adjacency
5305: Output Parameters:
5306: + useCone - Flag for variable influence starting with the cone operation
5307: - useClosure - Flag for variable influence using transitive closure
5309: Level: developer
5311: Notes:
5312: .vb
5313: FEM: Two points p and q are adjacent if q \in closure(star(p)), useCone = PETSC_FALSE, useClosure = PETSC_TRUE
5314: FVM: Two points p and q are adjacent if q \in support(p+cone(p)), useCone = PETSC_TRUE, useClosure = PETSC_FALSE
5315: FVM++: Two points p and q are adjacent if q \in star(closure(p)), useCone = PETSC_TRUE, useClosure = PETSC_TRUE
5316: .ve
5317: Further explanation can be found in the User's Manual Section on the Influence of Variables on One Another.
5319: .seealso: [](ch_dmbase), `DM`, `DMSetAdjacency()`, `DMGetField()`, `DMSetField()`
5320: @*/
5321: PetscErrorCode DMGetAdjacency(DM dm, PetscInt f, PetscBool *useCone, PetscBool *useClosure)
5322: {
5323: PetscFunctionBegin;
5325: if (useCone) PetscAssertPointer(useCone, 3);
5326: if (useClosure) PetscAssertPointer(useClosure, 4);
5327: if (f < 0) {
5328: if (useCone) *useCone = dm->adjacency[0];
5329: if (useClosure) *useClosure = dm->adjacency[1];
5330: } else {
5331: PetscInt Nf;
5333: PetscCall(DMGetNumFields(dm, &Nf));
5334: PetscCheck(f < Nf, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Field number %" PetscInt_FMT " must be in [0, %" PetscInt_FMT ")", f, Nf);
5335: if (useCone) *useCone = dm->fields[f].adjacency[0];
5336: if (useClosure) *useClosure = dm->fields[f].adjacency[1];
5337: }
5338: PetscFunctionReturn(PETSC_SUCCESS);
5339: }
5341: /*@
5342: DMSetAdjacency - Set the flags for determining variable influence
5344: Not Collective
5346: Input Parameters:
5347: + dm - The `DM` object
5348: . f - The field number
5349: . useCone - Flag for variable influence starting with the cone operation
5350: - useClosure - Flag for variable influence using transitive closure
5352: Level: developer
5354: Notes:
5355: .vb
5356: FEM: Two points p and q are adjacent if q \in closure(star(p)), useCone = PETSC_FALSE, useClosure = PETSC_TRUE
5357: FVM: Two points p and q are adjacent if q \in support(p+cone(p)), useCone = PETSC_TRUE, useClosure = PETSC_FALSE
5358: FVM++: Two points p and q are adjacent if q \in star(closure(p)), useCone = PETSC_TRUE, useClosure = PETSC_TRUE
5359: .ve
5360: Further explanation can be found in the User's Manual Section on the Influence of Variables on One Another.
5362: .seealso: [](ch_dmbase), `DM`, `DMGetAdjacency()`, `DMGetField()`, `DMSetField()`
5363: @*/
5364: PetscErrorCode DMSetAdjacency(DM dm, PetscInt f, PetscBool useCone, PetscBool useClosure)
5365: {
5366: PetscFunctionBegin;
5368: if (f < 0) {
5369: dm->adjacency[0] = useCone;
5370: dm->adjacency[1] = useClosure;
5371: } else {
5372: PetscInt Nf;
5374: PetscCall(DMGetNumFields(dm, &Nf));
5375: PetscCheck(f < Nf, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Field number %" PetscInt_FMT " must be in [0, %" PetscInt_FMT ")", f, Nf);
5376: dm->fields[f].adjacency[0] = useCone;
5377: dm->fields[f].adjacency[1] = useClosure;
5378: }
5379: PetscFunctionReturn(PETSC_SUCCESS);
5380: }
5382: /*@
5383: DMGetBasicAdjacency - Returns the flags for determining variable influence, using either the default or field 0 if it is defined
5385: Not collective
5387: Input Parameter:
5388: . dm - The `DM` object
5390: Output Parameters:
5391: + useCone - Flag for variable influence starting with the cone operation
5392: - useClosure - Flag for variable influence using transitive closure
5394: Level: developer
5396: Notes:
5397: .vb
5398: FEM: Two points p and q are adjacent if q \in closure(star(p)), useCone = PETSC_FALSE, useClosure = PETSC_TRUE
5399: FVM: Two points p and q are adjacent if q \in support(p+cone(p)), useCone = PETSC_TRUE, useClosure = PETSC_FALSE
5400: FVM++: Two points p and q are adjacent if q \in star(closure(p)), useCone = PETSC_TRUE, useClosure = PETSC_TRUE
5401: .ve
5403: .seealso: [](ch_dmbase), `DM`, `DMSetBasicAdjacency()`, `DMGetField()`, `DMSetField()`
5404: @*/
5405: PetscErrorCode DMGetBasicAdjacency(DM dm, PetscBool *useCone, PetscBool *useClosure)
5406: {
5407: PetscInt Nf;
5409: PetscFunctionBegin;
5411: if (useCone) PetscAssertPointer(useCone, 2);
5412: if (useClosure) PetscAssertPointer(useClosure, 3);
5413: PetscCall(DMGetNumFields(dm, &Nf));
5414: if (!Nf) {
5415: PetscCall(DMGetAdjacency(dm, PETSC_DEFAULT, useCone, useClosure));
5416: } else {
5417: PetscCall(DMGetAdjacency(dm, 0, useCone, useClosure));
5418: }
5419: PetscFunctionReturn(PETSC_SUCCESS);
5420: }
5422: /*@
5423: DMSetBasicAdjacency - Set the flags for determining variable influence, using either the default or field 0 if it is defined
5425: Not Collective
5427: Input Parameters:
5428: + dm - The `DM` object
5429: . useCone - Flag for variable influence starting with the cone operation
5430: - useClosure - Flag for variable influence using transitive closure
5432: Level: developer
5434: Notes:
5435: .vb
5436: FEM: Two points p and q are adjacent if q \in closure(star(p)), useCone = PETSC_FALSE, useClosure = PETSC_TRUE
5437: FVM: Two points p and q are adjacent if q \in support(p+cone(p)), useCone = PETSC_TRUE, useClosure = PETSC_FALSE
5438: FVM++: Two points p and q are adjacent if q \in star(closure(p)), useCone = PETSC_TRUE, useClosure = PETSC_TRUE
5439: .ve
5441: .seealso: [](ch_dmbase), `DM`, `DMGetBasicAdjacency()`, `DMGetField()`, `DMSetField()`
5442: @*/
5443: PetscErrorCode DMSetBasicAdjacency(DM dm, PetscBool useCone, PetscBool useClosure)
5444: {
5445: PetscInt Nf;
5447: PetscFunctionBegin;
5449: PetscCall(DMGetNumFields(dm, &Nf));
5450: if (!Nf) {
5451: PetscCall(DMSetAdjacency(dm, PETSC_DEFAULT, useCone, useClosure));
5452: } else {
5453: PetscCall(DMSetAdjacency(dm, 0, useCone, useClosure));
5454: }
5455: PetscFunctionReturn(PETSC_SUCCESS);
5456: }
5458: PetscErrorCode DMCompleteBCLabels_Internal(DM dm)
5459: {
5460: DM plex;
5461: DMLabel *labels, *glabels;
5462: const char **names;
5463: char *sendNames, *recvNames;
5464: PetscInt Nds, s, maxLabels = 0, maxLen = 0, gmaxLen, Nl = 0, gNl, l, gl, m;
5465: size_t len;
5466: MPI_Comm comm;
5467: PetscMPIInt rank, size, p, *counts, *displs;
5469: PetscFunctionBegin;
5470: PetscCall(PetscObjectGetComm((PetscObject)dm, &comm));
5471: PetscCallMPI(MPI_Comm_size(comm, &size));
5472: PetscCallMPI(MPI_Comm_rank(comm, &rank));
5473: PetscCall(DMGetNumDS(dm, &Nds));
5474: for (s = 0; s < Nds; ++s) {
5475: PetscDS dsBC;
5476: PetscInt numBd;
5478: PetscCall(DMGetRegionNumDS(dm, s, NULL, NULL, &dsBC, NULL));
5479: PetscCall(PetscDSGetNumBoundary(dsBC, &numBd));
5480: maxLabels += numBd;
5481: }
5482: PetscCall(PetscCalloc1(maxLabels, &labels));
5483: /* Get list of labels to be completed */
5484: for (s = 0; s < Nds; ++s) {
5485: PetscDS dsBC;
5486: PetscInt numBd;
5488: PetscCall(DMGetRegionNumDS(dm, s, NULL, NULL, &dsBC, NULL));
5489: PetscCall(PetscDSGetNumBoundary(dsBC, &numBd));
5490: for (PetscInt bd = 0; bd < numBd; ++bd) {
5491: DMLabel label;
5492: PetscInt field;
5493: PetscObject obj;
5494: PetscClassId id;
5496: PetscCall(PetscDSGetBoundary(dsBC, bd, NULL, NULL, NULL, &label, NULL, NULL, &field, NULL, NULL, NULL, NULL, NULL));
5497: PetscCall(DMGetField(dm, field, NULL, &obj));
5498: PetscCall(PetscObjectGetClassId(obj, &id));
5499: if (id != PETSCFE_CLASSID || !label) continue;
5500: for (l = 0; l < Nl; ++l)
5501: if (labels[l] == label) break;
5502: if (l == Nl) labels[Nl++] = label;
5503: }
5504: }
5505: /* Get label names */
5506: PetscCall(PetscMalloc1(Nl, &names));
5507: for (l = 0; l < Nl; ++l) PetscCall(PetscObjectGetName((PetscObject)labels[l], &names[l]));
5508: for (l = 0; l < Nl; ++l) {
5509: PetscCall(PetscStrlen(names[l], &len));
5510: maxLen = PetscMax(maxLen, (PetscInt)len + 2);
5511: }
5512: PetscCall(PetscFree(labels));
5513: PetscCallMPI(MPIU_Allreduce(&maxLen, &gmaxLen, 1, MPIU_INT, MPI_MAX, comm));
5514: PetscCall(PetscCalloc1(Nl * gmaxLen, &sendNames));
5515: for (l = 0; l < Nl; ++l) PetscCall(PetscStrncpy(&sendNames[gmaxLen * l], names[l], gmaxLen));
5516: PetscCall(PetscFree(names));
5517: /* Put all names on all processes */
5518: PetscCall(PetscCalloc2(size, &counts, size + 1, &displs));
5519: PetscCallMPI(MPI_Allgather(&Nl, 1, MPI_INT, counts, 1, MPI_INT, comm));
5520: for (p = 0; p < size; ++p) displs[p + 1] = displs[p] + counts[p];
5521: gNl = displs[size];
5522: for (p = 0; p < size; ++p) {
5523: counts[p] *= gmaxLen;
5524: displs[p] *= gmaxLen;
5525: }
5526: PetscCall(PetscCalloc2(gNl * gmaxLen, &recvNames, gNl, &glabels));
5527: PetscCallMPI(MPI_Allgatherv(sendNames, counts[rank], MPI_CHAR, recvNames, counts, displs, MPI_CHAR, comm));
5528: PetscCall(PetscFree2(counts, displs));
5529: PetscCall(PetscFree(sendNames));
5530: for (l = 0, gl = 0; l < gNl; ++l) {
5531: PetscCall(DMGetLabel(dm, &recvNames[l * gmaxLen], &glabels[gl]));
5532: PetscCheck(glabels[gl], PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Label %s missing on rank %d", &recvNames[l * gmaxLen], rank);
5533: for (m = 0; m < gl; ++m)
5534: if (glabels[m] == glabels[gl]) goto next_label;
5535: PetscCall(DMConvert(dm, DMPLEX, &plex));
5536: PetscCall(DMPlexLabelComplete(plex, glabels[gl]));
5537: PetscCall(DMDestroy(&plex));
5538: ++gl;
5539: next_label:
5540: continue;
5541: }
5542: PetscCall(PetscFree2(recvNames, glabels));
5543: PetscFunctionReturn(PETSC_SUCCESS);
5544: }
5546: static PetscErrorCode DMDSEnlarge_Static(DM dm, PetscInt NdsNew)
5547: {
5548: DMSpace *tmpd;
5549: PetscInt Nds = dm->Nds, s;
5551: PetscFunctionBegin;
5552: if (Nds >= NdsNew) PetscFunctionReturn(PETSC_SUCCESS);
5553: PetscCall(PetscMalloc1(NdsNew, &tmpd));
5554: for (s = 0; s < Nds; ++s) tmpd[s] = dm->probs[s];
5555: for (s = Nds; s < NdsNew; ++s) {
5556: tmpd[s].ds = NULL;
5557: tmpd[s].label = NULL;
5558: tmpd[s].fields = NULL;
5559: }
5560: PetscCall(PetscFree(dm->probs));
5561: dm->Nds = NdsNew;
5562: dm->probs = tmpd;
5563: PetscFunctionReturn(PETSC_SUCCESS);
5564: }
5566: /*@
5567: DMGetNumDS - Get the number of discrete systems in the `DM`
5569: Not Collective
5571: Input Parameter:
5572: . dm - The `DM`
5574: Output Parameter:
5575: . Nds - The number of `PetscDS` objects
5577: Level: intermediate
5579: .seealso: [](ch_dmbase), `DM`, `DMGetDS()`, `DMGetCellDS()`
5580: @*/
5581: PetscErrorCode DMGetNumDS(DM dm, PetscInt *Nds)
5582: {
5583: PetscFunctionBegin;
5585: PetscAssertPointer(Nds, 2);
5586: *Nds = dm->Nds;
5587: PetscFunctionReturn(PETSC_SUCCESS);
5588: }
5590: /*@
5591: DMClearDS - Remove all discrete systems from the `DM`
5593: Logically Collective
5595: Input Parameter:
5596: . dm - The `DM`
5598: Level: intermediate
5600: .seealso: [](ch_dmbase), `DM`, `DMGetNumDS()`, `DMGetDS()`, `DMSetField()`
5601: @*/
5602: PetscErrorCode DMClearDS(DM dm)
5603: {
5604: PetscInt s;
5606: PetscFunctionBegin;
5608: for (s = 0; s < dm->Nds; ++s) {
5609: PetscCall(PetscDSDestroy(&dm->probs[s].ds));
5610: PetscCall(PetscDSDestroy(&dm->probs[s].dsIn));
5611: PetscCall(DMLabelDestroy(&dm->probs[s].label));
5612: PetscCall(ISDestroy(&dm->probs[s].fields));
5613: }
5614: PetscCall(PetscFree(dm->probs));
5615: dm->probs = NULL;
5616: dm->Nds = 0;
5617: PetscFunctionReturn(PETSC_SUCCESS);
5618: }
5620: /*@
5621: DMGetDS - Get the default `PetscDS`
5623: Not Collective
5625: Input Parameter:
5626: . dm - The `DM`
5628: Output Parameter:
5629: . ds - The default `PetscDS`
5631: Level: intermediate
5633: Note:
5634: The `ds` is owned by the `dm` and should not be destroyed directly.
5636: .seealso: [](ch_dmbase), `DM`, `DMGetCellDS()`, `DMGetRegionDS()`
5637: @*/
5638: PetscErrorCode DMGetDS(DM dm, PetscDS *ds)
5639: {
5640: PetscFunctionBeginHot;
5642: PetscAssertPointer(ds, 2);
5643: PetscCheck(dm->Nds > 0, PetscObjectComm((PetscObject)dm), PETSC_ERR_ARG_WRONGSTATE, "Need to call DMCreateDS() before calling DMGetDS()");
5644: *ds = dm->probs[0].ds;
5645: PetscFunctionReturn(PETSC_SUCCESS);
5646: }
5648: /*@
5649: DMGetCellDS - Get the `PetscDS` defined on a given cell
5651: Not Collective
5653: Input Parameters:
5654: + dm - The `DM`
5655: - point - Cell for the `PetscDS`
5657: Output Parameters:
5658: + ds - The `PetscDS` defined on the given cell
5659: - dsIn - The `PetscDS` for input on the given cell, or `NULL` if the same ds
5661: Level: developer
5663: .seealso: [](ch_dmbase), `DM`, `DMGetDS()`, `DMSetRegionDS()`
5664: @*/
5665: PetscErrorCode DMGetCellDS(DM dm, PetscInt point, PetscDS *ds, PetscDS *dsIn)
5666: {
5667: PetscDS dsDef = NULL;
5668: PetscInt s;
5670: PetscFunctionBeginHot;
5672: if (ds) PetscAssertPointer(ds, 3);
5673: if (dsIn) PetscAssertPointer(dsIn, 4);
5674: PetscCheck(point >= 0, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Mesh point cannot be negative: %" PetscInt_FMT, point);
5675: if (ds) *ds = NULL;
5676: if (dsIn) *dsIn = NULL;
5677: for (s = 0; s < dm->Nds; ++s) {
5678: PetscInt val;
5680: if (!dm->probs[s].label) {
5681: dsDef = dm->probs[s].ds;
5682: } else {
5683: PetscCall(DMLabelGetValue(dm->probs[s].label, point, &val));
5684: if (val >= 0) {
5685: if (ds) *ds = dm->probs[s].ds;
5686: if (dsIn) *dsIn = dm->probs[s].dsIn;
5687: break;
5688: }
5689: }
5690: }
5691: if (ds && !*ds) *ds = dsDef;
5692: PetscFunctionReturn(PETSC_SUCCESS);
5693: }
5695: /*@
5696: DMGetRegionDS - Get the `PetscDS` for a given mesh region, defined by a `DMLabel`
5698: Not Collective
5700: Input Parameters:
5701: + dm - The `DM`
5702: - label - The `DMLabel` defining the mesh region, or `NULL` for the entire mesh
5704: Output Parameters:
5705: + fields - The `IS` containing the `DM` field numbers for the fields in this `PetscDS`, or `NULL`
5706: . ds - The `PetscDS` defined on the given region, or `NULL`
5707: - dsIn - The `PetscDS` for input in the given region, or `NULL`
5709: Level: advanced
5711: Note:
5712: If a non-`NULL` label is given, but there is no `PetscDS` on that specific label,
5713: the `PetscDS` for the full domain (if present) is returned. Returns with
5714: fields = `NULL` and ds = `NULL` if there is no `PetscDS` for the full domain.
5716: .seealso: [](ch_dmbase), `DM`, `DMGetRegionNumDS()`, `DMSetRegionDS()`, `DMGetDS()`, `DMGetCellDS()`
5717: @*/
5718: PetscErrorCode DMGetRegionDS(DM dm, DMLabel label, IS *fields, PetscDS *ds, PetscDS *dsIn)
5719: {
5720: PetscInt Nds = dm->Nds, s;
5722: PetscFunctionBegin;
5725: if (fields) {
5726: PetscAssertPointer(fields, 3);
5727: *fields = NULL;
5728: }
5729: if (ds) {
5730: PetscAssertPointer(ds, 4);
5731: *ds = NULL;
5732: }
5733: if (dsIn) {
5734: PetscAssertPointer(dsIn, 5);
5735: *dsIn = NULL;
5736: }
5737: for (s = 0; s < Nds; ++s) {
5738: if (dm->probs[s].label == label || !dm->probs[s].label) {
5739: if (fields) *fields = dm->probs[s].fields;
5740: if (ds) *ds = dm->probs[s].ds;
5741: if (dsIn) *dsIn = dm->probs[s].dsIn;
5742: if (dm->probs[s].label) PetscFunctionReturn(PETSC_SUCCESS);
5743: }
5744: }
5745: PetscFunctionReturn(PETSC_SUCCESS);
5746: }
5748: /*@
5749: DMSetRegionDS - Set the `PetscDS` for a given mesh region, defined by a `DMLabel`
5751: Collective
5753: Input Parameters:
5754: + dm - The `DM`
5755: . label - The `DMLabel` defining the mesh region, or `NULL` for the entire mesh
5756: . fields - The `IS` containing the `DM` field numbers for the fields in this `PetscDS`, or `NULL` for all fields
5757: . ds - The `PetscDS` defined on the given region
5758: - dsIn - The `PetscDS` for input on the given cell, or `NULL` if it is the same `PetscDS`
5760: Level: advanced
5762: Note:
5763: If the label has a `PetscDS` defined, it will be replaced. Otherwise, it will be added to the `DM`. If the `PetscDS` is replaced,
5764: the fields argument is ignored.
5766: .seealso: [](ch_dmbase), `DM`, `DMGetRegionDS()`, `DMSetRegionNumDS()`, `DMGetDS()`, `DMGetCellDS()`
5767: @*/
5768: PetscErrorCode DMSetRegionDS(DM dm, DMLabel label, IS fields, PetscDS ds, PetscDS dsIn)
5769: {
5770: PetscInt Nds = dm->Nds, s;
5772: PetscFunctionBegin;
5778: for (s = 0; s < Nds; ++s) {
5779: if (dm->probs[s].label == label) {
5780: PetscCall(PetscDSDestroy(&dm->probs[s].ds));
5781: PetscCall(PetscDSDestroy(&dm->probs[s].dsIn));
5782: dm->probs[s].ds = ds;
5783: dm->probs[s].dsIn = dsIn;
5784: PetscFunctionReturn(PETSC_SUCCESS);
5785: }
5786: }
5787: PetscCall(DMDSEnlarge_Static(dm, Nds + 1));
5788: PetscCall(PetscObjectReference((PetscObject)label));
5789: PetscCall(PetscObjectReference((PetscObject)fields));
5790: PetscCall(PetscObjectReference((PetscObject)ds));
5791: PetscCall(PetscObjectReference((PetscObject)dsIn));
5792: if (!label) {
5793: /* Put the NULL label at the front, so it is returned as the default */
5794: for (s = Nds - 1; s >= 0; --s) dm->probs[s + 1] = dm->probs[s];
5795: Nds = 0;
5796: }
5797: dm->probs[Nds].label = label;
5798: dm->probs[Nds].fields = fields;
5799: dm->probs[Nds].ds = ds;
5800: dm->probs[Nds].dsIn = dsIn;
5801: PetscFunctionReturn(PETSC_SUCCESS);
5802: }
5804: /*@
5805: DMGetRegionNumDS - Get the `PetscDS` for a given mesh region, defined by the region number
5807: Not Collective
5809: Input Parameters:
5810: + dm - The `DM`
5811: - num - The region number, in [0, Nds)
5813: Output Parameters:
5814: + label - The region label, or `NULL`
5815: . fields - The `IS` containing the `DM` field numbers for the fields in this `PetscDS`, or `NULL`
5816: . ds - The `PetscDS` defined on the given region, or `NULL`
5817: - dsIn - The `PetscDS` for input in the given region, or `NULL`
5819: Level: advanced
5821: .seealso: [](ch_dmbase), `DM`, `DMGetRegionDS()`, `DMSetRegionDS()`, `DMGetDS()`, `DMGetCellDS()`
5822: @*/
5823: PetscErrorCode DMGetRegionNumDS(DM dm, PetscInt num, DMLabel *label, IS *fields, PetscDS *ds, PetscDS *dsIn)
5824: {
5825: PetscInt Nds;
5827: PetscFunctionBegin;
5829: PetscCall(DMGetNumDS(dm, &Nds));
5830: PetscCheck((num >= 0) && (num < Nds), PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Region number %" PetscInt_FMT " is not in [0, %" PetscInt_FMT ")", num, Nds);
5831: if (label) {
5832: PetscAssertPointer(label, 3);
5833: *label = dm->probs[num].label;
5834: }
5835: if (fields) {
5836: PetscAssertPointer(fields, 4);
5837: *fields = dm->probs[num].fields;
5838: }
5839: if (ds) {
5840: PetscAssertPointer(ds, 5);
5841: *ds = dm->probs[num].ds;
5842: }
5843: if (dsIn) {
5844: PetscAssertPointer(dsIn, 6);
5845: *dsIn = dm->probs[num].dsIn;
5846: }
5847: PetscFunctionReturn(PETSC_SUCCESS);
5848: }
5850: /*@
5851: DMSetRegionNumDS - Set the `PetscDS` for a given mesh region, defined by the region number
5853: Not Collective
5855: Input Parameters:
5856: + dm - The `DM`
5857: . num - The region number, in [0, Nds)
5858: . label - The region label, or `NULL`
5859: . fields - The `IS` containing the `DM` field numbers for the fields in this `PetscDS`, or `NULL` to prevent setting
5860: . ds - The `PetscDS` defined on the given region, or `NULL` to prevent setting
5861: - dsIn - The `PetscDS` for input on the given cell, or `NULL` if it is the same `PetscDS`
5863: Level: advanced
5865: .seealso: [](ch_dmbase), `DM`, `DMGetRegionDS()`, `DMSetRegionDS()`, `DMGetDS()`, `DMGetCellDS()`
5866: @*/
5867: PetscErrorCode DMSetRegionNumDS(DM dm, PetscInt num, DMLabel label, IS fields, PetscDS ds, PetscDS dsIn)
5868: {
5869: PetscInt Nds;
5871: PetscFunctionBegin;
5874: PetscCall(DMGetNumDS(dm, &Nds));
5875: PetscCheck((num >= 0) && (num < Nds), PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Region number %" PetscInt_FMT " is not in [0, %" PetscInt_FMT ")", num, Nds);
5876: PetscCall(PetscObjectReference((PetscObject)label));
5877: PetscCall(DMLabelDestroy(&dm->probs[num].label));
5878: dm->probs[num].label = label;
5879: if (fields) {
5881: PetscCall(PetscObjectReference((PetscObject)fields));
5882: PetscCall(ISDestroy(&dm->probs[num].fields));
5883: dm->probs[num].fields = fields;
5884: }
5885: if (ds) {
5887: PetscCall(PetscObjectReference((PetscObject)ds));
5888: PetscCall(PetscDSDestroy(&dm->probs[num].ds));
5889: dm->probs[num].ds = ds;
5890: }
5891: if (dsIn) {
5893: PetscCall(PetscObjectReference((PetscObject)dsIn));
5894: PetscCall(PetscDSDestroy(&dm->probs[num].dsIn));
5895: dm->probs[num].dsIn = dsIn;
5896: }
5897: PetscFunctionReturn(PETSC_SUCCESS);
5898: }
5900: /*@
5901: DMFindRegionNum - Find the region number for a given `PetscDS`, or -1 if it is not found.
5903: Not Collective
5905: Input Parameters:
5906: + dm - The `DM`
5907: - ds - The `PetscDS` defined on the given region
5909: Output Parameter:
5910: . num - The region number, in [0, Nds), or -1 if not found
5912: Level: advanced
5914: .seealso: [](ch_dmbase), `DM`, `DMGetRegionNumDS()`, `DMGetRegionDS()`, `DMSetRegionDS()`, `DMGetDS()`, `DMGetCellDS()`
5915: @*/
5916: PetscErrorCode DMFindRegionNum(DM dm, PetscDS ds, PetscInt *num)
5917: {
5918: PetscInt Nds, n;
5920: PetscFunctionBegin;
5923: PetscAssertPointer(num, 3);
5924: PetscCall(DMGetNumDS(dm, &Nds));
5925: for (n = 0; n < Nds; ++n)
5926: if (ds == dm->probs[n].ds) break;
5927: if (n >= Nds) *num = -1;
5928: else *num = n;
5929: PetscFunctionReturn(PETSC_SUCCESS);
5930: }
5932: /*@
5933: DMCreateFEDefault - Create a `PetscFE` based on the celltype for the mesh
5935: Not Collective
5937: Input Parameters:
5938: + dm - The `DM`
5939: . Nc - The number of components for the field
5940: . prefix - The options prefix for the output `PetscFE`, or `NULL`
5941: - qorder - The quadrature order or `PETSC_DETERMINE` to use `PetscSpace` polynomial degree
5943: Output Parameter:
5944: . fem - The `PetscFE`
5946: Level: intermediate
5948: Note:
5949: This is a convenience method that just calls `PetscFECreateByCell()` underneath.
5951: .seealso: [](ch_dmbase), `DM`, `PetscFECreateByCell()`, `DMAddField()`, `DMCreateDS()`, `DMGetCellDS()`, `DMGetRegionDS()`
5952: @*/
5953: PetscErrorCode DMCreateFEDefault(DM dm, PetscInt Nc, const char prefix[], PetscInt qorder, PetscFE *fem)
5954: {
5955: DMPolytopeType ct;
5956: PetscInt dim, cStart;
5958: PetscFunctionBegin;
5961: if (prefix) PetscAssertPointer(prefix, 3);
5963: PetscAssertPointer(fem, 5);
5964: PetscCall(DMGetDimension(dm, &dim));
5965: PetscCall(DMPlexGetHeightStratum(dm, 0, &cStart, NULL));
5966: PetscCall(DMPlexGetCellType(dm, cStart, &ct));
5967: PetscCall(PetscFECreateByCell(PETSC_COMM_SELF, dim, Nc, ct, prefix, qorder, fem));
5968: PetscFunctionReturn(PETSC_SUCCESS);
5969: }
5971: /*@
5972: DMCreateDS - Create the discrete systems for the `DM` based upon the fields added to the `DM`
5974: Collective
5976: Input Parameter:
5977: . dm - The `DM`
5979: Options Database Key:
5980: . -dm_petscds_view - View all the `PetscDS` objects in this `DM`
5982: Level: intermediate
5984: Developer Note:
5985: The name of this function is wrong. Create functions always return the created object as one of the arguments.
5987: .seealso: [](ch_dmbase), `DM`, `DMSetField`, `DMAddField()`, `DMGetDS()`, `DMGetCellDS()`, `DMGetRegionDS()`, `DMSetRegionDS()`
5988: @*/
5989: PetscErrorCode DMCreateDS(DM dm)
5990: {
5991: MPI_Comm comm;
5992: PetscDS dsDef;
5993: DMLabel *labelSet;
5994: PetscInt dE, Nf = dm->Nf, f, s, Nl, l, Ndef, k;
5995: PetscBool doSetup = PETSC_TRUE, flg;
5997: PetscFunctionBegin;
5999: if (!dm->fields) PetscFunctionReturn(PETSC_SUCCESS);
6000: PetscCall(PetscObjectGetComm((PetscObject)dm, &comm));
6001: PetscCall(DMGetCoordinateDim(dm, &dE));
6002: // Create nullspace constructor slots
6003: PetscCall(PetscFree2(dm->nullspaceConstructors, dm->nearnullspaceConstructors));
6004: PetscCall(PetscCalloc2(Nf, &dm->nullspaceConstructors, Nf, &dm->nearnullspaceConstructors));
6005: /* Determine how many regions we have */
6006: PetscCall(PetscMalloc1(Nf, &labelSet));
6007: Nl = 0;
6008: Ndef = 0;
6009: for (f = 0; f < Nf; ++f) {
6010: DMLabel label = dm->fields[f].label;
6011: PetscInt l;
6013: #ifdef PETSC_HAVE_LIBCEED
6014: /* Move CEED context to discretizations */
6015: {
6016: PetscClassId id;
6018: PetscCall(PetscObjectGetClassId(dm->fields[f].disc, &id));
6019: if (id == PETSCFE_CLASSID) {
6020: Ceed ceed;
6022: PetscCall(DMGetCeed(dm, &ceed));
6023: PetscCall(PetscFESetCeed((PetscFE)dm->fields[f].disc, ceed));
6024: }
6025: }
6026: #endif
6027: if (!label) {
6028: ++Ndef;
6029: continue;
6030: }
6031: for (l = 0; l < Nl; ++l)
6032: if (label == labelSet[l]) break;
6033: if (l < Nl) continue;
6034: labelSet[Nl++] = label;
6035: }
6036: /* Create default DS if there are no labels to intersect with */
6037: PetscCall(DMGetRegionDS(dm, NULL, NULL, &dsDef, NULL));
6038: if (!dsDef && Ndef && !Nl) {
6039: IS fields;
6040: PetscInt *fld, nf;
6042: for (f = 0, nf = 0; f < Nf; ++f)
6043: if (!dm->fields[f].label) ++nf;
6044: PetscCheck(nf, comm, PETSC_ERR_PLIB, "All fields have labels, but we are trying to create a default DS");
6045: PetscCall(PetscMalloc1(nf, &fld));
6046: for (f = 0, nf = 0; f < Nf; ++f)
6047: if (!dm->fields[f].label) fld[nf++] = f;
6048: PetscCall(ISCreate(PETSC_COMM_SELF, &fields));
6049: PetscCall(PetscObjectSetOptionsPrefix((PetscObject)fields, "dm_fields_"));
6050: PetscCall(ISSetType(fields, ISGENERAL));
6051: PetscCall(ISGeneralSetIndices(fields, nf, fld, PETSC_OWN_POINTER));
6053: PetscCall(PetscDSCreate(PETSC_COMM_SELF, &dsDef));
6054: PetscCall(DMSetRegionDS(dm, NULL, fields, dsDef, NULL));
6055: PetscCall(PetscDSDestroy(&dsDef));
6056: PetscCall(ISDestroy(&fields));
6057: }
6058: PetscCall(DMGetRegionDS(dm, NULL, NULL, &dsDef, NULL));
6059: if (dsDef) PetscCall(PetscDSSetCoordinateDimension(dsDef, dE));
6060: /* Intersect labels with default fields */
6061: if (Ndef && Nl) {
6062: DM plex;
6063: DMLabel cellLabel;
6064: IS fieldIS, allcellIS, defcellIS = NULL;
6065: PetscInt *fields;
6066: const PetscInt *cells;
6067: PetscInt depth, nf = 0, n, c;
6069: PetscCall(DMConvert(dm, DMPLEX, &plex));
6070: PetscCall(DMPlexGetDepth(plex, &depth));
6071: PetscCall(DMGetStratumIS(plex, "dim", depth, &allcellIS));
6072: if (!allcellIS) PetscCall(DMGetStratumIS(plex, "depth", depth, &allcellIS));
6073: /* TODO This looks like it only works for one label */
6074: for (l = 0; l < Nl; ++l) {
6075: DMLabel label = labelSet[l];
6076: IS pointIS;
6078: PetscCall(ISDestroy(&defcellIS));
6079: PetscCall(DMLabelGetStratumIS(label, 1, &pointIS));
6080: PetscCall(ISDifference(allcellIS, pointIS, &defcellIS));
6081: PetscCall(ISDestroy(&pointIS));
6082: }
6083: PetscCall(ISDestroy(&allcellIS));
6085: PetscCall(DMLabelCreate(PETSC_COMM_SELF, "defaultCells", &cellLabel));
6086: PetscCall(ISGetLocalSize(defcellIS, &n));
6087: PetscCall(ISGetIndices(defcellIS, &cells));
6088: for (c = 0; c < n; ++c) PetscCall(DMLabelSetValue(cellLabel, cells[c], 1));
6089: PetscCall(ISRestoreIndices(defcellIS, &cells));
6090: PetscCall(ISDestroy(&defcellIS));
6091: PetscCall(DMPlexLabelComplete(plex, cellLabel));
6093: PetscCall(PetscMalloc1(Ndef, &fields));
6094: for (f = 0; f < Nf; ++f)
6095: if (!dm->fields[f].label) fields[nf++] = f;
6096: PetscCall(ISCreate(PETSC_COMM_SELF, &fieldIS));
6097: PetscCall(PetscObjectSetOptionsPrefix((PetscObject)fieldIS, "dm_fields_"));
6098: PetscCall(ISSetType(fieldIS, ISGENERAL));
6099: PetscCall(ISGeneralSetIndices(fieldIS, nf, fields, PETSC_OWN_POINTER));
6101: PetscCall(PetscDSCreate(PETSC_COMM_SELF, &dsDef));
6102: PetscCall(DMSetRegionDS(dm, cellLabel, fieldIS, dsDef, NULL));
6103: PetscCall(PetscDSSetCoordinateDimension(dsDef, dE));
6104: PetscCall(DMLabelDestroy(&cellLabel));
6105: PetscCall(PetscDSDestroy(&dsDef));
6106: PetscCall(ISDestroy(&fieldIS));
6107: PetscCall(DMDestroy(&plex));
6108: }
6109: /* Create label DSes
6110: - WE ONLY SUPPORT IDENTICAL OR DISJOINT LABELS
6111: */
6112: /* TODO Should check that labels are disjoint */
6113: for (l = 0; l < Nl; ++l) {
6114: DMLabel label = labelSet[l];
6115: PetscDS ds, dsIn = NULL;
6116: IS fields;
6117: PetscInt *fld, nf;
6119: PetscCall(PetscDSCreate(PETSC_COMM_SELF, &ds));
6120: for (f = 0, nf = 0; f < Nf; ++f)
6121: if (label == dm->fields[f].label || !dm->fields[f].label) ++nf;
6122: PetscCall(PetscMalloc1(nf, &fld));
6123: for (f = 0, nf = 0; f < Nf; ++f)
6124: if (label == dm->fields[f].label || !dm->fields[f].label) fld[nf++] = f;
6125: PetscCall(ISCreate(PETSC_COMM_SELF, &fields));
6126: PetscCall(PetscObjectSetOptionsPrefix((PetscObject)fields, "dm_fields_"));
6127: PetscCall(ISSetType(fields, ISGENERAL));
6128: PetscCall(ISGeneralSetIndices(fields, nf, fld, PETSC_OWN_POINTER));
6129: PetscCall(PetscDSSetCoordinateDimension(ds, dE));
6130: {
6131: DMPolytopeType ct;
6132: PetscInt lStart, lEnd;
6133: PetscBool isCohesiveLocal = PETSC_FALSE, isCohesive;
6135: PetscCall(DMLabelGetBounds(label, &lStart, &lEnd));
6136: if (lStart >= 0) {
6137: PetscCall(DMPlexGetCellType(dm, lStart, &ct));
6138: switch (ct) {
6139: case DM_POLYTOPE_POINT_PRISM_TENSOR:
6140: case DM_POLYTOPE_SEG_PRISM_TENSOR:
6141: case DM_POLYTOPE_TRI_PRISM_TENSOR:
6142: case DM_POLYTOPE_QUAD_PRISM_TENSOR:
6143: isCohesiveLocal = PETSC_TRUE;
6144: break;
6145: default:
6146: break;
6147: }
6148: }
6149: PetscCallMPI(MPIU_Allreduce(&isCohesiveLocal, &isCohesive, 1, MPI_C_BOOL, MPI_LOR, comm));
6150: if (isCohesive) {
6151: PetscCall(PetscDSCreate(PETSC_COMM_SELF, &dsIn));
6152: PetscCall(PetscDSSetCoordinateDimension(dsIn, dE));
6153: }
6154: for (f = 0, nf = 0; f < Nf; ++f) {
6155: if (label == dm->fields[f].label || !dm->fields[f].label) {
6156: if (label == dm->fields[f].label) {
6157: PetscCall(PetscDSSetDiscretization(ds, nf, NULL));
6158: PetscCall(PetscDSSetCohesive(ds, nf, isCohesive));
6159: if (dsIn) {
6160: PetscCall(PetscDSSetDiscretization(dsIn, nf, NULL));
6161: PetscCall(PetscDSSetCohesive(dsIn, nf, isCohesive));
6162: }
6163: }
6164: ++nf;
6165: }
6166: }
6167: }
6168: PetscCall(DMSetRegionDS(dm, label, fields, ds, dsIn));
6169: PetscCall(ISDestroy(&fields));
6170: PetscCall(PetscDSDestroy(&ds));
6171: PetscCall(PetscDSDestroy(&dsIn));
6172: }
6173: PetscCall(PetscFree(labelSet));
6174: /* Set fields in DSes */
6175: for (s = 0; s < dm->Nds; ++s) {
6176: PetscDS ds = dm->probs[s].ds;
6177: PetscDS dsIn = dm->probs[s].dsIn;
6178: IS fields = dm->probs[s].fields;
6179: const PetscInt *fld;
6180: PetscInt nf, dsnf;
6181: PetscBool isCohesive;
6183: PetscCall(PetscDSGetNumFields(ds, &dsnf));
6184: PetscCall(PetscDSIsCohesive(ds, &isCohesive));
6185: PetscCall(ISGetLocalSize(fields, &nf));
6186: PetscCall(ISGetIndices(fields, &fld));
6187: for (f = 0; f < nf; ++f) {
6188: PetscObject disc = dm->fields[fld[f]].disc;
6189: PetscBool isCohesiveField;
6190: PetscClassId id;
6192: /* Handle DS with no fields */
6193: if (dsnf) PetscCall(PetscDSGetCohesive(ds, f, &isCohesiveField));
6194: /* If this is a cohesive cell, then regular fields need the lower dimensional discretization */
6195: if (isCohesive) {
6196: if (!isCohesiveField) {
6197: PetscObject bdDisc;
6199: PetscCall(PetscFEGetHeightSubspace((PetscFE)disc, 1, (PetscFE *)&bdDisc));
6200: PetscCall(PetscDSSetDiscretization(ds, f, bdDisc));
6201: PetscCall(PetscDSSetDiscretization(dsIn, f, disc));
6202: } else {
6203: PetscCall(PetscDSSetDiscretization(ds, f, disc));
6204: PetscCall(PetscDSSetDiscretization(dsIn, f, disc));
6205: }
6206: } else {
6207: PetscCall(PetscDSSetDiscretization(ds, f, disc));
6208: }
6209: /* We allow people to have placeholder fields and construct the Section by hand */
6210: PetscCall(PetscObjectGetClassId(disc, &id));
6211: if ((id != PETSCFE_CLASSID) && (id != PETSCFV_CLASSID)) doSetup = PETSC_FALSE;
6212: }
6213: PetscCall(ISRestoreIndices(fields, &fld));
6214: }
6215: /* Allow k-jet tabulation */
6216: PetscCall(PetscOptionsGetInt(NULL, ((PetscObject)dm)->prefix, "-dm_ds_jet_degree", &k, &flg));
6217: if (flg) {
6218: for (s = 0; s < dm->Nds; ++s) {
6219: PetscDS ds = dm->probs[s].ds;
6220: PetscDS dsIn = dm->probs[s].dsIn;
6221: PetscInt Nf;
6223: PetscCall(PetscDSGetNumFields(ds, &Nf));
6224: for (PetscInt f = 0; f < Nf; ++f) {
6225: PetscCall(PetscDSSetJetDegree(ds, f, k));
6226: if (dsIn) PetscCall(PetscDSSetJetDegree(dsIn, f, k));
6227: }
6228: }
6229: }
6230: /* Setup DSes */
6231: if (doSetup) {
6232: for (s = 0; s < dm->Nds; ++s) {
6233: if (dm->setfromoptionscalled) {
6234: PetscCall(PetscDSSetFromOptions(dm->probs[s].ds));
6235: if (dm->probs[s].dsIn) PetscCall(PetscDSSetFromOptions(dm->probs[s].dsIn));
6236: }
6237: PetscCall(PetscDSSetUp(dm->probs[s].ds));
6238: if (dm->probs[s].dsIn) PetscCall(PetscDSSetUp(dm->probs[s].dsIn));
6239: }
6240: }
6241: PetscFunctionReturn(PETSC_SUCCESS);
6242: }
6244: /*@
6245: DMUseTensorOrder - Use a tensor product closure ordering for the default section
6247: Input Parameters:
6248: + dm - The DM
6249: - tensor - Flag for tensor order
6251: Level: developer
6253: .seealso: `DMPlexSetClosurePermutationTensor()`, `PetscSectionResetClosurePermutation()`
6254: @*/
6255: PetscErrorCode DMUseTensorOrder(DM dm, PetscBool tensor)
6256: {
6257: PetscInt Nf;
6258: PetscBool reorder = PETSC_TRUE, isPlex;
6260: PetscFunctionBegin;
6261: PetscCall(PetscObjectTypeCompare((PetscObject)dm, DMPLEX, &isPlex));
6262: PetscCall(DMGetNumFields(dm, &Nf));
6263: for (PetscInt f = 0; f < Nf; ++f) {
6264: PetscObject obj;
6265: PetscClassId id;
6267: PetscCall(DMGetField(dm, f, NULL, &obj));
6268: PetscCall(PetscObjectGetClassId(obj, &id));
6269: if (id == PETSCFE_CLASSID) {
6270: PetscSpace sp;
6271: PetscBool tensor;
6273: PetscCall(PetscFEGetBasisSpace((PetscFE)obj, &sp));
6274: PetscCall(PetscSpacePolynomialGetTensor(sp, &tensor));
6275: reorder = reorder && tensor ? PETSC_TRUE : PETSC_FALSE;
6276: } else reorder = PETSC_FALSE;
6277: }
6278: if (tensor) {
6279: if (reorder && isPlex) PetscCall(DMPlexSetClosurePermutationTensor(dm, PETSC_DETERMINE, NULL));
6280: } else {
6281: PetscSection s;
6283: PetscCall(DMGetLocalSection(dm, &s));
6284: if (s) PetscCall(PetscSectionResetClosurePermutation(s));
6285: }
6286: PetscFunctionReturn(PETSC_SUCCESS);
6287: }
6289: /*@
6290: DMComputeExactSolution - Compute the exact solution for a given `DM`, using the `PetscDS` information.
6292: Collective
6294: Input Parameters:
6295: + dm - The `DM`
6296: - time - The time
6298: Output Parameters:
6299: + u - The vector will be filled with exact solution values, or `NULL`
6300: - u_t - The vector will be filled with the time derivative of exact solution values, or `NULL`
6302: Level: developer
6304: Note:
6305: The user must call `PetscDSSetExactSolution()` before using this routine
6307: .seealso: [](ch_dmbase), `DM`, `PetscDSSetExactSolution()`
6308: @*/
6309: PetscErrorCode DMComputeExactSolution(DM dm, PetscReal time, Vec u, Vec u_t)
6310: {
6311: PetscErrorCode (**exacts)(PetscInt, PetscReal, const PetscReal x[], PetscInt, PetscScalar *u, PetscCtx ctx);
6312: void **ectxs;
6313: Vec locu, locu_t;
6314: PetscInt Nf, Nds, s;
6316: PetscFunctionBegin;
6318: if (u) {
6320: PetscCall(DMGetLocalVector(dm, &locu));
6321: PetscCall(VecSet(locu, 0.));
6322: }
6323: if (u_t) {
6325: PetscCall(DMGetLocalVector(dm, &locu_t));
6326: PetscCall(VecSet(locu_t, 0.));
6327: }
6328: PetscCall(DMGetNumFields(dm, &Nf));
6329: PetscCall(PetscMalloc2(Nf, &exacts, Nf, &ectxs));
6330: PetscCall(DMGetNumDS(dm, &Nds));
6331: for (s = 0; s < Nds; ++s) {
6332: PetscDS ds;
6333: DMLabel label;
6334: IS fieldIS;
6335: const PetscInt *fields, id = 1;
6336: PetscInt dsNf;
6338: PetscCall(DMGetRegionNumDS(dm, s, &label, &fieldIS, &ds, NULL));
6339: PetscCall(PetscDSGetNumFields(ds, &dsNf));
6340: PetscCall(ISGetIndices(fieldIS, &fields));
6341: PetscCall(PetscArrayzero(exacts, Nf));
6342: PetscCall(PetscArrayzero(ectxs, Nf));
6343: if (u) {
6344: for (PetscInt f = 0; f < dsNf; ++f) PetscCall(PetscDSGetExactSolution(ds, fields[f], &exacts[fields[f]], &ectxs[fields[f]]));
6345: if (label) PetscCall(DMProjectFunctionLabelLocal(dm, time, label, 1, &id, 0, NULL, exacts, ectxs, INSERT_ALL_VALUES, locu));
6346: else PetscCall(DMProjectFunctionLocal(dm, time, exacts, ectxs, INSERT_ALL_VALUES, locu));
6347: }
6348: if (u_t) {
6349: PetscCall(PetscArrayzero(exacts, Nf));
6350: PetscCall(PetscArrayzero(ectxs, Nf));
6351: for (PetscInt f = 0; f < dsNf; ++f) PetscCall(PetscDSGetExactSolutionTimeDerivative(ds, fields[f], &exacts[fields[f]], &ectxs[fields[f]]));
6352: if (label) PetscCall(DMProjectFunctionLabelLocal(dm, time, label, 1, &id, 0, NULL, exacts, ectxs, INSERT_ALL_VALUES, locu_t));
6353: else PetscCall(DMProjectFunctionLocal(dm, time, exacts, ectxs, INSERT_ALL_VALUES, locu_t));
6354: }
6355: PetscCall(ISRestoreIndices(fieldIS, &fields));
6356: }
6357: if (u) {
6358: PetscCall(PetscObjectSetName((PetscObject)u, "Exact Solution"));
6359: PetscCall(PetscObjectSetOptionsPrefix((PetscObject)u, "exact_"));
6360: }
6361: if (u_t) {
6362: PetscCall(PetscObjectSetName((PetscObject)u, "Exact Solution Time Derivative"));
6363: PetscCall(PetscObjectSetOptionsPrefix((PetscObject)u_t, "exact_t_"));
6364: }
6365: PetscCall(PetscFree2(exacts, ectxs));
6366: if (u) {
6367: PetscCall(DMLocalToGlobalBegin(dm, locu, INSERT_ALL_VALUES, u));
6368: PetscCall(DMLocalToGlobalEnd(dm, locu, INSERT_ALL_VALUES, u));
6369: PetscCall(DMRestoreLocalVector(dm, &locu));
6370: }
6371: if (u_t) {
6372: PetscCall(DMLocalToGlobalBegin(dm, locu_t, INSERT_ALL_VALUES, u_t));
6373: PetscCall(DMLocalToGlobalEnd(dm, locu_t, INSERT_ALL_VALUES, u_t));
6374: PetscCall(DMRestoreLocalVector(dm, &locu_t));
6375: }
6376: PetscFunctionReturn(PETSC_SUCCESS);
6377: }
6379: static PetscErrorCode DMTransferDS_Internal(DM dm, DMLabel label, IS fields, PetscInt minDegree, PetscInt maxDegree, PetscDS ds, PetscDS dsIn)
6380: {
6381: PetscDS dsNew, dsInNew = NULL;
6383: PetscFunctionBegin;
6384: PetscCall(PetscDSCreate(PetscObjectComm((PetscObject)ds), &dsNew));
6385: PetscCall(PetscDSCopy(ds, minDegree, maxDegree, dm, dsNew));
6386: if (dsIn) {
6387: PetscCall(PetscDSCreate(PetscObjectComm((PetscObject)dsIn), &dsInNew));
6388: PetscCall(PetscDSCopy(dsIn, minDegree, maxDegree, dm, dsInNew));
6389: }
6390: PetscCall(DMSetRegionDS(dm, label, fields, dsNew, dsInNew));
6391: PetscCall(PetscDSDestroy(&dsNew));
6392: PetscCall(PetscDSDestroy(&dsInNew));
6393: PetscFunctionReturn(PETSC_SUCCESS);
6394: }
6396: /*@
6397: DMCopyDS - Copy the discrete systems for the `DM` into another `DM`
6399: Collective
6401: Input Parameters:
6402: + dm - The `DM`
6403: . minDegree - Minimum degree for a discretization, or `PETSC_DETERMINE` for no limit
6404: - maxDegree - Maximum degree for a discretization, or `PETSC_DETERMINE` for no limit
6406: Output Parameter:
6407: . newdm - The `DM`
6409: Level: advanced
6411: .seealso: [](ch_dmbase), `DM`, `DMCopyFields()`, `DMAddField()`, `DMGetDS()`, `DMGetCellDS()`, `DMGetRegionDS()`, `DMSetRegionDS()`
6412: @*/
6413: PetscErrorCode DMCopyDS(DM dm, PetscInt minDegree, PetscInt maxDegree, DM newdm)
6414: {
6415: PetscInt Nds;
6417: PetscFunctionBegin;
6418: if (dm == newdm) PetscFunctionReturn(PETSC_SUCCESS);
6419: PetscCall(DMGetNumDS(dm, &Nds));
6420: PetscCall(DMClearDS(newdm));
6421: for (PetscInt s = 0; s < Nds; ++s) {
6422: DMLabel label;
6423: IS fields;
6424: PetscDS ds, dsIn, newds;
6425: PetscInt Nbd;
6427: PetscCall(DMGetRegionNumDS(dm, s, &label, &fields, &ds, &dsIn));
6428: /* TODO: We need to change all keys from labels in the old DM to labels in the new DM */
6429: PetscCall(DMTransferDS_Internal(newdm, label, fields, minDegree, maxDegree, ds, dsIn));
6430: /* Complete new labels in the new DS */
6431: PetscCall(DMGetRegionDS(newdm, label, NULL, &newds, NULL));
6432: PetscCall(PetscDSGetNumBoundary(newds, &Nbd));
6433: for (PetscInt bd = 0; bd < Nbd; ++bd) {
6434: PetscWeakForm wf;
6435: DMLabel label;
6436: PetscInt field;
6438: PetscCall(PetscDSGetBoundary(newds, bd, &wf, NULL, NULL, &label, NULL, NULL, &field, NULL, NULL, NULL, NULL, NULL));
6439: PetscCall(PetscWeakFormReplaceLabel(wf, label));
6440: }
6441: }
6442: PetscCall(DMCompleteBCLabels_Internal(newdm));
6443: PetscFunctionReturn(PETSC_SUCCESS);
6444: }
6446: /*@
6447: DMCopyDisc - Copy the fields and discrete systems for the `DM` into another `DM`
6449: Collective
6451: Input Parameter:
6452: . dm - The `DM`
6454: Output Parameter:
6455: . newdm - The `DM`
6457: Level: advanced
6459: Developer Note:
6460: Really ugly name, nothing in PETSc is called a `Disc` plus it is an ugly abbreviation
6462: .seealso: [](ch_dmbase), `DM`, `DMCopyFields()`, `DMCopyDS()`
6463: @*/
6464: PetscErrorCode DMCopyDisc(DM dm, DM newdm)
6465: {
6466: PetscFunctionBegin;
6467: PetscCall(DMCopyFields(dm, PETSC_DETERMINE, PETSC_DETERMINE, newdm));
6468: PetscCall(DMCopyDS(dm, PETSC_DETERMINE, PETSC_DETERMINE, newdm));
6469: PetscFunctionReturn(PETSC_SUCCESS);
6470: }
6472: /*@
6473: DMGetDimension - Return the topological dimension of the `DM`
6475: Not Collective
6477: Input Parameter:
6478: . dm - The `DM`
6480: Output Parameter:
6481: . dim - The topological dimension
6483: Level: beginner
6485: .seealso: [](ch_dmbase), `DM`, `DMSetDimension()`, `DMCreate()`
6486: @*/
6487: PetscErrorCode DMGetDimension(DM dm, PetscInt *dim)
6488: {
6489: PetscFunctionBegin;
6491: PetscAssertPointer(dim, 2);
6492: *dim = dm->dim;
6493: PetscFunctionReturn(PETSC_SUCCESS);
6494: }
6496: /*@
6497: DMSetDimension - Set the topological dimension of the `DM`
6499: Collective
6501: Input Parameters:
6502: + dm - The `DM`
6503: - dim - The topological dimension
6505: Level: beginner
6507: .seealso: [](ch_dmbase), `DM`, `DMGetDimension()`, `DMCreate()`
6508: @*/
6509: PetscErrorCode DMSetDimension(DM dm, PetscInt dim)
6510: {
6511: PetscDS ds;
6512: PetscInt Nds;
6514: PetscFunctionBegin;
6517: if (dm->dim != dim) PetscCall(DMSetPeriodicity(dm, NULL, NULL, NULL));
6518: dm->dim = dim;
6519: if (dm->dim >= 0) {
6520: PetscCall(DMGetNumDS(dm, &Nds));
6521: for (PetscInt n = 0; n < Nds; ++n) {
6522: PetscCall(DMGetRegionNumDS(dm, n, NULL, NULL, &ds, NULL));
6523: if (ds->dimEmbed < 0) PetscCall(PetscDSSetCoordinateDimension(ds, dim));
6524: }
6525: }
6526: PetscFunctionReturn(PETSC_SUCCESS);
6527: }
6529: /*@
6530: DMGetDimPoints - Get the half-open interval for all points of a given dimension
6532: Collective
6534: Input Parameters:
6535: + dm - the `DM`
6536: - dim - the dimension
6538: Output Parameters:
6539: + pStart - The first point of the given dimension
6540: - pEnd - The first point following points of the given dimension
6542: Level: intermediate
6544: Note:
6545: The points are vertices in the Hasse diagram encoding the topology. This is explained in
6546: https://arxiv.org/abs/0908.4427. If no points exist of this dimension in the storage scheme,
6547: then the interval is empty.
6549: .seealso: [](ch_dmbase), `DM`, `DMPLEX`, `DMPlexGetDepthStratum()`, `DMPlexGetHeightStratum()`
6550: @*/
6551: PetscErrorCode DMGetDimPoints(DM dm, PetscInt dim, PetscInt *pStart, PetscInt *pEnd)
6552: {
6553: PetscInt d;
6555: PetscFunctionBegin;
6557: PetscCall(DMGetDimension(dm, &d));
6558: PetscCheck((dim >= 0) && (dim <= d), PetscObjectComm((PetscObject)dm), PETSC_ERR_ARG_OUTOFRANGE, "Invalid dimension %" PetscInt_FMT, dim);
6559: PetscUseTypeMethod(dm, getdimpoints, dim, pStart, pEnd);
6560: PetscFunctionReturn(PETSC_SUCCESS);
6561: }
6563: /*@
6564: DMGetOutputDM - Retrieve the `DM` associated with the layout for output
6566: Collective
6568: Input Parameter:
6569: . dm - The original `DM`
6571: Output Parameter:
6572: . odm - The `DM` which provides the layout for output
6574: Level: intermediate
6576: Note:
6577: In some situations the vector obtained with `DMCreateGlobalVector()` excludes points for degrees of freedom that are associated with fixed (Dirichelet) boundary
6578: conditions since the algebraic solver does not solve for those variables. The output `DM` includes these excluded points and its global vector contains the
6579: locations for those dof so that they can be output to a file or other viewer along with the unconstrained dof.
6581: .seealso: [](ch_dmbase), `DM`, `VecView()`, `DMGetGlobalSection()`, `DMCreateGlobalVector()`, `PetscSectionHasConstraints()`, `DMSetGlobalSection()`
6582: @*/
6583: PetscErrorCode DMGetOutputDM(DM dm, DM *odm)
6584: {
6585: PetscSection section;
6586: IS perm;
6587: PetscBool hasConstraints, newDM, gnewDM;
6588: PetscInt num_face_sfs = 0;
6590: PetscFunctionBegin;
6592: PetscAssertPointer(odm, 2);
6593: PetscCall(DMGetLocalSection(dm, §ion));
6594: PetscCall(PetscSectionHasConstraints(section, &hasConstraints));
6595: PetscCall(PetscSectionGetPermutation(section, &perm));
6596: PetscCall(DMPlexGetIsoperiodicFaceSF(dm, &num_face_sfs, NULL));
6597: newDM = hasConstraints || perm || (num_face_sfs > 0) ? PETSC_TRUE : PETSC_FALSE;
6598: PetscCallMPI(MPIU_Allreduce(&newDM, &gnewDM, 1, MPI_C_BOOL, MPI_LOR, PetscObjectComm((PetscObject)dm)));
6599: if (!gnewDM) {
6600: *odm = dm;
6601: PetscFunctionReturn(PETSC_SUCCESS);
6602: }
6603: if (!dm->dmBC) {
6604: PetscSection newSection, gsection;
6605: PetscSF sf, sfNatural;
6606: PetscBool usePerm = dm->ignorePermOutput ? PETSC_FALSE : PETSC_TRUE;
6608: PetscCall(DMClone(dm, &dm->dmBC));
6609: PetscCall(DMCopyDisc(dm, dm->dmBC));
6610: PetscCall(PetscSectionClone(section, &newSection));
6611: PetscCall(DMSetLocalSection(dm->dmBC, newSection));
6612: PetscCall(PetscSectionDestroy(&newSection));
6613: PetscCall(DMGetNaturalSF(dm, &sfNatural));
6614: PetscCall(DMSetNaturalSF(dm->dmBC, sfNatural));
6615: PetscCall(DMGetPointSF(dm->dmBC, &sf));
6616: PetscCall(PetscSectionCreateGlobalSection(section, sf, usePerm, PETSC_TRUE, PETSC_FALSE, &gsection));
6617: PetscCall(DMSetGlobalSection(dm->dmBC, gsection));
6618: PetscCall(PetscSectionDestroy(&gsection));
6619: }
6620: *odm = dm->dmBC;
6621: PetscFunctionReturn(PETSC_SUCCESS);
6622: }
6624: /*@
6625: DMGetOutputSequenceNumber - Retrieve the sequence number/value for output
6627: Input Parameter:
6628: . dm - The original `DM`
6630: Output Parameters:
6631: + num - The output sequence number
6632: - val - The output sequence value
6634: Level: intermediate
6636: Note:
6637: This is intended for output that should appear in sequence, for instance
6638: a set of timesteps in an `PETSCVIEWERHDF5` file, or a set of realizations of a stochastic system.
6640: Developer Note:
6641: The `DM` serves as a convenient place to store the current iteration value. The iteration is not
6642: not directly related to the `DM`.
6644: .seealso: [](ch_dmbase), `DM`, `VecView()`
6645: @*/
6646: PetscErrorCode DMGetOutputSequenceNumber(DM dm, PetscInt *num, PetscReal *val)
6647: {
6648: PetscFunctionBegin;
6650: if (num) {
6651: PetscAssertPointer(num, 2);
6652: *num = dm->outputSequenceNum;
6653: }
6654: if (val) {
6655: PetscAssertPointer(val, 3);
6656: *val = dm->outputSequenceVal;
6657: }
6658: PetscFunctionReturn(PETSC_SUCCESS);
6659: }
6661: /*@
6662: DMSetOutputSequenceNumber - Set the sequence number/value for output
6664: Input Parameters:
6665: + dm - The original `DM`
6666: . num - The output sequence number
6667: - val - The output sequence value
6669: Level: intermediate
6671: Note:
6672: This is intended for output that should appear in sequence, for instance
6673: a set of timesteps in an `PETSCVIEWERHDF5` file, or a set of realizations of a stochastic system.
6675: .seealso: [](ch_dmbase), `DM`, `VecView()`
6676: @*/
6677: PetscErrorCode DMSetOutputSequenceNumber(DM dm, PetscInt num, PetscReal val)
6678: {
6679: PetscFunctionBegin;
6681: dm->outputSequenceNum = num;
6682: dm->outputSequenceVal = val;
6683: PetscFunctionReturn(PETSC_SUCCESS);
6684: }
6686: /*@
6687: DMOutputSequenceLoad - Retrieve the sequence value from a `PetscViewer`
6689: Input Parameters:
6690: + dm - The original `DM`
6691: . viewer - The `PetscViewer` to get it from
6692: . name - The sequence name
6693: - num - The output sequence number
6695: Output Parameter:
6696: . val - The output sequence value
6698: Level: intermediate
6700: Note:
6701: This is intended for output that should appear in sequence, for instance
6702: a set of timesteps in an `PETSCVIEWERHDF5` file, or a set of realizations of a stochastic system.
6704: Developer Note:
6705: It is unclear at the user API level why a `DM` is needed as input
6707: .seealso: [](ch_dmbase), `DM`, `DMGetOutputSequenceNumber()`, `DMSetOutputSequenceNumber()`, `VecView()`
6708: @*/
6709: PetscErrorCode DMOutputSequenceLoad(DM dm, PetscViewer viewer, const char name[], PetscInt num, PetscReal *val)
6710: {
6711: PetscBool ishdf5;
6713: PetscFunctionBegin;
6716: PetscAssertPointer(name, 3);
6717: PetscAssertPointer(val, 5);
6718: PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERHDF5, &ishdf5));
6719: PetscCheck(ishdf5, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Invalid viewer; open viewer with PetscViewerHDF5Open()");
6720: #if defined(PETSC_HAVE_HDF5)
6721: PetscScalar value;
6723: PetscCall(DMSequenceLoad_HDF5_Internal(dm, name, num, &value, viewer));
6724: *val = PetscRealPart(value);
6725: #endif
6726: PetscFunctionReturn(PETSC_SUCCESS);
6727: }
6729: /*@
6730: DMGetOutputSequenceLength - Retrieve the number of sequence values from a `PetscViewer`
6732: Input Parameters:
6733: + dm - The original `DM`
6734: . viewer - The `PetscViewer` to get it from
6735: - name - The sequence name
6737: Output Parameter:
6738: . len - The length of the output sequence
6740: Level: intermediate
6742: Note:
6743: This is intended for output that should appear in sequence, for instance
6744: a set of timesteps in an `PETSCVIEWERHDF5` file, or a set of realizations of a stochastic system.
6746: Developer Note:
6747: It is unclear at the user API level why a `DM` is needed as input
6749: .seealso: [](ch_dmbase), `DM`, `DMGetOutputSequenceNumber()`, `DMSetOutputSequenceNumber()`, `VecView()`
6750: @*/
6751: PetscErrorCode DMGetOutputSequenceLength(DM dm, PetscViewer viewer, const char name[], PetscInt *len)
6752: {
6753: PetscBool ishdf5;
6755: PetscFunctionBegin;
6758: PetscAssertPointer(name, 3);
6759: PetscAssertPointer(len, 4);
6760: PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERHDF5, &ishdf5));
6761: PetscCheck(ishdf5, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Invalid viewer; open viewer with PetscViewerHDF5Open()");
6762: #if defined(PETSC_HAVE_HDF5)
6763: PetscCall(DMSequenceGetLength_HDF5_Internal(dm, name, len, viewer));
6764: #endif
6765: PetscFunctionReturn(PETSC_SUCCESS);
6766: }
6768: /*@
6769: DMGetUseNatural - Get the flag for creating a mapping to the natural order when a `DM` is (re)distributed in parallel
6771: Not Collective
6773: Input Parameter:
6774: . dm - The `DM`
6776: Output Parameter:
6777: . useNatural - `PETSC_TRUE` to build the mapping to a natural order during distribution
6779: Level: beginner
6781: .seealso: [](ch_dmbase), `DM`, `DMSetUseNatural()`, `DMCreate()`
6782: @*/
6783: PetscErrorCode DMGetUseNatural(DM dm, PetscBool *useNatural)
6784: {
6785: PetscFunctionBegin;
6787: PetscAssertPointer(useNatural, 2);
6788: *useNatural = dm->useNatural;
6789: PetscFunctionReturn(PETSC_SUCCESS);
6790: }
6792: /*@
6793: DMSetUseNatural - Set the flag for creating a mapping to the natural order when a `DM` is (re)distributed in parallel
6795: Collective
6797: Input Parameters:
6798: + dm - The `DM`
6799: - useNatural - `PETSC_TRUE` to build the mapping to a natural order during distribution
6801: Level: beginner
6803: Note:
6804: This also causes the map to be build after `DMCreateSubDM()` and `DMCreateSuperDM()`
6806: .seealso: [](ch_dmbase), `DM`, `DMGetUseNatural()`, `DMCreate()`, `DMPlexDistribute()`, `DMCreateSubDM()`, `DMCreateSuperDM()`
6807: @*/
6808: PetscErrorCode DMSetUseNatural(DM dm, PetscBool useNatural)
6809: {
6810: PetscFunctionBegin;
6813: dm->useNatural = useNatural;
6814: PetscFunctionReturn(PETSC_SUCCESS);
6815: }
6817: /*@
6818: DMCreateLabel - Create a label of the given name if it does not already exist in the `DM`
6820: Not Collective
6822: Input Parameters:
6823: + dm - The `DM` object
6824: - name - The label name
6826: Level: intermediate
6828: .seealso: [](ch_dmbase), `DM`, `DMLabelCreate()`, `DMHasLabel()`, `DMGetLabelValue()`, `DMSetLabelValue()`, `DMGetStratumIS()`
6829: @*/
6830: PetscErrorCode DMCreateLabel(DM dm, const char name[])
6831: {
6832: PetscBool flg;
6833: DMLabel label;
6835: PetscFunctionBegin;
6837: PetscAssertPointer(name, 2);
6838: PetscCall(DMHasLabel(dm, name, &flg));
6839: if (!flg) {
6840: PetscCall(DMLabelCreate(PETSC_COMM_SELF, name, &label));
6841: PetscCall(DMAddLabel(dm, label));
6842: PetscCall(DMLabelDestroy(&label));
6843: }
6844: PetscFunctionReturn(PETSC_SUCCESS);
6845: }
6847: /*@
6848: DMCreateLabelAtIndex - Create a label of the given name at the given index. If it already exists in the `DM`, move it to this index.
6850: Not Collective
6852: Input Parameters:
6853: + dm - The `DM` object
6854: . l - The index for the label
6855: - name - The label name
6857: Level: intermediate
6859: .seealso: [](ch_dmbase), `DM`, `DMCreateLabel()`, `DMLabelCreate()`, `DMHasLabel()`, `DMGetLabelValue()`, `DMSetLabelValue()`, `DMGetStratumIS()`
6860: @*/
6861: PetscErrorCode DMCreateLabelAtIndex(DM dm, PetscInt l, const char name[])
6862: {
6863: DMLabelLink orig, prev = NULL;
6864: DMLabel label;
6865: PetscInt Nl, m;
6866: PetscBool flg, match;
6867: const char *lname;
6869: PetscFunctionBegin;
6871: PetscAssertPointer(name, 3);
6872: PetscCall(DMHasLabel(dm, name, &flg));
6873: if (!flg) {
6874: PetscCall(DMLabelCreate(PETSC_COMM_SELF, name, &label));
6875: PetscCall(DMAddLabel(dm, label));
6876: PetscCall(DMLabelDestroy(&label));
6877: }
6878: PetscCall(DMGetNumLabels(dm, &Nl));
6879: PetscCheck(l < Nl, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Label index %" PetscInt_FMT " must be in [0, %" PetscInt_FMT ")", l, Nl);
6880: for (m = 0, orig = dm->labels; m < Nl; ++m, prev = orig, orig = orig->next) {
6881: PetscCall(PetscObjectGetName((PetscObject)orig->label, &lname));
6882: PetscCall(PetscStrcmp(name, lname, &match));
6883: if (match) break;
6884: }
6885: if (m == l) PetscFunctionReturn(PETSC_SUCCESS);
6886: if (!m) dm->labels = orig->next;
6887: else prev->next = orig->next;
6888: if (!l) {
6889: orig->next = dm->labels;
6890: dm->labels = orig;
6891: } else {
6892: for (m = 0, prev = dm->labels; m < l - 1; ++m, prev = prev->next);
6893: orig->next = prev->next;
6894: prev->next = orig;
6895: }
6896: PetscFunctionReturn(PETSC_SUCCESS);
6897: }
6899: /*@
6900: DMGetLabelValue - Get the value in a `DMLabel` for the given point, with -1 as the default
6902: Not Collective
6904: Input Parameters:
6905: + dm - The `DM` object
6906: . name - The label name
6907: - point - The mesh point
6909: Output Parameter:
6910: . value - The label value for this point, or -1 if the point is not in the label
6912: Level: beginner
6914: .seealso: [](ch_dmbase), `DM`, `DMLabelGetValue()`, `DMSetLabelValue()`, `DMGetStratumIS()`
6915: @*/
6916: PetscErrorCode DMGetLabelValue(DM dm, const char name[], PetscInt point, PetscInt *value)
6917: {
6918: DMLabel label;
6920: PetscFunctionBegin;
6922: PetscAssertPointer(name, 2);
6923: PetscCall(DMGetLabel(dm, name, &label));
6924: PetscCheck(label, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "No label named %s was found", name);
6925: PetscCall(DMLabelGetValue(label, point, value));
6926: PetscFunctionReturn(PETSC_SUCCESS);
6927: }
6929: /*@
6930: DMSetLabelValue - Add a point to a `DMLabel` with given value
6932: Not Collective
6934: Input Parameters:
6935: + dm - The `DM` object
6936: . name - The label name
6937: . point - The mesh point
6938: - value - The label value for this point
6940: Output Parameter:
6942: Level: beginner
6944: .seealso: [](ch_dmbase), `DM`, `DMLabelSetValue()`, `DMGetStratumIS()`, `DMClearLabelValue()`
6945: @*/
6946: PetscErrorCode DMSetLabelValue(DM dm, const char name[], PetscInt point, PetscInt value)
6947: {
6948: DMLabel label;
6950: PetscFunctionBegin;
6952: PetscAssertPointer(name, 2);
6953: PetscCall(DMGetLabel(dm, name, &label));
6954: if (!label) {
6955: PetscCall(DMCreateLabel(dm, name));
6956: PetscCall(DMGetLabel(dm, name, &label));
6957: }
6958: PetscCall(DMLabelSetValue(label, point, value));
6959: PetscFunctionReturn(PETSC_SUCCESS);
6960: }
6962: /*@
6963: DMClearLabelValue - Remove a point from a `DMLabel` with given value
6965: Not Collective
6967: Input Parameters:
6968: + dm - The `DM` object
6969: . name - The label name
6970: . point - The mesh point
6971: - value - The label value for this point
6973: Level: beginner
6975: .seealso: [](ch_dmbase), `DM`, `DMLabelClearValue()`, `DMSetLabelValue()`, `DMGetStratumIS()`
6976: @*/
6977: PetscErrorCode DMClearLabelValue(DM dm, const char name[], PetscInt point, PetscInt value)
6978: {
6979: DMLabel label;
6981: PetscFunctionBegin;
6983: PetscAssertPointer(name, 2);
6984: PetscCall(DMGetLabel(dm, name, &label));
6985: if (!label) PetscFunctionReturn(PETSC_SUCCESS);
6986: PetscCall(DMLabelClearValue(label, point, value));
6987: PetscFunctionReturn(PETSC_SUCCESS);
6988: }
6990: /*@
6991: DMGetLabelSize - Get the value of `DMLabelGetNumValues()` of a `DMLabel` in the `DM`
6993: Not Collective
6995: Input Parameters:
6996: + dm - The `DM` object
6997: - name - The label name
6999: Output Parameter:
7000: . size - The number of different integer ids, or 0 if the label does not exist
7002: Level: beginner
7004: Developer Note:
7005: This should be renamed to something like `DMGetLabelNumValues()` or removed.
7007: .seealso: [](ch_dmbase), `DM`, `DMLabelGetNumValues()`, `DMSetLabelValue()`, `DMGetLabel()`
7008: @*/
7009: PetscErrorCode DMGetLabelSize(DM dm, const char name[], PetscInt *size)
7010: {
7011: DMLabel label;
7013: PetscFunctionBegin;
7015: PetscAssertPointer(name, 2);
7016: PetscAssertPointer(size, 3);
7017: PetscCall(DMGetLabel(dm, name, &label));
7018: *size = 0;
7019: if (!label) PetscFunctionReturn(PETSC_SUCCESS);
7020: PetscCall(DMLabelGetNumValues(label, size));
7021: PetscFunctionReturn(PETSC_SUCCESS);
7022: }
7024: /*@
7025: DMGetLabelIdIS - Get the `DMLabelGetValueIS()` from a `DMLabel` in the `DM`
7027: Not Collective
7029: Input Parameters:
7030: + dm - The `DM` object
7031: - name - The label name
7033: Output Parameter:
7034: . ids - The integer ids, or `NULL` if the label does not exist
7036: Level: beginner
7038: .seealso: [](ch_dmbase), `DM`, `DMLabelGetValueIS()`, `DMGetLabelSize()`
7039: @*/
7040: PetscErrorCode DMGetLabelIdIS(DM dm, const char name[], IS *ids)
7041: {
7042: DMLabel label;
7044: PetscFunctionBegin;
7046: PetscAssertPointer(name, 2);
7047: PetscAssertPointer(ids, 3);
7048: PetscCall(DMGetLabel(dm, name, &label));
7049: *ids = NULL;
7050: if (label) PetscCall(DMLabelGetValueIS(label, ids));
7051: else {
7052: /* returning an empty IS */
7053: PetscCall(ISCreateGeneral(PETSC_COMM_SELF, 0, NULL, PETSC_USE_POINTER, ids));
7054: }
7055: PetscFunctionReturn(PETSC_SUCCESS);
7056: }
7058: /*@
7059: DMGetStratumSize - Get the number of points in a label stratum
7061: Not Collective
7063: Input Parameters:
7064: + dm - The `DM` object
7065: . name - The label name of the stratum
7066: - value - The stratum value
7068: Output Parameter:
7069: . size - The number of points, also called the stratum size
7071: Level: beginner
7073: .seealso: [](ch_dmbase), `DM`, `DMLabelGetStratumSize()`, `DMGetLabelSize()`, `DMGetLabelIds()`
7074: @*/
7075: PetscErrorCode DMGetStratumSize(DM dm, const char name[], PetscInt value, PetscInt *size)
7076: {
7077: DMLabel label;
7079: PetscFunctionBegin;
7081: PetscAssertPointer(name, 2);
7082: PetscAssertPointer(size, 4);
7083: PetscCall(DMGetLabel(dm, name, &label));
7084: *size = 0;
7085: if (!label) PetscFunctionReturn(PETSC_SUCCESS);
7086: PetscCall(DMLabelGetStratumSize(label, value, size));
7087: PetscFunctionReturn(PETSC_SUCCESS);
7088: }
7090: /*@
7091: DMGetStratumIS - Get the points in a label stratum
7093: Not Collective
7095: Input Parameters:
7096: + dm - The `DM` object
7097: . name - The label name
7098: - value - The stratum value
7100: Output Parameter:
7101: . points - The stratum points, or `NULL` if the label does not exist or does not have that value
7103: Level: beginner
7105: .seealso: [](ch_dmbase), `DM`, `DMLabelGetStratumIS()`, `DMGetStratumSize()`
7106: @*/
7107: PetscErrorCode DMGetStratumIS(DM dm, const char name[], PetscInt value, IS *points)
7108: {
7109: DMLabel label;
7111: PetscFunctionBegin;
7113: PetscAssertPointer(name, 2);
7114: PetscAssertPointer(points, 4);
7115: PetscCall(DMGetLabel(dm, name, &label));
7116: *points = NULL;
7117: if (!label) PetscFunctionReturn(PETSC_SUCCESS);
7118: PetscCall(DMLabelGetStratumIS(label, value, points));
7119: PetscFunctionReturn(PETSC_SUCCESS);
7120: }
7122: /*@
7123: DMSetStratumIS - Set the points in a label stratum
7125: Not Collective
7127: Input Parameters:
7128: + dm - The `DM` object
7129: . name - The label name
7130: . value - The stratum value
7131: - points - The stratum points
7133: Level: beginner
7135: .seealso: [](ch_dmbase), `DM`, `DMLabel`, `DMClearLabelStratum()`, `DMLabelClearStratum()`, `DMLabelSetStratumIS()`, `DMGetStratumSize()`
7136: @*/
7137: PetscErrorCode DMSetStratumIS(DM dm, const char name[], PetscInt value, IS points)
7138: {
7139: DMLabel label;
7141: PetscFunctionBegin;
7143: PetscAssertPointer(name, 2);
7145: PetscCall(DMGetLabel(dm, name, &label));
7146: if (!label) PetscFunctionReturn(PETSC_SUCCESS);
7147: PetscCall(DMLabelSetStratumIS(label, value, points));
7148: PetscFunctionReturn(PETSC_SUCCESS);
7149: }
7151: /*@
7152: DMClearLabelStratum - Remove all points from a stratum from a `DMLabel`
7154: Not Collective
7156: Input Parameters:
7157: + dm - The `DM` object
7158: . name - The label name
7159: - value - The label value for this point
7161: Output Parameter:
7163: Level: beginner
7165: .seealso: [](ch_dmbase), `DM`, `DMLabel`, `DMLabelClearStratum()`, `DMSetLabelValue()`, `DMGetStratumIS()`, `DMClearLabelValue()`
7166: @*/
7167: PetscErrorCode DMClearLabelStratum(DM dm, const char name[], PetscInt value)
7168: {
7169: DMLabel label;
7171: PetscFunctionBegin;
7173: PetscAssertPointer(name, 2);
7174: PetscCall(DMGetLabel(dm, name, &label));
7175: if (!label) PetscFunctionReturn(PETSC_SUCCESS);
7176: PetscCall(DMLabelClearStratum(label, value));
7177: PetscFunctionReturn(PETSC_SUCCESS);
7178: }
7180: /*@
7181: DMGetNumLabels - Return the number of labels defined by on the `DM`
7183: Not Collective
7185: Input Parameter:
7186: . dm - The `DM` object
7188: Output Parameter:
7189: . numLabels - the number of Labels
7191: Level: intermediate
7193: .seealso: [](ch_dmbase), `DM`, `DMLabel`, `DMGetLabelByNum()`, `DMGetLabelName()`, `DMGetLabelValue()`, `DMSetLabelValue()`, `DMGetStratumIS()`
7194: @*/
7195: PetscErrorCode DMGetNumLabels(DM dm, PetscInt *numLabels)
7196: {
7197: DMLabelLink next = dm->labels;
7198: PetscInt n = 0;
7200: PetscFunctionBegin;
7202: PetscAssertPointer(numLabels, 2);
7203: while (next) {
7204: ++n;
7205: next = next->next;
7206: }
7207: *numLabels = n;
7208: PetscFunctionReturn(PETSC_SUCCESS);
7209: }
7211: /*@
7212: DMGetLabelName - Return the name of nth label
7214: Not Collective
7216: Input Parameters:
7217: + dm - The `DM` object
7218: - n - the label number
7220: Output Parameter:
7221: . name - the label name
7223: Level: intermediate
7225: Developer Note:
7226: Some of the functions that appropriate on labels using their number have the suffix ByNum, others do not.
7228: .seealso: [](ch_dmbase), `DM`, `DMLabel`, `DMGetLabelByNum()`, `DMGetLabel()`, `DMGetLabelValue()`, `DMSetLabelValue()`, `DMGetStratumIS()`
7229: @*/
7230: PetscErrorCode DMGetLabelName(DM dm, PetscInt n, const char *name[])
7231: {
7232: DMLabelLink next = dm->labels;
7233: PetscInt l = 0;
7235: PetscFunctionBegin;
7237: PetscAssertPointer(name, 3);
7238: while (next) {
7239: if (l == n) {
7240: PetscCall(PetscObjectGetName((PetscObject)next->label, name));
7241: PetscFunctionReturn(PETSC_SUCCESS);
7242: }
7243: ++l;
7244: next = next->next;
7245: }
7246: SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Label %" PetscInt_FMT " does not exist in this DM", n);
7247: }
7249: /*@
7250: DMHasLabel - Determine whether the `DM` has a label of a given name
7252: Not Collective
7254: Input Parameters:
7255: + dm - The `DM` object
7256: - name - The label name
7258: Output Parameter:
7259: . hasLabel - `PETSC_TRUE` if the label is present
7261: Level: intermediate
7263: .seealso: [](ch_dmbase), `DM`, `DMLabel`, `DMGetLabel()`, `DMGetLabelByNum()`, `DMCreateLabel()`, `DMGetLabelValue()`, `DMSetLabelValue()`, `DMGetStratumIS()`
7264: @*/
7265: PetscErrorCode DMHasLabel(DM dm, const char name[], PetscBool *hasLabel)
7266: {
7267: DMLabelLink next = dm->labels;
7268: const char *lname;
7270: PetscFunctionBegin;
7272: PetscAssertPointer(name, 2);
7273: PetscAssertPointer(hasLabel, 3);
7274: *hasLabel = PETSC_FALSE;
7275: while (next) {
7276: PetscCall(PetscObjectGetName((PetscObject)next->label, &lname));
7277: PetscCall(PetscStrcmp(name, lname, hasLabel));
7278: if (*hasLabel) break;
7279: next = next->next;
7280: }
7281: PetscFunctionReturn(PETSC_SUCCESS);
7282: }
7284: // PetscClangLinter pragma ignore: -fdoc-section-header-unknown
7285: /*@
7286: DMGetLabel - Return the label of a given name, or `NULL`, from a `DM`
7288: Not Collective
7290: Input Parameters:
7291: + dm - The `DM` object
7292: - name - The label name
7294: Output Parameter:
7295: . label - The `DMLabel`, or `NULL` if the label is absent
7297: Default labels in a `DMPLEX`:
7298: + "depth" - Holds the depth (co-dimension) of each mesh point
7299: . "celltype" - Holds the topological type of each cell
7300: . "ghost" - If the DM is distributed with overlap, this marks the cells and faces in the overlap
7301: . "Cell Sets" - Mirrors the cell sets defined by GMsh and ExodusII
7302: . "Face Sets" - Mirrors the face sets defined by GMsh and ExodusII
7303: - "Vertex Sets" - Mirrors the vertex sets defined by GMsh
7305: Level: intermediate
7307: .seealso: [](ch_dmbase), `DM`, `DMLabel`, `DMHasLabel()`, `DMGetLabelByNum()`, `DMAddLabel()`, `DMCreateLabel()`, `DMPlexGetDepthLabel()`, `DMPlexGetCellType()`
7308: @*/
7309: PetscErrorCode DMGetLabel(DM dm, const char name[], DMLabel *label)
7310: {
7311: DMLabelLink next = dm->labels;
7312: PetscBool hasLabel;
7313: const char *lname;
7315: PetscFunctionBegin;
7317: PetscAssertPointer(name, 2);
7318: PetscAssertPointer(label, 3);
7319: *label = NULL;
7320: while (next) {
7321: PetscCall(PetscObjectGetName((PetscObject)next->label, &lname));
7322: PetscCall(PetscStrcmp(name, lname, &hasLabel));
7323: if (hasLabel) {
7324: *label = next->label;
7325: break;
7326: }
7327: next = next->next;
7328: }
7329: PetscFunctionReturn(PETSC_SUCCESS);
7330: }
7332: /*@
7333: DMGetLabelByNum - Return the nth label on a `DM`
7335: Not Collective
7337: Input Parameters:
7338: + dm - The `DM` object
7339: - n - the label number
7341: Output Parameter:
7342: . label - the label
7344: Level: intermediate
7346: .seealso: [](ch_dmbase), `DM`, `DMLabel`, `DMAddLabel()`, `DMGetLabelValue()`, `DMSetLabelValue()`, `DMGetStratumIS()`
7347: @*/
7348: PetscErrorCode DMGetLabelByNum(DM dm, PetscInt n, DMLabel *label)
7349: {
7350: DMLabelLink next = dm->labels;
7351: PetscInt l = 0;
7353: PetscFunctionBegin;
7355: PetscAssertPointer(label, 3);
7356: while (next) {
7357: if (l == n) {
7358: *label = next->label;
7359: PetscFunctionReturn(PETSC_SUCCESS);
7360: }
7361: ++l;
7362: next = next->next;
7363: }
7364: SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Label %" PetscInt_FMT " does not exist in this DM", n);
7365: }
7367: /*@
7368: DMAddLabel - Add the label to this `DM`
7370: Not Collective
7372: Input Parameters:
7373: + dm - The `DM` object
7374: - label - The `DMLabel`
7376: Level: developer
7378: .seealso: [](ch_dmbase), `DM`, `DMLabel`, `DMCreateLabel()`, `DMHasLabel()`, `DMGetLabelValue()`, `DMSetLabelValue()`, `DMGetStratumIS()`
7379: @*/
7380: PetscErrorCode DMAddLabel(DM dm, DMLabel label)
7381: {
7382: DMLabelLink l, *p, tmpLabel;
7383: PetscBool hasLabel;
7384: const char *lname;
7385: PetscBool flg;
7387: PetscFunctionBegin;
7389: PetscCall(PetscObjectGetName((PetscObject)label, &lname));
7390: PetscCall(DMHasLabel(dm, lname, &hasLabel));
7391: PetscCheck(!hasLabel, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Label %s already exists in this DM", lname);
7392: PetscCall(PetscCalloc1(1, &tmpLabel));
7393: tmpLabel->label = label;
7394: tmpLabel->output = PETSC_TRUE;
7395: for (p = &dm->labels; (l = *p); p = &l->next) { }
7396: *p = tmpLabel;
7397: PetscCall(PetscObjectReference((PetscObject)label));
7398: PetscCall(PetscStrcmp(lname, "depth", &flg));
7399: if (flg) dm->depthLabel = label;
7400: PetscCall(PetscStrcmp(lname, "celltype", &flg));
7401: if (flg) dm->celltypeLabel = label;
7402: PetscFunctionReturn(PETSC_SUCCESS);
7403: }
7405: // PetscClangLinter pragma ignore: -fdoc-section-header-unknown
7406: /*@
7407: DMSetLabel - Replaces the label of a given name, or ignores it if the name is not present
7409: Not Collective
7411: Input Parameters:
7412: + dm - The `DM` object
7413: - label - The `DMLabel`, having the same name, to substitute
7415: Default labels in a `DMPLEX`:
7416: + "depth" - Holds the depth (co-dimension) of each mesh point
7417: . "celltype" - Holds the topological type of each cell
7418: . "ghost" - If the DM is distributed with overlap, this marks the cells and faces in the overlap
7419: . "Cell Sets" - Mirrors the cell sets defined by GMsh and ExodusII
7420: . "Face Sets" - Mirrors the face sets defined by GMsh and ExodusII
7421: - "Vertex Sets" - Mirrors the vertex sets defined by GMsh
7423: Level: intermediate
7425: .seealso: [](ch_dmbase), `DM`, `DMLabel`, `DMCreateLabel()`, `DMHasLabel()`, `DMPlexGetDepthLabel()`, `DMPlexGetCellType()`
7426: @*/
7427: PetscErrorCode DMSetLabel(DM dm, DMLabel label)
7428: {
7429: DMLabelLink next = dm->labels;
7430: PetscBool hasLabel, flg;
7431: const char *name, *lname;
7433: PetscFunctionBegin;
7436: PetscCall(PetscObjectGetName((PetscObject)label, &name));
7437: while (next) {
7438: PetscCall(PetscObjectGetName((PetscObject)next->label, &lname));
7439: PetscCall(PetscStrcmp(name, lname, &hasLabel));
7440: if (hasLabel) {
7441: PetscCall(PetscObjectReference((PetscObject)label));
7442: PetscCall(PetscStrcmp(lname, "depth", &flg));
7443: if (flg) dm->depthLabel = label;
7444: PetscCall(PetscStrcmp(lname, "celltype", &flg));
7445: if (flg) dm->celltypeLabel = label;
7446: PetscCall(DMLabelDestroy(&next->label));
7447: next->label = label;
7448: break;
7449: }
7450: next = next->next;
7451: }
7452: PetscFunctionReturn(PETSC_SUCCESS);
7453: }
7455: /*@
7456: DMRemoveLabel - Remove the label given by name from this `DM`
7458: Not Collective
7460: Input Parameters:
7461: + dm - The `DM` object
7462: - name - The label name
7464: Output Parameter:
7465: . label - The `DMLabel`, or `NULL` if the label is absent. Pass in `NULL` to call `DMLabelDestroy()` on the label, otherwise the
7466: caller is responsible for calling `DMLabelDestroy()`.
7468: Level: developer
7470: .seealso: [](ch_dmbase), `DM`, `DMLabel`, `DMCreateLabel()`, `DMHasLabel()`, `DMGetLabel()`, `DMGetLabelValue()`, `DMSetLabelValue()`, `DMLabelDestroy()`, `DMRemoveLabelBySelf()`
7471: @*/
7472: PetscErrorCode DMRemoveLabel(DM dm, const char name[], DMLabel *label)
7473: {
7474: DMLabelLink link, *pnext;
7475: PetscBool hasLabel;
7476: const char *lname;
7478: PetscFunctionBegin;
7480: PetscAssertPointer(name, 2);
7481: if (label) {
7482: PetscAssertPointer(label, 3);
7483: *label = NULL;
7484: }
7485: for (pnext = &dm->labels; (link = *pnext); pnext = &link->next) {
7486: PetscCall(PetscObjectGetName((PetscObject)link->label, &lname));
7487: PetscCall(PetscStrcmp(name, lname, &hasLabel));
7488: if (hasLabel) {
7489: *pnext = link->next; /* Remove from list */
7490: PetscCall(PetscStrcmp(name, "depth", &hasLabel));
7491: if (hasLabel) dm->depthLabel = NULL;
7492: PetscCall(PetscStrcmp(name, "celltype", &hasLabel));
7493: if (hasLabel) dm->celltypeLabel = NULL;
7494: if (label) *label = link->label;
7495: else PetscCall(DMLabelDestroy(&link->label));
7496: PetscCall(PetscFree(link));
7497: break;
7498: }
7499: }
7500: PetscFunctionReturn(PETSC_SUCCESS);
7501: }
7503: /*@
7504: DMRemoveLabelBySelf - Remove the label from this `DM`
7506: Not Collective
7508: Input Parameters:
7509: + dm - The `DM` object
7510: . label - The `DMLabel` to be removed from the `DM`
7511: - failNotFound - Should it fail if the label is not found in the `DM`?
7513: Level: developer
7515: Note:
7516: Only exactly the same instance is removed if found, name match is ignored.
7517: If the `DM` has an exclusive reference to the label, the label gets destroyed and
7518: *label nullified.
7520: .seealso: [](ch_dmbase), `DM`, `DMLabel`, `DMCreateLabel()`, `DMHasLabel()`, `DMGetLabel()`, `DMGetLabelValue()`, `DMSetLabelValue()`, `DMLabelDestroy()`, `DMRemoveLabel()`
7521: @*/
7522: PetscErrorCode DMRemoveLabelBySelf(DM dm, DMLabel *label, PetscBool failNotFound)
7523: {
7524: DMLabelLink link, *pnext;
7525: PetscBool hasLabel = PETSC_FALSE;
7527: PetscFunctionBegin;
7529: PetscAssertPointer(label, 2);
7530: if (!*label && !failNotFound) PetscFunctionReturn(PETSC_SUCCESS);
7533: for (pnext = &dm->labels; (link = *pnext); pnext = &link->next) {
7534: if (*label == link->label) {
7535: hasLabel = PETSC_TRUE;
7536: *pnext = link->next; /* Remove from list */
7537: if (*label == dm->depthLabel) dm->depthLabel = NULL;
7538: if (*label == dm->celltypeLabel) dm->celltypeLabel = NULL;
7539: if (((PetscObject)link->label)->refct < 2) *label = NULL; /* nullify if exclusive reference */
7540: PetscCall(DMLabelDestroy(&link->label));
7541: PetscCall(PetscFree(link));
7542: break;
7543: }
7544: }
7545: PetscCheck(hasLabel || !failNotFound, PetscObjectComm((PetscObject)dm), PETSC_ERR_ARG_WRONG, "Given label not found in DM");
7546: PetscFunctionReturn(PETSC_SUCCESS);
7547: }
7549: /*@
7550: DMGetLabelOutput - Get the output flag for a given label
7552: Not Collective
7554: Input Parameters:
7555: + dm - The `DM` object
7556: - name - The label name
7558: Output Parameter:
7559: . output - The flag for output
7561: Level: developer
7563: .seealso: [](ch_dmbase), `DM`, `DMLabel`, `DMSetLabelOutput()`, `DMCreateLabel()`, `DMHasLabel()`, `DMGetLabelValue()`, `DMSetLabelValue()`, `DMGetStratumIS()`
7564: @*/
7565: PetscErrorCode DMGetLabelOutput(DM dm, const char name[], PetscBool *output)
7566: {
7567: DMLabelLink next = dm->labels;
7568: const char *lname;
7570: PetscFunctionBegin;
7572: PetscAssertPointer(name, 2);
7573: PetscAssertPointer(output, 3);
7574: while (next) {
7575: PetscBool flg;
7577: PetscCall(PetscObjectGetName((PetscObject)next->label, &lname));
7578: PetscCall(PetscStrcmp(name, lname, &flg));
7579: if (flg) {
7580: *output = next->output;
7581: PetscFunctionReturn(PETSC_SUCCESS);
7582: }
7583: next = next->next;
7584: }
7585: SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "No label named %s was present in this dm", name);
7586: }
7588: /*@
7589: DMSetLabelOutput - Set if a given label should be saved to a `PetscViewer` in calls to `DMView()`
7591: Not Collective
7593: Input Parameters:
7594: + dm - The `DM` object
7595: . name - The label name
7596: - output - `PETSC_TRUE` to save the label to the viewer
7598: Level: developer
7600: .seealso: [](ch_dmbase), `DM`, `DMLabel`, `DMGetOutputFlag()`, `DMGetLabelOutput()`, `DMCreateLabel()`, `DMHasLabel()`, `DMGetLabelValue()`, `DMSetLabelValue()`, `DMGetStratumIS()`
7601: @*/
7602: PetscErrorCode DMSetLabelOutput(DM dm, const char name[], PetscBool output)
7603: {
7604: DMLabelLink next = dm->labels;
7605: const char *lname;
7607: PetscFunctionBegin;
7609: PetscAssertPointer(name, 2);
7610: while (next) {
7611: PetscBool flg;
7613: PetscCall(PetscObjectGetName((PetscObject)next->label, &lname));
7614: PetscCall(PetscStrcmp(name, lname, &flg));
7615: if (flg) {
7616: next->output = output;
7617: PetscFunctionReturn(PETSC_SUCCESS);
7618: }
7619: next = next->next;
7620: }
7621: SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "No label named %s was present in this dm", name);
7622: }
7624: /*@
7625: DMCopyLabels - Copy labels from one `DM` mesh to another `DM` with a superset of the points
7627: Collective
7629: Input Parameters:
7630: + dmA - The `DM` object with initial labels
7631: . dmB - The `DM` object to which labels are copied
7632: . mode - Copy labels by pointers (`PETSC_OWN_POINTER`) or duplicate them (`PETSC_COPY_VALUES`)
7633: . all - Copy all labels including "depth", "dim", and "celltype" (`PETSC_TRUE`) which are otherwise ignored (`PETSC_FALSE`)
7634: - emode - How to behave when a `DMLabel` in the source and destination `DM`s with the same name is encountered (see `DMCopyLabelsMode`)
7636: Level: intermediate
7638: Note:
7639: This is typically used when interpolating or otherwise adding to a mesh, or testing.
7641: .seealso: [](ch_dmbase), `DM`, `DMLabel`, `DMAddLabel()`, `DMCopyLabelsMode`
7642: @*/
7643: PetscErrorCode DMCopyLabels(DM dmA, DM dmB, PetscCopyMode mode, PetscBool all, DMCopyLabelsMode emode)
7644: {
7645: DMLabel label, labelNew, labelOld;
7646: const char *name;
7647: PetscBool flg;
7648: DMLabelLink link;
7650: PetscFunctionBegin;
7655: PetscCheck(mode != PETSC_USE_POINTER, PetscObjectComm((PetscObject)dmA), PETSC_ERR_SUP, "PETSC_USE_POINTER not supported for objects");
7656: if (dmA == dmB) PetscFunctionReturn(PETSC_SUCCESS);
7657: for (link = dmA->labels; link; link = link->next) {
7658: label = link->label;
7659: PetscCall(PetscObjectGetName((PetscObject)label, &name));
7660: if (!all) {
7661: PetscCall(PetscStrcmp(name, "depth", &flg));
7662: if (flg) continue;
7663: PetscCall(PetscStrcmp(name, "dim", &flg));
7664: if (flg) continue;
7665: PetscCall(PetscStrcmp(name, "celltype", &flg));
7666: if (flg) continue;
7667: }
7668: PetscCall(DMGetLabel(dmB, name, &labelOld));
7669: if (labelOld) {
7670: switch (emode) {
7671: case DM_COPY_LABELS_KEEP:
7672: continue;
7673: case DM_COPY_LABELS_REPLACE:
7674: PetscCall(DMRemoveLabelBySelf(dmB, &labelOld, PETSC_TRUE));
7675: break;
7676: case DM_COPY_LABELS_FAIL:
7677: SETERRQ(PetscObjectComm((PetscObject)dmA), PETSC_ERR_ARG_OUTOFRANGE, "Label %s already exists in destination DM", name);
7678: default:
7679: SETERRQ(PetscObjectComm((PetscObject)dmA), PETSC_ERR_ARG_OUTOFRANGE, "Unhandled DMCopyLabelsMode %d", (int)emode);
7680: }
7681: }
7682: if (mode == PETSC_COPY_VALUES) PetscCall(DMLabelDuplicate(label, &labelNew));
7683: else labelNew = label;
7684: PetscCall(DMAddLabel(dmB, labelNew));
7685: if (mode == PETSC_COPY_VALUES) PetscCall(DMLabelDestroy(&labelNew));
7686: }
7687: PetscFunctionReturn(PETSC_SUCCESS);
7688: }
7690: /*@C
7691: DMCompareLabels - Compare labels between two `DM` objects
7693: Collective; No Fortran Support
7695: Input Parameters:
7696: + dm0 - First `DM` object
7697: - dm1 - Second `DM` object
7699: Output Parameters:
7700: + equal - (Optional) Flag whether labels of `dm0` and `dm1` are the same
7701: - message - (Optional) Message describing the difference, or `NULL` if there is no difference
7703: Level: intermediate
7705: Notes:
7706: The output flag equal will be the same on all processes.
7708: If equal is passed as `NULL` and difference is found, an error is thrown on all processes.
7710: Make sure to pass equal is `NULL` on all processes or none of them.
7712: The output message is set independently on each rank.
7714: message must be freed with `PetscFree()`
7716: If message is passed as `NULL` and a difference is found, the difference description is printed to `stderr` in synchronized manner.
7718: Make sure to pass message as `NULL` on all processes or no processes.
7720: Labels are matched by name. If the number of labels and their names are equal,
7721: `DMLabelCompare()` is used to compare each pair of labels with the same name.
7723: Developer Note:
7724: Cannot automatically generate the Fortran stub because `message` must be freed with `PetscFree()`
7726: .seealso: [](ch_dmbase), `DM`, `DMLabel`, `DMAddLabel()`, `DMCopyLabelsMode`, `DMLabelCompare()`
7727: @*/
7728: PetscErrorCode DMCompareLabels(DM dm0, DM dm1, PetscBool *equal, char *message[]) PeNS
7729: {
7730: PetscInt n;
7731: char msg[PETSC_MAX_PATH_LEN] = "";
7732: PetscBool eq;
7733: MPI_Comm comm;
7734: PetscMPIInt rank;
7736: PetscFunctionBegin;
7739: PetscCheckSameComm(dm0, 1, dm1, 2);
7740: if (equal) PetscAssertPointer(equal, 3);
7741: if (message) PetscAssertPointer(message, 4);
7742: PetscCall(PetscObjectGetComm((PetscObject)dm0, &comm));
7743: PetscCallMPI(MPI_Comm_rank(comm, &rank));
7744: {
7745: PetscInt n1;
7747: PetscCall(DMGetNumLabels(dm0, &n));
7748: PetscCall(DMGetNumLabels(dm1, &n1));
7749: eq = (PetscBool)(n == n1);
7750: if (!eq) PetscCall(PetscSNPrintf(msg, sizeof(msg), "Number of labels in dm0 = %" PetscInt_FMT " != %" PetscInt_FMT " = Number of labels in dm1", n, n1));
7751: PetscCallMPI(MPIU_Allreduce(MPI_IN_PLACE, &eq, 1, MPI_C_BOOL, MPI_LAND, comm));
7752: if (!eq) goto finish;
7753: }
7754: for (PetscInt i = 0; i < n; i++) {
7755: DMLabel l0, l1;
7756: const char *name;
7757: char *msgInner;
7759: /* Ignore label order */
7760: PetscCall(DMGetLabelByNum(dm0, i, &l0));
7761: PetscCall(PetscObjectGetName((PetscObject)l0, &name));
7762: PetscCall(DMGetLabel(dm1, name, &l1));
7763: if (!l1) {
7764: PetscCall(PetscSNPrintf(msg, sizeof(msg), "Label \"%s\" (#%" PetscInt_FMT " in dm0) not found in dm1", name, i));
7765: eq = PETSC_FALSE;
7766: break;
7767: }
7768: PetscCall(DMLabelCompare(comm, l0, l1, &eq, &msgInner));
7769: PetscCall(PetscStrncpy(msg, msgInner, sizeof(msg)));
7770: PetscCall(PetscFree(msgInner));
7771: if (!eq) break;
7772: }
7773: PetscCallMPI(MPIU_Allreduce(MPI_IN_PLACE, &eq, 1, MPI_C_BOOL, MPI_LAND, comm));
7774: finish:
7775: /* If message output arg not set, print to stderr */
7776: if (message) {
7777: *message = NULL;
7778: if (msg[0]) PetscCall(PetscStrallocpy(msg, message));
7779: } else {
7780: if (msg[0]) PetscCall(PetscSynchronizedFPrintf(comm, PETSC_STDERR, "[%d] %s\n", rank, msg));
7781: PetscCall(PetscSynchronizedFlush(comm, PETSC_STDERR));
7782: }
7783: /* If same output arg not ser and labels are not equal, throw error */
7784: if (equal) *equal = eq;
7785: else PetscCheck(eq, comm, PETSC_ERR_ARG_INCOMP, "DMLabels are not the same in dm0 and dm1");
7786: PetscFunctionReturn(PETSC_SUCCESS);
7787: }
7789: PetscErrorCode DMSetLabelValue_Fast(DM dm, DMLabel *label, const char name[], PetscInt point, PetscInt value)
7790: {
7791: PetscFunctionBegin;
7792: PetscAssertPointer(label, 2);
7793: if (!*label) {
7794: PetscCall(DMCreateLabel(dm, name));
7795: PetscCall(DMGetLabel(dm, name, label));
7796: }
7797: PetscCall(DMLabelSetValue(*label, point, value));
7798: PetscFunctionReturn(PETSC_SUCCESS);
7799: }
7801: /*
7802: Many mesh programs, such as Triangle and TetGen, allow only a single label for each mesh point. Therefore, we would
7803: like to encode all label IDs using a single, universal label. We can do this by assigning an integer to every
7804: (label, id) pair in the DM.
7806: However, a mesh point can have multiple labels, so we must separate all these values. We will assign a bit range to
7807: each label.
7808: */
7809: PetscErrorCode DMUniversalLabelCreate(DM dm, DMUniversalLabel *universal)
7810: {
7811: DMUniversalLabel ul;
7812: PetscBool *active;
7813: PetscInt pStart, pEnd, p, Nl, l, m;
7815: PetscFunctionBegin;
7816: PetscCall(PetscMalloc1(1, &ul));
7817: PetscCall(DMLabelCreate(PETSC_COMM_SELF, "universal", &ul->label));
7818: PetscCall(DMGetNumLabels(dm, &Nl));
7819: PetscCall(PetscCalloc1(Nl, &active));
7820: ul->Nl = 0;
7821: for (l = 0; l < Nl; ++l) {
7822: PetscBool isdepth, iscelltype;
7823: const char *name;
7825: PetscCall(DMGetLabelName(dm, l, &name));
7826: PetscCall(PetscStrncmp(name, "depth", 6, &isdepth));
7827: PetscCall(PetscStrncmp(name, "celltype", 9, &iscelltype));
7828: active[l] = !(isdepth || iscelltype) ? PETSC_TRUE : PETSC_FALSE;
7829: if (active[l]) ++ul->Nl;
7830: }
7831: PetscCall(PetscCalloc5(ul->Nl, &ul->names, ul->Nl, &ul->indices, ul->Nl + 1, &ul->offsets, ul->Nl + 1, &ul->bits, ul->Nl, &ul->masks));
7832: ul->Nv = 0;
7833: for (l = 0, m = 0; l < Nl; ++l) {
7834: DMLabel label;
7835: PetscInt nv;
7836: const char *name;
7838: if (!active[l]) continue;
7839: PetscCall(DMGetLabelName(dm, l, &name));
7840: PetscCall(DMGetLabelByNum(dm, l, &label));
7841: PetscCall(DMLabelGetNumValues(label, &nv));
7842: PetscCall(PetscStrallocpy(name, &ul->names[m]));
7843: ul->indices[m] = l;
7844: ul->Nv += nv;
7845: ul->offsets[m + 1] = nv;
7846: ul->bits[m + 1] = PetscCeilReal(PetscLog2Real(nv + 1));
7847: ++m;
7848: }
7849: for (l = 1; l <= ul->Nl; ++l) {
7850: ul->offsets[l] = ul->offsets[l - 1] + ul->offsets[l];
7851: ul->bits[l] = ul->bits[l - 1] + ul->bits[l];
7852: }
7853: for (l = 0; l < ul->Nl; ++l) {
7854: ul->masks[l] = 0;
7855: for (PetscInt b = ul->bits[l]; b < ul->bits[l + 1]; ++b) ul->masks[l] |= 1 << b;
7856: }
7857: PetscCall(PetscMalloc1(ul->Nv, &ul->values));
7858: for (l = 0, m = 0; l < Nl; ++l) {
7859: DMLabel label;
7860: IS valueIS;
7861: const PetscInt *varr;
7862: PetscInt nv;
7864: if (!active[l]) continue;
7865: PetscCall(DMGetLabelByNum(dm, l, &label));
7866: PetscCall(DMLabelGetNumValues(label, &nv));
7867: PetscCall(DMLabelGetValueIS(label, &valueIS));
7868: PetscCall(ISGetIndices(valueIS, &varr));
7869: for (PetscInt v = 0; v < nv; ++v) ul->values[ul->offsets[m] + v] = varr[v];
7870: PetscCall(ISRestoreIndices(valueIS, &varr));
7871: PetscCall(ISDestroy(&valueIS));
7872: PetscCall(PetscSortInt(nv, &ul->values[ul->offsets[m]]));
7873: ++m;
7874: }
7875: PetscCall(DMPlexGetChart(dm, &pStart, &pEnd));
7876: for (p = pStart; p < pEnd; ++p) {
7877: PetscInt uval = 0;
7878: PetscBool marked = PETSC_FALSE;
7880: for (l = 0, m = 0; l < Nl; ++l) {
7881: DMLabel label;
7882: PetscInt val, defval, loc, nv;
7884: if (!active[l]) continue;
7885: PetscCall(DMGetLabelByNum(dm, l, &label));
7886: PetscCall(DMLabelGetValue(label, p, &val));
7887: PetscCall(DMLabelGetDefaultValue(label, &defval));
7888: if (val == defval) {
7889: ++m;
7890: continue;
7891: }
7892: nv = ul->offsets[m + 1] - ul->offsets[m];
7893: marked = PETSC_TRUE;
7894: PetscCall(PetscFindInt(val, nv, &ul->values[ul->offsets[m]], &loc));
7895: PetscCheck(loc >= 0, PETSC_COMM_SELF, PETSC_ERR_PLIB, "Label value %" PetscInt_FMT " not found in compression array", val);
7896: uval += (loc + 1) << ul->bits[m];
7897: ++m;
7898: }
7899: if (marked) PetscCall(DMLabelSetValue(ul->label, p, uval));
7900: }
7901: PetscCall(PetscFree(active));
7902: *universal = ul;
7903: PetscFunctionReturn(PETSC_SUCCESS);
7904: }
7906: PetscErrorCode DMUniversalLabelDestroy(DMUniversalLabel *universal)
7907: {
7908: PetscInt l;
7910: PetscFunctionBegin;
7911: for (l = 0; l < (*universal)->Nl; ++l) PetscCall(PetscFree((*universal)->names[l]));
7912: PetscCall(DMLabelDestroy(&(*universal)->label));
7913: PetscCall(PetscFree5((*universal)->names, (*universal)->indices, (*universal)->offsets, (*universal)->bits, (*universal)->masks));
7914: PetscCall(PetscFree((*universal)->values));
7915: PetscCall(PetscFree(*universal));
7916: *universal = NULL;
7917: PetscFunctionReturn(PETSC_SUCCESS);
7918: }
7920: PetscErrorCode DMUniversalLabelGetLabel(DMUniversalLabel ul, DMLabel *ulabel)
7921: {
7922: PetscFunctionBegin;
7923: PetscAssertPointer(ulabel, 2);
7924: *ulabel = ul->label;
7925: PetscFunctionReturn(PETSC_SUCCESS);
7926: }
7928: PetscErrorCode DMUniversalLabelCreateLabels(DMUniversalLabel ul, PetscBool preserveOrder, DM dm)
7929: {
7930: PetscInt Nl = ul->Nl, l;
7932: PetscFunctionBegin;
7934: for (l = 0; l < Nl; ++l) {
7935: if (preserveOrder) PetscCall(DMCreateLabelAtIndex(dm, ul->indices[l], ul->names[l]));
7936: else PetscCall(DMCreateLabel(dm, ul->names[l]));
7937: }
7938: if (preserveOrder) {
7939: for (l = 0; l < ul->Nl; ++l) {
7940: const char *name;
7941: PetscBool match;
7943: PetscCall(DMGetLabelName(dm, ul->indices[l], &name));
7944: PetscCall(PetscStrcmp(name, ul->names[l], &match));
7945: 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]);
7946: }
7947: }
7948: PetscFunctionReturn(PETSC_SUCCESS);
7949: }
7951: PetscErrorCode DMUniversalLabelSetLabelValue(DMUniversalLabel ul, DM dm, PetscBool useIndex, PetscInt p, PetscInt value)
7952: {
7953: PetscFunctionBegin;
7954: for (PetscInt l = 0; l < ul->Nl; ++l) {
7955: DMLabel label;
7956: PetscInt lval = (value & ul->masks[l]) >> ul->bits[l];
7958: if (lval) {
7959: if (useIndex) PetscCall(DMGetLabelByNum(dm, ul->indices[l], &label));
7960: else PetscCall(DMGetLabel(dm, ul->names[l], &label));
7961: PetscCall(DMLabelSetValue(label, p, ul->values[ul->offsets[l] + lval - 1]));
7962: }
7963: }
7964: PetscFunctionReturn(PETSC_SUCCESS);
7965: }
7967: /*@
7968: DMGetCoarseDM - Get the coarse `DM`from which this `DM` was obtained by refinement
7970: Not Collective
7972: Input Parameter:
7973: . dm - The `DM` object
7975: Output Parameter:
7976: . cdm - The coarse `DM`
7978: Level: intermediate
7980: .seealso: [](ch_dmbase), `DM`, `DMSetCoarseDM()`, `DMCoarsen()`
7981: @*/
7982: PetscErrorCode DMGetCoarseDM(DM dm, DM *cdm)
7983: {
7984: PetscFunctionBegin;
7986: PetscAssertPointer(cdm, 2);
7987: *cdm = dm->coarseMesh;
7988: PetscFunctionReturn(PETSC_SUCCESS);
7989: }
7991: /*@
7992: DMSetCoarseDM - Set the coarse `DM` from which this `DM` was obtained by refinement
7994: Input Parameters:
7995: + dm - The `DM` object
7996: - cdm - The coarse `DM`
7998: Level: intermediate
8000: Note:
8001: Normally this is set automatically by `DMRefine()`
8003: .seealso: [](ch_dmbase), `DM`, `DMGetCoarseDM()`, `DMCoarsen()`, `DMSetRefine()`, `DMSetFineDM()`
8004: @*/
8005: PetscErrorCode DMSetCoarseDM(DM dm, DM cdm)
8006: {
8007: PetscFunctionBegin;
8010: if (dm == cdm) cdm = NULL;
8011: PetscCall(PetscObjectReference((PetscObject)cdm));
8012: PetscCall(DMDestroy(&dm->coarseMesh));
8013: dm->coarseMesh = cdm;
8014: PetscFunctionReturn(PETSC_SUCCESS);
8015: }
8017: /*@
8018: DMGetFineDM - Get the fine mesh from which this `DM` was obtained by coarsening
8020: Input Parameter:
8021: . dm - The `DM` object
8023: Output Parameter:
8024: . fdm - The fine `DM`
8026: Level: intermediate
8028: .seealso: [](ch_dmbase), `DM`, `DMSetFineDM()`, `DMCoarsen()`, `DMRefine()`
8029: @*/
8030: PetscErrorCode DMGetFineDM(DM dm, DM *fdm)
8031: {
8032: PetscFunctionBegin;
8034: PetscAssertPointer(fdm, 2);
8035: *fdm = dm->fineMesh;
8036: PetscFunctionReturn(PETSC_SUCCESS);
8037: }
8039: /*@
8040: DMSetFineDM - Set the fine mesh from which this was obtained by coarsening
8042: Input Parameters:
8043: + dm - The `DM` object
8044: - fdm - The fine `DM`
8046: Level: developer
8048: Note:
8049: Normally this is set automatically by `DMCoarsen()`
8051: .seealso: [](ch_dmbase), `DM`, `DMGetFineDM()`, `DMCoarsen()`, `DMRefine()`
8052: @*/
8053: PetscErrorCode DMSetFineDM(DM dm, DM fdm)
8054: {
8055: PetscFunctionBegin;
8058: if (dm == fdm) fdm = NULL;
8059: PetscCall(PetscObjectReference((PetscObject)fdm));
8060: PetscCall(DMDestroy(&dm->fineMesh));
8061: dm->fineMesh = fdm;
8062: PetscFunctionReturn(PETSC_SUCCESS);
8063: }
8065: /*@C
8066: DMAddBoundary - Add a boundary condition, for a single field, to a model represented by a `DM`
8068: Collective
8070: Input Parameters:
8071: + dm - The `DM`, with a `PetscDS` that matches the problem being constrained
8072: . type - The type of condition, e.g. `DM_BC_ESSENTIAL_ANALYTIC`, `DM_BC_ESSENTIAL_FIELD` (Dirichlet), or `DM_BC_NATURAL` (Neumann)
8073: . name - The BC name
8074: . label - The label defining constrained points
8075: . Nv - The number of `DMLabel` values for constrained points
8076: . values - An array of values for constrained points
8077: . field - The field to constrain
8078: . Nc - The number of constrained field components (0 will constrain all components)
8079: . comps - An array of constrained component numbers
8080: . bcFunc - A pointwise function giving boundary values
8081: . bcFunc_t - A pointwise function giving the time derivative of the boundary values, or `NULL`
8082: - ctx - An optional user context for bcFunc
8084: Output Parameter:
8085: . bd - (Optional) Boundary number
8087: Options Database Keys:
8088: + -bc_NAME values - Overrides the boundary ids for boundary named NAME
8089: - -bc_NAME_comp comps - Overrides the boundary components for boundary named NAME
8091: Level: intermediate
8093: Notes:
8094: If the `DM` is of type `DMPLEX` and the field is of type `PetscFE`, then this function completes the label using `DMPlexLabelComplete()`.
8096: Both bcFunc and bcFunc_t will depend on the boundary condition type. If the type if `DM_BC_ESSENTIAL`, then the calling sequence is\:
8097: .vb
8098: void bcFunc(PetscInt dim, PetscReal time, const PetscReal x[], PetscInt Nc, PetscScalar bcval[])
8099: .ve
8101: If the type is `DM_BC_ESSENTIAL_FIELD` or other _FIELD value, then the calling sequence is\:
8103: .vb
8104: void bcFunc(PetscInt dim, PetscInt Nf, PetscInt NfAux,
8105: const PetscInt uOff[], const PetscInt uOff_x[], const PetscScalar u[], const PetscScalar u_t[], const PetscScalar u_x[],
8106: const PetscInt aOff[], const PetscInt aOff_x[], const PetscScalar a[], const PetscScalar a_t[], const PetscScalar a_x[],
8107: PetscReal time, const PetscReal x[], PetscScalar bcval[])
8108: .ve
8109: + dim - the spatial dimension
8110: . Nf - the number of fields
8111: . uOff - the offset into u[] and u_t[] for each field
8112: . uOff_x - the offset into u_x[] for each field
8113: . u - each field evaluated at the current point
8114: . u_t - the time derivative of each field evaluated at the current point
8115: . u_x - the gradient of each field evaluated at the current point
8116: . aOff - the offset into a[] and a_t[] for each auxiliary field
8117: . aOff_x - the offset into a_x[] for each auxiliary field
8118: . a - each auxiliary field evaluated at the current point
8119: . a_t - the time derivative of each auxiliary field evaluated at the current point
8120: . a_x - the gradient of auxiliary each field evaluated at the current point
8121: . t - current time
8122: . x - coordinates of the current point
8123: . numConstants - number of constant parameters
8124: . constants - constant parameters
8125: - bcval - output values at the current point
8127: .seealso: [](ch_dmbase), `DM`, `DSGetBoundary()`, `PetscDSAddBoundary()`
8128: @*/
8129: 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)
8130: {
8131: PetscDS ds;
8133: PetscFunctionBegin;
8140: PetscCheck(!dm->localSection, PetscObjectComm((PetscObject)dm), PETSC_ERR_ARG_WRONGSTATE, "Cannot add boundary to DM after creating local section");
8141: PetscCall(DMGetDS(dm, &ds));
8142: /* Complete label */
8143: if (label) {
8144: PetscObject obj;
8145: PetscClassId id;
8147: PetscCall(DMGetField(dm, field, NULL, &obj));
8148: PetscCall(PetscObjectGetClassId(obj, &id));
8149: if (id == PETSCFE_CLASSID) {
8150: DM plex;
8152: PetscCall(DMConvert(dm, DMPLEX, &plex));
8153: if (plex) PetscCall(DMPlexLabelComplete(plex, label));
8154: PetscCall(DMDestroy(&plex));
8155: }
8156: }
8157: PetscCall(PetscDSAddBoundary(ds, type, name, label, Nv, values, field, Nc, comps, bcFunc, bcFunc_t, ctx, bd));
8158: PetscFunctionReturn(PETSC_SUCCESS);
8159: }
8161: /* TODO Remove this since now the structures are the same */
8162: static PetscErrorCode DMPopulateBoundary(DM dm)
8163: {
8164: PetscDS ds;
8165: DMBoundary *lastnext;
8166: DSBoundary dsbound;
8168: PetscFunctionBegin;
8169: PetscCall(DMGetDS(dm, &ds));
8170: dsbound = ds->boundary;
8171: if (dm->boundary) {
8172: DMBoundary next = dm->boundary;
8174: /* quick check to see if the PetscDS has changed */
8175: if (next->dsboundary == dsbound) PetscFunctionReturn(PETSC_SUCCESS);
8176: /* the PetscDS has changed: tear down and rebuild */
8177: while (next) {
8178: DMBoundary b = next;
8180: next = b->next;
8181: PetscCall(PetscFree(b));
8182: }
8183: dm->boundary = NULL;
8184: }
8186: lastnext = &dm->boundary;
8187: while (dsbound) {
8188: DMBoundary dmbound;
8190: PetscCall(PetscNew(&dmbound));
8191: dmbound->dsboundary = dsbound;
8192: dmbound->label = dsbound->label;
8193: /* push on the back instead of the front so that it is in the same order as in the PetscDS */
8194: *lastnext = dmbound;
8195: lastnext = &dmbound->next;
8196: dsbound = dsbound->next;
8197: }
8198: PetscFunctionReturn(PETSC_SUCCESS);
8199: }
8201: /* TODO: missing manual page */
8202: PetscErrorCode DMIsBoundaryPoint(DM dm, PetscInt point, PetscBool *isBd)
8203: {
8204: DMBoundary b;
8206: PetscFunctionBegin;
8208: PetscAssertPointer(isBd, 3);
8209: *isBd = PETSC_FALSE;
8210: PetscCall(DMPopulateBoundary(dm));
8211: b = dm->boundary;
8212: while (b && !*isBd) {
8213: DMLabel label = b->label;
8214: DSBoundary dsb = b->dsboundary;
8216: if (label) {
8217: for (PetscInt i = 0; i < dsb->Nv && !*isBd; ++i) PetscCall(DMLabelStratumHasPoint(label, dsb->values[i], point, isBd));
8218: }
8219: b = b->next;
8220: }
8221: PetscFunctionReturn(PETSC_SUCCESS);
8222: }
8224: /*@
8225: DMHasBound - Determine whether a bound condition was specified
8227: Logically collective
8229: Input Parameter:
8230: . dm - The `DM`, with a `PetscDS` that matches the problem being constrained
8232: Output Parameter:
8233: . hasBound - Flag indicating if a bound condition was specified
8235: Level: intermediate
8237: .seealso: [](ch_dmbase), `DM`, `DSAddBoundary()`, `PetscDSAddBoundary()`
8238: @*/
8239: PetscErrorCode DMHasBound(DM dm, PetscBool *hasBound)
8240: {
8241: PetscDS ds;
8242: PetscInt Nf, numBd;
8244: PetscFunctionBegin;
8245: *hasBound = PETSC_FALSE;
8246: PetscCall(DMGetDS(dm, &ds));
8247: PetscCall(PetscDSGetNumFields(ds, &Nf));
8248: for (PetscInt f = 0; f < Nf; ++f) {
8249: PetscSimplePointFn *lfunc, *ufunc;
8251: PetscCall(PetscDSGetLowerBound(ds, f, &lfunc, NULL));
8252: PetscCall(PetscDSGetUpperBound(ds, f, &ufunc, NULL));
8253: if (lfunc || ufunc) *hasBound = PETSC_TRUE;
8254: }
8256: PetscCall(PetscDSGetNumBoundary(ds, &numBd));
8257: PetscCall(PetscDSUpdateBoundaryLabels(ds, dm));
8258: for (PetscInt b = 0; b < numBd; ++b) {
8259: PetscWeakForm wf;
8260: DMBoundaryConditionType type;
8261: const char *name;
8262: DMLabel label;
8263: PetscInt numids;
8264: const PetscInt *ids;
8265: PetscInt field, Nc;
8266: const PetscInt *comps;
8267: PetscVoidFn *bvfunc;
8268: void *ctx;
8270: PetscCall(PetscDSGetBoundary(ds, b, &wf, &type, &name, &label, &numids, &ids, &field, &Nc, &comps, &bvfunc, NULL, &ctx));
8271: if (type == DM_BC_LOWER_BOUND || type == DM_BC_UPPER_BOUND) *hasBound = PETSC_TRUE;
8272: }
8273: PetscFunctionReturn(PETSC_SUCCESS);
8274: }
8276: /*@C
8277: DMProjectFunction - This projects the given function into the function space provided by a `DM`, putting the coefficients in a global vector.
8279: Collective
8281: Input Parameters:
8282: + dm - The `DM`
8283: . time - The time
8284: . funcs - The coordinate functions to evaluate, one per field
8285: . ctxs - Optional array of contexts to pass to each coordinate function. ctxs itself may be null.
8286: - mode - The insertion mode for values
8288: Output Parameter:
8289: . X - vector
8291: Calling sequence of `funcs`:
8292: + dim - The spatial dimension
8293: . time - The time at which to sample
8294: . x - The coordinates
8295: . Nc - The number of components
8296: . u - The output field values
8297: - ctx - optional function context
8299: Level: developer
8301: Developer Notes:
8302: This API is specific to only particular usage of `DM`
8304: The notes need to provide some information about what has to be provided to the `DM` to be able to perform the computation.
8306: .seealso: [](ch_dmbase), `DM`, `DMProjectFunctionLocal()`, `DMProjectFunctionLabel()`, `DMComputeL2Diff()`
8307: @*/
8308: 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)
8309: {
8310: Vec localX;
8312: PetscFunctionBegin;
8314: PetscCall(PetscLogEventBegin(DM_ProjectFunction, dm, X, 0, 0));
8315: PetscCall(DMGetLocalVector(dm, &localX));
8316: PetscCall(VecSet(localX, 0.));
8317: PetscCall(DMProjectFunctionLocal(dm, time, funcs, ctxs, mode, localX));
8318: PetscCall(DMLocalToGlobalBegin(dm, localX, mode, X));
8319: PetscCall(DMLocalToGlobalEnd(dm, localX, mode, X));
8320: PetscCall(DMRestoreLocalVector(dm, &localX));
8321: PetscCall(PetscLogEventEnd(DM_ProjectFunction, dm, X, 0, 0));
8322: PetscFunctionReturn(PETSC_SUCCESS);
8323: }
8325: /*@C
8326: DMProjectFunctionLocal - This projects the given function into the function space provided by a `DM`, putting the coefficients in a local vector.
8328: Not Collective
8330: Input Parameters:
8331: + dm - The `DM`
8332: . time - The time
8333: . funcs - The coordinate functions to evaluate, one per field
8334: . ctxs - Optional array of contexts to pass to each coordinate function. ctxs itself may be null.
8335: - mode - The insertion mode for values
8337: Output Parameter:
8338: . localX - vector
8340: Calling sequence of `funcs`:
8341: + dim - The spatial dimension
8342: . time - The current timestep
8343: . x - The coordinates
8344: . Nc - The number of components
8345: . u - The output field values
8346: - ctx - optional function context
8348: Level: developer
8350: Developer Notes:
8351: This API is specific to only particular usage of `DM`
8353: The notes need to provide some information about what has to be provided to the `DM` to be able to perform the computation.
8355: .seealso: [](ch_dmbase), `DM`, `DMProjectFunction()`, `DMProjectFunctionLabel()`, `DMComputeL2Diff()`
8356: @*/
8357: 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)
8358: {
8359: PetscFunctionBegin;
8362: PetscUseTypeMethod(dm, projectfunctionlocal, time, funcs, ctxs, mode, localX);
8363: PetscFunctionReturn(PETSC_SUCCESS);
8364: }
8366: /*@C
8367: 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.
8369: Collective
8371: Input Parameters:
8372: + dm - The `DM`
8373: . time - The time
8374: . numIds - The number of ids
8375: . ids - The ids
8376: . Nc - The number of components
8377: . comps - The components
8378: . label - The `DMLabel` selecting the portion of the mesh for projection
8379: . funcs - The coordinate functions to evaluate, one per field
8380: . ctxs - Optional array of contexts to pass to each coordinate function. ctxs may be null.
8381: - mode - The insertion mode for values
8383: Output Parameter:
8384: . X - vector
8386: Calling sequence of `funcs`:
8387: + dim - The spatial dimension
8388: . time - The current timestep
8389: . x - The coordinates
8390: . Nc - The number of components
8391: . u - The output field values
8392: - ctx - optional function context
8394: Level: developer
8396: Developer Notes:
8397: This API is specific to only particular usage of `DM`
8399: The notes need to provide some information about what has to be provided to the `DM` to be able to perform the computation.
8401: .seealso: [](ch_dmbase), `DM`, `DMProjectFunction()`, `DMProjectFunctionLocal()`, `DMProjectFunctionLabelLocal()`, `DMComputeL2Diff()`
8402: @*/
8403: 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)
8404: {
8405: Vec localX;
8407: PetscFunctionBegin;
8409: PetscCall(DMGetLocalVector(dm, &localX));
8410: PetscCall(VecSet(localX, 0.));
8411: PetscCall(DMProjectFunctionLabelLocal(dm, time, label, numIds, ids, Nc, comps, funcs, ctxs, mode, localX));
8412: PetscCall(DMLocalToGlobalBegin(dm, localX, mode, X));
8413: PetscCall(DMLocalToGlobalEnd(dm, localX, mode, X));
8414: PetscCall(DMRestoreLocalVector(dm, &localX));
8415: PetscFunctionReturn(PETSC_SUCCESS);
8416: }
8418: /*@C
8419: 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.
8421: Not Collective
8423: Input Parameters:
8424: + dm - The `DM`
8425: . time - The time
8426: . label - The `DMLabel` selecting the portion of the mesh for projection
8427: . numIds - The number of ids
8428: . ids - The ids
8429: . Nc - The number of components
8430: . comps - The components
8431: . funcs - The coordinate functions to evaluate, one per field
8432: . ctxs - Optional array of contexts to pass to each coordinate function. ctxs itself may be null.
8433: - mode - The insertion mode for values
8435: Output Parameter:
8436: . localX - vector
8438: Calling sequence of `funcs`:
8439: + dim - The spatial dimension
8440: . time - The current time
8441: . x - The coordinates
8442: . Nc - The number of components
8443: . u - The output field values
8444: - ctx - optional function context
8446: Level: developer
8448: Developer Notes:
8449: This API is specific to only particular usage of `DM`
8451: The notes need to provide some information about what has to be provided to the `DM` to be able to perform the computation.
8453: .seealso: [](ch_dmbase), `DM`, `DMProjectFunction()`, `DMProjectFunctionLocal()`, `DMProjectFunctionLabel()`, `DMComputeL2Diff()`
8454: @*/
8455: 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)
8456: {
8457: PetscFunctionBegin;
8460: PetscUseTypeMethod(dm, projectfunctionlabellocal, time, label, numIds, ids, Nc, comps, funcs, ctxs, mode, localX);
8461: PetscFunctionReturn(PETSC_SUCCESS);
8462: }
8464: /*@C
8465: 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.
8467: Not Collective
8469: Input Parameters:
8470: + dm - The `DM`
8471: . time - The time
8472: . localU - The input field vector; may be `NULL` if projection is defined purely by coordinates
8473: . funcs - The functions to evaluate, one per field
8474: - mode - The insertion mode for values
8476: Output Parameter:
8477: . localX - The output vector
8479: Calling sequence of `funcs`:
8480: + dim - The spatial dimension
8481: . Nf - The number of input fields
8482: . NfAux - The number of input auxiliary fields
8483: . uOff - The offset of each field in u[]
8484: . uOff_x - The offset of each field in u_x[]
8485: . u - The field values at this point in space
8486: . u_t - The field time derivative at this point in space (or `NULL`)
8487: . u_x - The field derivatives at this point in space
8488: . aOff - The offset of each auxiliary field in u[]
8489: . aOff_x - The offset of each auxiliary field in u_x[]
8490: . a - The auxiliary field values at this point in space
8491: . a_t - The auxiliary field time derivative at this point in space (or `NULL`)
8492: . a_x - The auxiliary field derivatives at this point in space
8493: . t - The current time
8494: . x - The coordinates of this point
8495: . numConstants - The number of constants
8496: . constants - The value of each constant
8497: - f - The value of the function at this point in space
8499: Level: intermediate
8501: Note:
8502: 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.
8503: 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
8504: a subdomain. You can also output a different number of fields than the input, with different discretizations. Last the auxiliary `DM`, attached to the
8505: auxiliary field vector, which is attached to dm, can also be different. It can have a different topology, number of fields, and discretizations.
8507: Developer Notes:
8508: This API is specific to only particular usage of `DM`
8510: The notes need to provide some information about what has to be provided to the `DM` to be able to perform the computation.
8512: .seealso: [](ch_dmbase), `DM`, `DMProjectField()`, `DMProjectFieldLabelLocal()`,
8513: `DMProjectFunction()`, `DMComputeL2Diff()`
8514: @*/
8515: 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)
8516: {
8517: PetscFunctionBegin;
8521: PetscUseTypeMethod(dm, projectfieldlocal, time, localU, funcs, mode, localX);
8522: PetscFunctionReturn(PETSC_SUCCESS);
8523: }
8525: /*@C
8526: 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.
8528: Not Collective
8530: Input Parameters:
8531: + dm - The `DM`
8532: . time - The time
8533: . label - The `DMLabel` marking the portion of the domain to output
8534: . numIds - The number of label ids to use
8535: . ids - The label ids to use for marking
8536: . Nc - The number of components to set in the output, or `PETSC_DETERMINE` for all components
8537: . comps - The components to set in the output, or `NULL` for all components
8538: . localU - The input field vector
8539: . funcs - The functions to evaluate, one per field
8540: - mode - The insertion mode for values
8542: Output Parameter:
8543: . localX - The output vector
8545: Calling sequence of `funcs`:
8546: + dim - The spatial dimension
8547: . Nf - The number of input fields
8548: . NfAux - The number of input auxiliary fields
8549: . uOff - The offset of each field in u[]
8550: . uOff_x - The offset of each field in u_x[]
8551: . u - The field values at this point in space
8552: . u_t - The field time derivative at this point in space (or `NULL`)
8553: . u_x - The field derivatives at this point in space
8554: . aOff - The offset of each auxiliary field in u[]
8555: . aOff_x - The offset of each auxiliary field in u_x[]
8556: . a - The auxiliary field values at this point in space
8557: . a_t - The auxiliary field time derivative at this point in space (or `NULL`)
8558: . a_x - The auxiliary field derivatives at this point in space
8559: . t - The current time
8560: . x - The coordinates of this point
8561: . numConstants - The number of constants
8562: . constants - The value of each constant
8563: - f - The value of the function at this point in space
8565: Level: intermediate
8567: Note:
8568: 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.
8569: 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
8570: a subdomain. You can also output a different number of fields than the input, with different discretizations. Last the auxiliary `DM`, attached to the
8571: auxiliary field vector, which is attached to dm, can also be different. It can have a different topology, number of fields, and discretizations.
8573: Developer Notes:
8574: This API is specific to only particular usage of `DM`
8576: The notes need to provide some information about what has to be provided to the `DM` to be able to perform the computation.
8578: .seealso: [](ch_dmbase), `DM`, `DMProjectField()`, `DMProjectFieldLabel()`, `DMProjectFunction()`, `DMComputeL2Diff()`
8579: @*/
8580: 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)
8581: {
8582: PetscFunctionBegin;
8586: PetscUseTypeMethod(dm, projectfieldlabellocal, time, label, numIds, ids, Nc, comps, localU, funcs, mode, localX);
8587: PetscFunctionReturn(PETSC_SUCCESS);
8588: }
8590: /*@C
8591: 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.
8593: Not Collective
8595: Input Parameters:
8596: + dm - The `DM`
8597: . time - The time
8598: . label - The `DMLabel` marking the portion of the domain to output
8599: . numIds - The number of label ids to use
8600: . ids - The label ids to use for marking
8601: . Nc - The number of components to set in the output, or `PETSC_DETERMINE` for all components
8602: . comps - The components to set in the output, or `NULL` for all components
8603: . U - The input field vector
8604: . funcs - The functions to evaluate, one per field
8605: - mode - The insertion mode for values
8607: Output Parameter:
8608: . X - The output vector
8610: Calling sequence of `funcs`:
8611: + dim - The spatial dimension
8612: . Nf - The number of input fields
8613: . NfAux - The number of input auxiliary fields
8614: . uOff - The offset of each field in u[]
8615: . uOff_x - The offset of each field in u_x[]
8616: . u - The field values at this point in space
8617: . u_t - The field time derivative at this point in space (or `NULL`)
8618: . u_x - The field derivatives at this point in space
8619: . aOff - The offset of each auxiliary field in u[]
8620: . aOff_x - The offset of each auxiliary field in u_x[]
8621: . a - The auxiliary field values at this point in space
8622: . a_t - The auxiliary field time derivative at this point in space (or `NULL`)
8623: . a_x - The auxiliary field derivatives at this point in space
8624: . t - The current time
8625: . x - The coordinates of this point
8626: . numConstants - The number of constants
8627: . constants - The value of each constant
8628: - f - The value of the function at this point in space
8630: Level: intermediate
8632: Note:
8633: 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.
8634: 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
8635: a subdomain. You can also output a different number of fields than the input, with different discretizations. Last the auxiliary `DM`, attached to the
8636: auxiliary field vector, which is attached to dm, can also be different. It can have a different topology, number of fields, and discretizations.
8638: Developer Notes:
8639: This API is specific to only particular usage of `DM`
8641: The notes need to provide some information about what has to be provided to the `DM` to be able to perform the computation.
8643: .seealso: [](ch_dmbase), `DM`, `DMProjectField()`, `DMProjectFieldLabelLocal()`, `DMProjectFunction()`, `DMComputeL2Diff()`
8644: @*/
8645: 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)
8646: {
8647: DM dmIn;
8648: Vec localU, localX;
8650: PetscFunctionBegin;
8652: PetscCall(VecGetDM(U, &dmIn));
8653: PetscCall(DMGetLocalVector(dmIn, &localU));
8654: PetscCall(DMGetLocalVector(dm, &localX));
8655: PetscCall(VecSet(localX, 0.));
8656: PetscCall(DMGlobalToLocalBegin(dmIn, U, mode, localU));
8657: PetscCall(DMGlobalToLocalEnd(dmIn, U, mode, localU));
8658: PetscCall(DMProjectFieldLabelLocal(dm, time, label, numIds, ids, Nc, comps, localU, funcs, mode, localX));
8659: PetscCall(DMLocalToGlobalBegin(dm, localX, mode, X));
8660: PetscCall(DMLocalToGlobalEnd(dm, localX, mode, X));
8661: PetscCall(DMRestoreLocalVector(dm, &localX));
8662: PetscCall(DMRestoreLocalVector(dmIn, &localU));
8663: PetscFunctionReturn(PETSC_SUCCESS);
8664: }
8666: /*@C
8667: 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.
8669: Not Collective
8671: Input Parameters:
8672: + dm - The `DM`
8673: . time - The time
8674: . label - The `DMLabel` marking the portion of the domain boundary to output
8675: . numIds - The number of label ids to use
8676: . ids - The label ids to use for marking
8677: . Nc - The number of components to set in the output, or `PETSC_DETERMINE` for all components
8678: . comps - The components to set in the output, or `NULL` for all components
8679: . localU - The input field vector
8680: . funcs - The functions to evaluate, one per field
8681: - mode - The insertion mode for values
8683: Output Parameter:
8684: . localX - The output vector
8686: Calling sequence of `funcs`:
8687: + dim - The spatial dimension
8688: . Nf - The number of input fields
8689: . NfAux - The number of input auxiliary fields
8690: . uOff - The offset of each field in u[]
8691: . uOff_x - The offset of each field in u_x[]
8692: . u - The field values at this point in space
8693: . u_t - The field time derivative at this point in space (or `NULL`)
8694: . u_x - The field derivatives at this point in space
8695: . aOff - The offset of each auxiliary field in u[]
8696: . aOff_x - The offset of each auxiliary field in u_x[]
8697: . a - The auxiliary field values at this point in space
8698: . a_t - The auxiliary field time derivative at this point in space (or `NULL`)
8699: . a_x - The auxiliary field derivatives at this point in space
8700: . t - The current time
8701: . x - The coordinates of this point
8702: . n - The face normal
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 U, 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()`, `DMProjectFieldLabelLocal()`, `DMProjectFunction()`, `DMComputeL2Diff()`
8721: @*/
8722: 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)
8723: {
8724: PetscFunctionBegin;
8728: PetscUseTypeMethod(dm, projectbdfieldlabellocal, time, label, numIds, ids, Nc, comps, localU, funcs, mode, localX);
8729: PetscFunctionReturn(PETSC_SUCCESS);
8730: }
8732: /*@C
8733: DMComputeL2Diff - This function computes the L_2 difference between a function u and an FEM interpolant solution u_h.
8735: Collective
8737: Input Parameters:
8738: + dm - The `DM`
8739: . time - The time
8740: . funcs - The functions to evaluate for each field component
8741: . ctxs - Optional array of contexts to pass to each function, or `NULL`.
8742: - X - The coefficient vector u_h, a global vector
8744: Output Parameter:
8745: . diff - The diff ||u - u_h||_2
8747: Level: developer
8749: Developer Notes:
8750: This API is specific to only particular usage of `DM`
8752: The notes need to provide some information about what has to be provided to the `DM` to be able to perform the computation.
8754: .seealso: [](ch_dmbase), `DM`, `DMProjectFunction()`, `DMComputeL2FieldDiff()`, `DMComputeL2GradientDiff()`
8755: @*/
8756: PetscErrorCode DMComputeL2Diff(DM dm, PetscReal time, PetscErrorCode (**funcs)(PetscInt, PetscReal, const PetscReal[], PetscInt, PetscScalar *, void *), void **ctxs, Vec X, PetscReal *diff)
8757: {
8758: PetscFunctionBegin;
8761: PetscUseTypeMethod(dm, computel2diff, time, funcs, ctxs, X, diff);
8762: PetscFunctionReturn(PETSC_SUCCESS);
8763: }
8765: /*@C
8766: DMComputeL2GradientDiff - This function computes the L_2 difference between the gradient of a function u and an FEM interpolant solution grad u_h.
8768: Collective
8770: Input Parameters:
8771: + dm - The `DM`
8772: . time - The time
8773: . funcs - The gradient functions to evaluate for each field component
8774: . ctxs - Optional array of contexts to pass to each function, or `NULL`.
8775: . X - The coefficient vector u_h, a global vector
8776: - n - The vector to project along
8778: Output Parameter:
8779: . diff - The diff ||(grad u - grad u_h) . n||_2
8781: Level: developer
8783: Developer Notes:
8784: This API is specific to only particular usage of `DM`
8786: The notes need to provide some information about what has to be provided to the `DM` to be able to perform the computation.
8788: .seealso: [](ch_dmbase), `DM`, `DMProjectFunction()`, `DMComputeL2Diff()`, `DMComputeL2FieldDiff()`
8789: @*/
8790: 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)
8791: {
8792: PetscFunctionBegin;
8795: PetscUseTypeMethod(dm, computel2gradientdiff, time, funcs, ctxs, X, n, diff);
8796: PetscFunctionReturn(PETSC_SUCCESS);
8797: }
8799: /*@C
8800: DMComputeL2FieldDiff - This function computes the L_2 difference between a function u and an FEM interpolant solution u_h, separated into field components.
8802: Collective
8804: Input Parameters:
8805: + dm - The `DM`
8806: . time - The time
8807: . funcs - The functions to evaluate for each field component
8808: . ctxs - Optional array of contexts to pass to each function, or `NULL`.
8809: - X - The coefficient vector u_h, a global vector
8811: Output Parameter:
8812: . diff - The array of differences, ||u^f - u^f_h||_2
8814: Level: developer
8816: Developer Notes:
8817: This API is specific to only particular usage of `DM`
8819: The notes need to provide some information about what has to be provided to the `DM` to be able to perform the computation.
8821: .seealso: [](ch_dmbase), `DM`, `DMProjectFunction()`, `DMComputeL2GradientDiff()`
8822: @*/
8823: PetscErrorCode DMComputeL2FieldDiff(DM dm, PetscReal time, PetscErrorCode (**funcs)(PetscInt, PetscReal, const PetscReal[], PetscInt, PetscScalar *, void *), void **ctxs, Vec X, PetscReal diff[])
8824: {
8825: PetscFunctionBegin;
8828: PetscUseTypeMethod(dm, computel2fielddiff, time, funcs, ctxs, X, diff);
8829: PetscFunctionReturn(PETSC_SUCCESS);
8830: }
8832: /*@C
8833: DMGetNeighbors - Gets an array containing the MPI ranks of all the processes neighbors
8835: Not Collective
8837: Input Parameter:
8838: . dm - The `DM`
8840: Output Parameters:
8841: + nranks - the number of neighbours
8842: - ranks - the neighbors ranks
8844: Level: beginner
8846: Note:
8847: Do not free the array, it is freed when the `DM` is destroyed.
8849: .seealso: [](ch_dmbase), `DM`, `DMDAGetNeighbors()`, `PetscSFGetRootRanks()`
8850: @*/
8851: PetscErrorCode DMGetNeighbors(DM dm, PetscInt *nranks, const PetscMPIInt *ranks[])
8852: {
8853: PetscFunctionBegin;
8855: PetscUseTypeMethod(dm, getneighbors, nranks, ranks);
8856: PetscFunctionReturn(PETSC_SUCCESS);
8857: }
8859: #include <petsc/private/matimpl.h>
8861: /*
8862: Converts the input vector to a ghosted vector and then calls the standard coloring code.
8863: This must be a different function because it requires DM which is not defined in the Mat library
8864: */
8865: static PetscErrorCode MatFDColoringApply_AIJDM(Mat J, MatFDColoring coloring, Vec x1, void *sctx)
8866: {
8867: PetscFunctionBegin;
8868: if (coloring->ctype == IS_COLORING_LOCAL) {
8869: Vec x1local;
8870: DM dm;
8871: PetscCall(MatGetDM(J, &dm));
8872: PetscCheck(dm, PetscObjectComm((PetscObject)J), PETSC_ERR_ARG_INCOMP, "IS_COLORING_LOCAL requires a DM");
8873: PetscCall(DMGetLocalVector(dm, &x1local));
8874: PetscCall(DMGlobalToLocalBegin(dm, x1, INSERT_VALUES, x1local));
8875: PetscCall(DMGlobalToLocalEnd(dm, x1, INSERT_VALUES, x1local));
8876: x1 = x1local;
8877: }
8878: PetscCall(MatFDColoringApply_AIJ(J, coloring, x1, sctx));
8879: if (coloring->ctype == IS_COLORING_LOCAL) {
8880: DM dm;
8881: PetscCall(MatGetDM(J, &dm));
8882: PetscCall(DMRestoreLocalVector(dm, &x1));
8883: }
8884: PetscFunctionReturn(PETSC_SUCCESS);
8885: }
8887: /*@
8888: MatFDColoringUseDM - allows a `MatFDColoring` object to use the `DM` associated with the matrix to compute a `IS_COLORING_LOCAL` coloring
8890: Input Parameters:
8891: + coloring - The matrix to get the `DM` from
8892: - fdcoloring - the `MatFDColoring` object
8894: Level: advanced
8896: Developer Note:
8897: This routine exists because the PETSc `Mat` library does not know about the `DM` objects
8899: .seealso: [](ch_dmbase), `DM`, `MatFDColoring`, `MatFDColoringCreate()`, `ISColoringType`
8900: @*/
8901: PetscErrorCode MatFDColoringUseDM(Mat coloring, MatFDColoring fdcoloring)
8902: {
8903: PetscFunctionBegin;
8904: coloring->ops->fdcoloringapply = MatFDColoringApply_AIJDM;
8905: PetscFunctionReturn(PETSC_SUCCESS);
8906: }
8908: /*@
8909: DMGetCompatibility - determine if two `DM`s are compatible
8911: Collective
8913: Input Parameters:
8914: + dm1 - the first `DM`
8915: - dm2 - the second `DM`
8917: Output Parameters:
8918: + compatible - whether or not the two `DM`s are compatible
8919: - set - whether or not the compatible value was actually determined and set
8921: Level: advanced
8923: Notes:
8924: Two `DM`s are deemed compatible if they represent the same parallel decomposition
8925: of the same topology. This implies that the section (field data) on one
8926: "makes sense" with respect to the topology and parallel decomposition of the other.
8927: Loosely speaking, compatible `DM`s represent the same domain and parallel
8928: decomposition, but hold different data.
8930: Typically, one would confirm compatibility if intending to simultaneously iterate
8931: over a pair of vectors obtained from different `DM`s.
8933: For example, two `DMDA` objects are compatible if they have the same local
8934: and global sizes and the same stencil width. They can have different numbers
8935: of degrees of freedom per node. Thus, one could use the node numbering from
8936: either `DM` in bounds for a loop over vectors derived from either `DM`.
8938: Consider the operation of summing data living on a 2-dof `DMDA` to data living
8939: on a 1-dof `DMDA`, which should be compatible, as in the following snippet.
8940: .vb
8941: ...
8942: PetscCall(DMGetCompatibility(da1,da2,&compatible,&set));
8943: if (set && compatible) {
8944: PetscCall(DMDAVecGetArrayDOF(da1,vec1,&arr1));
8945: PetscCall(DMDAVecGetArrayDOF(da2,vec2,&arr2));
8946: PetscCall(DMDAGetCorners(da1,&x,&y,NULL,&m,&n,NULL));
8947: for (j=y; j<y+n; ++j) {
8948: for (i=x; i<x+m, ++i) {
8949: arr1[j][i][0] = arr2[j][i][0] + arr2[j][i][1];
8950: }
8951: }
8952: PetscCall(DMDAVecRestoreArrayDOF(da1,vec1,&arr1));
8953: PetscCall(DMDAVecRestoreArrayDOF(da2,vec2,&arr2));
8954: } else {
8955: SETERRQ(PetscObjectComm((PetscObject)da1,PETSC_ERR_ARG_INCOMP,"DMDA objects incompatible");
8956: }
8957: ...
8958: .ve
8960: Checking compatibility might be expensive for a given implementation of `DM`,
8961: or might be impossible to unambiguously confirm or deny. For this reason,
8962: this function may decline to determine compatibility, and hence users should
8963: always check the "set" output parameter.
8965: A `DM` is always compatible with itself.
8967: In the current implementation, `DM`s which live on "unequal" communicators
8968: (MPI_UNEQUAL in the terminology of MPI_Comm_compare()) are always deemed
8969: incompatible.
8971: This function is labeled "Collective," as information about all subdomains
8972: is required on each rank. However, in `DM` implementations which store all this
8973: information locally, this function may be merely "Logically Collective".
8975: Developer Note:
8976: Compatibility is assumed to be a symmetric concept; `DM` A is compatible with `DM` B
8977: iff B is compatible with A. Thus, this function checks the implementations
8978: of both dm and dmc (if they are of different types), attempting to determine
8979: compatibility. It is left to `DM` implementers to ensure that symmetry is
8980: preserved. The simplest way to do this is, when implementing type-specific
8981: logic for this function, is to check for existing logic in the implementation
8982: of other `DM` types and let *set = PETSC_FALSE if found.
8984: .seealso: [](ch_dmbase), `DM`, `DMDACreateCompatibleDMDA()`, `DMStagCreateCompatibleDMStag()`
8985: @*/
8986: PetscErrorCode DMGetCompatibility(DM dm1, DM dm2, PetscBool *compatible, PetscBool *set)
8987: {
8988: PetscMPIInt compareResult;
8989: DMType type, type2;
8990: PetscBool sameType;
8992: PetscFunctionBegin;
8996: /* Declare a DM compatible with itself */
8997: if (dm1 == dm2) {
8998: *set = PETSC_TRUE;
8999: *compatible = PETSC_TRUE;
9000: PetscFunctionReturn(PETSC_SUCCESS);
9001: }
9003: /* Declare a DM incompatible with a DM that lives on an "unequal"
9004: communicator. Note that this does not preclude compatibility with
9005: DMs living on "congruent" or "similar" communicators, but this must be
9006: determined by the implementation-specific logic */
9007: PetscCallMPI(MPI_Comm_compare(PetscObjectComm((PetscObject)dm1), PetscObjectComm((PetscObject)dm2), &compareResult));
9008: if (compareResult == MPI_UNEQUAL) {
9009: *set = PETSC_TRUE;
9010: *compatible = PETSC_FALSE;
9011: PetscFunctionReturn(PETSC_SUCCESS);
9012: }
9014: /* Pass to the implementation-specific routine, if one exists. */
9015: if (dm1->ops->getcompatibility) {
9016: PetscUseTypeMethod(dm1, getcompatibility, dm2, compatible, set);
9017: if (*set) PetscFunctionReturn(PETSC_SUCCESS);
9018: }
9020: /* If dm1 and dm2 are of different types, then attempt to check compatibility
9021: with an implementation of this function from dm2 */
9022: PetscCall(DMGetType(dm1, &type));
9023: PetscCall(DMGetType(dm2, &type2));
9024: PetscCall(PetscStrcmp(type, type2, &sameType));
9025: if (!sameType && dm2->ops->getcompatibility) {
9026: PetscUseTypeMethod(dm2, getcompatibility, dm1, compatible, set); /* Note argument order */
9027: } else {
9028: *set = PETSC_FALSE;
9029: }
9030: PetscFunctionReturn(PETSC_SUCCESS);
9031: }
9033: /*@C
9034: DMMonitorSet - Sets an additional monitor function that is to be used after a solve to monitor discretization performance.
9036: Logically Collective
9038: Input Parameters:
9039: + dm - the `DM`
9040: . f - the monitor function
9041: . mctx - [optional] context for private data for the monitor routine (use `NULL` if no context is desired)
9042: - monitordestroy - [optional] routine that frees monitor context (may be `NULL`), see `PetscCtxDestroyFn` for the calling sequence
9044: Options Database Key:
9045: . -dm_monitor_cancel - cancels all monitors that have been hardwired into a code by calls to `DMMonitorSet()`, but
9046: does not cancel those set via the options database.
9048: Level: intermediate
9050: Note:
9051: Several different monitoring routines may be set by calling
9052: `DMMonitorSet()` multiple times or with `DMMonitorSetFromOptions()`; all will be called in the
9053: order in which they were set.
9055: Fortran Note:
9056: Only a single monitor function can be set for each `DM` object
9058: Developer Note:
9059: This API has a generic name but seems specific to a very particular aspect of the use of `DM`
9061: .seealso: [](ch_dmbase), `DM`, `DMMonitorCancel()`, `DMMonitorSetFromOptions()`, `DMMonitor()`, `PetscCtxDestroyFn`
9062: @*/
9063: PetscErrorCode DMMonitorSet(DM dm, PetscErrorCode (*f)(DM, void *), void *mctx, PetscCtxDestroyFn *monitordestroy)
9064: {
9065: PetscFunctionBegin;
9067: for (PetscInt m = 0; m < dm->numbermonitors; ++m) {
9068: PetscBool identical;
9070: PetscCall(PetscMonitorCompare((PetscErrorCode (*)(void))(PetscVoidFn *)f, mctx, monitordestroy, (PetscErrorCode (*)(void))(PetscVoidFn *)dm->monitor[m], dm->monitorcontext[m], dm->monitordestroy[m], &identical));
9071: if (identical) PetscFunctionReturn(PETSC_SUCCESS);
9072: }
9073: PetscCheck(dm->numbermonitors < MAXDMMONITORS, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Too many monitors set");
9074: dm->monitor[dm->numbermonitors] = f;
9075: dm->monitordestroy[dm->numbermonitors] = monitordestroy;
9076: dm->monitorcontext[dm->numbermonitors++] = mctx;
9077: PetscFunctionReturn(PETSC_SUCCESS);
9078: }
9080: /*@
9081: DMMonitorCancel - Clears all the monitor functions for a `DM` object.
9083: Logically Collective
9085: Input Parameter:
9086: . dm - the DM
9088: Options Database Key:
9089: . -dm_monitor_cancel - cancels all monitors that have been hardwired
9090: into a code by calls to `DMonitorSet()`, but does not cancel those
9091: set via the options database
9093: Level: intermediate
9095: Note:
9096: There is no way to clear one specific monitor from a `DM` object.
9098: .seealso: [](ch_dmbase), `DM`, `DMMonitorSet()`, `DMMonitorSetFromOptions()`, `DMMonitor()`
9099: @*/
9100: PetscErrorCode DMMonitorCancel(DM dm)
9101: {
9102: PetscFunctionBegin;
9104: for (PetscInt m = 0; m < dm->numbermonitors; ++m) {
9105: if (dm->monitordestroy[m]) PetscCall((*dm->monitordestroy[m])(&dm->monitorcontext[m]));
9106: }
9107: dm->numbermonitors = 0;
9108: PetscFunctionReturn(PETSC_SUCCESS);
9109: }
9111: /*@C
9112: DMMonitorSetFromOptions - Sets a monitor function and viewer appropriate for the type indicated by the user
9114: Collective
9116: Input Parameters:
9117: + dm - `DM` object you wish to monitor
9118: . name - the monitor type one is seeking
9119: . help - message indicating what monitoring is done
9120: . manual - manual page for the monitor
9121: . monitor - the monitor function, this must use a `PetscViewerFormat` as its context
9122: - 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
9124: Output Parameter:
9125: . flg - Flag set if the monitor was created
9127: Calling sequence of `monitor`:
9128: + dm - the `DM` to be monitored
9129: - ctx - monitor context
9131: Calling sequence of `monitorsetup`:
9132: + dm - the `DM` to be monitored
9133: - vf - the `PetscViewer` and format to be used by the monitor
9135: Level: developer
9137: .seealso: [](ch_dmbase), `DM`, `PetscOptionsCreateViewer()`, `PetscOptionsGetReal()`, `PetscOptionsHasName()`, `PetscOptionsGetString()`,
9138: `PetscOptionsGetIntArray()`, `PetscOptionsGetRealArray()`, `PetscOptionsBool()`,
9139: `PetscOptionsInt()`, `PetscOptionsString()`, `PetscOptionsReal()`,
9140: `PetscOptionsName()`, `PetscOptionsBegin()`, `PetscOptionsEnd()`, `PetscOptionsHeadBegin()`,
9141: `PetscOptionsStringArray()`, `PetscOptionsRealArray()`, `PetscOptionsScalar()`,
9142: `PetscOptionsBoolGroupBegin()`, `PetscOptionsBoolGroup()`, `PetscOptionsBoolGroupEnd()`,
9143: `PetscOptionsFList()`, `PetscOptionsEList()`, `DMMonitor()`, `DMMonitorSet()`
9144: @*/
9145: 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)
9146: {
9147: PetscViewer viewer;
9148: PetscViewerFormat format;
9150: PetscFunctionBegin;
9152: PetscCall(PetscOptionsCreateViewer(PetscObjectComm((PetscObject)dm), ((PetscObject)dm)->options, ((PetscObject)dm)->prefix, name, &viewer, &format, flg));
9153: if (*flg) {
9154: PetscViewerAndFormat *vf;
9156: PetscCall(PetscViewerAndFormatCreate(viewer, format, &vf));
9157: PetscCall(PetscViewerDestroy(&viewer));
9158: if (monitorsetup) PetscCall((*monitorsetup)(dm, vf));
9159: PetscCall(DMMonitorSet(dm, monitor, vf, (PetscCtxDestroyFn *)PetscViewerAndFormatDestroy));
9160: }
9161: PetscFunctionReturn(PETSC_SUCCESS);
9162: }
9164: /*@
9165: DMMonitor - runs the user provided monitor routines, if they exist
9167: Collective
9169: Input Parameter:
9170: . dm - The `DM`
9172: Level: developer
9174: Developer Note:
9175: Note should indicate when during the life of the `DM` the monitor is run. It appears to be
9176: related to the discretization process seems rather specialized since some `DM` have no
9177: concept of discretization.
9179: .seealso: [](ch_dmbase), `DM`, `DMMonitorSet()`, `DMMonitorSetFromOptions()`
9180: @*/
9181: PetscErrorCode DMMonitor(DM dm)
9182: {
9183: PetscFunctionBegin;
9184: if (!dm) PetscFunctionReturn(PETSC_SUCCESS);
9186: for (PetscInt m = 0; m < dm->numbermonitors; ++m) PetscCall((*dm->monitor[m])(dm, dm->monitorcontext[m]));
9187: PetscFunctionReturn(PETSC_SUCCESS);
9188: }
9190: /*@
9191: DMComputeError - Computes the error assuming the user has provided the exact solution functions
9193: Collective
9195: Input Parameters:
9196: + dm - The `DM`
9197: - sol - The solution vector
9199: Input/Output Parameter:
9200: . errors - An array of length Nf, the number of fields, or `NULL` for no output; on output
9201: contains the error in each field
9203: Output Parameter:
9204: . errorVec - A vector to hold the cellwise error (may be `NULL`)
9206: Level: developer
9208: Note:
9209: The exact solutions come from the `PetscDS` object, and the time comes from `DMGetOutputSequenceNumber()`.
9211: .seealso: [](ch_dmbase), `DM`, `DMMonitorSet()`, `DMGetRegionNumDS()`, `PetscDSGetExactSolution()`, `DMGetOutputSequenceNumber()`
9212: @*/
9213: PetscErrorCode DMComputeError(DM dm, Vec sol, PetscReal errors[], Vec *errorVec)
9214: {
9215: PetscErrorCode (**exactSol)(PetscInt, PetscReal, const PetscReal[], PetscInt, PetscScalar[], void *);
9216: void **ctxs;
9217: PetscReal time;
9218: PetscInt Nf, f, Nds, s;
9220: PetscFunctionBegin;
9221: PetscCall(DMGetNumFields(dm, &Nf));
9222: PetscCall(PetscCalloc2(Nf, &exactSol, Nf, &ctxs));
9223: PetscCall(DMGetNumDS(dm, &Nds));
9224: for (s = 0; s < Nds; ++s) {
9225: PetscDS ds;
9226: DMLabel label;
9227: IS fieldIS;
9228: const PetscInt *fields;
9229: PetscInt dsNf;
9231: PetscCall(DMGetRegionNumDS(dm, s, &label, &fieldIS, &ds, NULL));
9232: PetscCall(PetscDSGetNumFields(ds, &dsNf));
9233: if (fieldIS) PetscCall(ISGetIndices(fieldIS, &fields));
9234: for (f = 0; f < dsNf; ++f) {
9235: const PetscInt field = fields[f];
9236: PetscCall(PetscDSGetExactSolution(ds, field, &exactSol[field], &ctxs[field]));
9237: }
9238: if (fieldIS) PetscCall(ISRestoreIndices(fieldIS, &fields));
9239: }
9240: 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);
9241: PetscCall(DMGetOutputSequenceNumber(dm, NULL, &time));
9242: if (errors) PetscCall(DMComputeL2FieldDiff(dm, time, exactSol, ctxs, sol, errors));
9243: if (errorVec) {
9244: DM edm;
9245: DMPolytopeType ct;
9246: PetscBool simplex;
9247: PetscInt dim, cStart, Nf;
9249: PetscCall(DMClone(dm, &edm));
9250: PetscCall(DMGetDimension(edm, &dim));
9251: PetscCall(DMPlexGetHeightStratum(dm, 0, &cStart, NULL));
9252: PetscCall(DMPlexGetCellType(dm, cStart, &ct));
9253: simplex = DMPolytopeTypeGetNumVertices(ct) == DMPolytopeTypeGetDim(ct) + 1 ? PETSC_TRUE : PETSC_FALSE;
9254: PetscCall(DMGetNumFields(dm, &Nf));
9255: for (f = 0; f < Nf; ++f) {
9256: PetscFE fe, efe;
9257: PetscQuadrature q;
9258: const char *name;
9260: PetscCall(DMGetField(dm, f, NULL, (PetscObject *)&fe));
9261: PetscCall(PetscFECreateLagrange(PETSC_COMM_SELF, dim, Nf, simplex, 0, PETSC_DETERMINE, &efe));
9262: PetscCall(PetscObjectGetName((PetscObject)fe, &name));
9263: PetscCall(PetscObjectSetName((PetscObject)efe, name));
9264: PetscCall(PetscFEGetQuadrature(fe, &q));
9265: PetscCall(PetscFESetQuadrature(efe, q));
9266: PetscCall(DMSetField(edm, f, NULL, (PetscObject)efe));
9267: PetscCall(PetscFEDestroy(&efe));
9268: }
9269: PetscCall(DMCreateDS(edm));
9271: PetscCall(DMCreateGlobalVector(edm, errorVec));
9272: PetscCall(PetscObjectSetName((PetscObject)*errorVec, "Error"));
9273: PetscCall(DMPlexComputeL2DiffVec(dm, time, exactSol, ctxs, sol, *errorVec));
9274: PetscCall(DMDestroy(&edm));
9275: }
9276: PetscCall(PetscFree2(exactSol, ctxs));
9277: PetscFunctionReturn(PETSC_SUCCESS);
9278: }
9280: /*@
9281: DMGetNumAuxiliaryVec - Get the number of auxiliary vectors associated with this `DM`
9283: Not Collective
9285: Input Parameter:
9286: . dm - The `DM`
9288: Output Parameter:
9289: . numAux - The number of auxiliary data vectors
9291: Level: advanced
9293: .seealso: [](ch_dmbase), `DM`, `DMClearAuxiliaryVec()`, `DMSetAuxiliaryVec()`, `DMGetAuxiliaryLabels()`, `DMGetAuxiliaryVec()`
9294: @*/
9295: PetscErrorCode DMGetNumAuxiliaryVec(DM dm, PetscInt *numAux)
9296: {
9297: PetscFunctionBegin;
9299: PetscCall(PetscHMapAuxGetSize(dm->auxData, numAux));
9300: PetscFunctionReturn(PETSC_SUCCESS);
9301: }
9303: /*@
9304: DMGetAuxiliaryVec - Get the auxiliary vector for region specified by the given label and value, and equation part
9306: Not Collective
9308: Input Parameters:
9309: + dm - The `DM`
9310: . label - The `DMLabel`
9311: . value - The label value indicating the region
9312: - part - The equation part, or 0 if unused
9314: Output Parameter:
9315: . aux - The `Vec` holding auxiliary field data
9317: Level: advanced
9319: Note:
9320: If no auxiliary vector is found for this (label, value), (`NULL`, 0, 0) is checked as well.
9322: .seealso: [](ch_dmbase), `DM`, `DMClearAuxiliaryVec()`, `DMSetAuxiliaryVec()`, `DMGetNumAuxiliaryVec()`, `DMGetAuxiliaryLabels()`
9323: @*/
9324: PetscErrorCode DMGetAuxiliaryVec(DM dm, DMLabel label, PetscInt value, PetscInt part, Vec *aux)
9325: {
9326: PetscHashAuxKey key, wild = {NULL, 0, 0};
9327: PetscBool has;
9329: PetscFunctionBegin;
9332: key.label = label;
9333: key.value = value;
9334: key.part = part;
9335: PetscCall(PetscHMapAuxHas(dm->auxData, key, &has));
9336: if (has) PetscCall(PetscHMapAuxGet(dm->auxData, key, aux));
9337: else PetscCall(PetscHMapAuxGet(dm->auxData, wild, aux));
9338: PetscFunctionReturn(PETSC_SUCCESS);
9339: }
9341: /*@
9342: DMSetAuxiliaryVec - Set an auxiliary vector for region specified by the given label and value, and equation part
9344: Not Collective because auxiliary vectors are not parallel
9346: Input Parameters:
9347: + dm - The `DM`
9348: . label - The `DMLabel`
9349: . value - The label value indicating the region
9350: . part - The equation part, or 0 if unused
9351: - aux - The `Vec` holding auxiliary field data
9353: Level: advanced
9355: .seealso: [](ch_dmbase), `DM`, `DMClearAuxiliaryVec()`, `DMGetAuxiliaryVec()`, `DMGetAuxiliaryLabels()`, `DMCopyAuxiliaryVec()`
9356: @*/
9357: PetscErrorCode DMSetAuxiliaryVec(DM dm, DMLabel label, PetscInt value, PetscInt part, Vec aux)
9358: {
9359: Vec old;
9360: PetscHashAuxKey key;
9362: PetscFunctionBegin;
9365: key.label = label;
9366: key.value = value;
9367: key.part = part;
9368: PetscCall(PetscHMapAuxGet(dm->auxData, key, &old));
9369: PetscCall(PetscObjectReference((PetscObject)aux));
9370: if (!aux) PetscCall(PetscHMapAuxDel(dm->auxData, key));
9371: else PetscCall(PetscHMapAuxSet(dm->auxData, key, aux));
9372: PetscCall(VecDestroy(&old));
9373: PetscFunctionReturn(PETSC_SUCCESS);
9374: }
9376: /*@
9377: DMGetAuxiliaryLabels - Get the labels, values, and parts for all auxiliary vectors in this `DM`
9379: Not Collective
9381: Input Parameter:
9382: . dm - The `DM`
9384: Output Parameters:
9385: + labels - The `DMLabel`s for each `Vec`
9386: . values - The label values for each `Vec`
9387: - parts - The equation parts for each `Vec`
9389: Level: advanced
9391: Note:
9392: The arrays passed in must be at least as large as `DMGetNumAuxiliaryVec()`.
9394: .seealso: [](ch_dmbase), `DM`, `DMClearAuxiliaryVec()`, `DMGetNumAuxiliaryVec()`, `DMGetAuxiliaryVec()`, `DMSetAuxiliaryVec()`, `DMCopyAuxiliaryVec()`
9395: @*/
9396: PetscErrorCode DMGetAuxiliaryLabels(DM dm, DMLabel labels[], PetscInt values[], PetscInt parts[])
9397: {
9398: PetscHashAuxKey *keys;
9399: PetscInt n, i, off = 0;
9401: PetscFunctionBegin;
9403: PetscAssertPointer(labels, 2);
9404: PetscAssertPointer(values, 3);
9405: PetscAssertPointer(parts, 4);
9406: PetscCall(DMGetNumAuxiliaryVec(dm, &n));
9407: PetscCall(PetscMalloc1(n, &keys));
9408: PetscCall(PetscHMapAuxGetKeys(dm->auxData, &off, keys));
9409: for (i = 0; i < n; ++i) {
9410: labels[i] = keys[i].label;
9411: values[i] = keys[i].value;
9412: parts[i] = keys[i].part;
9413: }
9414: PetscCall(PetscFree(keys));
9415: PetscFunctionReturn(PETSC_SUCCESS);
9416: }
9418: /*@
9419: DMCopyAuxiliaryVec - Copy the auxiliary vector data on a `DM` to a new `DM`
9421: Not Collective
9423: Input Parameter:
9424: . dm - The `DM`
9426: Output Parameter:
9427: . dmNew - The new `DM`, now with the same auxiliary data
9429: Level: advanced
9431: Note:
9432: This is a shallow copy of the auxiliary vectors
9434: .seealso: [](ch_dmbase), `DM`, `DMClearAuxiliaryVec()`, `DMGetNumAuxiliaryVec()`, `DMGetAuxiliaryVec()`, `DMSetAuxiliaryVec()`
9435: @*/
9436: PetscErrorCode DMCopyAuxiliaryVec(DM dm, DM dmNew)
9437: {
9438: PetscFunctionBegin;
9441: if (dm == dmNew) PetscFunctionReturn(PETSC_SUCCESS);
9442: PetscCall(DMClearAuxiliaryVec(dmNew));
9444: PetscCall(PetscHMapAuxDestroy(&dmNew->auxData));
9445: PetscCall(PetscHMapAuxDuplicate(dm->auxData, &dmNew->auxData));
9446: {
9447: Vec *auxData;
9448: PetscInt n, i, off = 0;
9450: PetscCall(PetscHMapAuxGetSize(dmNew->auxData, &n));
9451: PetscCall(PetscMalloc1(n, &auxData));
9452: PetscCall(PetscHMapAuxGetVals(dmNew->auxData, &off, auxData));
9453: for (i = 0; i < n; ++i) PetscCall(PetscObjectReference((PetscObject)auxData[i]));
9454: PetscCall(PetscFree(auxData));
9455: }
9456: PetscFunctionReturn(PETSC_SUCCESS);
9457: }
9459: /*@
9460: DMClearAuxiliaryVec - Destroys the auxiliary vector information and creates a new empty one
9462: Not Collective
9464: Input Parameter:
9465: . dm - The `DM`
9467: Level: advanced
9469: .seealso: [](ch_dmbase), `DM`, `DMCopyAuxiliaryVec()`, `DMGetNumAuxiliaryVec()`, `DMGetAuxiliaryVec()`, `DMSetAuxiliaryVec()`
9470: @*/
9471: PetscErrorCode DMClearAuxiliaryVec(DM dm)
9472: {
9473: Vec *auxData;
9474: PetscInt n, i, off = 0;
9476: PetscFunctionBegin;
9477: PetscCall(PetscHMapAuxGetSize(dm->auxData, &n));
9478: PetscCall(PetscMalloc1(n, &auxData));
9479: PetscCall(PetscHMapAuxGetVals(dm->auxData, &off, auxData));
9480: for (i = 0; i < n; ++i) PetscCall(VecDestroy(&auxData[i]));
9481: PetscCall(PetscFree(auxData));
9482: PetscCall(PetscHMapAuxDestroy(&dm->auxData));
9483: PetscCall(PetscHMapAuxCreate(&dm->auxData));
9484: PetscFunctionReturn(PETSC_SUCCESS);
9485: }
9487: /*@
9488: DMPolytopeMatchOrientation - Determine an orientation (transformation) that takes the source face arrangement to the target face arrangement
9490: Not Collective
9492: Input Parameters:
9493: + ct - The `DMPolytopeType`
9494: . sourceCone - The source arrangement of faces
9495: - targetCone - The target arrangement of faces
9497: Output Parameters:
9498: + ornt - The orientation (transformation) which will take the source arrangement to the target arrangement
9499: - found - Flag indicating that a suitable orientation was found
9501: Level: advanced
9503: Note:
9504: An arrangement is a face order combined with an orientation for each face
9506: Each orientation (transformation) is labeled with an integer from negative `DMPolytopeTypeGetNumArrangements(ct)`/2 to `DMPolytopeTypeGetNumArrangements(ct)`/2
9507: that labels each arrangement (face ordering plus orientation for each face).
9509: See `DMPolytopeMatchVertexOrientation()` to find a new vertex orientation that takes the source vertex arrangement to the target vertex arrangement
9511: .seealso: [](ch_dmbase), `DM`, `DMPolytopeGetOrientation()`, `DMPolytopeMatchVertexOrientation()`, `DMPolytopeGetVertexOrientation()`
9512: @*/
9513: PetscErrorCode DMPolytopeMatchOrientation(DMPolytopeType ct, const PetscInt sourceCone[], const PetscInt targetCone[], PetscInt *ornt, PetscBool *found)
9514: {
9515: const PetscInt cS = DMPolytopeTypeGetConeSize(ct);
9516: const PetscInt nO = DMPolytopeTypeGetNumArrangements(ct) / 2;
9517: PetscInt o, c;
9519: PetscFunctionBegin;
9520: if (!nO) {
9521: *ornt = 0;
9522: *found = PETSC_TRUE;
9523: PetscFunctionReturn(PETSC_SUCCESS);
9524: }
9525: for (o = -nO; o < nO; ++o) {
9526: const PetscInt *arr = DMPolytopeTypeGetArrangement(ct, o);
9528: for (c = 0; c < cS; ++c)
9529: if (sourceCone[arr[c * 2]] != targetCone[c]) break;
9530: if (c == cS) {
9531: *ornt = o;
9532: break;
9533: }
9534: }
9535: *found = o == nO ? PETSC_FALSE : PETSC_TRUE;
9536: PetscFunctionReturn(PETSC_SUCCESS);
9537: }
9539: /*@
9540: DMPolytopeGetOrientation - Determine an orientation (transformation) that takes the source face arrangement to the target face arrangement
9542: Not Collective
9544: Input Parameters:
9545: + ct - The `DMPolytopeType`
9546: . sourceCone - The source arrangement of faces
9547: - targetCone - The target arrangement of faces
9549: Output Parameter:
9550: . ornt - The orientation (transformation) which will take the source arrangement to the target arrangement
9552: Level: advanced
9554: Note:
9555: This function is the same as `DMPolytopeMatchOrientation()` except it will generate an error if no suitable orientation can be found.
9557: Developer Note:
9558: It is unclear why this function needs to exist since one can simply call `DMPolytopeMatchOrientation()` and error if none is found
9560: .seealso: [](ch_dmbase), `DM`, `DMPolytopeType`, `DMPolytopeMatchOrientation()`, `DMPolytopeGetVertexOrientation()`, `DMPolytopeMatchVertexOrientation()`
9561: @*/
9562: PetscErrorCode DMPolytopeGetOrientation(DMPolytopeType ct, const PetscInt sourceCone[], const PetscInt targetCone[], PetscInt *ornt)
9563: {
9564: PetscBool found;
9566: PetscFunctionBegin;
9567: PetscCall(DMPolytopeMatchOrientation(ct, sourceCone, targetCone, ornt, &found));
9568: PetscCheck(found, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Could not find orientation for %s", DMPolytopeTypes[ct]);
9569: PetscFunctionReturn(PETSC_SUCCESS);
9570: }
9572: /*@
9573: DMPolytopeMatchVertexOrientation - Determine an orientation (transformation) that takes the source vertex arrangement to the target vertex arrangement
9575: Not Collective
9577: Input Parameters:
9578: + ct - The `DMPolytopeType`
9579: . sourceVert - The source arrangement of vertices
9580: - targetVert - The target arrangement of vertices
9582: Output Parameters:
9583: + ornt - The orientation (transformation) which will take the source arrangement to the target arrangement
9584: - found - Flag indicating that a suitable orientation was found
9586: Level: advanced
9588: Notes:
9589: An arrangement is a vertex order
9591: Each orientation (transformation) is labeled with an integer from negative `DMPolytopeTypeGetNumArrangements(ct)`/2 to `DMPolytopeTypeGetNumArrangements(ct)`/2
9592: that labels each arrangement (vertex ordering).
9594: See `DMPolytopeMatchOrientation()` to find a new face orientation that takes the source face arrangement to the target face arrangement
9596: .seealso: [](ch_dmbase), `DM`, `DMPolytopeType`, `DMPolytopeGetOrientation()`, `DMPolytopeMatchOrientation()`, `DMPolytopeTypeGetNumVertices()`, `DMPolytopeTypeGetVertexArrangement()`
9597: @*/
9598: PetscErrorCode DMPolytopeMatchVertexOrientation(DMPolytopeType ct, const PetscInt sourceVert[], const PetscInt targetVert[], PetscInt *ornt, PetscBool *found)
9599: {
9600: const PetscInt cS = DMPolytopeTypeGetNumVertices(ct);
9601: const PetscInt nO = DMPolytopeTypeGetNumArrangements(ct) / 2;
9602: PetscInt o, c;
9604: PetscFunctionBegin;
9605: if (!nO) {
9606: *ornt = 0;
9607: *found = PETSC_TRUE;
9608: PetscFunctionReturn(PETSC_SUCCESS);
9609: }
9610: for (o = -nO; o < nO; ++o) {
9611: const PetscInt *arr = DMPolytopeTypeGetVertexArrangement(ct, o);
9613: for (c = 0; c < cS; ++c)
9614: if (sourceVert[arr[c]] != targetVert[c]) break;
9615: if (c == cS) {
9616: *ornt = o;
9617: break;
9618: }
9619: }
9620: *found = o == nO ? PETSC_FALSE : PETSC_TRUE;
9621: PetscFunctionReturn(PETSC_SUCCESS);
9622: }
9624: /*@
9625: DMPolytopeGetVertexOrientation - Determine an orientation (transformation) that takes the source vertex arrangement to the target vertex arrangement
9627: Not Collective
9629: Input Parameters:
9630: + ct - The `DMPolytopeType`
9631: . sourceCone - The source arrangement of vertices
9632: - targetCone - The target arrangement of vertices
9634: Output Parameter:
9635: . ornt - The orientation (transformation) which will take the source arrangement to the target arrangement
9637: Level: advanced
9639: Note:
9640: This function is the same as `DMPolytopeMatchVertexOrientation()` except it errors if not orientation is possible.
9642: Developer Note:
9643: It is unclear why this function needs to exist since one can simply call `DMPolytopeMatchVertexOrientation()` and error if none is found
9645: .seealso: [](ch_dmbase), `DM`, `DMPolytopeType`, `DMPolytopeMatchVertexOrientation()`, `DMPolytopeGetOrientation()`
9646: @*/
9647: PetscErrorCode DMPolytopeGetVertexOrientation(DMPolytopeType ct, const PetscInt sourceCone[], const PetscInt targetCone[], PetscInt *ornt)
9648: {
9649: PetscBool found;
9651: PetscFunctionBegin;
9652: PetscCall(DMPolytopeMatchVertexOrientation(ct, sourceCone, targetCone, ornt, &found));
9653: PetscCheck(found, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Could not find orientation for %s", DMPolytopeTypes[ct]);
9654: PetscFunctionReturn(PETSC_SUCCESS);
9655: }
9657: /*@
9658: DMPolytopeInCellTest - Check whether a point lies inside the reference cell of given type
9660: Not Collective
9662: Input Parameters:
9663: + ct - The `DMPolytopeType`
9664: - point - Coordinates of the point
9666: Output Parameter:
9667: . inside - Flag indicating whether the point is inside the reference cell of given type
9669: Level: advanced
9671: .seealso: [](ch_dmbase), `DM`, `DMPolytopeType`, `DMLocatePoints()`
9672: @*/
9673: PetscErrorCode DMPolytopeInCellTest(DMPolytopeType ct, const PetscReal point[], PetscBool *inside)
9674: {
9675: PetscReal sum = 0.0;
9677: PetscFunctionBegin;
9678: *inside = PETSC_TRUE;
9679: switch (ct) {
9680: case DM_POLYTOPE_TRIANGLE:
9681: case DM_POLYTOPE_TETRAHEDRON:
9682: for (PetscInt d = 0; d < DMPolytopeTypeGetDim(ct); ++d) {
9683: if (point[d] < -1.0) {
9684: *inside = PETSC_FALSE;
9685: break;
9686: }
9687: sum += point[d];
9688: }
9689: if (sum > PETSC_SMALL) {
9690: *inside = PETSC_FALSE;
9691: break;
9692: }
9693: break;
9694: case DM_POLYTOPE_QUADRILATERAL:
9695: case DM_POLYTOPE_HEXAHEDRON:
9696: for (PetscInt d = 0; d < DMPolytopeTypeGetDim(ct); ++d)
9697: if (PetscAbsReal(point[d]) > 1. + PETSC_SMALL) {
9698: *inside = PETSC_FALSE;
9699: break;
9700: }
9701: break;
9702: default:
9703: SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Unsupported polytope type %s", DMPolytopeTypes[ct]);
9704: }
9705: PetscFunctionReturn(PETSC_SUCCESS);
9706: }
9708: /*@
9709: DMReorderSectionSetDefault - Set flag indicating whether the local section should be reordered by default
9711: Logically collective
9713: Input Parameters:
9714: + dm - The DM
9715: - reorder - Flag for reordering
9717: Level: intermediate
9719: .seealso: `DMReorderSectionGetDefault()`
9720: @*/
9721: PetscErrorCode DMReorderSectionSetDefault(DM dm, DMReorderDefaultFlag reorder)
9722: {
9723: PetscFunctionBegin;
9725: PetscTryMethod(dm, "DMReorderSectionSetDefault_C", (DM, DMReorderDefaultFlag), (dm, reorder));
9726: PetscFunctionReturn(PETSC_SUCCESS);
9727: }
9729: /*@
9730: DMReorderSectionGetDefault - Get flag indicating whether the local section should be reordered by default
9732: Not collective
9734: Input Parameter:
9735: . dm - The DM
9737: Output Parameter:
9738: . reorder - Flag for reordering
9740: Level: intermediate
9742: .seealso: `DMReorderSetDefault()`
9743: @*/
9744: PetscErrorCode DMReorderSectionGetDefault(DM dm, DMReorderDefaultFlag *reorder)
9745: {
9746: PetscFunctionBegin;
9748: PetscAssertPointer(reorder, 2);
9749: *reorder = DM_REORDER_DEFAULT_NOTSET;
9750: PetscTryMethod(dm, "DMReorderSectionGetDefault_C", (DM, DMReorderDefaultFlag *), (dm, reorder));
9751: PetscFunctionReturn(PETSC_SUCCESS);
9752: }
9754: /*@
9755: DMReorderSectionSetType - Set the type of local section reordering
9757: Logically collective
9759: Input Parameters:
9760: + dm - The DM
9761: - reorder - The reordering method
9763: Level: intermediate
9765: .seealso: `DMReorderSectionGetType()`, `DMReorderSectionSetDefault()`
9766: @*/
9767: PetscErrorCode DMReorderSectionSetType(DM dm, MatOrderingType reorder)
9768: {
9769: PetscFunctionBegin;
9771: PetscTryMethod(dm, "DMReorderSectionSetType_C", (DM, MatOrderingType), (dm, reorder));
9772: PetscFunctionReturn(PETSC_SUCCESS);
9773: }
9775: /*@
9776: DMReorderSectionGetType - Get the reordering type for the local section
9778: Not collective
9780: Input Parameter:
9781: . dm - The DM
9783: Output Parameter:
9784: . reorder - The reordering method
9786: Level: intermediate
9788: .seealso: `DMReorderSetDefault()`, `DMReorderSectionGetDefault()`
9789: @*/
9790: PetscErrorCode DMReorderSectionGetType(DM dm, MatOrderingType *reorder)
9791: {
9792: PetscFunctionBegin;
9794: PetscAssertPointer(reorder, 2);
9795: *reorder = NULL;
9796: PetscTryMethod(dm, "DMReorderSectionGetType_C", (DM, MatOrderingType *), (dm, reorder));
9797: PetscFunctionReturn(PETSC_SUCCESS);
9798: }