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 <petscdmfield.h>
7: #include <petscsf.h>
8: #include <petscds.h>
10: #ifdef PETSC_HAVE_LIBCEED
11: #include <petscfeceed.h>
12: #endif
14: #if !defined(PETSC_HAVE_WINDOWS_COMPILERS)
15: #include <petsc/private/valgrind/memcheck.h>
16: #endif
18: PetscClassId DM_CLASSID;
19: PetscClassId DMLABEL_CLASSID;
20: 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_AdaptInterpolator;
22: const char *const DMBoundaryTypes[] = {"NONE", "GHOSTED", "MIRROR", "PERIODIC", "TWIST", "DMBoundaryType", "DM_BOUNDARY_", NULL};
23: const char *const DMBoundaryConditionTypes[] = {"INVALID", "ESSENTIAL", "NATURAL", "INVALID", "INVALID", "ESSENTIAL_FIELD", "NATURAL_FIELD", "INVALID", "INVALID", "ESSENTIAL_BD_FIELD", "NATURAL_RIEMANN", "DMBoundaryConditionType", "DM_BC_", NULL};
24: const char *const DMPolytopeTypes[] = {"vertex", "segment", "tensor_segment", "triangle", "quadrilateral", "tensor_quad", "tetrahedron", "hexahedron", "triangular_prism", "tensor_triangular_prism", "tensor_quadrilateral_prism",
25: "pyramid", "FV_ghost_cell", "interior_ghost_cell", "unknown", "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.
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: .seealso: `DMSetType()`, `DMType`, `DMDACreate()`, `DMDA`, `DMSLICED`, `DMCOMPOSITE`, `DMPLEX`, `DMMOAB`, `DMNETWORK`
49: @*/
50: PetscErrorCode DMCreate(MPI_Comm comm, DM *dm)
51: {
52: DM v;
53: PetscDS ds;
56: *dm = NULL;
57: DMInitializePackage();
59: PetscHeaderCreate(v, DM_CLASSID, "DM", "Distribution Manager", "DM", comm, DMDestroy, DMView);
61: ((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: PetscSFCreate(comm, &v->sf);
70: 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: {
86: PetscInt i;
87: for (i = 0; i < 10; ++i) {
88: v->nullspaceConstructors[i] = NULL;
89: v->nearnullspaceConstructors[i] = NULL;
90: }
91: }
92: PetscDSCreate(PETSC_COMM_SELF, &ds);
93: DMSetRegionDS(v, NULL, NULL, ds);
94: PetscDSDestroy(&ds);
95: PetscHMapAuxCreate(&v->auxData);
96: v->dmBC = NULL;
97: v->coarseMesh = NULL;
98: v->outputSequenceNum = -1;
99: v->outputSequenceVal = 0.0;
100: DMSetVecType(v, VECSTANDARD);
101: DMSetMatType(v, MATAIJ);
103: *dm = v;
104: return 0;
105: }
107: /*@
108: DMClone - Creates a `DM` object with the same topology as the original.
110: Collective
112: Input Parameter:
113: . dm - The original `DM` object
115: Output Parameter:
116: . newdm - The new `DM` object
118: Level: beginner
120: Notes:
121: For some `DM` implementations this is a shallow clone, the result of which may share (reference counted) information with its parent. For example,
122: `DMClone()` applied to a `DMPLEX` object will result in a new `DMPLEX` that shares the topology with the original `DMPLEX`. It does not
123: share the `PetscSection` of the original `DM`.
125: The clone is considered set up if the original has been set up.
127: Use `DMConvert()` for a general way to create new `DM` from a given `DM`
129: .seealso: `DMDestroy()`, `DMCreate()`, `DMSetType()`, `DMSetLocalSection()`, `DMSetGlobalSection()`, `DMPLEX`, `DMSetType()`, `DMConvert()`
131: @*/
132: PetscErrorCode DMClone(DM dm, DM *newdm)
133: {
134: PetscSF sf;
135: Vec coords;
136: void *ctx;
137: PetscInt dim, cdim, i;
141: DMCreate(PetscObjectComm((PetscObject)dm), newdm);
142: DMCopyLabels(dm, *newdm, PETSC_COPY_VALUES, PETSC_TRUE, DM_COPY_LABELS_FAIL);
143: (*newdm)->leveldown = dm->leveldown;
144: (*newdm)->levelup = dm->levelup;
145: (*newdm)->prealloc_only = dm->prealloc_only;
146: PetscFree((*newdm)->vectype);
147: PetscStrallocpy(dm->vectype, (char **)&(*newdm)->vectype);
148: PetscFree((*newdm)->mattype);
149: PetscStrallocpy(dm->mattype, (char **)&(*newdm)->mattype);
150: DMGetDimension(dm, &dim);
151: DMSetDimension(*newdm, dim);
152: PetscTryTypeMethod(dm, clone, newdm);
153: (*newdm)->setupcalled = dm->setupcalled;
154: DMGetPointSF(dm, &sf);
155: DMSetPointSF(*newdm, sf);
156: DMGetApplicationContext(dm, &ctx);
157: DMSetApplicationContext(*newdm, ctx);
158: for (i = 0; i < 2; ++i) {
159: if (dm->coordinates[i].dm) {
160: DM ncdm;
161: PetscSection cs;
162: PetscInt pEnd = -1, pEndMax = -1;
164: DMGetLocalSection(dm->coordinates[i].dm, &cs);
165: if (cs) PetscSectionGetChart(cs, NULL, &pEnd);
166: MPI_Allreduce(&pEnd, &pEndMax, 1, MPIU_INT, MPI_MAX, PetscObjectComm((PetscObject)dm));
167: if (pEndMax >= 0) {
168: DMClone(dm->coordinates[i].dm, &ncdm);
169: DMCopyDisc(dm->coordinates[i].dm, ncdm);
170: DMSetLocalSection(ncdm, cs);
171: if (i) DMSetCellCoordinateDM(*newdm, ncdm);
172: else DMSetCoordinateDM(*newdm, ncdm);
173: DMDestroy(&ncdm);
174: }
175: }
176: }
177: DMGetCoordinateDim(dm, &cdim);
178: DMSetCoordinateDim(*newdm, cdim);
179: DMGetCoordinatesLocal(dm, &coords);
180: if (coords) {
181: DMSetCoordinatesLocal(*newdm, coords);
182: } else {
183: DMGetCoordinates(dm, &coords);
184: if (coords) DMSetCoordinates(*newdm, coords);
185: }
186: DMGetCellCoordinatesLocal(dm, &coords);
187: if (coords) {
188: DMSetCellCoordinatesLocal(*newdm, coords);
189: } else {
190: DMGetCellCoordinates(dm, &coords);
191: if (coords) DMSetCellCoordinates(*newdm, coords);
192: }
193: {
194: const PetscReal *maxCell, *Lstart, *L;
196: DMGetPeriodicity(dm, &maxCell, &Lstart, &L);
197: DMSetPeriodicity(*newdm, maxCell, Lstart, L);
198: }
199: {
200: PetscBool useCone, useClosure;
202: DMGetAdjacency(dm, PETSC_DEFAULT, &useCone, &useClosure);
203: DMSetAdjacency(*newdm, PETSC_DEFAULT, useCone, useClosure);
204: }
205: return 0;
206: }
208: /*@C
209: DMSetVecType - Sets the type of vector created with `DMCreateLocalVector()` and `DMCreateGlobalVector()`
211: Logically Collective on da
213: Input Parameters:
214: + da - initial distributed array
215: - ctype - the vector type, for example `VECSTANDARD`, `VECCUDA`, or `VECVIENNACL`
217: Options Database:
218: . -dm_vec_type ctype - the type of vector to create
220: Level: intermediate
222: .seealso: `DMCreate()`, `DMDestroy()`, `DM`, `DMDAInterpolationType`, `VecType`, `DMGetVecType()`, `DMSetMatType()`, `DMGetMatType()`,
223: `VECSTANDARD`, `VECCUDA`, `VECVIENNACL`, `DMCreateLocalVector()`, `DMCreateGlobalVector()`
224: @*/
225: PetscErrorCode DMSetVecType(DM da, VecType ctype)
226: {
228: PetscFree(da->vectype);
229: PetscStrallocpy(ctype, (char **)&da->vectype);
230: return 0;
231: }
233: /*@C
234: DMGetVecType - Gets the type of vector created with `DMCreateLocalVector()` and `DMCreateGlobalVector()`
236: Logically Collective on da
238: Input Parameter:
239: . da - initial distributed array
241: Output Parameter:
242: . ctype - the vector type
244: Level: intermediate
246: .seealso: `DMCreate()`, `DMDestroy()`, `DM`, `DMDAInterpolationType`, `VecType`, `DMSetMatType()`, `DMGetMatType()`, `DMSetVecType()`
247: @*/
248: PetscErrorCode DMGetVecType(DM da, VecType *ctype)
249: {
251: *ctype = da->vectype;
252: return 0;
253: }
255: /*@
256: VecGetDM - Gets the `DM` defining the data layout of the vector
258: Not collective
260: Input Parameter:
261: . v - The `Vec`
263: Output Parameter:
264: . dm - The `DM`
266: Level: intermediate
268: Note:
269: A `Vec` may not have a `DM` associated with it.
271: .seealso: `DM`, `VecSetDM()`, `DMGetLocalVector()`, `DMGetGlobalVector()`, `DMSetVecType()`
272: @*/
273: PetscErrorCode VecGetDM(Vec v, DM *dm)
274: {
277: PetscObjectQuery((PetscObject)v, "__PETSc_dm", (PetscObject *)dm);
278: return 0;
279: }
281: /*@
282: VecSetDM - Sets the `DM` defining the data layout of the vector.
284: Not collective
286: Input Parameters:
287: + v - The `Vec`
288: - dm - The `DM`
290: Note:
291: This is rarely used, generally one uses `DMGetLocalVector()` or `DMGetGlobalVector()` to create a vector associated with a given `DM`
293: 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.
295: Level: developer
297: .seealso: `VecGetDM()`, `DMGetLocalVector()`, `DMGetGlobalVector()`, `DMSetVecType()`
298: @*/
299: PetscErrorCode VecSetDM(Vec v, DM dm)
300: {
303: PetscObjectCompose((PetscObject)v, "__PETSc_dm", (PetscObject)dm);
304: return 0;
305: }
307: /*@C
308: DMSetISColoringType - Sets the type of coloring, `IS_COLORING_GLOBAL` or `IS_COLORING_LOCAL` that is created by the `DM`
310: Logically Collective on dm
312: Input Parameters:
313: + dm - the `DM` context
314: - ctype - the matrix type
316: Options Database:
317: . -dm_is_coloring_type - global or local
319: Level: intermediate
321: .seealso: `DMDACreate1d()`, `DMDACreate2d()`, `DMDACreate3d()`, `DMCreateMatrix()`, `DMCreateMassMatrix()`, `DMSetMatrixPreallocateOnly()`, `MatType`, `DMGetMatType()`,
322: `DMGetISColoringType()`, `ISColoringType`, `IS_COLORING_GLOBAL`, `IS_COLORING_LOCAL`
323: @*/
324: PetscErrorCode DMSetISColoringType(DM dm, ISColoringType ctype)
325: {
327: dm->coloringtype = ctype;
328: return 0;
329: }
331: /*@C
332: DMGetISColoringType - Gets the type of coloring, `IS_COLORING_GLOBAL` or `IS_COLORING_LOCAL` that is created by the `DM`
334: Logically Collective on dm
336: Input Parameter:
337: . dm - the `DM` context
339: Output Parameter:
340: . ctype - the matrix type
342: Options Database:
343: . -dm_is_coloring_type - global or local
345: Level: intermediate
347: .seealso: `DMDACreate1d()`, `DMDACreate2d()`, `DMDACreate3d()`, `DMCreateMatrix()`, `DMCreateMassMatrix()`, `DMSetMatrixPreallocateOnly()`, `MatType`, `DMGetMatType()`,
348: `DMGetISColoringType()`, `ISColoringType`, `IS_COLORING_GLOBAL`, `IS_COLORING_LOCAL`
349: @*/
350: PetscErrorCode DMGetISColoringType(DM dm, ISColoringType *ctype)
351: {
353: *ctype = dm->coloringtype;
354: return 0;
355: }
357: /*@C
358: DMSetMatType - Sets the type of matrix created with `DMCreateMatrix()`
360: Logically Collective on dm
362: Input Parameters:
363: + dm - the `DM` context
364: - ctype - the matrix type, for example `MATMPIAIJ`
366: Options Database:
367: . -dm_mat_type ctype - the type of the matrix to create, for example mpiaij
369: Level: intermediate
371: .seealso: `MatType`, `DMDACreate1d()`, `DMDACreate2d()`, `DMDACreate3d()`, `DMCreateMatrix()`, `DMCreateMassMatrix()`, `DMSetMatrixPreallocateOnly()`, `MatType`, `DMGetMatType()`, `DMSetMatType()`, `DMGetMatType()`, `DMCreateGlobalVector()`, `DMCreateLocalVector()`
372: @*/
373: PetscErrorCode DMSetMatType(DM dm, MatType ctype)
374: {
376: PetscFree(dm->mattype);
377: PetscStrallocpy(ctype, (char **)&dm->mattype);
378: return 0;
379: }
381: /*@C
382: DMGetMatType - Gets the type of matrix created with `DMCreateMatrix()`
384: Logically Collective on dm
386: Input Parameter:
387: . dm - the `DM` context
389: Output Parameter:
390: . ctype - the matrix type
392: Level: intermediate
394: .seealso: `DMDACreate1d()`, `DMDACreate2d()`, `DMDACreate3d()`, `DMCreateMatrix()`, `DMCreateMassMatrix()`, `DMSetMatrixPreallocateOnly()`, `MatType`, `DMSetMatType()`, `DMSetMatType()`, `DMGetMatType()`
395: @*/
396: PetscErrorCode DMGetMatType(DM dm, MatType *ctype)
397: {
399: *ctype = dm->mattype;
400: return 0;
401: }
403: /*@
404: MatGetDM - Gets the `DM` defining the data layout of the matrix
406: Not collective
408: Input Parameter:
409: . A - The `Mat`
411: Output Parameter:
412: . dm - The `DM`
414: Level: intermediate
416: Note:
417: A matrix may not have a `DM` associated with it
419: Developer Note:
420: Since the `Mat` class doesn't know about the `DM` class the `DM` object is associated with the `Mat` through a `PetscObjectCompose()` operation
422: .seealso: `MatSetDM()`, `DMCreateMatrix()`, `DMSetMatType()`
423: @*/
424: PetscErrorCode MatGetDM(Mat A, DM *dm)
425: {
428: PetscObjectQuery((PetscObject)A, "__PETSc_dm", (PetscObject *)dm);
429: return 0;
430: }
432: /*@
433: MatSetDM - Sets the `DM` defining the data layout of the matrix
435: Not collective
437: Input Parameters:
438: + A - The Mat
439: - dm - The DM
441: Level: developer
443: Note:
444: This is rarely used in practice, rather `DMCreateMatrix()` is used to create a matrix associated with a particular `DM`
446: Developer Note:
447: Since the `Mat` class doesn't know about the `DM` class the `DM` object is associated with
448: the `Mat` through a `PetscObjectCompose()` operation
450: .seealso: `MatGetDM()`, `DMCreateMatrix()`, `DMSetMatType()`
451: @*/
452: PetscErrorCode MatSetDM(Mat A, DM dm)
453: {
456: PetscObjectCompose((PetscObject)A, "__PETSc_dm", (PetscObject)dm);
457: return 0;
458: }
460: /*@C
461: DMSetOptionsPrefix - Sets the prefix prepended to all option names when searching through the options database
463: Logically Collective on dm
465: Input Parameters:
466: + da - the `DM` context
467: - prefix - the prefix to prepend
469: Notes:
470: A hyphen (-) must NOT be given at the beginning of the prefix name.
471: The first character of all runtime options is AUTOMATICALLY the hyphen.
473: Level: advanced
475: .seealso: `PetscObjectSetOptionsPrefix()`, `DMSetFromOptions()`
476: @*/
477: PetscErrorCode DMSetOptionsPrefix(DM dm, const char prefix[])
478: {
480: PetscObjectSetOptionsPrefix((PetscObject)dm, prefix);
481: if (dm->sf) PetscObjectSetOptionsPrefix((PetscObject)dm->sf, prefix);
482: if (dm->sectionSF) PetscObjectSetOptionsPrefix((PetscObject)dm->sectionSF, prefix);
483: return 0;
484: }
486: /*@C
487: DMAppendOptionsPrefix - Appends an additional string to an already exising prefix used for searching for
488: `DM` options in the options database.
490: Logically Collective on dm
492: Input Parameters:
493: + dm - the `DM` context
494: - prefix - the string to append to the current prefix
496: Notes:
497: 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.
498: A hyphen (-) must NOT be given at the beginning of the prefix name.
499: The first character of all runtime options is AUTOMATICALLY the hyphen.
501: Level: advanced
503: .seealso: `DMSetOptionsPrefix()`, `DMGetOptionsPrefix()`, `PetscObjectAppendOptionsPrefix()`, `DMSetFromOptions()`
504: @*/
505: PetscErrorCode DMAppendOptionsPrefix(DM dm, const char prefix[])
506: {
508: PetscObjectAppendOptionsPrefix((PetscObject)dm, prefix);
509: return 0;
510: }
512: /*@C
513: DMGetOptionsPrefix - Gets the prefix used for searching for all
514: DM options in the options database.
516: Not Collective
518: Input Parameters:
519: . dm - the `DM` context
521: Output Parameters:
522: . prefix - pointer to the prefix string used is returned
524: Fortran Note:
525: On the fortran side, the user should pass in a string 'prefix' of
526: sufficient length to hold the prefix.
528: Level: advanced
530: .seealso: `DMSetOptionsPrefix()`, `DMAppendOptionsPrefix()`, `DMSetFromOptions()`
531: @*/
532: PetscErrorCode DMGetOptionsPrefix(DM dm, const char *prefix[])
533: {
535: PetscObjectGetOptionsPrefix((PetscObject)dm, prefix);
536: return 0;
537: }
539: static PetscErrorCode DMCountNonCyclicReferences_Internal(DM dm, PetscBool recurseCoarse, PetscBool recurseFine, PetscInt *ncrefct)
540: {
541: PetscInt refct = ((PetscObject)dm)->refct;
543: *ncrefct = 0;
544: if (dm->coarseMesh && dm->coarseMesh->fineMesh == dm) {
545: refct--;
546: if (recurseCoarse) {
547: PetscInt coarseCount;
549: DMCountNonCyclicReferences_Internal(dm->coarseMesh, PETSC_TRUE, PETSC_FALSE, &coarseCount);
550: refct += coarseCount;
551: }
552: }
553: if (dm->fineMesh && dm->fineMesh->coarseMesh == dm) {
554: refct--;
555: if (recurseFine) {
556: PetscInt fineCount;
558: DMCountNonCyclicReferences_Internal(dm->fineMesh, PETSC_FALSE, PETSC_TRUE, &fineCount);
559: refct += fineCount;
560: }
561: }
562: *ncrefct = refct;
563: return 0;
564: }
566: /* Generic wrapper for DMCountNonCyclicReferences_Internal() */
567: PetscErrorCode DMCountNonCyclicReferences(PetscObject dm, PetscInt *ncrefct)
568: {
569: DMCountNonCyclicReferences_Internal((DM)dm, PETSC_TRUE, PETSC_TRUE, ncrefct);
570: return 0;
571: }
573: PetscErrorCode DMDestroyLabelLinkList_Internal(DM dm)
574: {
575: DMLabelLink next = dm->labels;
577: /* destroy the labels */
578: while (next) {
579: DMLabelLink tmp = next->next;
581: if (next->label == dm->depthLabel) dm->depthLabel = NULL;
582: if (next->label == dm->celltypeLabel) dm->celltypeLabel = NULL;
583: DMLabelDestroy(&next->label);
584: PetscFree(next);
585: next = tmp;
586: }
587: dm->labels = NULL;
588: return 0;
589: }
591: PetscErrorCode DMDestroyCoordinates_Private(DMCoordinates *c)
592: {
593: c->dim = PETSC_DEFAULT;
594: DMDestroy(&c->dm);
595: VecDestroy(&c->x);
596: VecDestroy(&c->xl);
597: DMFieldDestroy(&c->field);
598: return 0;
599: }
601: /*@C
602: DMDestroy - Destroys a `DM`.
604: Collective on dm
606: Input Parameter:
607: . dm - the `DM` object to destroy
609: Level: developer
611: .seealso: `DMCreate()`, `DMType`, `DMSetType()`, `DMView()`, `DMCreateGlobalVector()`, `DMCreateInterpolation()`, `DMCreateColoring()`, `DMCreateMatrix()`
613: @*/
614: PetscErrorCode DMDestroy(DM *dm)
615: {
616: PetscInt cnt;
617: DMNamedVecLink nlink, nnext;
619: if (!*dm) return 0;
622: /* count all non-cyclic references in the doubly-linked list of coarse<->fine meshes */
623: DMCountNonCyclicReferences_Internal(*dm, PETSC_TRUE, PETSC_TRUE, &cnt);
624: --((PetscObject)(*dm))->refct;
625: if (--cnt > 0) {
626: *dm = NULL;
627: return 0;
628: }
629: if (((PetscObject)(*dm))->refct < 0) return 0;
630: ((PetscObject)(*dm))->refct = 0;
632: DMClearGlobalVectors(*dm);
633: DMClearLocalVectors(*dm);
635: nnext = (*dm)->namedglobal;
636: (*dm)->namedglobal = NULL;
637: for (nlink = nnext; nlink; nlink = nnext) { /* Destroy the named vectors */
638: nnext = nlink->next;
640: PetscFree(nlink->name);
641: VecDestroy(&nlink->X);
642: PetscFree(nlink);
643: }
644: nnext = (*dm)->namedlocal;
645: (*dm)->namedlocal = NULL;
646: for (nlink = nnext; nlink; nlink = nnext) { /* Destroy the named local vectors */
647: nnext = nlink->next;
649: PetscFree(nlink->name);
650: VecDestroy(&nlink->X);
651: PetscFree(nlink);
652: }
654: /* Destroy the list of hooks */
655: {
656: DMCoarsenHookLink link, next;
657: for (link = (*dm)->coarsenhook; link; link = next) {
658: next = link->next;
659: PetscFree(link);
660: }
661: (*dm)->coarsenhook = NULL;
662: }
663: {
664: DMRefineHookLink link, next;
665: for (link = (*dm)->refinehook; link; link = next) {
666: next = link->next;
667: PetscFree(link);
668: }
669: (*dm)->refinehook = NULL;
670: }
671: {
672: DMSubDomainHookLink link, next;
673: for (link = (*dm)->subdomainhook; link; link = next) {
674: next = link->next;
675: PetscFree(link);
676: }
677: (*dm)->subdomainhook = NULL;
678: }
679: {
680: DMGlobalToLocalHookLink link, next;
681: for (link = (*dm)->gtolhook; link; link = next) {
682: next = link->next;
683: PetscFree(link);
684: }
685: (*dm)->gtolhook = NULL;
686: }
687: {
688: DMLocalToGlobalHookLink link, next;
689: for (link = (*dm)->ltoghook; link; link = next) {
690: next = link->next;
691: PetscFree(link);
692: }
693: (*dm)->ltoghook = NULL;
694: }
695: /* Destroy the work arrays */
696: {
697: DMWorkLink link, next;
699: for (link = (*dm)->workin; link; link = next) {
700: next = link->next;
701: PetscFree(link->mem);
702: PetscFree(link);
703: }
704: (*dm)->workin = NULL;
705: }
706: /* destroy the labels */
707: DMDestroyLabelLinkList_Internal(*dm);
708: /* destroy the fields */
709: DMClearFields(*dm);
710: /* destroy the boundaries */
711: {
712: DMBoundary next = (*dm)->boundary;
713: while (next) {
714: DMBoundary b = next;
716: next = b->next;
717: PetscFree(b);
718: }
719: }
721: PetscObjectDestroy(&(*dm)->dmksp);
722: PetscObjectDestroy(&(*dm)->dmsnes);
723: PetscObjectDestroy(&(*dm)->dmts);
725: if ((*dm)->ctx && (*dm)->ctxdestroy) (*(*dm)->ctxdestroy)(&(*dm)->ctx);
726: MatFDColoringDestroy(&(*dm)->fd);
727: ISLocalToGlobalMappingDestroy(&(*dm)->ltogmap);
728: PetscFree((*dm)->vectype);
729: PetscFree((*dm)->mattype);
731: PetscSectionDestroy(&(*dm)->localSection);
732: PetscSectionDestroy(&(*dm)->globalSection);
733: PetscLayoutDestroy(&(*dm)->map);
734: PetscSectionDestroy(&(*dm)->defaultConstraint.section);
735: MatDestroy(&(*dm)->defaultConstraint.mat);
736: PetscSFDestroy(&(*dm)->sf);
737: PetscSFDestroy(&(*dm)->sectionSF);
738: if ((*dm)->useNatural) {
739: if ((*dm)->sfNatural) PetscSFDestroy(&(*dm)->sfNatural);
740: PetscObjectDereference((PetscObject)(*dm)->sfMigration);
741: }
742: {
743: Vec *auxData;
744: PetscInt n, i, off = 0;
746: PetscHMapAuxGetSize((*dm)->auxData, &n);
747: PetscMalloc1(n, &auxData);
748: PetscHMapAuxGetVals((*dm)->auxData, &off, auxData);
749: for (i = 0; i < n; ++i) VecDestroy(&auxData[i]);
750: PetscFree(auxData);
751: PetscHMapAuxDestroy(&(*dm)->auxData);
752: }
753: if ((*dm)->coarseMesh && (*dm)->coarseMesh->fineMesh == *dm) DMSetFineDM((*dm)->coarseMesh, NULL);
755: DMDestroy(&(*dm)->coarseMesh);
756: if ((*dm)->fineMesh && (*dm)->fineMesh->coarseMesh == *dm) DMSetCoarseDM((*dm)->fineMesh, NULL);
757: DMDestroy(&(*dm)->fineMesh);
758: PetscFree((*dm)->Lstart);
759: PetscFree((*dm)->L);
760: PetscFree((*dm)->maxCell);
761: DMDestroyCoordinates_Private(&(*dm)->coordinates[0]);
762: DMDestroyCoordinates_Private(&(*dm)->coordinates[1]);
763: if ((*dm)->transformDestroy) (*(*dm)->transformDestroy)(*dm, (*dm)->transformCtx);
764: DMDestroy(&(*dm)->transformDM);
765: VecDestroy(&(*dm)->transform);
767: DMClearDS(*dm);
768: DMDestroy(&(*dm)->dmBC);
769: /* if memory was published with SAWs then destroy it */
770: PetscObjectSAWsViewOff((PetscObject)*dm);
772: if ((*dm)->ops->destroy) (*(*dm)->ops->destroy)(*dm);
773: DMMonitorCancel(*dm);
774: #ifdef PETSC_HAVE_LIBCEED
775: CeedElemRestrictionDestroy(&(*dm)->ceedERestrict);
776: CeedDestroy(&(*dm)->ceed);
777: #endif
778: /* We do not destroy (*dm)->data here so that we can reference count backend objects */
779: PetscHeaderDestroy(dm);
780: return 0;
781: }
783: /*@
784: DMSetUp - sets up the data structures inside a `DM` object
786: Collective on dm
788: Input Parameter:
789: . dm - the `DM` object to setup
791: Level: intermediate
793: Note:
794: This is usually called after various parameter setting operations and `DMSetFromOptions()` are called on the `DM`
796: .seealso: `DM`, `DMCreate()`, `DMSetType()`, `DMView()`, `DMCreateGlobalVector()`, `DMCreateInterpolation()`, `DMCreateColoring()`, `DMCreateMatrix()`
798: @*/
799: PetscErrorCode DMSetUp(DM dm)
800: {
802: if (dm->setupcalled) return 0;
803: PetscTryTypeMethod(dm, setup);
804: dm->setupcalled = PETSC_TRUE;
805: return 0;
806: }
808: /*@
809: DMSetFromOptions - sets parameters in a `DM` from the options database
811: Collective on dm
813: Input Parameter:
814: . dm - the `DM` object to set options for
816: Options Database:
817: + -dm_preallocate_only - Only preallocate the matrix for `DMCreateMatrix()` and `DMCreateMassMatrix()`, but do not fill it with zeros
818: . -dm_vec_type <type> - type of vector to create inside `DM`
819: . -dm_mat_type <type> - type of matrix to create inside `DM`
820: . -dm_is_coloring_type - <global or local>
821: - -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`
823: DMPLEX Specific creation options
824: + -dm_plex_filename <str> - File containing a mesh
825: . -dm_plex_boundary_filename <str> - File containing a mesh boundary
826: . -dm_plex_name <str> - Name of the mesh in the file
827: . -dm_plex_shape <shape> - The domain shape, such as `DM_SHAPE_BOX`, `DM_SHAPE_SPHERE`, etc.
828: . -dm_plex_cell <ct> - Cell shape
829: . -dm_plex_reference_cell_domain <bool> - Use a reference cell domain
830: . -dm_plex_dim <dim> - Set the topological dimension
831: . -dm_plex_simplex <bool> - `PETSC_TRUE` for simplex elements, `PETSC_FALSE` for tensor elements
832: . -dm_plex_interpolate <bool> - `PETSC_TRUE` turns on topological interpolation (creating edges and faces)
833: . -dm_plex_scale <sc> - Scale factor for mesh coordinates
834: . -dm_plex_box_faces <m,n,p> - Number of faces along each dimension
835: . -dm_plex_box_lower <x,y,z> - Specify lower-left-bottom coordinates for the box
836: . -dm_plex_box_upper <x,y,z> - Specify upper-right-top coordinates for the box
837: . -dm_plex_box_bd <bx,by,bz> - Specify the `DMBoundaryType `for each direction
838: . -dm_plex_sphere_radius <r> - The sphere radius
839: . -dm_plex_ball_radius <r> - Radius of the ball
840: . -dm_plex_cylinder_bd <bz> - Boundary type in the z direction
841: . -dm_plex_cylinder_num_wedges <n> - Number of wedges around the cylinder
842: . -dm_plex_reorder <order> - Reorder the mesh using the specified algorithm
843: . -dm_refine_pre <n> - The number of refinements before distribution
844: . -dm_refine_uniform_pre <bool> - Flag for uniform refinement before distribution
845: . -dm_refine_volume_limit_pre <v> - The maximum cell volume after refinement before distribution
846: . -dm_refine <n> - The number of refinements after distribution
847: . -dm_extrude <l> - Activate extrusion and specify the number of layers to extrude
848: . -dm_plex_transform_extrude_thickness <t> - The total thickness of extruded layers
849: . -dm_plex_transform_extrude_use_tensor <bool> - Use tensor cells when extruding
850: . -dm_plex_transform_extrude_symmetric <bool> - Extrude layers symmetrically about the surface
851: . -dm_plex_transform_extrude_normal <n0,...,nd> - Specify the extrusion direction
852: . -dm_plex_transform_extrude_thicknesses <t0,...,tl> - Specify thickness of each layer
853: . -dm_plex_create_fv_ghost_cells - Flag to create finite volume ghost cells on the boundary
854: . -dm_plex_fv_ghost_cells_label <name> - Label name for ghost cells boundary
855: . -dm_distribute <bool> - Flag to redistribute a mesh among processes
856: . -dm_distribute_overlap <n> - The size of the overlap halo
857: . -dm_plex_adj_cone <bool> - Set adjacency direction
858: - -dm_plex_adj_closure <bool> - Set adjacency size
860: DMPLEX Specific Checks
861: + -dm_plex_check_symmetry - Check that the adjacency information in the mesh is symmetric - `DMPlexCheckSymmetry()`
862: . -dm_plex_check_skeleton - Check that each cell has the correct number of vertices (only for homogeneous simplex or tensor meshes) - `DMPlexCheckSkeleton()`
863: . -dm_plex_check_faces - Check that the faces of each cell give a vertex order this is consistent with what we expect from the cell type - `DMPlexCheckFaces()`
864: . -dm_plex_check_geometry - Check that cells have positive volume - `DMPlexCheckGeometry()`
865: . -dm_plex_check_pointsf - Check some necessary conditions for `PointSF` - `DMPlexCheckPointSF()`
866: . -dm_plex_check_interface_cones - Check points on inter-partition interfaces have conforming order of cone points - `DMPlexCheckInterfaceCones()`
867: - -dm_plex_check_all - Perform all the checks above
869: Level: intermediate
871: .seealso: `DMView()`, `DMCreateGlobalVector()`, `DMCreateInterpolation()`, `DMCreateColoring()`, `DMCreateMatrix()`,
872: `DMPlexCheckSymmetry()`, `DMPlexCheckSkeleton()`, `DMPlexCheckFaces()`, `DMPlexCheckGeometry()`, `DMPlexCheckPointSF()`, `DMPlexCheckInterfaceCones()`,
873: `DMSetOptionsPrefix()`, `DM`, `DMType`, `DMPLEX`, `DMDA`
875: @*/
876: PetscErrorCode DMSetFromOptions(DM dm)
877: {
878: char typeName[256];
879: PetscBool flg;
882: dm->setfromoptionscalled = PETSC_TRUE;
883: if (dm->sf) PetscSFSetFromOptions(dm->sf);
884: if (dm->sectionSF) PetscSFSetFromOptions(dm->sectionSF);
885: PetscObjectOptionsBegin((PetscObject)dm);
886: PetscOptionsBool("-dm_preallocate_only", "only preallocate matrix, but do not set column indices", "DMSetMatrixPreallocateOnly", dm->prealloc_only, &dm->prealloc_only, NULL);
887: PetscOptionsFList("-dm_vec_type", "Vector type used for created vectors", "DMSetVecType", VecList, dm->vectype, typeName, 256, &flg);
888: if (flg) DMSetVecType(dm, typeName);
889: PetscOptionsFList("-dm_mat_type", "Matrix type used for created matrices", "DMSetMatType", MatList, dm->mattype ? dm->mattype : typeName, typeName, sizeof(typeName), &flg);
890: if (flg) DMSetMatType(dm, typeName);
891: PetscOptionsEnum("-dm_is_coloring_type", "Global or local coloring of Jacobian", "DMSetISColoringType", ISColoringTypes, (PetscEnum)dm->coloringtype, (PetscEnum *)&dm->coloringtype, NULL);
892: 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);
893: PetscTryTypeMethod(dm, setfromoptions, PetscOptionsObject);
894: /* process any options handlers added with PetscObjectAddOptionsHandler() */
895: PetscObjectProcessOptionsHandlers((PetscObject)dm, PetscOptionsObject);
896: PetscOptionsEnd();
897: return 0;
898: }
900: /*@C
901: DMViewFromOptions - View a `DM` in a particular way based on a request in the options database
903: Collective on dm
905: Input Parameters:
906: + dm - the `DM` object
907: . obj - optional object that provides the prefix for the options database (if NULL then the prefix in obj is used)
908: - optionname - option string that is used to activate viewing
910: Level: intermediate
912: Note:
913: See `PetscObjectViewFromOptions()` for a list of values that can be provided in the options database to determine how the `DM` is viewed
915: .seealso: `DM`, `DMView()`, `PetscObjectViewFromOptions()`, `DMCreate()`, `PetscObjectViewFromOptions()`
916: @*/
917: PetscErrorCode DMViewFromOptions(DM dm, PetscObject obj, const char name[])
918: {
920: PetscObjectViewFromOptions((PetscObject)dm, obj, name);
921: return 0;
922: }
924: /*@C
925: 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
926: save the `DM` in a binary file to be loaded later or create a visualization of the `DM`
928: Collective on dm
930: Input Parameters:
931: + dm - the `DM` object to view
932: - v - the viewer
934: Notes:
935: Using `PETSCVIEWERHDF5` type with `PETSC_VIEWER_HDF5_PETSC` as the `PetscViewerFormat` one can save multiple `DMPLEX`
936: meshes in a single HDF5 file. This in turn requires one to name the `DMPLEX` object with `PetscObjectSetName()`
937: before saving it with `DMView()` and before loading it with `DMLoad()` for identification of the mesh object.
939: Level: beginner
941: .seealso: `PetscViewer`, `PetscViewerFormat`, `PetscViewerSetFormat`(), `DMDestroy()`, `DMCreateGlobalVector()`, `DMCreateInterpolation()`, `DMCreateColoring()`, `DMCreateMatrix()`, `DMCreateMassMatrix()`, `DMLoad()`, `PetscObjectSetName()`
943: @*/
944: PetscErrorCode DMView(DM dm, PetscViewer v)
945: {
946: PetscBool isbinary;
947: PetscMPIInt size;
948: PetscViewerFormat format;
951: if (!v) PetscViewerASCIIGetStdout(PetscObjectComm((PetscObject)dm), &v);
953: /* Ideally, we would like to have this test on.
954: However, it currently breaks socket viz via GLVis.
955: During DMView(parallel_mesh,glvis_viewer), each
956: process opens a sequential ASCII socket to visualize
957: the local mesh, and PetscObjectView(dm,local_socket)
958: is internally called inside VecView_GLVis, incurring
959: in an error here */
961: PetscViewerCheckWritable(v);
963: PetscViewerGetFormat(v, &format);
964: MPI_Comm_size(PetscObjectComm((PetscObject)dm), &size);
965: if (size == 1 && format == PETSC_VIEWER_LOAD_BALANCE) return 0;
966: PetscObjectPrintClassNamePrefixType((PetscObject)dm, v);
967: PetscObjectTypeCompare((PetscObject)v, PETSCVIEWERBINARY, &isbinary);
968: if (isbinary) {
969: PetscInt classid = DM_FILE_CLASSID;
970: char type[256];
972: PetscViewerBinaryWrite(v, &classid, 1, PETSC_INT);
973: PetscStrncpy(type, ((PetscObject)dm)->type_name, 256);
974: PetscViewerBinaryWrite(v, type, 256, PETSC_CHAR);
975: }
976: PetscTryTypeMethod(dm, view, v);
977: return 0;
978: }
980: /*@
981: 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,
982: that is it has no ghost locations.
984: Collective on dm
986: Input Parameter:
987: . dm - the `DM` object
989: Output Parameter:
990: . vec - the global vector
992: Level: beginner
994: .seealso: `Vec`, `DMCreateLocalVector()`, `DMGetGlobalVector()`, `DMDestroy()`, `DMView()`, `DMCreateInterpolation()`, `DMCreateColoring()`, `DMCreateMatrix()`,
995: `DMGlobalToLocalBegin()`, `DMGlobalToLocalEnd()`
997: @*/
998: PetscErrorCode DMCreateGlobalVector(DM dm, Vec *vec)
999: {
1002: PetscUseTypeMethod(dm, createglobalvector, vec);
1003: if (PetscDefined(USE_DEBUG)) {
1004: DM vdm;
1006: VecGetDM(*vec, &vdm);
1008: }
1009: return 0;
1010: }
1012: /*@
1013: DMCreateLocalVector - Creates a local vector from a `DM` object.
1015: Not Collective
1017: Input Parameter:
1018: . dm - the `DM` object
1020: Output Parameter:
1021: . vec - the local vector
1023: Level: beginner
1025: Notes:
1026: A local vector usually has ghost locations that contain values that are owned by different MPI ranks. A global vector has no ghost locations.
1028: .seealso: `Vec`, `DMCreateGlobalVector()`, `DMGetLocalVector()`, `DMDestroy()`, `DMView()`, `DMCreateInterpolation()`, `DMCreateColoring()`, `DMCreateMatrix()`
1029: `DMGlobalToLocalBegin()`, `DMGlobalToLocalEnd()`
1031: @*/
1032: PetscErrorCode DMCreateLocalVector(DM dm, Vec *vec)
1033: {
1036: PetscUseTypeMethod(dm, createlocalvector, vec);
1037: if (PetscDefined(USE_DEBUG)) {
1038: DM vdm;
1040: VecGetDM(*vec, &vdm);
1042: }
1043: return 0;
1044: }
1046: /*@
1047: DMGetLocalToGlobalMapping - Accesses the local-to-global mapping in a `DM`.
1049: Collective on dm
1051: Input Parameter:
1052: . dm - the `DM` that provides the mapping
1054: Output Parameter:
1055: . ltog - the mapping
1057: Level: advanced
1059: Notes:
1060: The global to local mapping allows one to set values into the global vector or matrix using `VecSetValuesLocal()` and `MatSetValuesLocal()`
1062: Vectors obtained with `DMCreateGlobalVector()` and matrices obtained with `DMCreateMatrix()` already contain the global mapping so you do
1063: need to use this function with those objects.
1065: This mapping can then be used by `VecSetLocalToGlobalMapping()` or `MatSetLocalToGlobalMapping()`.
1067: .seealso: `DMCreateLocalVector()`, `DMCreateLocalVector()`, `DMCreateGlobalVector()`, `VecSetLocalToGlobalMapping()`, `MatSetLocalToGlobalMapping()`,
1068: `DMCreateMatrix()`
1069: @*/
1070: PetscErrorCode DMGetLocalToGlobalMapping(DM dm, ISLocalToGlobalMapping *ltog)
1071: {
1072: PetscInt bs = -1, bsLocal[2], bsMinMax[2];
1076: if (!dm->ltogmap) {
1077: PetscSection section, sectionGlobal;
1079: DMGetLocalSection(dm, §ion);
1080: if (section) {
1081: const PetscInt *cdofs;
1082: PetscInt *ltog;
1083: PetscInt pStart, pEnd, n, p, k, l;
1085: DMGetGlobalSection(dm, §ionGlobal);
1086: PetscSectionGetChart(section, &pStart, &pEnd);
1087: PetscSectionGetStorageSize(section, &n);
1088: PetscMalloc1(n, <og); /* We want the local+overlap size */
1089: for (p = pStart, l = 0; p < pEnd; ++p) {
1090: PetscInt bdof, cdof, dof, off, c, cind;
1092: /* Should probably use constrained dofs */
1093: PetscSectionGetDof(section, p, &dof);
1094: PetscSectionGetConstraintDof(section, p, &cdof);
1095: PetscSectionGetConstraintIndices(section, p, &cdofs);
1096: PetscSectionGetOffset(sectionGlobal, p, &off);
1097: /* If you have dofs, and constraints, and they are unequal, we set the blocksize to 1 */
1098: bdof = cdof && (dof - cdof) ? 1 : dof;
1099: if (dof) bs = bs < 0 ? bdof : PetscGCD(bs, bdof);
1101: for (c = 0, cind = 0; c < dof; ++c, ++l) {
1102: if (cind < cdof && c == cdofs[cind]) {
1103: ltog[l] = off < 0 ? off - c : -(off + c + 1);
1104: cind++;
1105: } else {
1106: ltog[l] = (off < 0 ? -(off + 1) : off) + c - cind;
1107: }
1108: }
1109: }
1110: /* Must have same blocksize on all procs (some might have no points) */
1111: bsLocal[0] = bs < 0 ? PETSC_MAX_INT : bs;
1112: bsLocal[1] = bs;
1113: PetscGlobalMinMaxInt(PetscObjectComm((PetscObject)dm), bsLocal, bsMinMax);
1114: if (bsMinMax[0] != bsMinMax[1]) {
1115: bs = 1;
1116: } else {
1117: bs = bsMinMax[0];
1118: }
1119: bs = bs < 0 ? 1 : bs;
1120: /* Must reduce indices by blocksize */
1121: if (bs > 1) {
1122: for (l = 0, k = 0; l < n; l += bs, ++k) {
1123: // Integer division of negative values truncates toward zero(!), not toward negative infinity
1124: ltog[k] = ltog[l] >= 0 ? ltog[l] / bs : -(-(ltog[l] + 1) / bs + 1);
1125: }
1126: n /= bs;
1127: }
1128: ISLocalToGlobalMappingCreate(PetscObjectComm((PetscObject)dm), bs, n, ltog, PETSC_OWN_POINTER, &dm->ltogmap);
1129: } else PetscUseTypeMethod(dm, getlocaltoglobalmapping);
1130: }
1131: *ltog = dm->ltogmap;
1132: return 0;
1133: }
1135: /*@
1136: DMGetBlockSize - Gets the inherent block size associated with a `DM`
1138: Not Collective
1140: Input Parameter:
1141: . dm - the `DM` with block structure
1143: Output Parameter:
1144: . bs - the block size, 1 implies no exploitable block structure
1146: Level: intermediate
1148: Note:
1149: This might be the number of degrees of freedom at each grid point for a structured grid.
1151: Complex `DM` that represent multiphysics or staggered grids or mixed-methods do not generally have a single inherent block size, but
1152: rather different locations in the vectors may have a different block size.
1154: .seealso: `ISCreateBlock()`, `VecSetBlockSize()`, `MatSetBlockSize()`, `DMGetLocalToGlobalMapping()`
1155: @*/
1156: PetscErrorCode DMGetBlockSize(DM dm, PetscInt *bs)
1157: {
1161: *bs = dm->bs;
1162: return 0;
1163: }
1165: /*@C
1166: DMCreateInterpolation - Gets the interpolation matrix between two `DM` objects. The resulting matrix map degrees of freedom in the vector obtained by
1167: `DMCreateGlobalVector()` on the coarse `DM` to similar vectors on the fine grid `DM`.
1169: Collective on dmc
1171: Input Parameters:
1172: + dmc - the `DM` object
1173: - dmf - the second, finer `DM` object
1175: Output Parameters:
1176: + mat - the interpolation
1177: - vec - the scaling (optional), see `DMCreateInterpolationScale()`
1179: Level: developer
1181: Notes:
1182: For `DMDA` objects this only works for "uniform refinement", that is the refined mesh was obtained `DMRefine()` or the coarse mesh was obtained by
1183: DMCoarsen(). The coordinates set into the `DMDA` are completely ignored in computing the interpolation.
1185: For `DMDA` objects you can use this interpolation (more precisely the interpolation from the `DMGetCoordinateDM()`) to interpolate the mesh coordinate
1186: vectors EXCEPT in the periodic case where it does not make sense since the coordinate vectors are not periodic.
1188: .seealso: `DMDestroy()`, `DMView()`, `DMCreateGlobalVector()`, `DMCreateColoring()`, `DMCreateMatrix()`, `DMCreateMassMatrix()`, `DMRefine()`, `DMCoarsen()`, `DMCreateRestriction()`, `DMCreateInterpolationScale()`
1190: @*/
1191: PetscErrorCode DMCreateInterpolation(DM dmc, DM dmf, Mat *mat, Vec *vec)
1192: {
1196: PetscLogEventBegin(DM_CreateInterpolation, dmc, dmf, 0, 0);
1197: PetscUseTypeMethod(dmc, createinterpolation, dmf, mat, vec);
1198: PetscLogEventEnd(DM_CreateInterpolation, dmc, dmf, 0, 0);
1199: return 0;
1200: }
1202: /*@
1203: DMCreateInterpolationScale - Forms L = 1/(R*1) where 1 is the vector of all ones, and R is the transpose of the interpolation between the `DM`.
1204: xcoarse = diag(L)*R*xfine preserves scale and is thus suitable for state (versus residual) restriction. In other words xcoarse is the coarse
1205: representation of xfine.
1207: Input Parameters:
1208: + dac - `DM` that defines a coarse mesh
1209: . daf - `DM` that defines a fine mesh
1210: - mat - the restriction (or interpolation operator) from fine to coarse
1212: Output Parameter:
1213: . scale - the scaled vector
1215: Level: advanced
1217: Developer Notes:
1218: If the fine-scale `DMDA` has the -dm_bind_below option set to true, then `DMCreateInterpolationScale()` calls `MatSetBindingPropagates()`
1219: on the restriction/interpolation operator to set the bindingpropagates flag to true.
1221: .seealso: `MatRestrict()`, `MatInterpolate()`, `DMCreateInterpolation()`, DMCreateRestriction()`, `DMCreateGlobalVector()`
1223: @*/
1224: PetscErrorCode DMCreateInterpolationScale(DM dac, DM daf, Mat mat, Vec *scale)
1225: {
1226: Vec fine;
1227: PetscScalar one = 1.0;
1228: #if defined(PETSC_HAVE_CUDA)
1229: PetscBool bindingpropagates, isbound;
1230: #endif
1232: DMCreateGlobalVector(daf, &fine);
1233: DMCreateGlobalVector(dac, scale);
1234: VecSet(fine, one);
1235: #if defined(PETSC_HAVE_CUDA)
1236: /* If the 'fine' Vec is bound to the CPU, it makes sense to bind 'mat' as well.
1237: * Note that we only do this for the CUDA case, right now, but if we add support for MatMultTranspose() via ViennaCL,
1238: * we'll need to do it for that case, too.*/
1239: VecGetBindingPropagates(fine, &bindingpropagates);
1240: if (bindingpropagates) {
1241: MatSetBindingPropagates(mat, PETSC_TRUE);
1242: VecBoundToCPU(fine, &isbound);
1243: MatBindToCPU(mat, isbound);
1244: }
1245: #endif
1246: MatRestrict(mat, fine, *scale);
1247: VecDestroy(&fine);
1248: VecReciprocal(*scale);
1249: return 0;
1250: }
1252: /*@
1253: DMCreateRestriction - Gets restriction matrix between two `DM` objects. The resulting matrix map degrees of freedom in the vector obtained by
1254: `DMCreateGlobalVector()` on the fine `DM` to similar vectors on the coarse grid `DM`.
1256: Collective on dmc
1258: Input Parameters:
1259: + dmc - the `DM` object
1260: - dmf - the second, finer `DM` object
1262: Output Parameter:
1263: . mat - the restriction
1265: Level: developer
1267: Note:
1268: This only works for `DMSTAG`. For many situations either the transpose of the operator obtained with `DMCreateInterpolation()` or that
1269: matrix multiplied by the vector obtained with `DMCreateInterpolationScale()` provides the desired object.
1271: .seealso: `DMRestrict()`, `DMInterpolate()`, `DMDestroy()`, `DMView()`, `DMCreateGlobalVector()`, `DMCreateColoring()`, `DMCreateMatrix()`, `DMCreateMassMatrix()`, `DMRefine()`, `DMCoarsen()`, `DMCreateInterpolation()`
1273: @*/
1274: PetscErrorCode DMCreateRestriction(DM dmc, DM dmf, Mat *mat)
1275: {
1279: PetscLogEventBegin(DM_CreateRestriction, dmc, dmf, 0, 0);
1280: PetscUseTypeMethod(dmc, createrestriction, dmf, mat);
1281: PetscLogEventEnd(DM_CreateRestriction, dmc, dmf, 0, 0);
1282: return 0;
1283: }
1285: /*@
1286: DMCreateInjection - Gets injection matrix between two `DM` objects. This is an operator that applied to a vector obtained with
1287: `DMCreateGlobalVector()` on the fine grid maps the values to a vector on the vector on the coarse `DM` by simply selecting the values
1288: on the coarse grid points. This compares to the operator obtained by `DMCreateRestriction()` or the transpose of the operator obtained
1289: by `DMCreateInterpolation()` that uses a "local weighted average" of the values around the coarse grid point as the coarse grid value.
1291: Collective on dac
1293: Input Parameters:
1294: + dac - the `DM` object
1295: - daf - the second, finer `DM` object
1297: Output Parameter:
1298: . mat - the injection
1300: Level: developer
1302: Note:
1303: For `DMDA` objects this only works for "uniform refinement", that is the refined mesh was obtained `DMRefine()` or the coarse mesh was obtained by
1304: `DMCoarsen()`. The coordinates set into the `DMDA` are completely ignored in computing the injection.
1306: .seealso: `DMDestroy()`, `DMView()`, `DMCreateGlobalVector()`, `DMCreateColoring()`, `DMCreateMatrix()`, `DMCreateMassMatrix()`, `DMCreateInterpolation()`,
1307: `DMCreateRestriction()`, `MatRestrict()`, `MatInterpolate()`
1309: @*/
1310: PetscErrorCode DMCreateInjection(DM dac, DM daf, Mat *mat)
1311: {
1315: PetscLogEventBegin(DM_CreateInjection, dac, daf, 0, 0);
1316: PetscUseTypeMethod(dac, createinjection, daf, mat);
1317: PetscLogEventEnd(DM_CreateInjection, dac, daf, 0, 0);
1318: return 0;
1319: }
1321: /*@
1322: 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
1323: a Galerkin finite element model on the `DM`
1325: Collective on dac
1327: Input Parameters:
1328: + dmc - the target `DM` object
1329: - dmf - the source `DM` object
1331: Output Parameter:
1332: . mat - the mass matrix
1334: Level: developer
1336: Notes:
1337: For `DMPLEX` the finite element model for the `DM` must have been already provided.
1339: if dmc is dmf then x^t M x is an approximation to the L2 norm of the vector x which is obtained by `DMCreateGlobalVector()`
1341: .seealso: `DMCreateMassMatrixLumped()`, `DMCreateMatrix()`, `DMCreateMassMatrix()`, `DMRefine()`, `DMCoarsen()`, `DMCreateRestriction()`, `DMCreateInterpolation()`, `DMCreateInjection()`
1342: @*/
1343: PetscErrorCode DMCreateMassMatrix(DM dmc, DM dmf, Mat *mat)
1344: {
1348: PetscLogEventBegin(DM_CreateMassMatrix, 0, 0, 0, 0);
1349: PetscUseTypeMethod(dmc, createmassmatrix, dmf, mat);
1350: PetscLogEventEnd(DM_CreateMassMatrix, 0, 0, 0, 0);
1351: return 0;
1352: }
1354: /*@
1355: DMCreateMassMatrixLumped - Gets the lumped mass matrix for a given `DM`
1357: Collective on dm
1359: Input Parameter:
1360: . dm - the `DM` object
1362: Output Parameter:
1363: . lm - the lumped mass matrix, which is a diagonal matrix, represented as a vector
1365: Level: developer
1367: Note:
1368: See `DMCreateMassMatrix()` for how to create the non-lumped version of the mass matrix.
1370: .seealso: `DMCreateMassMatrix()`, `DMCreateMatrix()`, `DMCreateMassMatrix()`, `DMRefine()`, `DMCoarsen()`, `DMCreateRestriction()`, `DMCreateInterpolation()`, `DMCreateInjection()`
1371: @*/
1372: PetscErrorCode DMCreateMassMatrixLumped(DM dm, Vec *lm)
1373: {
1376: PetscUseTypeMethod(dm, createmassmatrixlumped, lm);
1377: return 0;
1378: }
1380: /*@
1381: DMCreateColoring - Gets coloring of a graph associated with the `DM`. Often the graph represents the operator matrix associated with the discretization
1382: of a PDE on the `DM`.
1384: Collective on dm
1386: Input Parameters:
1387: + dm - the `DM` object
1388: - ctype - `IS_COLORING_LOCAL` or `IS_COLORING_GLOBAL`
1390: Output Parameter:
1391: . coloring - the coloring
1393: Notes:
1394: 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
1395: matrix comes from (what this function provides). In general using the mesh produces a more optimal coloring (fewer colors).
1397: This produces a coloring with the distance of 2, see `MatSetColoringDistance()` which can be used for efficiently computing Jacobians with `MatFDColoringCreate()`
1399: Level: developer
1401: .seealso: `DMDestroy()`, `DMView()`, `DMCreateGlobalVector()`, `DMCreateInterpolation()`, `DMCreateMatrix()`, `DMCreateMassMatrix()`, `DMSetMatType()`, `MatColoring`, `MatFDColoringCreate()`
1403: @*/
1404: PetscErrorCode DMCreateColoring(DM dm, ISColoringType ctype, ISColoring *coloring)
1405: {
1408: PetscUseTypeMethod(dm, getcoloring, ctype, coloring);
1409: return 0;
1410: }
1412: /*@
1413: DMCreateMatrix - Gets an empty matrix for a `DM` that is most commonly used to store the Jacobian of a discrete PDE operator.
1415: Collective on dm
1417: Input Parameter:
1418: . dm - the `DM` object
1420: Output Parameter:
1421: . mat - the empty Jacobian
1423: Level: beginner
1425: Options Database Keys:
1426: . -dm_preallocate_only - Only preallocate the matrix for `DMCreateMatrix()` and `DMCreateMassMatrix()`, but do not fill it with zeros
1428: Notes:
1429: This properly preallocates the number of nonzeros in the sparse matrix so you
1430: do not need to do it yourself.
1432: By default it also sets the nonzero structure and puts in the zero entries. To prevent setting
1433: the nonzero pattern call `DMSetMatrixPreallocateOnly()`
1435: For `DMDA`, when you call `MatView()` on this matrix it is displayed using the global natural ordering, NOT in the ordering used
1436: internally by PETSc.
1438: For `DMDA`, in general it is easiest to use `MatSetValuesStencil()` or `MatSetValuesLocal()` to put values into the matrix because
1439: `MatSetValues()` requires the indices for the global numbering for the `DMDA` which is complic`ated to compute
1441: .seealso: `DMDestroy()`, `DMView()`, `DMCreateGlobalVector()`, `DMCreateInterpolation()`, `DMSetMatType()`, `DMCreateMassMatrix()`
1443: @*/
1444: PetscErrorCode DMCreateMatrix(DM dm, Mat *mat)
1445: {
1448: MatInitializePackage();
1449: PetscLogEventBegin(DM_CreateMatrix, 0, 0, 0, 0);
1450: PetscUseTypeMethod(dm, creatematrix, mat);
1451: if (PetscDefined(USE_DEBUG)) {
1452: DM mdm;
1454: MatGetDM(*mat, &mdm);
1456: }
1457: /* Handle nullspace and near nullspace */
1458: if (dm->Nf) {
1459: MatNullSpace nullSpace;
1460: PetscInt Nf, f;
1462: DMGetNumFields(dm, &Nf);
1463: for (f = 0; f < Nf; ++f) {
1464: if (dm->nullspaceConstructors[f]) {
1465: (*dm->nullspaceConstructors[f])(dm, f, f, &nullSpace);
1466: MatSetNullSpace(*mat, nullSpace);
1467: MatNullSpaceDestroy(&nullSpace);
1468: break;
1469: }
1470: }
1471: for (f = 0; f < Nf; ++f) {
1472: if (dm->nearnullspaceConstructors[f]) {
1473: (*dm->nearnullspaceConstructors[f])(dm, f, f, &nullSpace);
1474: MatSetNearNullSpace(*mat, nullSpace);
1475: MatNullSpaceDestroy(&nullSpace);
1476: }
1477: }
1478: }
1479: PetscLogEventEnd(DM_CreateMatrix, 0, 0, 0, 0);
1480: return 0;
1481: }
1483: /*@
1484: DMSetMatrixPreallocateSkip - When `DMCreateMatrix()` is called the matrix sizes and `ISLocalToGlobalMapping` will be
1485: properly set, but the data structures to store values in the matrices will not be preallocated. This is most useful to reduce initialization costs when
1486: `MatSetPreallocationCOO()` and `MatSetValuesCOO()` will be used.
1488: Logically Collective on dm
1490: Input Parameters:
1491: + dm - the `DM`
1492: - skip - `PETSC_TRUE` to skip preallocation
1494: Level: developer
1496: .seealso: `DMCreateMatrix()`, `DMSetMatrixStructureOnly()`, `DMSetMatrixPreallocateOnly()`
1497: @*/
1498: PetscErrorCode DMSetMatrixPreallocateSkip(DM dm, PetscBool skip)
1499: {
1501: dm->prealloc_skip = skip;
1502: return 0;
1503: }
1505: /*@
1506: DMSetMatrixPreallocateOnly - When `DMCreateMatrix()` is called the matrix will be properly
1507: preallocated but the nonzero structure and zero values will not be set.
1509: Logically Collective on dm
1511: Input Parameters:
1512: + dm - the `DM`
1513: - only - `PETSC_TRUE` if only want preallocation
1515: Level: developer
1517: Options Database Keys:
1518: . -dm_preallocate_only - Only preallocate the matrix for `DMCreateMatrix()`, `DMCreateMassMatrix()`, but do not fill it with zeros
1520: .seealso: `DMCreateMatrix()`, `DMCreateMassMatrix()`, `DMSetMatrixStructureOnly()`, `DMSetMatrixPreallocateSkip()`
1521: @*/
1522: PetscErrorCode DMSetMatrixPreallocateOnly(DM dm, PetscBool only)
1523: {
1525: dm->prealloc_only = only;
1526: return 0;
1527: }
1529: /*@
1530: DMSetMatrixStructureOnly - When `DMCreateMatrix()` is called, the matrix structure will be created
1531: but the array for numerical values will not be allocated.
1533: Logically Collective on dm
1535: Input Parameters:
1536: + dm - the `DM`
1537: - only - `PETSC_TRUE` if you only want matrix stucture
1539: Level: developer
1541: .seealso: `DMCreateMatrix()`, `DMSetMatrixPreallocateOnly()`, `DMSetMatrixPreallocateSkip()`
1542: @*/
1543: PetscErrorCode DMSetMatrixStructureOnly(DM dm, PetscBool only)
1544: {
1546: dm->structure_only = only;
1547: return 0;
1548: }
1550: /*@C
1551: DMGetWorkArray - Gets a work array guaranteed to be at least the input size, restore with `DMRestoreWorkArray()`
1553: Not Collective
1555: Input Parameters:
1556: + dm - the `DM` object
1557: . count - The minimum size
1558: - dtype - MPI data type, often MPIU_REAL, MPIU_SCALAR, or MPIU_INT)
1560: Output Parameter:
1561: . array - the work array
1563: Level: developer
1565: Note:
1566: A `DM` may stash the array between instantations so using this routine may be more efficient than calling `PetscMalloc()`
1568: The array may contain nonzero values
1570: .seealso: `DMDestroy()`, `DMCreate()`, `DMRestoreWorkArray()`, `PetscMalloc()`
1571: @*/
1572: PetscErrorCode DMGetWorkArray(DM dm, PetscInt count, MPI_Datatype dtype, void *mem)
1573: {
1574: DMWorkLink link;
1575: PetscMPIInt dsize;
1579: if (dm->workin) {
1580: link = dm->workin;
1581: dm->workin = dm->workin->next;
1582: } else {
1583: PetscNew(&link);
1584: }
1585: MPI_Type_size(dtype, &dsize);
1586: if (((size_t)dsize * count) > link->bytes) {
1587: PetscFree(link->mem);
1588: PetscMalloc(dsize * count, &link->mem);
1589: link->bytes = dsize * count;
1590: }
1591: link->next = dm->workout;
1592: dm->workout = link;
1593: #if defined(__MEMCHECK_H) && (defined(PLAT_amd64_linux) || defined(PLAT_x86_linux) || defined(PLAT_amd64_darwin))
1594: VALGRIND_MAKE_MEM_NOACCESS((char *)link->mem + (size_t)dsize * count, link->bytes - (size_t)dsize * count);
1595: VALGRIND_MAKE_MEM_UNDEFINED(link->mem, (size_t)dsize * count);
1596: #endif
1597: *(void **)mem = link->mem;
1598: return 0;
1599: }
1601: /*@C
1602: DMRestoreWorkArray - Restores a work array obtained with `DMCreateWorkArray()`
1604: Not Collective
1606: Input Parameters:
1607: + dm - the `DM` object
1608: . count - The minimum size
1609: - dtype - MPI data type, often MPIU_REAL, MPIU_SCALAR, MPIU_INT
1611: Output Parameter:
1612: . array - the work array
1614: Level: developer
1616: Developer Notes:
1617: count and dtype are ignored, they are only needed for `DMGetWorkArray()`
1619: .seealso: `DMDestroy()`, `DMCreate()`, `DMGetWorkArray()`
1620: @*/
1621: PetscErrorCode DMRestoreWorkArray(DM dm, PetscInt count, MPI_Datatype dtype, void *mem)
1622: {
1623: DMWorkLink *p, link;
1627: for (p = &dm->workout; (link = *p); p = &link->next) {
1628: if (link->mem == *(void **)mem) {
1629: *p = link->next;
1630: link->next = dm->workin;
1631: dm->workin = link;
1632: *(void **)mem = NULL;
1633: return 0;
1634: }
1635: }
1636: SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Array was not checked out");
1637: }
1639: /*@C
1640: DMSetNullSpaceConstructor - Provide a callback function which constructs the nullspace for a given field, defined with `DMAddField()`, when function spaces
1641: are joined or split, such as in `DMCreateSubDM()`
1643: Logically collective on dm
1645: Input Parameters:
1646: + dm - The `DM`
1647: . field - The field number for the nullspace
1648: - nullsp - A callback to create the nullspace
1650: Calling sequence of nullsp:
1651: .vb
1652: PetscErrorCode nullsp(DM dm, PetscInt origField, PetscInt field, MatNullSpace *nullSpace)
1653: .ve
1654: + dm - The present `DM`
1655: . origField - The field number given above, in the original `DM`
1656: . field - The field number in dm
1657: - nullSpace - The nullspace for the given field
1659: Level: intermediate
1661: Fortran Notes:
1662: This function is not available from Fortran.
1664: .seealso: `DMAddField()`, `DMGetNullSpaceConstructor()`, `DMSetNearNullSpaceConstructor()`, `DMGetNearNullSpaceConstructor()`, `DMCreateSubDM()`, `DMCreateSuperDM()`
1665: @*/
1666: PetscErrorCode DMSetNullSpaceConstructor(DM dm, PetscInt field, PetscErrorCode (*nullsp)(DM, PetscInt, PetscInt, MatNullSpace *))
1667: {
1670: dm->nullspaceConstructors[field] = nullsp;
1671: return 0;
1672: }
1674: /*@C
1675: DMGetNullSpaceConstructor - Return the callback function which constructs the nullspace for a given field, defined with `DMAddField()`
1677: Not collective
1679: Input Parameters:
1680: + dm - The `DM`
1681: - field - The field number for the nullspace
1683: Output Parameter:
1684: . nullsp - A callback to create the nullspace
1686: Calling sequence of nullsp:
1687: .vb
1688: PetscErrorCode nullsp(DM dm, PetscInt origField, PetscInt field, MatNullSpace *nullSpace)
1689: .ve
1690: + dm - The present DM
1691: . origField - The field number given above, in the original DM
1692: . field - The field number in dm
1693: - nullSpace - The nullspace for the given field
1695: Fortran Note:
1696: This function is not available from Fortran.
1698: Level: intermediate
1700: .seealso: `DMAddField()`, `DMGetField()`, `DMSetNullSpaceConstructor()`, `DMSetNearNullSpaceConstructor()`, `DMGetNearNullSpaceConstructor()`, `DMCreateSubDM()`, `DMCreateSuperDM()`
1701: @*/
1702: PetscErrorCode DMGetNullSpaceConstructor(DM dm, PetscInt field, PetscErrorCode (**nullsp)(DM, PetscInt, PetscInt, MatNullSpace *))
1703: {
1707: *nullsp = dm->nullspaceConstructors[field];
1708: return 0;
1709: }
1711: /*@C
1712: DMSetNearNullSpaceConstructor - Provide a callback function which constructs the near-nullspace for a given field, defined with `DMAddField()`
1714: Logically collective on dm
1716: Input Parameters:
1717: + dm - The `DM`
1718: . field - The field number for the nullspace
1719: - nullsp - A callback to create the near-nullspace
1721: Calling sequence of nullsp:
1722: .vb
1723: PetscErrorCode nullsp(DM dm, PetscInt origField, PetscInt field, MatNullSpace *nullSpace)
1724: .ve
1725: + dm - The present `DM`
1726: . origField - The field number given above, in the original `DM`
1727: . field - The field number in dm
1728: - nullSpace - The nullspace for the given field
1730: Fortran Note:
1731: This function is not available from Fortran.
1733: Level: intermediate
1735: .seealso: `DMAddField()`, `DMGetNearNullSpaceConstructor()`, `DMSetNullSpaceConstructor()`, `DMGetNullSpaceConstructor()`, `DMCreateSubDM()`, `DMCreateSuperDM()`,
1736: `MatNullSpace`
1737: @*/
1738: PetscErrorCode DMSetNearNullSpaceConstructor(DM dm, PetscInt field, PetscErrorCode (*nullsp)(DM, PetscInt, PetscInt, MatNullSpace *))
1739: {
1742: dm->nearnullspaceConstructors[field] = nullsp;
1743: return 0;
1744: }
1746: /*@C
1747: DMGetNearNullSpaceConstructor - Return the callback function which constructs the near-nullspace for a given field, defined with `DMAddField()`
1749: Not collective
1751: Input Parameters:
1752: + dm - The `DM`
1753: - field - The field number for the nullspace
1755: Output Parameter:
1756: . nullsp - A callback to create the near-nullspace
1758: Calling sequence of nullsp:
1759: .vb
1760: PetscErrorCode nullsp(DM dm, PetscInt origField, PetscInt field, MatNullSpace *nullSpace)
1761: .ve
1762: + dm - The present `DM`
1763: . origField - The field number given above, in the original `DM`
1764: . field - The field number in dm
1765: - nullSpace - The nullspace for the given field
1767: Fortran Note:
1768: This function is not available from Fortran.
1770: Level: intermediate
1772: .seealso: `DMAddField()`, `DMGetField()`, `DMSetNearNullSpaceConstructor()`, `DMSetNullSpaceConstructor()`, `DMGetNullSpaceConstructor()`, `DMCreateSubDM()`,
1773: `MatNullSpace`, `DMCreateSuperDM()`
1774: @*/
1775: PetscErrorCode DMGetNearNullSpaceConstructor(DM dm, PetscInt field, PetscErrorCode (**nullsp)(DM, PetscInt, PetscInt, MatNullSpace *))
1776: {
1780: *nullsp = dm->nearnullspaceConstructors[field];
1781: return 0;
1782: }
1784: /*@C
1785: DMCreateFieldIS - Creates a set of `IS` objects with the global indices of dofs for each field defined with `DMAddField()`
1787: Not collective
1789: Input Parameter:
1790: . dm - the `DM` object
1792: Output Parameters:
1793: + numFields - The number of fields (or NULL if not requested)
1794: . fieldNames - The number of each field (or NULL if not requested)
1795: - fields - The global indices for each field (or NULL if not requested)
1797: Level: intermediate
1799: Note:
1800: The user is responsible for freeing all requested arrays. In particular, every entry of names should be freed with
1801: `PetscFree()`, every entry of fields should be destroyed with `ISDestroy()`, and both arrays should be freed with
1802: `PetscFree()`.
1804: Fortran Note:
1805: Not available in Fortran.
1807: Developer Note:
1808: It is not clear why both this function and `DMCreateFieldDecomposition()` exist. Having two seems redundant and confusing. This function should
1809: likely be removed.
1811: .seealso: `DMAddField()`, `DMGetField()`, `DMDestroy()`, `DMView()`, `DMCreateInterpolation()`, `DMCreateColoring()`, `DMCreateMatrix()`,
1812: `DMCreateFieldDecomposition()`
1813: @*/
1814: PetscErrorCode DMCreateFieldIS(DM dm, PetscInt *numFields, char ***fieldNames, IS **fields)
1815: {
1816: PetscSection section, sectionGlobal;
1819: if (numFields) {
1821: *numFields = 0;
1822: }
1823: if (fieldNames) {
1825: *fieldNames = NULL;
1826: }
1827: if (fields) {
1829: *fields = NULL;
1830: }
1831: DMGetLocalSection(dm, §ion);
1832: if (section) {
1833: PetscInt *fieldSizes, *fieldNc, **fieldIndices;
1834: PetscInt nF, f, pStart, pEnd, p;
1836: DMGetGlobalSection(dm, §ionGlobal);
1837: PetscSectionGetNumFields(section, &nF);
1838: PetscMalloc3(nF, &fieldSizes, nF, &fieldNc, nF, &fieldIndices);
1839: PetscSectionGetChart(sectionGlobal, &pStart, &pEnd);
1840: for (f = 0; f < nF; ++f) {
1841: fieldSizes[f] = 0;
1842: PetscSectionGetFieldComponents(section, f, &fieldNc[f]);
1843: }
1844: for (p = pStart; p < pEnd; ++p) {
1845: PetscInt gdof;
1847: PetscSectionGetDof(sectionGlobal, p, &gdof);
1848: if (gdof > 0) {
1849: for (f = 0; f < nF; ++f) {
1850: PetscInt fdof, fcdof, fpdof;
1852: PetscSectionGetFieldDof(section, p, f, &fdof);
1853: PetscSectionGetFieldConstraintDof(section, p, f, &fcdof);
1854: fpdof = fdof - fcdof;
1855: if (fpdof && fpdof != fieldNc[f]) {
1856: /* Layout does not admit a pointwise block size */
1857: fieldNc[f] = 1;
1858: }
1859: fieldSizes[f] += fpdof;
1860: }
1861: }
1862: }
1863: for (f = 0; f < nF; ++f) {
1864: PetscMalloc1(fieldSizes[f], &fieldIndices[f]);
1865: fieldSizes[f] = 0;
1866: }
1867: for (p = pStart; p < pEnd; ++p) {
1868: PetscInt gdof, goff;
1870: PetscSectionGetDof(sectionGlobal, p, &gdof);
1871: if (gdof > 0) {
1872: PetscSectionGetOffset(sectionGlobal, p, &goff);
1873: for (f = 0; f < nF; ++f) {
1874: PetscInt fdof, fcdof, fc;
1876: PetscSectionGetFieldDof(section, p, f, &fdof);
1877: PetscSectionGetFieldConstraintDof(section, p, f, &fcdof);
1878: for (fc = 0; fc < fdof - fcdof; ++fc, ++fieldSizes[f]) fieldIndices[f][fieldSizes[f]] = goff++;
1879: }
1880: }
1881: }
1882: if (numFields) *numFields = nF;
1883: if (fieldNames) {
1884: PetscMalloc1(nF, fieldNames);
1885: for (f = 0; f < nF; ++f) {
1886: const char *fieldName;
1888: PetscSectionGetFieldName(section, f, &fieldName);
1889: PetscStrallocpy(fieldName, (char **)&(*fieldNames)[f]);
1890: }
1891: }
1892: if (fields) {
1893: PetscMalloc1(nF, fields);
1894: for (f = 0; f < nF; ++f) {
1895: PetscInt bs, in[2], out[2];
1897: ISCreateGeneral(PetscObjectComm((PetscObject)dm), fieldSizes[f], fieldIndices[f], PETSC_OWN_POINTER, &(*fields)[f]);
1898: in[0] = -fieldNc[f];
1899: in[1] = fieldNc[f];
1900: MPIU_Allreduce(in, out, 2, MPIU_INT, MPI_MAX, PetscObjectComm((PetscObject)dm));
1901: bs = (-out[0] == out[1]) ? out[1] : 1;
1902: ISSetBlockSize((*fields)[f], bs);
1903: }
1904: }
1905: PetscFree3(fieldSizes, fieldNc, fieldIndices);
1906: } else PetscTryTypeMethod(dm, createfieldis, numFields, fieldNames, fields);
1907: return 0;
1908: }
1910: /*@C
1911: DMCreateFieldDecomposition - Returns a list of `IS` objects defining a decomposition of a problem into subproblems
1912: corresponding to different fields: each `IS` contains the global indices of the dofs of the
1913: corresponding field, defined by `DMAddField()`. The optional list of `DM`s define the `DM` for each subproblem.
1914: The same as `DMCreateFieldIS()` but also returns a `DM` for each field.
1916: Not collective
1918: Input Parameter:
1919: . dm - the `DM` object
1921: Output Parameters:
1922: + len - The number of fields (or NULL if not requested)
1923: . namelist - The name for each field (or NULL if not requested)
1924: . islist - The global indices for each field (or NULL if not requested)
1925: - dmlist - The `DM`s for each field subproblem (or NULL, if not requested; if NULL is returned, no `DM`s are defined)
1927: Level: intermediate
1929: Note:
1930: The user is responsible for freeing all requested arrays. In particular, every entry of names should be freed with
1931: `PetscFree()`, every entry of is should be destroyed with `ISDestroy()`, every entry of dm should be destroyed with `DMDestroy()`,
1932: and all of the arrays should be freed with `PetscFree()`.
1934: Fortran Note:
1935: Not available in Fortran.
1937: Developer Note:
1938: It is not clear why this function and `DMCreateFieldIS()` exist. Having two seems redundant and confusing.
1940: .seealso: `DMAddField()`, `DMCreateFieldIS()`, `DMCreateSubDM()`, `DMCreateDomainDecomposition()`, `DMDestroy()`, `DMView()`, `DMCreateInterpolation()`, `DMCreateColoring()`, `DMCreateMatrix()`, `DMCreateMassMatrix()`, `DMCreateFieldIS()`
1941: @*/
1942: PetscErrorCode DMCreateFieldDecomposition(DM dm, PetscInt *len, char ***namelist, IS **islist, DM **dmlist)
1943: {
1945: if (len) {
1947: *len = 0;
1948: }
1949: if (namelist) {
1951: *namelist = NULL;
1952: }
1953: if (islist) {
1955: *islist = NULL;
1956: }
1957: if (dmlist) {
1959: *dmlist = NULL;
1960: }
1961: /*
1962: Is it a good idea to apply the following check across all impls?
1963: Perhaps some impls can have a well-defined decomposition before DMSetUp?
1964: This, however, follows the general principle that accessors are not well-behaved until the object is set up.
1965: */
1967: if (!dm->ops->createfielddecomposition) {
1968: PetscSection section;
1969: PetscInt numFields, f;
1971: DMGetLocalSection(dm, §ion);
1972: if (section) PetscSectionGetNumFields(section, &numFields);
1973: if (section && numFields && dm->ops->createsubdm) {
1974: if (len) *len = numFields;
1975: if (namelist) PetscMalloc1(numFields, namelist);
1976: if (islist) PetscMalloc1(numFields, islist);
1977: if (dmlist) PetscMalloc1(numFields, dmlist);
1978: for (f = 0; f < numFields; ++f) {
1979: const char *fieldName;
1981: DMCreateSubDM(dm, 1, &f, islist ? &(*islist)[f] : NULL, dmlist ? &(*dmlist)[f] : NULL);
1982: if (namelist) {
1983: PetscSectionGetFieldName(section, f, &fieldName);
1984: PetscStrallocpy(fieldName, (char **)&(*namelist)[f]);
1985: }
1986: }
1987: } else {
1988: DMCreateFieldIS(dm, len, namelist, islist);
1989: /* By default there are no DMs associated with subproblems. */
1990: if (dmlist) *dmlist = NULL;
1991: }
1992: } else PetscUseTypeMethod(dm, createfielddecomposition, len, namelist, islist, dmlist);
1993: return 0;
1994: }
1996: /*@C
1997: DMCreateSubDM - Returns an IS and DM encapsulating a subproblem defined by the fields passed in.
1998: The fields are defined by DMCreateFieldIS().
2000: Not collective
2002: Input Parameters:
2003: + dm - The `DM `object
2004: . numFields - The number of fields to select
2005: - fields - The field numbers of the selected fields
2007: Output Parameters:
2008: + is - The global indices for all the degrees of freedom in the new sub `DM`
2009: - subdm - The `DM` for the subproblem
2011: Note:
2012: You need to call `DMPlexSetMigrationSF()` on the original `DM` if you want the Global-To-Natural map to be automatically constructed
2014: Level: intermediate
2016: .seealso: `DMCreateFieldIS()`, `DMCreateFieldDecomposition()`, `DMAddField()`, `DMCreateSuperDM()`, `DM`, `IS`, `DMPlexSetMigrationSF()`, `DMDestroy()`, `DMView()`, `DMCreateInterpolation()`, `DMCreateColoring()`, `DMCreateMatrix()`, `DMCreateMassMatrix()`, `DMCreateFieldIS()`
2017: @*/
2018: PetscErrorCode DMCreateSubDM(DM dm, PetscInt numFields, const PetscInt fields[], IS *is, DM *subdm)
2019: {
2024: PetscUseTypeMethod(dm, createsubdm, numFields, fields, is, subdm);
2025: return 0;
2026: }
2028: /*@C
2029: DMCreateSuperDM - Returns an arrays of `IS` and `DM` encapsulating a superproblem defined by multiple `DM`s passed in.
2031: Not collective
2033: Input Parameters:
2034: + dms - The `DM` objects
2035: - n - The number of `DM`s
2037: Output Parameters:
2038: + is - The global indices for each of subproblem within the super `DM`, or NULL
2039: - superdm - The `DM` for the superproblem
2041: Note:
2042: You need to call `DMPlexSetMigrationSF()` on the original `DM` if you want the Global-To-Natural map to be automatically constructed
2044: Level: intermediate
2046: .seealso: `DM`, `DMCreateSubDM()`, `DMPlexSetMigrationSF()`, `DMDestroy()`, `DMView()`, `DMCreateInterpolation()`, `DMCreateColoring()`, `DMCreateMatrix()`, `DMCreateMassMatrix()`, `DMCreateFieldIS()`
2047: @*/
2048: PetscErrorCode DMCreateSuperDM(DM dms[], PetscInt n, IS **is, DM *superdm)
2049: {
2050: PetscInt i;
2057: if (n) {
2058: DM dm = dms[0];
2059: (*dm->ops->createsuperdm)(dms, n, is, superdm);
2060: }
2061: return 0;
2062: }
2064: /*@C
2065: DMCreateDomainDecomposition - Returns lists of `IS` objects defining a decomposition of a problem into subproblems
2066: corresponding to restrictions to pairs of nested subdomains: each `IS` contains the global
2067: indices of the dofs of the corresponding subdomains with in the dofs of the original `DM`.
2068: The inner subdomains conceptually define a nonoverlapping covering, while outer subdomains can overlap.
2069: The optional list of `DM`s define a `DM` for each subproblem.
2071: Not collective
2073: Input Parameter:
2074: . dm - the `DM` object
2076: Output Parameters:
2077: + n - The number of subproblems in the domain decomposition (or NULL if not requested)
2078: . namelist - The name for each subdomain (or NULL if not requested)
2079: . innerislist - The global indices for each inner subdomain (or NULL, if not requested)
2080: . outerislist - The global indices for each outer subdomain (or NULL, if not requested)
2081: - dmlist - The `DM`s for each subdomain subproblem (or NULL, if not requested; if NULL is returned, no `DM`s are defined)
2083: Level: intermediate
2085: Note:
2086: The user is responsible for freeing all requested arrays. In particular, every entry of names should be freed with
2087: `PetscFree()`, every entry of is should be destroyed with `ISDestroy()`, every entry of dm should be destroyed with `DMDestroy()`,
2088: and all of the arrays should be freed with `PetscFree()`.
2090: Questions:
2091: The dmlist is for the inner subdomains or the outer subdomains or all subdomains?
2093: .seealso: `DMCreateFieldDecomposition()`, `DMDestroy()`, `DMCreateDomainDecompositionScatters()`, `DMView()`, `DMCreateInterpolation()`, `DMCreateColoring()`, `DMCreateMatrix()`, `DMCreateMassMatrix()`, `DMCreateFieldDecomposition()`
2094: @*/
2095: PetscErrorCode DMCreateDomainDecomposition(DM dm, PetscInt *n, char ***namelist, IS **innerislist, IS **outerislist, DM **dmlist)
2096: {
2097: DMSubDomainHookLink link;
2098: PetscInt i, l;
2101: if (n) {
2103: *n = 0;
2104: }
2105: if (namelist) {
2107: *namelist = NULL;
2108: }
2109: if (innerislist) {
2111: *innerislist = NULL;
2112: }
2113: if (outerislist) {
2115: *outerislist = NULL;
2116: }
2117: if (dmlist) {
2119: *dmlist = NULL;
2120: }
2121: /*
2122: Is it a good idea to apply the following check across all impls?
2123: Perhaps some impls can have a well-defined decomposition before DMSetUp?
2124: This, however, follows the general principle that accessors are not well-behaved until the object is set up.
2125: */
2127: if (dm->ops->createdomaindecomposition) {
2128: PetscUseTypeMethod(dm, createdomaindecomposition, &l, namelist, innerislist, outerislist, dmlist);
2129: /* copy subdomain hooks and context over to the subdomain DMs */
2130: if (dmlist && *dmlist) {
2131: for (i = 0; i < l; i++) {
2132: for (link = dm->subdomainhook; link; link = link->next) {
2133: if (link->ddhook) (*link->ddhook)(dm, (*dmlist)[i], link->ctx);
2134: }
2135: if (dm->ctx) (*dmlist)[i]->ctx = dm->ctx;
2136: }
2137: }
2138: if (n) *n = l;
2139: }
2140: return 0;
2141: }
2143: /*@C
2144: DMCreateDomainDecompositionScatters - Returns scatters to the subdomain vectors from the global vector
2146: Not collective
2148: Input Parameters:
2149: + dm - the `DM` object
2150: . n - the number of subdomain scatters
2151: - subdms - the local subdomains
2153: Output Parameters:
2154: + iscat - scatter from global vector to nonoverlapping global vector entries on subdomain
2155: . oscat - scatter from global vector to overlapping global vector entries on subdomain
2156: - gscat - scatter from global vector to local vector on subdomain (fills in ghosts)
2158: Note:
2159: This is an alternative to the iis and ois arguments in `DMCreateDomainDecomposition()` that allow for the solution
2160: of general nonlinear problems with overlapping subdomain methods. While merely having index sets that enable subsets
2161: of the residual equations to be created is fine for linear problems, nonlinear problems require local assembly of
2162: solution and residual data.
2164: Questions:
2165: Can the subdms input be anything or are they exactly the `DM` obtained from `DMCreateDomainDecomposition()`?
2167: Level: developer
2169: .seealso: `DM`, `DMCreateDomainDecomposition()`, `DMDestroy()`, `DMView()`, `DMCreateInterpolation()`, `DMCreateColoring()`, `DMCreateMatrix()`, `DMCreateMassMatrix()`, `DMCreateFieldIS()`
2170: @*/
2171: PetscErrorCode DMCreateDomainDecompositionScatters(DM dm, PetscInt n, DM *subdms, VecScatter **iscat, VecScatter **oscat, VecScatter **gscat)
2172: {
2175: PetscUseTypeMethod(dm, createddscatters, n, subdms, iscat, oscat, gscat);
2176: return 0;
2177: }
2179: /*@
2180: DMRefine - Refines a `DM` object using a standard nonadaptive refinement of the underlying mesh
2182: Collective on dm
2184: Input Parameters:
2185: + dm - the `DM` object
2186: - comm - the communicator to contain the new `DM` object (or `MPI_COMM_NULL`)
2188: Output Parameter:
2189: . dmf - the refined `D`M, or NULL
2191: Options Database Keys:
2192: . -dm_plex_cell_refiner <strategy> - chooses the refinement strategy, e.g. regular, tohex
2194: Note:
2195: If no refinement was done, the return value is NULL
2197: Level: developer
2199: .seealso: `DMCoarsen()`, `DMDestroy()`, `DMView()`, `DMCreateGlobalVector()`, `DMCreateInterpolation()`
2200: @*/
2201: PetscErrorCode DMRefine(DM dm, MPI_Comm comm, DM *dmf)
2202: {
2203: DMRefineHookLink link;
2206: PetscLogEventBegin(DM_Refine, dm, 0, 0, 0);
2207: PetscUseTypeMethod(dm, refine, comm, dmf);
2208: if (*dmf) {
2209: (*dmf)->ops->creatematrix = dm->ops->creatematrix;
2211: PetscObjectCopyFortranFunctionPointers((PetscObject)dm, (PetscObject)*dmf);
2213: (*dmf)->ctx = dm->ctx;
2214: (*dmf)->leveldown = dm->leveldown;
2215: (*dmf)->levelup = dm->levelup + 1;
2217: DMSetMatType(*dmf, dm->mattype);
2218: for (link = dm->refinehook; link; link = link->next) {
2219: if (link->refinehook) (*link->refinehook)(dm, *dmf, link->ctx);
2220: }
2221: }
2222: PetscLogEventEnd(DM_Refine, dm, 0, 0, 0);
2223: return 0;
2224: }
2226: /*@C
2227: DMRefineHookAdd - adds a callback to be run when interpolating a nonlinear problem to a finer grid
2229: Logically Collective on coarse
2231: Input Parameters:
2232: + coarse - `DM` on which to run a hook when interpolating to a finer level
2233: . refinehook - function to run when setting up the finer level
2234: . interphook - function to run to update data on finer levels (once per `SNESSolve`())
2235: - ctx - [optional] user-defined context for provide data for the hooks (may be NULL)
2237: Calling sequence of refinehook:
2238: $ refinehook(DM coarse,DM fine,void *ctx);
2240: + coarse - coarse level `DM`
2241: . fine - fine level `DM` to interpolate problem to
2242: - ctx - optional user-defined function context
2244: Calling sequence for interphook:
2245: $ interphook(DM coarse,Mat interp,DM fine,void *ctx)
2247: + coarse - coarse level `DM`
2248: . interp - matrix interpolating a coarse-level solution to the finer grid
2249: . fine - fine level `DM` to update
2250: - ctx - optional user-defined function context
2252: Level: advanced
2254: Notes:
2255: This function is only needed if auxiliary data that is attached to the `DM`s via, for example, `PetscObjectCompose()`, needs to be
2256: passed to fine grids while grid sequencing.
2258: The actual interpolation is done when `DMInterpolate()` is called.
2260: If this function is called multiple times, the hooks will be run in the order they are added.
2262: Fortran Note:
2263: This function is not available from Fortran.
2265: .seealso: `DM`, `DMCoarsenHookAdd()`, `DMInterpolate()`, `SNESFASGetInterpolation()`, `SNESFASGetInjection()`, `PetscObjectCompose()`, `PetscContainerCreate()`
2266: @*/
2267: PetscErrorCode DMRefineHookAdd(DM coarse, PetscErrorCode (*refinehook)(DM, DM, void *), PetscErrorCode (*interphook)(DM, Mat, DM, void *), void *ctx)
2268: {
2269: DMRefineHookLink link, *p;
2272: for (p = &coarse->refinehook; *p; p = &(*p)->next) { /* Scan to the end of the current list of hooks */
2273: if ((*p)->refinehook == refinehook && (*p)->interphook == interphook && (*p)->ctx == ctx) return 0;
2274: }
2275: PetscNew(&link);
2276: link->refinehook = refinehook;
2277: link->interphook = interphook;
2278: link->ctx = ctx;
2279: link->next = NULL;
2280: *p = link;
2281: return 0;
2282: }
2284: /*@C
2285: DMRefineHookRemove - remove a callback from the list of hooks, that have been set with `DMRefineHookAdd()`, to be run when interpolating
2286: a nonlinear problem to a finer grid
2288: Logically Collective on coarse
2290: Input Parameters:
2291: + coarse - the `DM` on which to run a hook when restricting to a coarser level
2292: . refinehook - function to run when setting up a finer level
2293: . interphook - function to run to update data on finer levels
2294: - ctx - [optional] user-defined context for provide data for the hooks (may be NULL)
2296: Level: advanced
2298: Note:
2299: This function does nothing if the hook is not in the list.
2301: Fortran Note:
2302: This function is not available from Fortran.
2304: .seealso: `DMRefineHookAdd()`, `DMCoarsenHookRemove()`, `DMInterpolate()`, `SNESFASGetInterpolation()`, `SNESFASGetInjection()`, `PetscObjectCompose()`, `PetscContainerCreate()`
2305: @*/
2306: PetscErrorCode DMRefineHookRemove(DM coarse, PetscErrorCode (*refinehook)(DM, DM, void *), PetscErrorCode (*interphook)(DM, Mat, DM, void *), void *ctx)
2307: {
2308: DMRefineHookLink link, *p;
2311: for (p = &coarse->refinehook; *p; p = &(*p)->next) { /* Search the list of current hooks */
2312: if ((*p)->refinehook == refinehook && (*p)->interphook == interphook && (*p)->ctx == ctx) {
2313: link = *p;
2314: *p = link->next;
2315: PetscFree(link);
2316: break;
2317: }
2318: }
2319: return 0;
2320: }
2322: /*@
2323: DMInterpolate - interpolates user-defined problem data attached to a `DM` to a finer `DM` by running hooks registered by `DMRefineHookAdd()`
2325: Collective if any hooks are
2327: Input Parameters:
2328: + coarse - coarser `DM` to use as a base
2329: . interp - interpolation matrix, apply using `MatInterpolate()`
2330: - fine - finer `DM` to update
2332: Level: developer
2334: Developer Note:
2335: This routine is called `DMInterpolate()` while the hook is called `DMRefineHookAdd()`. It would be better to have an
2336: an API with consistent terminology.
2338: .seealso: `DM`, `DMRefineHookAdd()`, `MatInterpolate()`
2339: @*/
2340: PetscErrorCode DMInterpolate(DM coarse, Mat interp, DM fine)
2341: {
2342: DMRefineHookLink link;
2344: for (link = fine->refinehook; link; link = link->next) {
2345: if (link->interphook) (*link->interphook)(coarse, interp, fine, link->ctx);
2346: }
2347: return 0;
2348: }
2350: /*@
2351: DMInterpolateSolution - Interpolates a solution from a coarse mesh to a fine mesh.
2353: Collective on dm
2355: Input Parameters:
2356: + coarse - coarse `DM`
2357: . fine - fine `DM`
2358: . interp - (optional) the matrix computed by `DMCreateInterpolation()`. Implementations may not need this, but if it
2359: is available it can avoid some recomputation. If it is provided, `MatInterpolate()` will be used if
2360: the coarse `DM` does not have a specialized implementation.
2361: - coarseSol - solution on the coarse mesh
2363: Output Parameter:
2364: . fineSol - the interpolation of coarseSol to the fine mesh
2366: Level: developer
2368: Note:
2369: This function exists because the interpolation of a solution vector between meshes is not always a linear
2370: map. For example, if a boundary value problem has an inhomogeneous Dirichlet boundary condition that is compressed
2371: out of the solution vector. Or if interpolation is inherently a nonlinear operation, such as a method using
2372: slope-limiting reconstruction.
2374: Developer Note:
2375: This doesn't just interpolate "solutions" so its API name is questionable.
2377: .seealso: `DMInterpolate()`, `DMCreateInterpolation()`
2378: @*/
2379: PetscErrorCode DMInterpolateSolution(DM coarse, DM fine, Mat interp, Vec coarseSol, Vec fineSol)
2380: {
2381: PetscErrorCode (*interpsol)(DM, DM, Mat, Vec, Vec) = NULL;
2388: PetscObjectQueryFunction((PetscObject)coarse, "DMInterpolateSolution_C", &interpsol);
2389: if (interpsol) {
2390: (*interpsol)(coarse, fine, interp, coarseSol, fineSol);
2391: } else if (interp) {
2392: MatInterpolate(interp, coarseSol, fineSol);
2393: } else SETERRQ(PetscObjectComm((PetscObject)coarse), PETSC_ERR_SUP, "DM %s does not implement DMInterpolateSolution()", ((PetscObject)coarse)->type_name);
2394: return 0;
2395: }
2397: /*@
2398: DMGetRefineLevel - Gets the number of refinements that have generated this `DM` from some initial `DM`.
2400: Not Collective
2402: Input Parameter:
2403: . dm - the `DM` object
2405: Output Parameter:
2406: . level - number of refinements
2408: Level: developer
2410: Note:
2411: This can be used, by example, to set the number of coarser levels associated with this `DM` for a multigrid solver.
2413: .seealso: `DMRefine()`, `DMCoarsen()`, `DMGetCoarsenLevel()`, `DMDestroy()`, `DMView()`, `DMCreateGlobalVector()`, `DMCreateInterpolation()`
2415: @*/
2416: PetscErrorCode DMGetRefineLevel(DM dm, PetscInt *level)
2417: {
2419: *level = dm->levelup;
2420: return 0;
2421: }
2423: /*@
2424: DMSetRefineLevel - Sets the number of refinements that have generated this `DM`.
2426: Not Collective
2428: Input Parameters:
2429: + dm - the `DM` object
2430: - level - number of refinements
2432: Level: advanced
2434: Notes:
2435: This value is used by `PCMG` to determine how many multigrid levels to use
2437: The values are usually set automatically by the process that is causing the refinements of an initial `DM` by calling this routine.
2439: .seealso: `DMGetRefineLevel()`, `DMCoarsen()`, `DMGetCoarsenLevel()`, `DMDestroy()`, `DMView()`, `DMCreateGlobalVector()`, `DMCreateInterpolation()`
2441: @*/
2442: PetscErrorCode DMSetRefineLevel(DM dm, PetscInt level)
2443: {
2445: dm->levelup = level;
2446: return 0;
2447: }
2449: /*@
2450: DMExtrude - Extrude a `DM` object from a surface
2452: Collective on dm
2454: Input Parameters:
2455: + dm - the `DM` object
2456: - layers - the number of extruded cell layers
2458: Output Parameter:
2459: . dme - the extruded `DM`, or NULL
2461: Note:
2462: If no extrusion was done, the return value is NULL
2464: Level: developer
2466: .seealso: `DMRefine()`, `DMCoarsen()`, `DMDestroy()`, `DMView()`, `DMCreateGlobalVector()`
2467: @*/
2468: PetscErrorCode DMExtrude(DM dm, PetscInt layers, DM *dme)
2469: {
2471: PetscUseTypeMethod(dm, extrude, layers, dme);
2472: if (*dme) {
2473: (*dme)->ops->creatematrix = dm->ops->creatematrix;
2474: PetscObjectCopyFortranFunctionPointers((PetscObject)dm, (PetscObject)*dme);
2475: (*dme)->ctx = dm->ctx;
2476: DMSetMatType(*dme, dm->mattype);
2477: }
2478: return 0;
2479: }
2481: PetscErrorCode DMGetBasisTransformDM_Internal(DM dm, DM *tdm)
2482: {
2485: *tdm = dm->transformDM;
2486: return 0;
2487: }
2489: PetscErrorCode DMGetBasisTransformVec_Internal(DM dm, Vec *tv)
2490: {
2493: *tv = dm->transform;
2494: return 0;
2495: }
2497: /*@
2498: DMHasBasisTransform - Whether the `DM` employs a basis transformation from functions in global vectors to functions in local vectors
2500: Input Parameter:
2501: . dm - The DM
2503: Output Parameter:
2504: . flg - PETSC_TRUE if a basis transformation should be done
2506: Level: developer
2508: .seealso: `DM`, `DMPlexGlobalToLocalBasis()`, `DMPlexLocalToGlobalBasis()`, `DMPlexCreateBasisRotation()`
2509: @*/
2510: PetscErrorCode DMHasBasisTransform(DM dm, PetscBool *flg)
2511: {
2512: Vec tv;
2516: DMGetBasisTransformVec_Internal(dm, &tv);
2517: *flg = tv ? PETSC_TRUE : PETSC_FALSE;
2518: return 0;
2519: }
2521: PetscErrorCode DMConstructBasisTransform_Internal(DM dm)
2522: {
2523: PetscSection s, ts;
2524: PetscScalar *ta;
2525: PetscInt cdim, pStart, pEnd, p, Nf, f, Nc, dof;
2527: DMGetCoordinateDim(dm, &cdim);
2528: DMGetLocalSection(dm, &s);
2529: PetscSectionGetChart(s, &pStart, &pEnd);
2530: PetscSectionGetNumFields(s, &Nf);
2531: DMClone(dm, &dm->transformDM);
2532: DMGetLocalSection(dm->transformDM, &ts);
2533: PetscSectionSetNumFields(ts, Nf);
2534: PetscSectionSetChart(ts, pStart, pEnd);
2535: for (f = 0; f < Nf; ++f) {
2536: PetscSectionGetFieldComponents(s, f, &Nc);
2537: /* We could start to label fields by their transformation properties */
2538: if (Nc != cdim) continue;
2539: for (p = pStart; p < pEnd; ++p) {
2540: PetscSectionGetFieldDof(s, p, f, &dof);
2541: if (!dof) continue;
2542: PetscSectionSetFieldDof(ts, p, f, PetscSqr(cdim));
2543: PetscSectionAddDof(ts, p, PetscSqr(cdim));
2544: }
2545: }
2546: PetscSectionSetUp(ts);
2547: DMCreateLocalVector(dm->transformDM, &dm->transform);
2548: VecGetArray(dm->transform, &ta);
2549: for (p = pStart; p < pEnd; ++p) {
2550: for (f = 0; f < Nf; ++f) {
2551: PetscSectionGetFieldDof(ts, p, f, &dof);
2552: if (dof) {
2553: PetscReal x[3] = {0.0, 0.0, 0.0};
2554: PetscScalar *tva;
2555: const PetscScalar *A;
2557: /* TODO Get quadrature point for this dual basis vector for coordinate */
2558: (*dm->transformGetMatrix)(dm, x, PETSC_TRUE, &A, dm->transformCtx);
2559: DMPlexPointLocalFieldRef(dm->transformDM, p, f, ta, (void *)&tva);
2560: PetscArraycpy(tva, A, PetscSqr(cdim));
2561: }
2562: }
2563: }
2564: VecRestoreArray(dm->transform, &ta);
2565: return 0;
2566: }
2568: PetscErrorCode DMCopyTransform(DM dm, DM newdm)
2569: {
2572: newdm->transformCtx = dm->transformCtx;
2573: newdm->transformSetUp = dm->transformSetUp;
2574: newdm->transformDestroy = NULL;
2575: newdm->transformGetMatrix = dm->transformGetMatrix;
2576: if (newdm->transformSetUp) DMConstructBasisTransform_Internal(newdm);
2577: return 0;
2578: }
2580: /*@C
2581: DMGlobalToLocalHookAdd - adds a callback to be run when `DMGlobalToLocal()` is called
2583: Logically Collective on dm
2585: Input Parameters:
2586: + dm - the `DM`
2587: . beginhook - function to run at the beginning of `DMGlobalToLocalBegin()`
2588: . endhook - function to run after `DMGlobalToLocalEnd()` has completed
2589: - ctx - [optional] user-defined context for provide data for the hooks (may be NULL)
2591: Calling sequence for beginhook:
2592: $ beginhook(DM fine,VecScatter out,VecScatter in,DM coarse,void *ctx)
2594: + dm - global DM
2595: . g - global vector
2596: . mode - mode
2597: . l - local vector
2598: - ctx - optional user-defined function context
2600: Calling sequence for endhook:
2601: $ endhook(DM fine,VecScatter out,VecScatter in,DM coarse,void *ctx)
2603: + global - global DM
2604: - ctx - optional user-defined function context
2606: Level: advanced
2608: Note:
2609: 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.
2611: .seealso: `DM`, `DMGlobalToLocal()`, `DMRefineHookAdd()`, `SNESFASGetInterpolation()`, `SNESFASGetInjection()`, `PetscObjectCompose()`, `PetscContainerCreate()`
2612: @*/
2613: PetscErrorCode DMGlobalToLocalHookAdd(DM dm, PetscErrorCode (*beginhook)(DM, Vec, InsertMode, Vec, void *), PetscErrorCode (*endhook)(DM, Vec, InsertMode, Vec, void *), void *ctx)
2614: {
2615: DMGlobalToLocalHookLink link, *p;
2618: for (p = &dm->gtolhook; *p; p = &(*p)->next) { } /* Scan to the end of the current list of hooks */
2619: PetscNew(&link);
2620: link->beginhook = beginhook;
2621: link->endhook = endhook;
2622: link->ctx = ctx;
2623: link->next = NULL;
2624: *p = link;
2625: return 0;
2626: }
2628: static PetscErrorCode DMGlobalToLocalHook_Constraints(DM dm, Vec g, InsertMode mode, Vec l, void *ctx)
2629: {
2630: Mat cMat;
2631: Vec cVec, cBias;
2632: PetscSection section, cSec;
2633: PetscInt pStart, pEnd, p, dof;
2636: DMGetDefaultConstraints(dm, &cSec, &cMat, &cBias);
2637: if (cMat && (mode == INSERT_VALUES || mode == INSERT_ALL_VALUES || mode == INSERT_BC_VALUES)) {
2638: PetscInt nRows;
2640: MatGetSize(cMat, &nRows, NULL);
2641: if (nRows <= 0) return 0;
2642: DMGetLocalSection(dm, §ion);
2643: MatCreateVecs(cMat, NULL, &cVec);
2644: MatMult(cMat, l, cVec);
2645: if (cBias) VecAXPY(cVec, 1., cBias);
2646: PetscSectionGetChart(cSec, &pStart, &pEnd);
2647: for (p = pStart; p < pEnd; p++) {
2648: PetscSectionGetDof(cSec, p, &dof);
2649: if (dof) {
2650: PetscScalar *vals;
2651: VecGetValuesSection(cVec, cSec, p, &vals);
2652: VecSetValuesSection(l, section, p, vals, INSERT_ALL_VALUES);
2653: }
2654: }
2655: VecDestroy(&cVec);
2656: }
2657: return 0;
2658: }
2660: /*@
2661: DMGlobalToLocal - update local vectors from global vector
2663: Neighbor-wise Collective on dm
2665: Input Parameters:
2666: + dm - the `DM` object
2667: . g - the global vector
2668: . mode - `INSERT_VALUES` or `ADD_VALUES`
2669: - l - the local vector
2671: Notes:
2672: The communication involved in this update can be overlapped with computation by instead using
2673: `DMGlobalToLocalBegin()` and `DMGlobalToLocalEnd()`.
2675: `DMGlobalToLocalHookAdd()` may be used to provide additional operations that are performed during the update process.
2677: Level: beginner
2679: .seealso: `DM`, `DMGlobalToLocalHookAdd()`, `DMCoarsen()`, `DMDestroy()`, `DMView()`, `DMCreateGlobalVector()`, `DMCreateInterpolation()`,
2680: `DMGlobalToLocalEnd()`, `DMLocalToGlobalBegin()`, `DMLocalToGlobal()`, `DMLocalToGlobalBegin()`, `DMLocalToGlobalEnd()`,
2681: `DMGlobalToLocalBegin()` `DMGlobalToLocalEnd()`
2683: @*/
2684: PetscErrorCode DMGlobalToLocal(DM dm, Vec g, InsertMode mode, Vec l)
2685: {
2686: DMGlobalToLocalBegin(dm, g, mode, l);
2687: DMGlobalToLocalEnd(dm, g, mode, l);
2688: return 0;
2689: }
2691: /*@
2692: DMGlobalToLocalBegin - Begins updating local vectors from global vector
2694: Neighbor-wise Collective on dm
2696: Input Parameters:
2697: + dm - the `DM` object
2698: . g - the global vector
2699: . mode - `INSERT_VALUES` or `ADD_VALUES`
2700: - l - the local vector
2702: Level: intermediate
2704: Notes:
2705: The operation is completed with `DMGlobalToLocalEnd()`
2707: One can perform local computations between the `DMGlobalToLocalBegin()` and `DMGlobalToLocalEnd()` to overlap communication and computation
2709: `DMGlobalToLocal()` is a short form of `DMGlobalToLocalBegin()` and `DMGlobalToLocalEnd()`
2711: `DMGlobalToLocalHookAdd()` may be used to provide additional operations that are performed during the update process.
2713: .seealso: `DMCoarsen()`, `DMDestroy()`, `DMView()`, `DMCreateGlobalVector()`, `DMCreateInterpolation()`, `DMGlobalToLocal()`, `DMGlobalToLocalEnd()`, `DMLocalToGlobalBegin()`, `DMLocalToGlobal()`, `DMLocalToGlobalBegin()`, `DMLocalToGlobalEnd()`
2715: @*/
2716: PetscErrorCode DMGlobalToLocalBegin(DM dm, Vec g, InsertMode mode, Vec l)
2717: {
2718: PetscSF sf;
2719: DMGlobalToLocalHookLink link;
2722: for (link = dm->gtolhook; link; link = link->next) {
2723: if (link->beginhook) (*link->beginhook)(dm, g, mode, l, link->ctx);
2724: }
2725: DMGetSectionSF(dm, &sf);
2726: if (sf) {
2727: const PetscScalar *gArray;
2728: PetscScalar *lArray;
2729: PetscMemType lmtype, gmtype;
2732: VecGetArrayAndMemType(l, &lArray, &lmtype);
2733: VecGetArrayReadAndMemType(g, &gArray, &gmtype);
2734: PetscSFBcastWithMemTypeBegin(sf, MPIU_SCALAR, gmtype, gArray, lmtype, lArray, MPI_REPLACE);
2735: VecRestoreArrayAndMemType(l, &lArray);
2736: VecRestoreArrayReadAndMemType(g, &gArray);
2737: } else {
2738: (*dm->ops->globaltolocalbegin)(dm, g, mode == INSERT_ALL_VALUES ? INSERT_VALUES : (mode == ADD_ALL_VALUES ? ADD_VALUES : mode), l);
2739: }
2740: return 0;
2741: }
2743: /*@
2744: DMGlobalToLocalEnd - Ends updating local vectors from global vector
2746: Neighbor-wise Collective on dm
2748: Input Parameters:
2749: + dm - the `DM` object
2750: . g - the global vector
2751: . mode - `INSERT_VALUES` or `ADD_VALUES`
2752: - l - the local vector
2754: Level: intermediate
2756: Note:
2757: See `DMGlobalToLocalBegin()` for details.
2759: .seealso: `DMCoarsen()`, `DMDestroy()`, `DMView()`, `DMCreateGlobalVector()`, `DMCreateInterpolation()`, `DMGlobalToLocal()`, `DMLocalToGlobalBegin()`, `DMLocalToGlobal()`, `DMLocalToGlobalBegin()`, `DMLocalToGlobalEnd()`
2761: @*/
2762: PetscErrorCode DMGlobalToLocalEnd(DM dm, Vec g, InsertMode mode, Vec l)
2763: {
2764: PetscSF sf;
2765: const PetscScalar *gArray;
2766: PetscScalar *lArray;
2767: PetscBool transform;
2768: DMGlobalToLocalHookLink link;
2769: PetscMemType lmtype, gmtype;
2772: DMGetSectionSF(dm, &sf);
2773: DMHasBasisTransform(dm, &transform);
2774: if (sf) {
2777: VecGetArrayAndMemType(l, &lArray, &lmtype);
2778: VecGetArrayReadAndMemType(g, &gArray, &gmtype);
2779: PetscSFBcastEnd(sf, MPIU_SCALAR, gArray, lArray, MPI_REPLACE);
2780: VecRestoreArrayAndMemType(l, &lArray);
2781: VecRestoreArrayReadAndMemType(g, &gArray);
2782: if (transform) DMPlexGlobalToLocalBasis(dm, l);
2783: } else {
2784: (*dm->ops->globaltolocalend)(dm, g, mode == INSERT_ALL_VALUES ? INSERT_VALUES : (mode == ADD_ALL_VALUES ? ADD_VALUES : mode), l);
2785: }
2786: DMGlobalToLocalHook_Constraints(dm, g, mode, l, NULL);
2787: for (link = dm->gtolhook; link; link = link->next) {
2788: if (link->endhook) (*link->endhook)(dm, g, mode, l, link->ctx);
2789: }
2790: return 0;
2791: }
2793: /*@C
2794: DMLocalToGlobalHookAdd - adds a callback to be run when a local to global is called
2796: Logically Collective on dm
2798: Input Parameters:
2799: + dm - the `DM`
2800: . beginhook - function to run at the beginning of `DMLocalToGlobalBegin()`
2801: . endhook - function to run after `DMLocalToGlobalEnd()` has completed
2802: - ctx - [optional] user-defined context for provide data for the hooks (may be NULL)
2804: Calling sequence for beginhook:
2805: $ beginhook(DM fine,Vec l,InsertMode mode,Vec g,void *ctx)
2807: + dm - global `DM`
2808: . l - local vector
2809: . mode - mode
2810: . g - global vector
2811: - ctx - optional user-defined function context
2813: Calling sequence for endhook:
2814: $ endhook(DM fine,Vec l,InsertMode mode,Vec g,void *ctx)
2816: + global - global `DM`
2817: . l - local vector
2818: . mode - mode
2819: . g - global vector
2820: - ctx - optional user-defined function context
2822: Level: advanced
2824: .seealso: `DMLocalToGlobal()`, `DMRefineHookAdd()`, `DMGlobalToLocalHookAdd()`, `SNESFASGetInterpolation()`, `SNESFASGetInjection()`, `PetscObjectCompose()`, `PetscContainerCreate()`
2825: @*/
2826: PetscErrorCode DMLocalToGlobalHookAdd(DM dm, PetscErrorCode (*beginhook)(DM, Vec, InsertMode, Vec, void *), PetscErrorCode (*endhook)(DM, Vec, InsertMode, Vec, void *), void *ctx)
2827: {
2828: DMLocalToGlobalHookLink link, *p;
2831: for (p = &dm->ltoghook; *p; p = &(*p)->next) { } /* Scan to the end of the current list of hooks */
2832: PetscNew(&link);
2833: link->beginhook = beginhook;
2834: link->endhook = endhook;
2835: link->ctx = ctx;
2836: link->next = NULL;
2837: *p = link;
2838: return 0;
2839: }
2841: static PetscErrorCode DMLocalToGlobalHook_Constraints(DM dm, Vec l, InsertMode mode, Vec g, void *ctx)
2842: {
2843: Mat cMat;
2844: Vec cVec;
2845: PetscSection section, cSec;
2846: PetscInt pStart, pEnd, p, dof;
2849: DMGetDefaultConstraints(dm, &cSec, &cMat, NULL);
2850: if (cMat && (mode == ADD_VALUES || mode == ADD_ALL_VALUES || mode == ADD_BC_VALUES)) {
2851: PetscInt nRows;
2853: MatGetSize(cMat, &nRows, NULL);
2854: if (nRows <= 0) return 0;
2855: DMGetLocalSection(dm, §ion);
2856: MatCreateVecs(cMat, NULL, &cVec);
2857: PetscSectionGetChart(cSec, &pStart, &pEnd);
2858: for (p = pStart; p < pEnd; p++) {
2859: PetscSectionGetDof(cSec, p, &dof);
2860: if (dof) {
2861: PetscInt d;
2862: PetscScalar *vals;
2863: VecGetValuesSection(l, section, p, &vals);
2864: VecSetValuesSection(cVec, cSec, p, vals, mode);
2865: /* for this to be the true transpose, we have to zero the values that
2866: * we just extracted */
2867: for (d = 0; d < dof; d++) vals[d] = 0.;
2868: }
2869: }
2870: MatMultTransposeAdd(cMat, cVec, l, l);
2871: VecDestroy(&cVec);
2872: }
2873: return 0;
2874: }
2875: /*@
2876: DMLocalToGlobal - updates global vectors from local vectors
2878: Neighbor-wise Collective on dm
2880: Input Parameters:
2881: + dm - the `DM` object
2882: . l - the local vector
2883: . 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.
2884: - g - the global vector
2886: Notes:
2887: The communication involved in this update can be overlapped with computation by using
2888: `DMLocalToGlobalBegin()` and `DMLocalToGlobalEnd()`.
2890: In the `ADD_VALUES` case you normally would zero the receiving vector before beginning this operation.
2892: `INSERT_VALUES` is not supported for `DMDA`; in that case simply compute the values directly into a global vector instead of a local one.
2894: Use `DMLocalToGlobalHookAdd()` to add additional operations that are performed on the data during the update process
2896: Level: beginner
2898: .seealso: `DMLocalToGlobalBegin()`, `DMLocalToGlobalEnd()`, `DMCoarsen()`, `DMDestroy()`, `DMView()`, `DMCreateGlobalVector()`, `DMCreateInterpolation()`, `DMGlobalToLocal()`, `DMGlobalToLocalEnd()`, `DMGlobalToLocalBegin()`, `DMLocalToGlobalHookAdd()`, `DMGlobaToLocallHookAdd()`
2900: @*/
2901: PetscErrorCode DMLocalToGlobal(DM dm, Vec l, InsertMode mode, Vec g)
2902: {
2903: DMLocalToGlobalBegin(dm, l, mode, g);
2904: DMLocalToGlobalEnd(dm, l, mode, g);
2905: return 0;
2906: }
2908: /*@
2909: DMLocalToGlobalBegin - begins updating global vectors from local vectors
2911: Neighbor-wise Collective on dm
2913: Input Parameters:
2914: + dm - the `DM` object
2915: . l - the local vector
2916: . 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.
2917: - g - the global vector
2919: Notes:
2920: In the `ADD_VALUES` case you normally would zero the receiving vector before beginning this operation.
2922: `INSERT_VALUES is` not supported for `DMDA`, in that case simply compute the values directly into a global vector instead of a local one.
2924: Use `DMLocalToGlobalEnd()` to complete the communication process.
2926: `DMLocalToGlobal()` is a short form of `DMLocalToGlobalBegin()` and `DMLocalToGlobalEnd()`
2928: `DMLocalToGlobalHookAdd()` may be used to provide additional operations that are performed during the update process.
2930: Level: intermediate
2932: .seealso: `DMLocalToGlobal()`, `DMLocalToGlobalEnd()`, `DMCoarsen()`, `DMDestroy()`, `DMView()`, `DMCreateGlobalVector()`, `DMCreateInterpolation()`, `DMGlobalToLocal()`, `DMGlobalToLocalEnd()`, `DMGlobalToLocalBegin()`
2934: @*/
2935: PetscErrorCode DMLocalToGlobalBegin(DM dm, Vec l, InsertMode mode, Vec g)
2936: {
2937: PetscSF sf;
2938: PetscSection s, gs;
2939: DMLocalToGlobalHookLink link;
2940: Vec tmpl;
2941: const PetscScalar *lArray;
2942: PetscScalar *gArray;
2943: PetscBool isInsert, transform, l_inplace = PETSC_FALSE, g_inplace = PETSC_FALSE;
2944: PetscMemType lmtype = PETSC_MEMTYPE_HOST, gmtype = PETSC_MEMTYPE_HOST;
2947: for (link = dm->ltoghook; link; link = link->next) {
2948: if (link->beginhook) (*link->beginhook)(dm, l, mode, g, link->ctx);
2949: }
2950: DMLocalToGlobalHook_Constraints(dm, l, mode, g, NULL);
2951: DMGetSectionSF(dm, &sf);
2952: DMGetLocalSection(dm, &s);
2953: switch (mode) {
2954: case INSERT_VALUES:
2955: case INSERT_ALL_VALUES:
2956: case INSERT_BC_VALUES:
2957: isInsert = PETSC_TRUE;
2958: break;
2959: case ADD_VALUES:
2960: case ADD_ALL_VALUES:
2961: case ADD_BC_VALUES:
2962: isInsert = PETSC_FALSE;
2963: break;
2964: default:
2965: SETERRQ(PetscObjectComm((PetscObject)dm), PETSC_ERR_ARG_OUTOFRANGE, "Invalid insertion mode %d", mode);
2966: }
2967: if ((sf && !isInsert) || (s && isInsert)) {
2968: DMHasBasisTransform(dm, &transform);
2969: if (transform) {
2970: DMGetNamedLocalVector(dm, "__petsc_dm_transform_local_copy", &tmpl);
2971: VecCopy(l, tmpl);
2972: DMPlexLocalToGlobalBasis(dm, tmpl);
2973: VecGetArrayRead(tmpl, &lArray);
2974: } else if (isInsert) {
2975: VecGetArrayRead(l, &lArray);
2976: } else {
2977: VecGetArrayReadAndMemType(l, &lArray, &lmtype);
2978: l_inplace = PETSC_TRUE;
2979: }
2980: if (s && isInsert) {
2981: VecGetArray(g, &gArray);
2982: } else {
2983: VecGetArrayAndMemType(g, &gArray, &gmtype);
2984: g_inplace = PETSC_TRUE;
2985: }
2986: if (sf && !isInsert) {
2987: PetscSFReduceWithMemTypeBegin(sf, MPIU_SCALAR, lmtype, lArray, gmtype, gArray, MPIU_SUM);
2988: } else if (s && isInsert) {
2989: PetscInt gStart, pStart, pEnd, p;
2991: DMGetGlobalSection(dm, &gs);
2992: PetscSectionGetChart(s, &pStart, &pEnd);
2993: VecGetOwnershipRange(g, &gStart, NULL);
2994: for (p = pStart; p < pEnd; ++p) {
2995: PetscInt dof, gdof, cdof, gcdof, off, goff, d, e;
2997: PetscSectionGetDof(s, p, &dof);
2998: PetscSectionGetDof(gs, p, &gdof);
2999: PetscSectionGetConstraintDof(s, p, &cdof);
3000: PetscSectionGetConstraintDof(gs, p, &gcdof);
3001: PetscSectionGetOffset(s, p, &off);
3002: PetscSectionGetOffset(gs, p, &goff);
3003: /* Ignore off-process data and points with no global data */
3004: if (!gdof || goff < 0) continue;
3006: /* If no constraints are enforced in the global vector */
3007: if (!gcdof) {
3008: for (d = 0; d < dof; ++d) gArray[goff - gStart + d] = lArray[off + d];
3009: /* If constraints are enforced in the global vector */
3010: } else if (cdof == gcdof) {
3011: const PetscInt *cdofs;
3012: PetscInt cind = 0;
3014: PetscSectionGetConstraintIndices(s, p, &cdofs);
3015: for (d = 0, e = 0; d < dof; ++d) {
3016: if ((cind < cdof) && (d == cdofs[cind])) {
3017: ++cind;
3018: continue;
3019: }
3020: gArray[goff - gStart + e++] = lArray[off + d];
3021: }
3022: } 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);
3023: }
3024: }
3025: if (g_inplace) {
3026: VecRestoreArrayAndMemType(g, &gArray);
3027: } else {
3028: VecRestoreArray(g, &gArray);
3029: }
3030: if (transform) {
3031: VecRestoreArrayRead(tmpl, &lArray);
3032: DMRestoreNamedLocalVector(dm, "__petsc_dm_transform_local_copy", &tmpl);
3033: } else if (l_inplace) {
3034: VecRestoreArrayReadAndMemType(l, &lArray);
3035: } else {
3036: VecRestoreArrayRead(l, &lArray);
3037: }
3038: } else {
3039: (*dm->ops->localtoglobalbegin)(dm, l, mode == INSERT_ALL_VALUES ? INSERT_VALUES : (mode == ADD_ALL_VALUES ? ADD_VALUES : mode), g);
3040: }
3041: return 0;
3042: }
3044: /*@
3045: DMLocalToGlobalEnd - updates global vectors from local vectors
3047: Neighbor-wise Collective on dm
3049: Input Parameters:
3050: + dm - the `DM` object
3051: . l - the local vector
3052: . mode - `INSERT_VALUES` or `ADD_VALUES`
3053: - g - the global vector
3055: Level: intermediate
3057: Note:
3058: See `DMLocalToGlobalBegin()` for full details
3060: .seealso: `DMLocalToGlobalBegin()`, `DMCoarsen()`, `DMDestroy()`, `DMView()`, `DMCreateGlobalVector()`, `DMCreateInterpolation()`, `DMGlobalToLocalEnd()`, `DMGlobalToLocalEnd()`
3062: @*/
3063: PetscErrorCode DMLocalToGlobalEnd(DM dm, Vec l, InsertMode mode, Vec g)
3064: {
3065: PetscSF sf;
3066: PetscSection s;
3067: DMLocalToGlobalHookLink link;
3068: PetscBool isInsert, transform;
3071: DMGetSectionSF(dm, &sf);
3072: DMGetLocalSection(dm, &s);
3073: switch (mode) {
3074: case INSERT_VALUES:
3075: case INSERT_ALL_VALUES:
3076: isInsert = PETSC_TRUE;
3077: break;
3078: case ADD_VALUES:
3079: case ADD_ALL_VALUES:
3080: isInsert = PETSC_FALSE;
3081: break;
3082: default:
3083: SETERRQ(PetscObjectComm((PetscObject)dm), PETSC_ERR_ARG_OUTOFRANGE, "Invalid insertion mode %d", mode);
3084: }
3085: if (sf && !isInsert) {
3086: const PetscScalar *lArray;
3087: PetscScalar *gArray;
3088: Vec tmpl;
3090: DMHasBasisTransform(dm, &transform);
3091: if (transform) {
3092: DMGetNamedLocalVector(dm, "__petsc_dm_transform_local_copy", &tmpl);
3093: VecGetArrayRead(tmpl, &lArray);
3094: } else {
3095: VecGetArrayReadAndMemType(l, &lArray, NULL);
3096: }
3097: VecGetArrayAndMemType(g, &gArray, NULL);
3098: PetscSFReduceEnd(sf, MPIU_SCALAR, lArray, gArray, MPIU_SUM);
3099: if (transform) {
3100: VecRestoreArrayRead(tmpl, &lArray);
3101: DMRestoreNamedLocalVector(dm, "__petsc_dm_transform_local_copy", &tmpl);
3102: } else {
3103: VecRestoreArrayReadAndMemType(l, &lArray);
3104: }
3105: VecRestoreArrayAndMemType(g, &gArray);
3106: } else if (s && isInsert) {
3107: } else {
3108: (*dm->ops->localtoglobalend)(dm, l, mode == INSERT_ALL_VALUES ? INSERT_VALUES : (mode == ADD_ALL_VALUES ? ADD_VALUES : mode), g);
3109: }
3110: for (link = dm->ltoghook; link; link = link->next) {
3111: if (link->endhook) (*link->endhook)(dm, g, mode, l, link->ctx);
3112: }
3113: return 0;
3114: }
3116: /*@
3117: DMLocalToLocalBegin - Begins the process of mapping values from a local vector (that include ghost points
3118: that contain irrelevant values) to another local vector where the ghost
3119: points in the second are set correctly from values on other MPI ranks. Must be followed by `DMLocalToLocalEnd()`.
3121: Neighbor-wise Collective on dm
3123: Input Parameters:
3124: + dm - the `DM` object
3125: . g - the original local vector
3126: - mode - one of `INSERT_VALUES` or `ADD_VALUES`
3128: Output Parameter:
3129: . l - the local vector with correct ghost values
3131: Level: intermediate
3133: .seealso: `DMLocalToLocalEnd(), `DMCoarsen()`, `DMDestroy()`, `DMView()`, `DMCreateLocalVector()`, `DMCreateGlobalVector()`, `DMCreateInterpolation()`, `DMLocalToLocalEnd()`, `DMGlobalToLocalEnd()`, `DMLocalToGlobalBegin()`
3135: @*/
3136: PetscErrorCode DMLocalToLocalBegin(DM dm, Vec g, InsertMode mode, Vec l)
3137: {
3139: (*dm->ops->localtolocalbegin)(dm, g, mode == INSERT_ALL_VALUES ? INSERT_VALUES : (mode == ADD_ALL_VALUES ? ADD_VALUES : mode), l);
3140: return 0;
3141: }
3143: /*@
3144: DMLocalToLocalEnd - Maps from a local vector to another local vector where the ghost
3145: points in the second are set correctly. Must be preceded by `DMLocalToLocalBegin()`.
3147: Neighbor-wise Collective on dm
3149: Input Parameters:
3150: + da - the `DM` object
3151: . g - the original local vector
3152: - mode - one of `INSERT_VALUES` or `ADD_VALUES`
3154: Output Parameter:
3155: . l - the local vector with correct ghost values
3157: Level: intermediate
3159: .seealso: `DMLocalToLocalBegin()`, `DMCoarsen()`, `DMDestroy()`, `DMView()`, `DMCreateLocalVector()`, `DMCreateGlobalVector()`, `DMCreateInterpolation()`, `DMLocalToLocalBegin()`, `DMGlobalToLocalEnd()`, `DMLocalToGlobalBegin()`
3161: @*/
3162: PetscErrorCode DMLocalToLocalEnd(DM dm, Vec g, InsertMode mode, Vec l)
3163: {
3165: (*dm->ops->localtolocalend)(dm, g, mode == INSERT_ALL_VALUES ? INSERT_VALUES : (mode == ADD_ALL_VALUES ? ADD_VALUES : mode), l);
3166: return 0;
3167: }
3169: /*@
3170: DMCoarsen - Coarsens a `DM` object using a standard, non-adaptive coarsening of the underlying mesh
3172: Collective on dm
3174: Input Parameters:
3175: + dm - the `DM` object
3176: - comm - the communicator to contain the new `DM` object (or MPI_COMM_NULL)
3178: Output Parameter:
3179: . dmc - the coarsened `DM`
3181: Level: developer
3183: .seealso: `DM`, `DMRefine()`, `DMDestroy()`, `DMView()`, `DMCreateGlobalVector()`, `DMCreateInterpolation()`
3185: @*/
3186: PetscErrorCode DMCoarsen(DM dm, MPI_Comm comm, DM *dmc)
3187: {
3188: DMCoarsenHookLink link;
3191: PetscLogEventBegin(DM_Coarsen, dm, 0, 0, 0);
3192: PetscUseTypeMethod(dm, coarsen, comm, dmc);
3193: if (*dmc) {
3194: (*dmc)->bind_below = dm->bind_below; /* Propagate this from parent DM; otherwise -dm_bind_below will be useless for multigrid cases. */
3195: DMSetCoarseDM(dm, *dmc);
3196: (*dmc)->ops->creatematrix = dm->ops->creatematrix;
3197: PetscObjectCopyFortranFunctionPointers((PetscObject)dm, (PetscObject)*dmc);
3198: (*dmc)->ctx = dm->ctx;
3199: (*dmc)->levelup = dm->levelup;
3200: (*dmc)->leveldown = dm->leveldown + 1;
3201: DMSetMatType(*dmc, dm->mattype);
3202: for (link = dm->coarsenhook; link; link = link->next) {
3203: if (link->coarsenhook) (*link->coarsenhook)(dm, *dmc, link->ctx);
3204: }
3205: }
3206: PetscLogEventEnd(DM_Coarsen, dm, 0, 0, 0);
3208: return 0;
3209: }
3211: /*@C
3212: DMCoarsenHookAdd - adds a callback to be run when restricting a nonlinear problem to the coarse grid
3214: Logically Collective on fine
3216: Input Parameters:
3217: + fine - `DM` on which to run a hook when restricting to a coarser level
3218: . coarsenhook - function to run when setting up a coarser level
3219: . restricthook - function to run to update data on coarser levels (called once per `SNESSolve()`)
3220: - ctx - [optional] user-defined context for provide data for the hooks (may be NULL)
3222: Calling sequence of coarsenhook:
3223: $ coarsenhook(DM fine,DM coarse,void *ctx);
3225: + fine - fine level `DM`
3226: . coarse - coarse level `DM` to restrict problem to
3227: - ctx - optional user-defined function context
3229: Calling sequence for restricthook:
3230: $ restricthook(DM fine,Mat mrestrict,Vec rscale,Mat inject,DM coarse,void *ctx)
3231: $
3232: + fine - fine level `DM`
3233: . mrestrict - matrix restricting a fine-level solution to the coarse grid, usually the transpose of the interpolation
3234: . rscale - scaling vector for restriction
3235: . inject - matrix restricting by injection
3236: . coarse - coarse level DM to update
3237: - ctx - optional user-defined function context
3239: Level: advanced
3241: Notes:
3242: 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`.
3244: If this function is called multiple times, the hooks will be run in the order they are added.
3246: In order to compose with nonlinear preconditioning without duplicating storage, the hook should be implemented to
3247: extract the finest level information from its context (instead of from the `SNES`).
3249: The hooks are automatically called by `DMRestrict()`
3251: Fortran Note:
3252: This function is not available from Fortran.
3254: .seealso: `DMCoarsenHookRemove()`, `DMRefineHookAdd()`, `SNESFASGetInterpolation()`, `SNESFASGetInjection()`, `PetscObjectCompose()`, `PetscContainerCreate()`
3255: @*/
3256: PetscErrorCode DMCoarsenHookAdd(DM fine, PetscErrorCode (*coarsenhook)(DM, DM, void *), PetscErrorCode (*restricthook)(DM, Mat, Vec, Mat, DM, void *), void *ctx)
3257: {
3258: DMCoarsenHookLink link, *p;
3261: for (p = &fine->coarsenhook; *p; p = &(*p)->next) { /* Scan to the end of the current list of hooks */
3262: if ((*p)->coarsenhook == coarsenhook && (*p)->restricthook == restricthook && (*p)->ctx == ctx) return 0;
3263: }
3264: PetscNew(&link);
3265: link->coarsenhook = coarsenhook;
3266: link->restricthook = restricthook;
3267: link->ctx = ctx;
3268: link->next = NULL;
3269: *p = link;
3270: return 0;
3271: }
3273: /*@C
3274: DMCoarsenHookRemove - remove a callback set with `DMCoarsenHookAdd()`
3276: Logically Collective on fine
3278: Input Parameters:
3279: + fine - `DM` on which to run a hook when restricting to a coarser level
3280: . coarsenhook - function to run when setting up a coarser level
3281: . restricthook - function to run to update data on coarser levels
3282: - ctx - [optional] user-defined context for provide data for the hooks (may be NULL)
3284: Level: advanced
3286: Note:
3287: This function does nothing if the hook is not in the list.
3289: Fortran Note:
3290: This function is not available from Fortran.
3292: .seealso: `DMCoarsenHookAdd()`, `DMRefineHookAdd()`, `SNESFASGetInterpolation()`, `SNESFASGetInjection()`, `PetscObjectCompose()`, `PetscContainerCreate()`
3293: @*/
3294: PetscErrorCode DMCoarsenHookRemove(DM fine, PetscErrorCode (*coarsenhook)(DM, DM, void *), PetscErrorCode (*restricthook)(DM, Mat, Vec, Mat, DM, void *), void *ctx)
3295: {
3296: DMCoarsenHookLink link, *p;
3299: for (p = &fine->coarsenhook; *p; p = &(*p)->next) { /* Search the list of current hooks */
3300: if ((*p)->coarsenhook == coarsenhook && (*p)->restricthook == restricthook && (*p)->ctx == ctx) {
3301: link = *p;
3302: *p = link->next;
3303: PetscFree(link);
3304: break;
3305: }
3306: }
3307: return 0;
3308: }
3310: /*@
3311: DMRestrict - restricts user-defined problem data to a coarser `DM` by running hooks registered by `DMCoarsenHookAdd()`
3313: Collective if any hooks are
3315: Input Parameters:
3316: + fine - finer `DM` from which the data is obtained
3317: . restrct - restriction matrix, apply using `MatRestrict()`, usually the transpose of the interpolation
3318: . rscale - scaling vector for restriction
3319: . inject - injection matrix, also use `MatRestrict()`
3320: - coarse - coarser DM to update
3322: Level: developer
3324: Developer Note:
3325: Though this routine is called `DMRestrict()` the hooks are added with `DMCoarsenHookAdd()`, a consistent terminology would be better
3327: .seealso: `DMCoarsenHookAdd()`, `MatRestrict()`, `DMInterpolate()`, `DMRefineHookAdd()`
3328: @*/
3329: PetscErrorCode DMRestrict(DM fine, Mat restrct, Vec rscale, Mat inject, DM coarse)
3330: {
3331: DMCoarsenHookLink link;
3333: for (link = fine->coarsenhook; link; link = link->next) {
3334: if (link->restricthook) (*link->restricthook)(fine, restrct, rscale, inject, coarse, link->ctx);
3335: }
3336: return 0;
3337: }
3339: /*@C
3340: DMSubDomainHookAdd - adds a callback to be run when restricting a problem to the coarse grid
3342: Logically Collective on global
3344: Input Parameters:
3345: + global - global `DM`
3346: . ddhook - function to run to pass data to the decomposition `DM` upon its creation
3347: . restricthook - function to run to update data on block solve (at the beginning of the block solve)
3348: - ctx - [optional] user-defined context for provide data for the hooks (may be NULL)
3350: Calling sequence for ddhook:
3351: $ ddhook(DM global,DM block,void *ctx)
3353: + global - global `DM`
3354: . block - block `DM`
3355: - ctx - optional user-defined function context
3357: Calling sequence for restricthook:
3358: $ restricthook(DM global,VecScatter out,VecScatter in,DM block,void *ctx)
3360: + global - global `DM`
3361: . out - scatter to the outer (with ghost and overlap points) block vector
3362: . in - scatter to block vector values only owned locally
3363: . block - block `DM`
3364: - ctx - optional user-defined function context
3366: Level: advanced
3368: Notes:
3369: This function is only needed if auxiliary data needs to be set up on subdomain `DM`s.
3371: If this function is called multiple times, the hooks will be run in the order they are added.
3373: In order to compose with nonlinear preconditioning without duplicating storage, the hook should be implemented to
3374: extract the global information from its context (instead of from the `SNES`).
3376: Fortran Note:
3377: This function is not available from Fortran.
3379: .seealso: `DMSubDomainHookRemove()`, `DMRefineHookAdd()`, `SNESFASGetInterpolation()`, `SNESFASGetInjection()`, `PetscObjectCompose()`, `PetscContainerCreate()`
3380: @*/
3381: PetscErrorCode DMSubDomainHookAdd(DM global, PetscErrorCode (*ddhook)(DM, DM, void *), PetscErrorCode (*restricthook)(DM, VecScatter, VecScatter, DM, void *), void *ctx)
3382: {
3383: DMSubDomainHookLink link, *p;
3386: for (p = &global->subdomainhook; *p; p = &(*p)->next) { /* Scan to the end of the current list of hooks */
3387: if ((*p)->ddhook == ddhook && (*p)->restricthook == restricthook && (*p)->ctx == ctx) return 0;
3388: }
3389: PetscNew(&link);
3390: link->restricthook = restricthook;
3391: link->ddhook = ddhook;
3392: link->ctx = ctx;
3393: link->next = NULL;
3394: *p = link;
3395: return 0;
3396: }
3398: /*@C
3399: DMSubDomainHookRemove - remove a callback from the list to be run when restricting a problem to the coarse grid
3401: Logically Collective on global
3403: Input Parameters:
3404: + global - global `DM`
3405: . ddhook - function to run to pass data to the decomposition `DM` upon its creation
3406: . restricthook - function to run to update data on block solve (at the beginning of the block solve)
3407: - ctx - [optional] user-defined context for provide data for the hooks (may be NULL)
3409: Level: advanced
3411: Fortran Note:
3412: This function is not available from Fortran.
3414: .seealso: `DMSubDomainHookAdd()`, `SNESFASGetInterpolation()`, `SNESFASGetInjection()`, `PetscObjectCompose()`, `PetscContainerCreate()`
3415: @*/
3416: PetscErrorCode DMSubDomainHookRemove(DM global, PetscErrorCode (*ddhook)(DM, DM, void *), PetscErrorCode (*restricthook)(DM, VecScatter, VecScatter, DM, void *), void *ctx)
3417: {
3418: DMSubDomainHookLink link, *p;
3421: for (p = &global->subdomainhook; *p; p = &(*p)->next) { /* Search the list of current hooks */
3422: if ((*p)->ddhook == ddhook && (*p)->restricthook == restricthook && (*p)->ctx == ctx) {
3423: link = *p;
3424: *p = link->next;
3425: PetscFree(link);
3426: break;
3427: }
3428: }
3429: return 0;
3430: }
3432: /*@
3433: DMSubDomainRestrict - restricts user-defined problem data to a block `DM` by running hooks registered by `DMSubDomainHookAdd()`
3435: Collective if any hooks are
3437: Input Parameters:
3438: + fine - finer `DM` to use as a base
3439: . oscatter - scatter from domain global vector filling subdomain global vector with overlap
3440: . gscatter - scatter from domain global vector filling subdomain local vector with ghosts
3441: - coarse - coarser `DM` to update
3443: Level: developer
3445: .seealso: `DMCoarsenHookAdd()`, `MatRestrict()`
3446: @*/
3447: PetscErrorCode DMSubDomainRestrict(DM global, VecScatter oscatter, VecScatter gscatter, DM subdm)
3448: {
3449: DMSubDomainHookLink link;
3451: for (link = global->subdomainhook; link; link = link->next) {
3452: if (link->restricthook) (*link->restricthook)(global, oscatter, gscatter, subdm, link->ctx);
3453: }
3454: return 0;
3455: }
3457: /*@
3458: DMGetCoarsenLevel - Gets the number of coarsenings that have generated this `DM`.
3460: Not Collective
3462: Input Parameter:
3463: . dm - the `DM` object
3465: Output Parameter:
3466: . level - number of coarsenings
3468: Level: developer
3470: .seealso: `DMCoarsen()`, `DMSetCoarsenLevel()`, `DMGetRefineLevel()`, `DMDestroy()`, `DMView()`, `DMCreateGlobalVector()`, `DMCreateInterpolation()`
3472: @*/
3473: PetscErrorCode DMGetCoarsenLevel(DM dm, PetscInt *level)
3474: {
3477: *level = dm->leveldown;
3478: return 0;
3479: }
3481: /*@
3482: DMSetCoarsenLevel - Sets the number of coarsenings that have generated this `DM`.
3484: Collective on dm
3486: Input Parameters:
3487: + dm - the `DM` object
3488: - level - number of coarsenings
3490: Level: developer
3492: Note:
3493: This is rarely used directly, the information is automatically set when a `DM` is created with `DMCoarsen()`
3495: .seealso: `DMSetCoarsenLevel()`, `DMCoarsen()`, `DMGetCoarsenLevel()`, `DMGetRefineLevel()`, `DMDestroy()`, `DMView()`, `DMCreateGlobalVector()`, `DMCreateInterpolation()`
3496: @*/
3497: PetscErrorCode DMSetCoarsenLevel(DM dm, PetscInt level)
3498: {
3500: dm->leveldown = level;
3501: return 0;
3502: }
3504: /*@C
3505: DMRefineHierarchy - Refines a `DM` object, all levels at once
3507: Collective on dm
3509: Input Parameters:
3510: + dm - the `DM` object
3511: - nlevels - the number of levels of refinement
3513: Output Parameter:
3514: . dmf - the refined `DM` hierarchy
3516: Level: developer
3518: .seealso: `DMCoarsen()`, `DMCoarsenHierarchy()`, `DMDestroy()`, `DMView()`, `DMCreateGlobalVector()`, `DMCreateInterpolation()`
3520: @*/
3521: PetscErrorCode DMRefineHierarchy(DM dm, PetscInt nlevels, DM dmf[])
3522: {
3525: if (nlevels == 0) return 0;
3527: if (dm->ops->refinehierarchy) {
3528: PetscUseTypeMethod(dm, refinehierarchy, nlevels, dmf);
3529: } else if (dm->ops->refine) {
3530: PetscInt i;
3532: DMRefine(dm, PetscObjectComm((PetscObject)dm), &dmf[0]);
3533: for (i = 1; i < nlevels; i++) DMRefine(dmf[i - 1], PetscObjectComm((PetscObject)dm), &dmf[i]);
3534: } else SETERRQ(PetscObjectComm((PetscObject)dm), PETSC_ERR_SUP, "No RefineHierarchy for this DM yet");
3535: return 0;
3536: }
3538: /*@C
3539: DMCoarsenHierarchy - Coarsens a `DM` object, all levels at once
3541: Collective on dm
3543: Input Parameters:
3544: + dm - the `DM` object
3545: - nlevels - the number of levels of coarsening
3547: Output Parameter:
3548: . dmc - the coarsened `DM` hierarchy
3550: Level: developer
3552: .seealso: `DMCoarsen()`, `DMRefineHierarchy()`, `DMDestroy()`, `DMView()`, `DMCreateGlobalVector()`, `DMCreateInterpolation()`
3554: @*/
3555: PetscErrorCode DMCoarsenHierarchy(DM dm, PetscInt nlevels, DM dmc[])
3556: {
3559: if (nlevels == 0) return 0;
3561: if (dm->ops->coarsenhierarchy) {
3562: PetscUseTypeMethod(dm, coarsenhierarchy, nlevels, dmc);
3563: } else if (dm->ops->coarsen) {
3564: PetscInt i;
3566: DMCoarsen(dm, PetscObjectComm((PetscObject)dm), &dmc[0]);
3567: for (i = 1; i < nlevels; i++) DMCoarsen(dmc[i - 1], PetscObjectComm((PetscObject)dm), &dmc[i]);
3568: } else SETERRQ(PetscObjectComm((PetscObject)dm), PETSC_ERR_SUP, "No CoarsenHierarchy for this DM yet");
3569: return 0;
3570: }
3572: /*@C
3573: DMSetApplicationContextDestroy - Sets a user function that will be called to destroy the application context when the `DM` is destroyed
3575: Logically Collective if the function is collective
3577: Input Parameters:
3578: + dm - the `DM` object
3579: - destroy - the destroy function
3581: Level: intermediate
3583: .seealso: `DMSetApplicationContext()`, `DMView()`, `DMCreateGlobalVector()`, `DMCreateInterpolation()`, `DMCreateColoring()`, `DMCreateMatrix()`, `DMCreateMassMatrix()`, `DMGetApplicationContext()`
3585: @*/
3586: PetscErrorCode DMSetApplicationContextDestroy(DM dm, PetscErrorCode (*destroy)(void **))
3587: {
3589: dm->ctxdestroy = destroy;
3590: return 0;
3591: }
3593: /*@
3594: DMSetApplicationContext - Set a user context into a `DM` object
3596: Not Collective
3598: Input Parameters:
3599: + dm - the `DM` object
3600: - ctx - the user context
3602: Level: intermediate
3604: Note:
3605: A user context is a way to pass problem specific information that is accessable whenever the `DM` is available
3607: .seealso: `DMGetApplicationContext()`, `DMView()`, `DMCreateGlobalVector()`, `DMCreateInterpolation()`, `DMCreateColoring()`, `DMCreateMatrix()`, `DMCreateMassMatrix()`, `DMGetApplicationContext()`
3609: @*/
3610: PetscErrorCode DMSetApplicationContext(DM dm, void *ctx)
3611: {
3613: dm->ctx = ctx;
3614: return 0;
3615: }
3617: /*@
3618: DMGetApplicationContext - Gets a user context from a `DM` object
3620: Not Collective
3622: Input Parameter:
3623: . dm - the `DM` object
3625: Output Parameter:
3626: . ctx - the user context
3628: Level: intermediate
3630: Note:
3631: A user context is a way to pass problem specific information that is accessable whenever the `DM` is available
3633: .seealso: `DMGetApplicationContext()`, `DMView()`, `DMCreateGlobalVector()`, `DMCreateInterpolation()`, `DMCreateColoring()`, `DMCreateMatrix()`, `DMCreateMassMatrix()`, `DMGetApplicationContext()`
3635: @*/
3636: PetscErrorCode DMGetApplicationContext(DM dm, void *ctx)
3637: {
3639: *(void **)ctx = dm->ctx;
3640: return 0;
3641: }
3643: /*@C
3644: DMSetVariableBounds - sets a function to compute the lower and upper bound vectors for `SNESVI`.
3646: Logically Collective on dm
3648: Input Parameters:
3649: + dm - the DM object
3650: - f - the function that computes variable bounds used by SNESVI (use NULL to cancel a previous function that was set)
3652: Level: intermediate
3654: .seealso: `DMComputeVariableBounds()`, `DMHasVariableBounds()`, `DMView()`, `DMCreateGlobalVector()`, `DMCreateInterpolation()`, `DMCreateColoring()`, `DMCreateMatrix()`, `DMCreateMassMatrix()`, `DMGetApplicationContext()`,
3655: `DMSetJacobian()`
3657: @*/
3658: PetscErrorCode DMSetVariableBounds(DM dm, PetscErrorCode (*f)(DM, Vec, Vec))
3659: {
3661: dm->ops->computevariablebounds = f;
3662: return 0;
3663: }
3665: /*@
3666: DMHasVariableBounds - does the `DM` object have a variable bounds function?
3668: Not Collective
3670: Input Parameter:
3671: . dm - the `DM` object to destroy
3673: Output Parameter:
3674: . flg - `PETSC_TRUE` if the variable bounds function exists
3676: Level: developer
3678: .seealso: `DMComputeVariableBounds()`, `DMView()`, `DMCreateGlobalVector()`, `DMCreateInterpolation()`, `DMCreateColoring()`, `DMCreateMatrix()`, `DMCreateMassMatrix()`, `DMGetApplicationContext()`
3680: @*/
3681: PetscErrorCode DMHasVariableBounds(DM dm, PetscBool *flg)
3682: {
3685: *flg = (dm->ops->computevariablebounds) ? PETSC_TRUE : PETSC_FALSE;
3686: return 0;
3687: }
3689: /*@C
3690: DMComputeVariableBounds - compute variable bounds used by `SNESVI`.
3692: Logically Collective on dm
3694: Input Parameter:
3695: . dm - the `DM` object
3697: Output parameters:
3698: + xl - lower bound
3699: - xu - upper bound
3701: Level: advanced
3703: Notes:
3704: This is generally not called by users. It calls the function provided by the user with DMSetVariableBounds()
3706: .seealso: `DMHasVariableBounds()`, `DMView()`, `DMCreateGlobalVector()`, `DMCreateInterpolation()`, `DMCreateColoring()`, `DMCreateMatrix()`, `DMCreateMassMatrix()`, `DMGetApplicationContext()`
3708: @*/
3709: PetscErrorCode DMComputeVariableBounds(DM dm, Vec xl, Vec xu)
3710: {
3714: PetscUseTypeMethod(dm, computevariablebounds, xl, xu);
3715: return 0;
3716: }
3718: /*@
3719: DMHasColoring - does the `DM` object have a method of providing a coloring?
3721: Not Collective
3723: Input Parameter:
3724: . dm - the DM object
3726: Output Parameter:
3727: . flg - `PETSC_TRUE` if the `DM` has facilities for `DMCreateColoring()`.
3729: Level: developer
3731: .seealso: `DMCreateColoring()`
3733: @*/
3734: PetscErrorCode DMHasColoring(DM dm, PetscBool *flg)
3735: {
3738: *flg = (dm->ops->getcoloring) ? PETSC_TRUE : PETSC_FALSE;
3739: return 0;
3740: }
3742: /*@
3743: DMHasCreateRestriction - does the `DM` object have a method of providing a restriction?
3745: Not Collective
3747: Input Parameter:
3748: . dm - the `DM` object
3750: Output Parameter:
3751: . flg - `PETSC_TRUE` if the `DM` has facilities for `DMCreateRestriction()`.
3753: Level: developer
3755: .seealso: `DMCreateRestriction()`, `DMHasCreateInterpolation()`, `DMHasCreateInjection()`
3757: @*/
3758: PetscErrorCode DMHasCreateRestriction(DM dm, PetscBool *flg)
3759: {
3762: *flg = (dm->ops->createrestriction) ? PETSC_TRUE : PETSC_FALSE;
3763: return 0;
3764: }
3766: /*@
3767: DMHasCreateInjection - does the `DM` object have a method of providing an injection?
3769: Not Collective
3771: Input Parameter:
3772: . dm - the `DM` object
3774: Output Parameter:
3775: . flg - `PETSC_TRUE` if the `DM` has facilities for `DMCreateInjection()`.
3777: Level: developer
3779: .seealso: `DMCreateInjection()`, `DMHasCreateRestriction()`, `DMHasCreateInterpolation()`
3781: @*/
3782: PetscErrorCode DMHasCreateInjection(DM dm, PetscBool *flg)
3783: {
3786: if (dm->ops->hascreateinjection) PetscUseTypeMethod(dm, hascreateinjection, flg);
3787: else *flg = (dm->ops->createinjection) ? PETSC_TRUE : PETSC_FALSE;
3788: return 0;
3789: }
3791: PetscFunctionList DMList = NULL;
3792: PetscBool DMRegisterAllCalled = PETSC_FALSE;
3794: /*@C
3795: DMSetType - Builds a `DM`, for a particular `DM` implementation.
3797: Collective on dm
3799: Input Parameters:
3800: + dm - The `DM` object
3801: - method - The name of the `DMType`, for example `DMDA`, `DMPLEX`
3803: Options Database Key:
3804: . -dm_type <type> - Sets the `DM` type; use -help for a list of available types
3806: Level: intermediate
3808: Note:
3809: Of the `DM` is constructed by directly calling a function to construct a particular `DM`, for example, `DMDACreate2d()` or `DMPLEXCreateBoxMesh()`
3811: .seealso: `DMType`, `DMDA`, `DMPLEX`, `DMGetType()`, `DMCreate()`, `DMDACreate2d()`
3812: @*/
3813: PetscErrorCode DMSetType(DM dm, DMType method)
3814: {
3815: PetscErrorCode (*r)(DM);
3816: PetscBool match;
3819: PetscObjectTypeCompare((PetscObject)dm, method, &match);
3820: if (match) return 0;
3822: DMRegisterAll();
3823: PetscFunctionListFind(DMList, method, &r);
3826: PetscTryTypeMethod(dm, destroy);
3827: PetscMemzero(dm->ops, sizeof(*dm->ops));
3828: PetscObjectChangeTypeName((PetscObject)dm, method);
3829: (*r)(dm);
3830: return 0;
3831: }
3833: /*@C
3834: DMGetType - Gets the `DM` type name (as a string) from the `DM`.
3836: Not Collective
3838: Input Parameter:
3839: . dm - The `DM`
3841: Output Parameter:
3842: . type - The `DMType` name
3844: Level: intermediate
3846: .seealso: `DMType`, `DMDA`, `DMPLEX`, `DMSetType()`, `DMCreate()`
3847: @*/
3848: PetscErrorCode DMGetType(DM dm, DMType *type)
3849: {
3852: DMRegisterAll();
3853: *type = ((PetscObject)dm)->type_name;
3854: return 0;
3855: }
3857: /*@C
3858: DMConvert - Converts a `DM` to another `DM`, either of the same or different type.
3860: Collective on dm
3862: Input Parameters:
3863: + dm - the `DM`
3864: - newtype - new `DM` type (use "same" for the same type)
3866: Output Parameter:
3867: . M - pointer to new `DM`
3869: Notes:
3870: Cannot be used to convert a sequential `DM` to a parallel or a parallel to sequential,
3871: the MPI communicator of the generated `DM` is always the same as the communicator
3872: of the input `DM`.
3874: Level: intermediate
3876: .seealso: `DM`, `DMSetType()`, `DMCreate()`, `DMClone()`
3877: @*/
3878: PetscErrorCode DMConvert(DM dm, DMType newtype, DM *M)
3879: {
3880: DM B;
3881: char convname[256];
3882: PetscBool sametype /*, issame */;
3887: PetscObjectTypeCompare((PetscObject)dm, newtype, &sametype);
3888: /* PetscStrcmp(newtype, "same", &issame); */
3889: if (sametype) {
3890: *M = dm;
3891: PetscObjectReference((PetscObject)dm);
3892: return 0;
3893: } else {
3894: PetscErrorCode (*conv)(DM, DMType, DM *) = NULL;
3896: /*
3897: Order of precedence:
3898: 1) See if a specialized converter is known to the current DM.
3899: 2) See if a specialized converter is known to the desired DM class.
3900: 3) See if a good general converter is registered for the desired class
3901: 4) See if a good general converter is known for the current matrix.
3902: 5) Use a really basic converter.
3903: */
3905: /* 1) See if a specialized converter is known to the current DM and the desired class */
3906: PetscStrncpy(convname, "DMConvert_", sizeof(convname));
3907: PetscStrlcat(convname, ((PetscObject)dm)->type_name, sizeof(convname));
3908: PetscStrlcat(convname, "_", sizeof(convname));
3909: PetscStrlcat(convname, newtype, sizeof(convname));
3910: PetscStrlcat(convname, "_C", sizeof(convname));
3911: PetscObjectQueryFunction((PetscObject)dm, convname, &conv);
3912: if (conv) goto foundconv;
3914: /* 2) See if a specialized converter is known to the desired DM class. */
3915: DMCreate(PetscObjectComm((PetscObject)dm), &B);
3916: DMSetType(B, newtype);
3917: PetscStrncpy(convname, "DMConvert_", sizeof(convname));
3918: PetscStrlcat(convname, ((PetscObject)dm)->type_name, sizeof(convname));
3919: PetscStrlcat(convname, "_", sizeof(convname));
3920: PetscStrlcat(convname, newtype, sizeof(convname));
3921: PetscStrlcat(convname, "_C", sizeof(convname));
3922: PetscObjectQueryFunction((PetscObject)B, convname, &conv);
3923: if (conv) {
3924: DMDestroy(&B);
3925: goto foundconv;
3926: }
3928: #if 0
3929: /* 3) See if a good general converter is registered for the desired class */
3930: conv = B->ops->convertfrom;
3931: DMDestroy(&B);
3932: if (conv) goto foundconv;
3934: /* 4) See if a good general converter is known for the current matrix */
3935: if (dm->ops->convert) {
3936: conv = dm->ops->convert;
3937: }
3938: if (conv) goto foundconv;
3939: #endif
3941: /* 5) Use a really basic converter. */
3942: SETERRQ(PetscObjectComm((PetscObject)dm), PETSC_ERR_SUP, "No conversion possible between DM types %s and %s", ((PetscObject)dm)->type_name, newtype);
3944: foundconv:
3945: PetscLogEventBegin(DM_Convert, dm, 0, 0, 0);
3946: (*conv)(dm, newtype, M);
3947: /* Things that are independent of DM type: We should consult DMClone() here */
3948: {
3949: const PetscReal *maxCell, *Lstart, *L;
3951: DMGetPeriodicity(dm, &maxCell, &Lstart, &L);
3952: DMSetPeriodicity(*M, maxCell, Lstart, L);
3953: (*M)->prealloc_only = dm->prealloc_only;
3954: PetscFree((*M)->vectype);
3955: PetscStrallocpy(dm->vectype, (char **)&(*M)->vectype);
3956: PetscFree((*M)->mattype);
3957: PetscStrallocpy(dm->mattype, (char **)&(*M)->mattype);
3958: }
3959: PetscLogEventEnd(DM_Convert, dm, 0, 0, 0);
3960: }
3961: PetscObjectStateIncrease((PetscObject)*M);
3962: return 0;
3963: }
3965: /*--------------------------------------------------------------------------------------------------------------------*/
3967: /*@C
3968: DMRegister - Adds a new `DM` type implementation
3970: Not Collective
3972: Input Parameters:
3973: + name - The name of a new user-defined creation routine
3974: - create_func - The creation routine itself
3976: Notes:
3977: DMRegister() may be called multiple times to add several user-defined `DM`s
3979: Sample usage:
3980: .vb
3981: DMRegister("my_da", MyDMCreate);
3982: .ve
3984: Then, your DM type can be chosen with the procedural interface via
3985: .vb
3986: DMCreate(MPI_Comm, DM *);
3987: DMSetType(DM,"my_da");
3988: .ve
3989: or at runtime via the option
3990: .vb
3991: -da_type my_da
3992: .ve
3994: Level: advanced
3996: .seealso: `DM`, `DMType`, `DMSetType()`, `DMRegisterAll()`, `DMRegisterDestroy()`
3998: @*/
3999: PetscErrorCode DMRegister(const char sname[], PetscErrorCode (*function)(DM))
4000: {
4001: DMInitializePackage();
4002: PetscFunctionListAdd(&DMList, sname, function);
4003: return 0;
4004: }
4006: /*@C
4007: DMLoad - Loads a DM that has been stored in binary with `DMView()`.
4009: Collective on viewer
4011: Input Parameters:
4012: + newdm - the newly loaded `DM`, this needs to have been created with `DMCreate()` or
4013: some related function before a call to `DMLoad()`.
4014: - viewer - binary file viewer, obtained from `PetscViewerBinaryOpen()` or
4015: `PETSCVIEWERHDF5` file viewer, obtained from `PetscViewerHDF5Open()`
4017: Level: intermediate
4019: Notes:
4020: The type is determined by the data in the file, any type set into the DM before this call is ignored.
4022: Using `PETSCVIEWERHDF5` type with `PETSC_VIEWER_HDF5_PETSC` format, one can save multiple `DMPLEX`
4023: meshes in a single HDF5 file. This in turn requires one to name the `DMPLEX` object with `PetscObjectSetName()`
4024: before saving it with `DMView()` and before loading it with `DMLoad()` for identification of the mesh object.
4026: Notes for advanced users:
4027: Most users should not need to know the details of the binary storage
4028: format, since `DMLoad()` and `DMView()` completely hide these details.
4029: But for anyone who's interested, the standard binary matrix storage
4030: format is
4031: .vb
4032: has not yet been determined
4033: .ve
4035: .seealso: `PetscViewerBinaryOpen()`, `DMView()`, `MatLoad()`, `VecLoad()`
4036: @*/
4037: PetscErrorCode DMLoad(DM newdm, PetscViewer viewer)
4038: {
4039: PetscBool isbinary, ishdf5;
4043: PetscViewerCheckReadable(viewer);
4044: PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERBINARY, &isbinary);
4045: PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERHDF5, &ishdf5);
4046: PetscLogEventBegin(DM_Load, viewer, 0, 0, 0);
4047: if (isbinary) {
4048: PetscInt classid;
4049: char type[256];
4051: PetscViewerBinaryRead(viewer, &classid, 1, NULL, PETSC_INT);
4053: PetscViewerBinaryRead(viewer, type, 256, NULL, PETSC_CHAR);
4054: DMSetType(newdm, type);
4055: PetscTryTypeMethod(newdm, load, viewer);
4056: } else if (ishdf5) {
4057: PetscTryTypeMethod(newdm, load, viewer);
4058: } else SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Invalid viewer; open viewer with PetscViewerBinaryOpen() or PetscViewerHDF5Open()");
4059: PetscLogEventEnd(DM_Load, viewer, 0, 0, 0);
4060: return 0;
4061: }
4063: /******************************** FEM Support **********************************/
4065: PetscErrorCode DMPrintCellVector(PetscInt c, const char name[], PetscInt len, const PetscScalar x[])
4066: {
4067: PetscInt f;
4069: PetscPrintf(PETSC_COMM_SELF, "Cell %" PetscInt_FMT " Element %s\n", c, name);
4070: for (f = 0; f < len; ++f) PetscPrintf(PETSC_COMM_SELF, " | %g |\n", (double)PetscRealPart(x[f]));
4071: return 0;
4072: }
4074: PetscErrorCode DMPrintCellMatrix(PetscInt c, const char name[], PetscInt rows, PetscInt cols, const PetscScalar A[])
4075: {
4076: PetscInt f, g;
4078: PetscPrintf(PETSC_COMM_SELF, "Cell %" PetscInt_FMT " Element %s\n", c, name);
4079: for (f = 0; f < rows; ++f) {
4080: PetscPrintf(PETSC_COMM_SELF, " |");
4081: for (g = 0; g < cols; ++g) PetscPrintf(PETSC_COMM_SELF, " % 9.5g", (double)PetscRealPart(A[f * cols + g]));
4082: PetscPrintf(PETSC_COMM_SELF, " |\n");
4083: }
4084: return 0;
4085: }
4087: PetscErrorCode DMPrintLocalVec(DM dm, const char name[], PetscReal tol, Vec X)
4088: {
4089: PetscInt localSize, bs;
4090: PetscMPIInt size;
4091: Vec x, xglob;
4092: const PetscScalar *xarray;
4094: MPI_Comm_size(PetscObjectComm((PetscObject)dm), &size);
4095: VecDuplicate(X, &x);
4096: VecCopy(X, x);
4097: VecChop(x, tol);
4098: PetscPrintf(PetscObjectComm((PetscObject)dm), "%s:\n", name);
4099: if (size > 1) {
4100: VecGetLocalSize(x, &localSize);
4101: VecGetArrayRead(x, &xarray);
4102: VecGetBlockSize(x, &bs);
4103: VecCreateMPIWithArray(PetscObjectComm((PetscObject)dm), bs, localSize, PETSC_DETERMINE, xarray, &xglob);
4104: } else {
4105: xglob = x;
4106: }
4107: VecView(xglob, PETSC_VIEWER_STDOUT_(PetscObjectComm((PetscObject)dm)));
4108: if (size > 1) {
4109: VecDestroy(&xglob);
4110: VecRestoreArrayRead(x, &xarray);
4111: }
4112: VecDestroy(&x);
4113: return 0;
4114: }
4116: /*@
4117: DMGetSection - Get the `PetscSection` encoding the local data layout for the `DM`. This is equivalent to `DMGetLocalSection()`. Deprecated in v3.12
4119: Input Parameter:
4120: . dm - The `DM`
4122: Output Parameter:
4123: . section - The `PetscSection`
4125: Options Database Keys:
4126: . -dm_petscsection_view - View the `PetscSection` created by the `DM`
4128: Level: advanced
4130: Notes:
4131: Use `DMGetLocalSection()` in new code.
4133: This gets a borrowed reference, so the user should not destroy this `PetscSection`.
4135: .seealso: `DMGetLocalSection()`, `DMSetLocalSection()`, `DMGetGlobalSection()`
4136: @*/
4137: PetscErrorCode DMGetSection(DM dm, PetscSection *section)
4138: {
4139: DMGetLocalSection(dm, section);
4140: return 0;
4141: }
4143: /*@
4144: DMGetLocalSection - Get the `PetscSection` encoding the local data layout for the `DM`.
4146: Input Parameter:
4147: . dm - The `DM`
4149: Output Parameter:
4150: . section - The `PetscSection`
4152: Options Database Keys:
4153: . -dm_petscsection_view - View the section created by the `DM`
4155: Level: intermediate
4157: Note:
4158: This gets a borrowed reference, so the user should not destroy this `PetscSection`.
4160: .seealso: `DMSetLocalSection()`, `DMGetGlobalSection()`
4161: @*/
4162: PetscErrorCode DMGetLocalSection(DM dm, PetscSection *section)
4163: {
4166: if (!dm->localSection && dm->ops->createlocalsection) {
4167: PetscInt d;
4169: if (dm->setfromoptionscalled) {
4170: PetscObject obj = (PetscObject)dm;
4171: PetscViewer viewer;
4172: PetscViewerFormat format;
4173: PetscBool flg;
4175: PetscOptionsGetViewer(PetscObjectComm(obj), obj->options, obj->prefix, "-dm_petscds_view", &viewer, &format, &flg);
4176: if (flg) PetscViewerPushFormat(viewer, format);
4177: for (d = 0; d < dm->Nds; ++d) {
4178: PetscDSSetFromOptions(dm->probs[d].ds);
4179: if (flg) PetscDSView(dm->probs[d].ds, viewer);
4180: }
4181: if (flg) {
4182: PetscViewerFlush(viewer);
4183: PetscViewerPopFormat(viewer);
4184: PetscViewerDestroy(&viewer);
4185: }
4186: }
4187: PetscUseTypeMethod(dm, createlocalsection);
4188: if (dm->localSection) PetscObjectViewFromOptions((PetscObject)dm->localSection, NULL, "-dm_petscsection_view");
4189: }
4190: *section = dm->localSection;
4191: return 0;
4192: }
4194: /*@
4195: DMSetSection - Set the `PetscSection` encoding the local data layout for the `DM`. This is equivalent to `DMSetLocalSection()`. Deprecated in v3.12
4197: Input Parameters:
4198: + dm - The `DM`
4199: - section - The `PetscSection`
4201: Level: advanced
4203: Notes:
4204: Use `DMSetLocalSection()` in new code.
4206: Any existing `PetscSection` will be destroyed
4208: .seealso: `DMSetLocalSection()`, `DMGetLocalSection()`, `DMSetGlobalSection()`
4209: @*/
4210: PetscErrorCode DMSetSection(DM dm, PetscSection section)
4211: {
4212: DMSetLocalSection(dm, section);
4213: return 0;
4214: }
4216: /*@
4217: DMSetLocalSection - Set the `PetscSection` encoding the local data layout for the `DM`.
4219: Input Parameters:
4220: + dm - The `DM`
4221: - section - The `PetscSection`
4223: Level: intermediate
4225: Note:
4226: Any existing Section will be destroyed
4228: .seealso: `PetscSection`, `DMGetLocalSection()`, `DMSetGlobalSection()`
4229: @*/
4230: PetscErrorCode DMSetLocalSection(DM dm, PetscSection section)
4231: {
4232: PetscInt numFields = 0;
4233: PetscInt f;
4237: PetscObjectReference((PetscObject)section);
4238: PetscSectionDestroy(&dm->localSection);
4239: dm->localSection = section;
4240: if (section) PetscSectionGetNumFields(dm->localSection, &numFields);
4241: if (numFields) {
4242: DMSetNumFields(dm, numFields);
4243: for (f = 0; f < numFields; ++f) {
4244: PetscObject disc;
4245: const char *name;
4247: PetscSectionGetFieldName(dm->localSection, f, &name);
4248: DMGetField(dm, f, NULL, &disc);
4249: PetscObjectSetName(disc, name);
4250: }
4251: }
4252: /* The global section will be rebuilt in the next call to DMGetGlobalSection(). */
4253: PetscSectionDestroy(&dm->globalSection);
4254: return 0;
4255: }
4257: /*@
4258: DMGetDefaultConstraints - Get the `PetscSection` and `Mat` that specify the local constraint interpolation. See `DMSetDefaultConstraints()` for a description of the purpose of constraint interpolation.
4260: not collective
4262: Input Parameter:
4263: . dm - The `DM`
4265: Output Parameters:
4266: + 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.
4267: . 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.
4268: - bias - Vector containing bias to be added to constrained dofs
4270: Level: advanced
4272: Note:
4273: This gets borrowed references, so the user should not destroy the `PetscSection`, `Mat`, or `Vec`.
4275: .seealso: `DMSetDefaultConstraints()`
4276: @*/
4277: PetscErrorCode DMGetDefaultConstraints(DM dm, PetscSection *section, Mat *mat, Vec *bias)
4278: {
4280: if (!dm->defaultConstraint.section && !dm->defaultConstraint.mat && dm->ops->createdefaultconstraints) PetscUseTypeMethod(dm, createdefaultconstraints);
4281: if (section) *section = dm->defaultConstraint.section;
4282: if (mat) *mat = dm->defaultConstraint.mat;
4283: if (bias) *bias = dm->defaultConstraint.bias;
4284: return 0;
4285: }
4287: /*@
4288: DMSetDefaultConstraints - Set the `PetscSection` and `Mat` that specify the local constraint interpolation.
4290: 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()`.
4292: 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.
4294: collective on dm
4296: Input Parameters:
4297: + dm - The `DM`
4298: . 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).
4299: . 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).
4300: - 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).
4302: Level: advanced
4304: Note:
4305: This increments the references of the `PetscSection`, `Mat`, and `Vec`, so they user can destroy them.
4307: .seealso: `DMGetDefaultConstraints()`
4308: @*/
4309: PetscErrorCode DMSetDefaultConstraints(DM dm, PetscSection section, Mat mat, Vec bias)
4310: {
4311: PetscMPIInt result;
4314: if (section) {
4316: MPI_Comm_compare(PETSC_COMM_SELF, PetscObjectComm((PetscObject)section), &result);
4318: }
4319: if (mat) {
4321: MPI_Comm_compare(PETSC_COMM_SELF, PetscObjectComm((PetscObject)mat), &result);
4323: }
4324: if (bias) {
4326: MPI_Comm_compare(PETSC_COMM_SELF, PetscObjectComm((PetscObject)bias), &result);
4328: }
4329: PetscObjectReference((PetscObject)section);
4330: PetscSectionDestroy(&dm->defaultConstraint.section);
4331: dm->defaultConstraint.section = section;
4332: PetscObjectReference((PetscObject)mat);
4333: MatDestroy(&dm->defaultConstraint.mat);
4334: dm->defaultConstraint.mat = mat;
4335: PetscObjectReference((PetscObject)bias);
4336: VecDestroy(&dm->defaultConstraint.bias);
4337: dm->defaultConstraint.bias = bias;
4338: return 0;
4339: }
4341: #if defined(PETSC_USE_DEBUG)
4342: /*
4343: DMDefaultSectionCheckConsistency - Check the consistentcy of the global and local sections. Generates and error if they are not consistent.
4345: Input Parameters:
4346: + dm - The `DM`
4347: . localSection - `PetscSection` describing the local data layout
4348: - globalSection - `PetscSection` describing the global data layout
4350: Level: intermediate
4352: .seealso: `DMGetSectionSF()`, `DMSetSectionSF()`
4353: */
4354: static PetscErrorCode DMDefaultSectionCheckConsistency_Internal(DM dm, PetscSection localSection, PetscSection globalSection)
4355: {
4356: MPI_Comm comm;
4357: PetscLayout layout;
4358: const PetscInt *ranges;
4359: PetscInt pStart, pEnd, p, nroots;
4360: PetscMPIInt size, rank;
4361: PetscBool valid = PETSC_TRUE, gvalid;
4363: PetscObjectGetComm((PetscObject)dm, &comm);
4365: MPI_Comm_size(comm, &size);
4366: MPI_Comm_rank(comm, &rank);
4367: PetscSectionGetChart(globalSection, &pStart, &pEnd);
4368: PetscSectionGetConstrainedStorageSize(globalSection, &nroots);
4369: PetscLayoutCreate(comm, &layout);
4370: PetscLayoutSetBlockSize(layout, 1);
4371: PetscLayoutSetLocalSize(layout, nroots);
4372: PetscLayoutSetUp(layout);
4373: PetscLayoutGetRanges(layout, &ranges);
4374: for (p = pStart; p < pEnd; ++p) {
4375: PetscInt dof, cdof, off, gdof, gcdof, goff, gsize, d;
4377: PetscSectionGetDof(localSection, p, &dof);
4378: PetscSectionGetOffset(localSection, p, &off);
4379: PetscSectionGetConstraintDof(localSection, p, &cdof);
4380: PetscSectionGetDof(globalSection, p, &gdof);
4381: PetscSectionGetConstraintDof(globalSection, p, &gcdof);
4382: PetscSectionGetOffset(globalSection, p, &goff);
4383: if (!gdof) continue; /* Censored point */
4384: if ((gdof < 0 ? -(gdof + 1) : gdof) != dof) {
4385: PetscSynchronizedPrintf(comm, "[%d]Global dof %" PetscInt_FMT " for point %" PetscInt_FMT " not equal to local dof %" PetscInt_FMT "\n", rank, gdof, p, dof);
4386: valid = PETSC_FALSE;
4387: }
4388: if (gcdof && (gcdof != cdof)) {
4389: PetscSynchronizedPrintf(comm, "[%d]Global constraints %" PetscInt_FMT " for point %" PetscInt_FMT " not equal to local constraints %" PetscInt_FMT "\n", rank, gcdof, p, cdof);
4390: valid = PETSC_FALSE;
4391: }
4392: if (gdof < 0) {
4393: gsize = gdof < 0 ? -(gdof + 1) - gcdof : gdof - gcdof;
4394: for (d = 0; d < gsize; ++d) {
4395: PetscInt offset = -(goff + 1) + d, r;
4397: PetscFindInt(offset, size + 1, ranges, &r);
4398: if (r < 0) r = -(r + 2);
4399: if ((r < 0) || (r >= size)) {
4400: PetscSynchronizedPrintf(comm, "[%d]Point %" PetscInt_FMT " mapped to invalid process %" PetscInt_FMT " (%" PetscInt_FMT ", %" PetscInt_FMT ")\n", rank, p, r, gdof, goff);
4401: valid = PETSC_FALSE;
4402: break;
4403: }
4404: }
4405: }
4406: }
4407: PetscLayoutDestroy(&layout);
4408: PetscSynchronizedFlush(comm, NULL);
4409: MPIU_Allreduce(&valid, &gvalid, 1, MPIU_BOOL, MPI_LAND, comm);
4410: if (!gvalid) {
4411: DMView(dm, NULL);
4412: SETERRQ(comm, PETSC_ERR_ARG_WRONG, "Inconsistent local and global sections");
4413: }
4414: return 0;
4415: }
4416: #endif
4418: /*@
4419: DMGetGlobalSection - Get the `PetscSection` encoding the global data layout for the `DM`.
4421: Collective on dm
4423: Input Parameter:
4424: . dm - The `DM`
4426: Output Parameter:
4427: . section - The `PetscSection`
4429: Level: intermediate
4431: Note:
4432: This gets a borrowed reference, so the user should not destroy this `PetscSection`.
4434: .seealso: `DMSetLocalSection()`, `DMGetLocalSection()`
4435: @*/
4436: PetscErrorCode DMGetGlobalSection(DM dm, PetscSection *section)
4437: {
4440: if (!dm->globalSection) {
4441: PetscSection s;
4443: DMGetLocalSection(dm, &s);
4446: PetscSectionCreateGlobalSection(s, dm->sf, PETSC_FALSE, PETSC_FALSE, &dm->globalSection);
4447: PetscLayoutDestroy(&dm->map);
4448: PetscSectionGetValueLayout(PetscObjectComm((PetscObject)dm), dm->globalSection, &dm->map);
4449: PetscSectionViewFromOptions(dm->globalSection, NULL, "-global_section_view");
4450: }
4451: *section = dm->globalSection;
4452: return 0;
4453: }
4455: /*@
4456: DMSetGlobalSection - Set the `PetscSection` encoding the global data layout for the `DM`.
4458: Input Parameters:
4459: + dm - The `DM`
4460: - section - The PetscSection, or NULL
4462: Level: intermediate
4464: Note:
4465: Any existing `PetscSection` will be destroyed
4467: .seealso: `DMGetGlobalSection()`, `DMSetLocalSection()`
4468: @*/
4469: PetscErrorCode DMSetGlobalSection(DM dm, PetscSection section)
4470: {
4473: PetscObjectReference((PetscObject)section);
4474: PetscSectionDestroy(&dm->globalSection);
4475: dm->globalSection = section;
4476: #if defined(PETSC_USE_DEBUG)
4477: if (section) DMDefaultSectionCheckConsistency_Internal(dm, dm->localSection, section);
4478: #endif
4479: return 0;
4480: }
4482: /*@
4483: DMGetSectionSF - Get the `PetscSF` encoding the parallel dof overlap for the `DM`. If it has not been set,
4484: it is created from the default `PetscSection` layouts in the `DM`.
4486: Input Parameter:
4487: . dm - The `DM`
4489: Output Parameter:
4490: . sf - The `PetscSF`
4492: Level: intermediate
4494: Note:
4495: This gets a borrowed reference, so the user should not destroy this `PetscSF`.
4497: .seealso: `DMSetSectionSF()`, `DMCreateSectionSF()`
4498: @*/
4499: PetscErrorCode DMGetSectionSF(DM dm, PetscSF *sf)
4500: {
4501: PetscInt nroots;
4505: if (!dm->sectionSF) PetscSFCreate(PetscObjectComm((PetscObject)dm), &dm->sectionSF);
4506: PetscSFGetGraph(dm->sectionSF, &nroots, NULL, NULL, NULL);
4507: if (nroots < 0) {
4508: PetscSection section, gSection;
4510: DMGetLocalSection(dm, §ion);
4511: if (section) {
4512: DMGetGlobalSection(dm, &gSection);
4513: DMCreateSectionSF(dm, section, gSection);
4514: } else {
4515: *sf = NULL;
4516: return 0;
4517: }
4518: }
4519: *sf = dm->sectionSF;
4520: return 0;
4521: }
4523: /*@
4524: DMSetSectionSF - Set the `PetscSF` encoding the parallel dof overlap for the `DM`
4526: Input Parameters:
4527: + dm - The `DM`
4528: - sf - The `PetscSF`
4530: Level: intermediate
4532: Note:
4533: Any previous `PetscSF` is destroyed
4535: .seealso: `DMGetSectionSF()`, `DMCreateSectionSF()`
4536: @*/
4537: PetscErrorCode DMSetSectionSF(DM dm, PetscSF sf)
4538: {
4541: PetscObjectReference((PetscObject)sf);
4542: PetscSFDestroy(&dm->sectionSF);
4543: dm->sectionSF = sf;
4544: return 0;
4545: }
4547: /*@C
4548: DMCreateSectionSF - Create the `PetscSF` encoding the parallel dof overlap for the `DM` based upon the `PetscSection`s
4549: describing the data layout.
4551: Input Parameters:
4552: + dm - The `DM`
4553: . localSection - `PetscSection` describing the local data layout
4554: - globalSection - `PetscSection` describing the global data layout
4556: Level: developer
4558: Note:
4559: One usually uses `DMGetSectionSF()` to obtain the `PetscSF`
4561: Developer Note:
4562: Since this routine has for arguments the two sections from the `DM` and puts the resulting `PetscSF`
4563: directly into the `DM`, perhaps this function should not take the local and global sections as
4564: input and should just obtain them from the `DM`?
4566: .seealso: `DMGetSectionSF()`, `DMSetSectionSF()`, `DMGetLocalSection()`, `DMGetGlobalSection()`
4567: @*/
4568: PetscErrorCode DMCreateSectionSF(DM dm, PetscSection localSection, PetscSection globalSection)
4569: {
4571: PetscSFSetGraphSection(dm->sectionSF, localSection, globalSection);
4572: return 0;
4573: }
4575: /*@
4576: DMGetPointSF - Get the `PetscSF` encoding the parallel section point overlap for the `DM`.
4578: Not collective but the resulting `PetscSF` is collective
4580: Input Parameter:
4581: . dm - The `DM`
4583: Output Parameter:
4584: . sf - The `PetscSF`
4586: Level: intermediate
4588: Note:
4589: This gets a borrowed reference, so the user should not destroy this `PetscSF`.
4591: .seealso: `DMSetPointSF()`, `DMGetSectionSF()`, `DMSetSectionSF()`, `DMCreateSectionSF()`
4592: @*/
4593: PetscErrorCode DMGetPointSF(DM dm, PetscSF *sf)
4594: {
4597: *sf = dm->sf;
4598: return 0;
4599: }
4601: /*@
4602: DMSetPointSF - Set the `PetscSF` encoding the parallel section point overlap for the `DM`.
4604: Collective on dm
4606: Input Parameters:
4607: + dm - The `DM`
4608: - sf - The` PetscSF`
4610: Level: intermediate
4612: .seealso: `DMGetPointSF()`, `DMGetSectionSF()`, `DMSetSectionSF()`, `DMCreateSectionSF()`
4613: @*/
4614: PetscErrorCode DMSetPointSF(DM dm, PetscSF sf)
4615: {
4618: PetscObjectReference((PetscObject)sf);
4619: PetscSFDestroy(&dm->sf);
4620: dm->sf = sf;
4621: return 0;
4622: }
4624: /*@
4625: DMGetNaturalSF - Get the `PetscSF` encoding the map back to the original mesh ordering
4627: Input Parameter:
4628: . dm - The `DM`
4630: Output Parameter:
4631: . sf - The `PetscSF`
4633: Level: intermediate
4635: Note:
4636: This gets a borrowed reference, so the user should not destroy this `PetscSF`.
4638: .seealso: `DMSetNaturalSF()`, `DMSetUseNatural()`, `DMGetUseNatural()`, `DMPlexCreateGlobalToNaturalSF()`, `DMPlexDistribute()`
4639: @*/
4640: PetscErrorCode DMGetNaturalSF(DM dm, PetscSF *sf)
4641: {
4644: *sf = dm->sfNatural;
4645: return 0;
4646: }
4648: /*@
4649: DMSetNaturalSF - Set the PetscSF encoding the map back to the original mesh ordering
4651: Input Parameters:
4652: + dm - The DM
4653: - sf - The PetscSF
4655: Level: intermediate
4657: .seealso: `DMGetNaturalSF()`, `DMSetUseNatural()`, `DMGetUseNatural()`, `DMPlexCreateGlobalToNaturalSF()`, `DMPlexDistribute()`
4658: @*/
4659: PetscErrorCode DMSetNaturalSF(DM dm, PetscSF sf)
4660: {
4663: PetscObjectReference((PetscObject)sf);
4664: PetscSFDestroy(&dm->sfNatural);
4665: dm->sfNatural = sf;
4666: return 0;
4667: }
4669: static PetscErrorCode DMSetDefaultAdjacency_Private(DM dm, PetscInt f, PetscObject disc)
4670: {
4671: PetscClassId id;
4673: PetscObjectGetClassId(disc, &id);
4674: if (id == PETSCFE_CLASSID) {
4675: DMSetAdjacency(dm, f, PETSC_FALSE, PETSC_TRUE);
4676: } else if (id == PETSCFV_CLASSID) {
4677: DMSetAdjacency(dm, f, PETSC_TRUE, PETSC_FALSE);
4678: } else {
4679: DMSetAdjacency(dm, f, PETSC_FALSE, PETSC_TRUE);
4680: }
4681: return 0;
4682: }
4684: static PetscErrorCode DMFieldEnlarge_Static(DM dm, PetscInt NfNew)
4685: {
4686: RegionField *tmpr;
4687: PetscInt Nf = dm->Nf, f;
4689: if (Nf >= NfNew) return 0;
4690: PetscMalloc1(NfNew, &tmpr);
4691: for (f = 0; f < Nf; ++f) tmpr[f] = dm->fields[f];
4692: for (f = Nf; f < NfNew; ++f) {
4693: tmpr[f].disc = NULL;
4694: tmpr[f].label = NULL;
4695: tmpr[f].avoidTensor = PETSC_FALSE;
4696: }
4697: PetscFree(dm->fields);
4698: dm->Nf = NfNew;
4699: dm->fields = tmpr;
4700: return 0;
4701: }
4703: /*@
4704: DMClearFields - Remove all fields from the DM
4706: Logically collective on dm
4708: Input Parameter:
4709: . dm - The DM
4711: Level: intermediate
4713: .seealso: `DMGetNumFields()`, `DMSetNumFields()`, `DMSetField()`
4714: @*/
4715: PetscErrorCode DMClearFields(DM dm)
4716: {
4717: PetscInt f;
4720: for (f = 0; f < dm->Nf; ++f) {
4721: PetscObjectDestroy(&dm->fields[f].disc);
4722: DMLabelDestroy(&dm->fields[f].label);
4723: }
4724: PetscFree(dm->fields);
4725: dm->fields = NULL;
4726: dm->Nf = 0;
4727: return 0;
4728: }
4730: /*@
4731: DMGetNumFields - Get the number of fields in the DM
4733: Not collective
4735: Input Parameter:
4736: . dm - The DM
4738: Output Parameter:
4739: . Nf - The number of fields
4741: Level: intermediate
4743: .seealso: `DMSetNumFields()`, `DMSetField()`
4744: @*/
4745: PetscErrorCode DMGetNumFields(DM dm, PetscInt *numFields)
4746: {
4749: *numFields = dm->Nf;
4750: return 0;
4751: }
4753: /*@
4754: DMSetNumFields - Set the number of fields in the DM
4756: Logically collective on dm
4758: Input Parameters:
4759: + dm - The DM
4760: - Nf - The number of fields
4762: Level: intermediate
4764: .seealso: `DMGetNumFields()`, `DMSetField()`
4765: @*/
4766: PetscErrorCode DMSetNumFields(DM dm, PetscInt numFields)
4767: {
4768: PetscInt Nf, f;
4771: DMGetNumFields(dm, &Nf);
4772: for (f = Nf; f < numFields; ++f) {
4773: PetscContainer obj;
4775: PetscContainerCreate(PetscObjectComm((PetscObject)dm), &obj);
4776: DMAddField(dm, NULL, (PetscObject)obj);
4777: PetscContainerDestroy(&obj);
4778: }
4779: return 0;
4780: }
4782: /*@
4783: DMGetField - Return the `DMLabel` and discretization object for a given `DM` field
4785: Not collective
4787: Input Parameters:
4788: + dm - The `DM`
4789: - f - The field number
4791: Output Parameters:
4792: + label - The label indicating the support of the field, or NULL for the entire mesh (pass in NULL if not needed)
4793: - disc - The discretization object (pass in NULL if not needed)
4795: Level: intermediate
4797: .seealso: `DMAddField()`, `DMSetField()`
4798: @*/
4799: PetscErrorCode DMGetField(DM dm, PetscInt f, DMLabel *label, PetscObject *disc)
4800: {
4804: if (label) *label = dm->fields[f].label;
4805: if (disc) *disc = dm->fields[f].disc;
4806: return 0;
4807: }
4809: /* Does not clear the DS */
4810: PetscErrorCode DMSetField_Internal(DM dm, PetscInt f, DMLabel label, PetscObject disc)
4811: {
4812: DMFieldEnlarge_Static(dm, f + 1);
4813: DMLabelDestroy(&dm->fields[f].label);
4814: PetscObjectDestroy(&dm->fields[f].disc);
4815: dm->fields[f].label = label;
4816: dm->fields[f].disc = disc;
4817: PetscObjectReference((PetscObject)label);
4818: PetscObjectReference((PetscObject)disc);
4819: return 0;
4820: }
4822: /*@
4823: DMSetField - Set the discretization object for a given `DM` field. Usually one would call `DMAddField()` which automatically handles
4824: the field numbering.
4826: Logically collective on dm
4828: Input Parameters:
4829: + dm - The `DM`
4830: . f - The field number
4831: . label - The label indicating the support of the field, or NULL for the entire mesh
4832: - disc - The discretization object
4834: Level: intermediate
4836: .seealso: `DMAddField()`, `DMGetField()`
4837: @*/
4838: PetscErrorCode DMSetField(DM dm, PetscInt f, DMLabel label, PetscObject disc)
4839: {
4844: DMSetField_Internal(dm, f, label, disc);
4845: DMSetDefaultAdjacency_Private(dm, f, disc);
4846: DMClearDS(dm);
4847: return 0;
4848: }
4850: /*@
4851: DMAddField - Add a field to a `DM` object. A field is a function space defined by of a set of discretization points (geometric entities)
4852: and a discretization object that defines the function space associated with those points.
4854: Logically collective on dm
4856: Input Parameters:
4857: + dm - The `DM`
4858: . label - The label indicating the support of the field, or NULL for the entire mesh
4859: - disc - The discretization object
4861: Level: intermediate
4863: Notes:
4864: The label already exists or will be added to the `DM` with `DMSetLabel()`.
4866: For example, a piecewise continous pressure field can be defined by coefficients at the cell centers of a mesh and piecewise constant functions
4867: 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
4868: geometry entities, a `DMLabel` indicating a subset of those geometric entities, and a discretization object, such as a `PetscFE`.
4870: .seealso: `DMSetLabel()`, `DMSetField()`, `DMGetField()`, `PetscFE`
4871: @*/
4872: PetscErrorCode DMAddField(DM dm, DMLabel label, PetscObject disc)
4873: {
4874: PetscInt Nf = dm->Nf;
4879: DMFieldEnlarge_Static(dm, Nf + 1);
4880: dm->fields[Nf].label = label;
4881: dm->fields[Nf].disc = disc;
4882: PetscObjectReference((PetscObject)label);
4883: PetscObjectReference((PetscObject)disc);
4884: DMSetDefaultAdjacency_Private(dm, Nf, disc);
4885: DMClearDS(dm);
4886: return 0;
4887: }
4889: /*@
4890: DMSetFieldAvoidTensor - Set flag to avoid defining the field on tensor cells
4892: Logically collective on dm
4894: Input Parameters:
4895: + dm - The `DM`
4896: . f - The field index
4897: - avoidTensor - `PETSC_TRUE` to skip defining the field on tensor cells
4899: Level: intermediate
4901: .seealso: `DMGetFieldAvoidTensor()`, `DMSetField()`, `DMGetField()`
4902: @*/
4903: PetscErrorCode DMSetFieldAvoidTensor(DM dm, PetscInt f, PetscBool avoidTensor)
4904: {
4906: dm->fields[f].avoidTensor = avoidTensor;
4907: return 0;
4908: }
4910: /*@
4911: DMGetFieldAvoidTensor - Get flag to avoid defining the field on tensor cells
4913: Not collective
4915: Input Parameters:
4916: + dm - The `DM`
4917: - f - The field index
4919: Output Parameter:
4920: . avoidTensor - The flag to avoid defining the field on tensor cells
4922: Level: intermediate
4924: .seealso: `DMAddField()`, `DMSetField()`, `DMGetField()`, `DMSetFieldAvoidTensor()`, `DMSetField()`, `DMGetField()`
4925: @*/
4926: PetscErrorCode DMGetFieldAvoidTensor(DM dm, PetscInt f, PetscBool *avoidTensor)
4927: {
4929: *avoidTensor = dm->fields[f].avoidTensor;
4930: return 0;
4931: }
4933: /*@
4934: DMCopyFields - Copy the discretizations for the `DM` into another `DM`
4936: Collective on dm
4938: Input Parameter:
4939: . dm - The `DM`
4941: Output Parameter:
4942: . newdm - The `DM`
4944: Level: advanced
4946: .seealso: `DMGetField()`, `DMSetField()`, `DMAddField()`, `DMCopyDS()`, `DMGetDS()`, `DMGetCellDS()`
4947: @*/
4948: PetscErrorCode DMCopyFields(DM dm, DM newdm)
4949: {
4950: PetscInt Nf, f;
4952: if (dm == newdm) return 0;
4953: DMGetNumFields(dm, &Nf);
4954: DMClearFields(newdm);
4955: for (f = 0; f < Nf; ++f) {
4956: DMLabel label;
4957: PetscObject field;
4958: PetscBool useCone, useClosure;
4960: DMGetField(dm, f, &label, &field);
4961: DMSetField(newdm, f, label, field);
4962: DMGetAdjacency(dm, f, &useCone, &useClosure);
4963: DMSetAdjacency(newdm, f, useCone, useClosure);
4964: }
4965: return 0;
4966: }
4968: /*@
4969: DMGetAdjacency - Returns the flags for determining variable influence
4971: Not collective
4973: Input Parameters:
4974: + dm - The DM object
4975: - f - The field number, or PETSC_DEFAULT for the default adjacency
4977: Output Parameters:
4978: + useCone - Flag for variable influence starting with the cone operation
4979: - useClosure - Flag for variable influence using transitive closure
4981: Notes:
4982: $ FEM: Two points p and q are adjacent if q \in closure(star(p)), useCone = PETSC_FALSE, useClosure = PETSC_TRUE
4983: $ FVM: Two points p and q are adjacent if q \in support(p+cone(p)), useCone = PETSC_TRUE, useClosure = PETSC_FALSE
4984: $ FVM++: Two points p and q are adjacent if q \in star(closure(p)), useCone = PETSC_TRUE, useClosure = PETSC_TRUE
4985: Further explanation can be found in the User's Manual Section on the Influence of Variables on One Another.
4987: Level: developer
4989: .seealso: `DMSetAdjacency()`, `DMGetField()`, `DMSetField()`
4990: @*/
4991: PetscErrorCode DMGetAdjacency(DM dm, PetscInt f, PetscBool *useCone, PetscBool *useClosure)
4992: {
4996: if (f < 0) {
4997: if (useCone) *useCone = dm->adjacency[0];
4998: if (useClosure) *useClosure = dm->adjacency[1];
4999: } else {
5000: PetscInt Nf;
5002: DMGetNumFields(dm, &Nf);
5004: if (useCone) *useCone = dm->fields[f].adjacency[0];
5005: if (useClosure) *useClosure = dm->fields[f].adjacency[1];
5006: }
5007: return 0;
5008: }
5010: /*@
5011: DMSetAdjacency - Set the flags for determining variable influence
5013: Not collective
5015: Input Parameters:
5016: + dm - The DM object
5017: . f - The field number
5018: . useCone - Flag for variable influence starting with the cone operation
5019: - useClosure - Flag for variable influence using transitive closure
5021: Notes:
5022: $ FEM: Two points p and q are adjacent if q \in closure(star(p)), useCone = PETSC_FALSE, useClosure = PETSC_TRUE
5023: $ FVM: Two points p and q are adjacent if q \in support(p+cone(p)), useCone = PETSC_TRUE, useClosure = PETSC_FALSE
5024: $ FVM++: Two points p and q are adjacent if q \in star(closure(p)), useCone = PETSC_TRUE, useClosure = PETSC_TRUE
5025: Further explanation can be found in the User's Manual Section on the Influence of Variables on One Another.
5027: Level: developer
5029: .seealso: `DMGetAdjacency()`, `DMGetField()`, `DMSetField()`
5030: @*/
5031: PetscErrorCode DMSetAdjacency(DM dm, PetscInt f, PetscBool useCone, PetscBool useClosure)
5032: {
5034: if (f < 0) {
5035: dm->adjacency[0] = useCone;
5036: dm->adjacency[1] = useClosure;
5037: } else {
5038: PetscInt Nf;
5040: DMGetNumFields(dm, &Nf);
5042: dm->fields[f].adjacency[0] = useCone;
5043: dm->fields[f].adjacency[1] = useClosure;
5044: }
5045: return 0;
5046: }
5048: /*@
5049: DMGetBasicAdjacency - Returns the flags for determining variable influence, using either the default or field 0 if it is defined
5051: Not collective
5053: Input Parameter:
5054: . dm - The DM object
5056: Output Parameters:
5057: + useCone - Flag for variable influence starting with the cone operation
5058: - useClosure - Flag for variable influence using transitive closure
5060: Notes:
5061: $ FEM: Two points p and q are adjacent if q \in closure(star(p)), useCone = PETSC_FALSE, useClosure = PETSC_TRUE
5062: $ FVM: Two points p and q are adjacent if q \in support(p+cone(p)), useCone = PETSC_TRUE, useClosure = PETSC_FALSE
5063: $ FVM++: Two points p and q are adjacent if q \in star(closure(p)), useCone = PETSC_TRUE, useClosure = PETSC_TRUE
5065: Level: developer
5067: .seealso: `DMSetBasicAdjacency()`, `DMGetField()`, `DMSetField()`
5068: @*/
5069: PetscErrorCode DMGetBasicAdjacency(DM dm, PetscBool *useCone, PetscBool *useClosure)
5070: {
5071: PetscInt Nf;
5076: DMGetNumFields(dm, &Nf);
5077: if (!Nf) {
5078: DMGetAdjacency(dm, PETSC_DEFAULT, useCone, useClosure);
5079: } else {
5080: DMGetAdjacency(dm, 0, useCone, useClosure);
5081: }
5082: return 0;
5083: }
5085: /*@
5086: DMSetBasicAdjacency - Set the flags for determining variable influence, using either the default or field 0 if it is defined
5088: Not collective
5090: Input Parameters:
5091: + dm - The DM object
5092: . useCone - Flag for variable influence starting with the cone operation
5093: - useClosure - Flag for variable influence using transitive closure
5095: Notes:
5096: $ FEM: Two points p and q are adjacent if q \in closure(star(p)), useCone = PETSC_FALSE, useClosure = PETSC_TRUE
5097: $ FVM: Two points p and q are adjacent if q \in support(p+cone(p)), useCone = PETSC_TRUE, useClosure = PETSC_FALSE
5098: $ FVM++: Two points p and q are adjacent if q \in star(closure(p)), useCone = PETSC_TRUE, useClosure = PETSC_TRUE
5100: Level: developer
5102: .seealso: `DMGetBasicAdjacency()`, `DMGetField()`, `DMSetField()`
5103: @*/
5104: PetscErrorCode DMSetBasicAdjacency(DM dm, PetscBool useCone, PetscBool useClosure)
5105: {
5106: PetscInt Nf;
5109: DMGetNumFields(dm, &Nf);
5110: if (!Nf) {
5111: DMSetAdjacency(dm, PETSC_DEFAULT, useCone, useClosure);
5112: } else {
5113: DMSetAdjacency(dm, 0, useCone, useClosure);
5114: }
5115: return 0;
5116: }
5118: PetscErrorCode DMCompleteBCLabels_Internal(DM dm)
5119: {
5120: DM plex;
5121: DMLabel *labels, *glabels;
5122: const char **names;
5123: char *sendNames, *recvNames;
5124: PetscInt Nds, s, maxLabels = 0, maxLen = 0, gmaxLen, Nl = 0, gNl, l, gl, m;
5125: size_t len;
5126: MPI_Comm comm;
5127: PetscMPIInt rank, size, p, *counts, *displs;
5129: PetscObjectGetComm((PetscObject)dm, &comm);
5130: MPI_Comm_size(comm, &size);
5131: MPI_Comm_rank(comm, &rank);
5132: DMGetNumDS(dm, &Nds);
5133: for (s = 0; s < Nds; ++s) {
5134: PetscDS dsBC;
5135: PetscInt numBd;
5137: DMGetRegionNumDS(dm, s, NULL, NULL, &dsBC);
5138: PetscDSGetNumBoundary(dsBC, &numBd);
5139: maxLabels += numBd;
5140: }
5141: PetscCalloc1(maxLabels, &labels);
5142: /* Get list of labels to be completed */
5143: for (s = 0; s < Nds; ++s) {
5144: PetscDS dsBC;
5145: PetscInt numBd, bd;
5147: DMGetRegionNumDS(dm, s, NULL, NULL, &dsBC);
5148: PetscDSGetNumBoundary(dsBC, &numBd);
5149: for (bd = 0; bd < numBd; ++bd) {
5150: DMLabel label;
5151: PetscInt field;
5152: PetscObject obj;
5153: PetscClassId id;
5155: PetscDSGetBoundary(dsBC, bd, NULL, NULL, NULL, &label, NULL, NULL, &field, NULL, NULL, NULL, NULL, NULL);
5156: DMGetField(dm, field, NULL, &obj);
5157: PetscObjectGetClassId(obj, &id);
5158: if (!(id == PETSCFE_CLASSID) || !label) continue;
5159: for (l = 0; l < Nl; ++l)
5160: if (labels[l] == label) break;
5161: if (l == Nl) labels[Nl++] = label;
5162: }
5163: }
5164: /* Get label names */
5165: PetscMalloc1(Nl, &names);
5166: for (l = 0; l < Nl; ++l) PetscObjectGetName((PetscObject)labels[l], &names[l]);
5167: for (l = 0; l < Nl; ++l) {
5168: PetscStrlen(names[l], &len);
5169: maxLen = PetscMax(maxLen, (PetscInt)len + 2);
5170: }
5171: PetscFree(labels);
5172: MPI_Allreduce(&maxLen, &gmaxLen, 1, MPIU_INT, MPI_MAX, comm);
5173: PetscCalloc1(Nl * gmaxLen, &sendNames);
5174: for (l = 0; l < Nl; ++l) PetscStrcpy(&sendNames[gmaxLen * l], names[l]);
5175: PetscFree(names);
5176: /* Put all names on all processes */
5177: PetscCalloc2(size, &counts, size + 1, &displs);
5178: MPI_Allgather(&Nl, 1, MPI_INT, counts, 1, MPI_INT, comm);
5179: for (p = 0; p < size; ++p) displs[p + 1] = displs[p] + counts[p];
5180: gNl = displs[size];
5181: for (p = 0; p < size; ++p) {
5182: counts[p] *= gmaxLen;
5183: displs[p] *= gmaxLen;
5184: }
5185: PetscCalloc2(gNl * gmaxLen, &recvNames, gNl, &glabels);
5186: MPI_Allgatherv(sendNames, counts[rank], MPI_CHAR, recvNames, counts, displs, MPI_CHAR, comm);
5187: PetscFree2(counts, displs);
5188: PetscFree(sendNames);
5189: for (l = 0, gl = 0; l < gNl; ++l) {
5190: DMGetLabel(dm, &recvNames[l * gmaxLen], &glabels[gl]);
5192: for (m = 0; m < gl; ++m)
5193: if (glabels[m] == glabels[gl]) continue;
5194: DMConvert(dm, DMPLEX, &plex);
5195: DMPlexLabelComplete(plex, glabels[gl]);
5196: DMDestroy(&plex);
5197: ++gl;
5198: }
5199: PetscFree2(recvNames, glabels);
5200: return 0;
5201: }
5203: static PetscErrorCode DMDSEnlarge_Static(DM dm, PetscInt NdsNew)
5204: {
5205: DMSpace *tmpd;
5206: PetscInt Nds = dm->Nds, s;
5208: if (Nds >= NdsNew) return 0;
5209: PetscMalloc1(NdsNew, &tmpd);
5210: for (s = 0; s < Nds; ++s) tmpd[s] = dm->probs[s];
5211: for (s = Nds; s < NdsNew; ++s) {
5212: tmpd[s].ds = NULL;
5213: tmpd[s].label = NULL;
5214: tmpd[s].fields = NULL;
5215: }
5216: PetscFree(dm->probs);
5217: dm->Nds = NdsNew;
5218: dm->probs = tmpd;
5219: return 0;
5220: }
5222: /*@
5223: DMGetNumDS - Get the number of discrete systems in the DM
5225: Not collective
5227: Input Parameter:
5228: . dm - The DM
5230: Output Parameter:
5231: . Nds - The number of PetscDS objects
5233: Level: intermediate
5235: .seealso: `DMGetDS()`, `DMGetCellDS()`
5236: @*/
5237: PetscErrorCode DMGetNumDS(DM dm, PetscInt *Nds)
5238: {
5241: *Nds = dm->Nds;
5242: return 0;
5243: }
5245: /*@
5246: DMClearDS - Remove all discrete systems from the DM
5248: Logically collective on dm
5250: Input Parameter:
5251: . dm - The DM
5253: Level: intermediate
5255: .seealso: `DMGetNumDS()`, `DMGetDS()`, `DMSetField()`
5256: @*/
5257: PetscErrorCode DMClearDS(DM dm)
5258: {
5259: PetscInt s;
5262: for (s = 0; s < dm->Nds; ++s) {
5263: PetscDSDestroy(&dm->probs[s].ds);
5264: DMLabelDestroy(&dm->probs[s].label);
5265: ISDestroy(&dm->probs[s].fields);
5266: }
5267: PetscFree(dm->probs);
5268: dm->probs = NULL;
5269: dm->Nds = 0;
5270: return 0;
5271: }
5273: /*@
5274: DMGetDS - Get the default PetscDS
5276: Not collective
5278: Input Parameter:
5279: . dm - The DM
5281: Output Parameter:
5282: . prob - The default PetscDS
5284: Level: intermediate
5286: .seealso: `DMGetCellDS()`, `DMGetRegionDS()`
5287: @*/
5288: PetscErrorCode DMGetDS(DM dm, PetscDS *prob)
5289: {
5293: if (dm->Nds <= 0) {
5294: PetscDS ds;
5296: PetscDSCreate(PETSC_COMM_SELF, &ds);
5297: DMSetRegionDS(dm, NULL, NULL, ds);
5298: PetscDSDestroy(&ds);
5299: }
5300: *prob = dm->probs[0].ds;
5301: return 0;
5302: }
5304: /*@
5305: DMGetCellDS - Get the PetscDS defined on a given cell
5307: Not collective
5309: Input Parameters:
5310: + dm - The DM
5311: - point - Cell for the DS
5313: Output Parameter:
5314: . prob - The PetscDS defined on the given cell
5316: Level: developer
5318: .seealso: `DMGetDS()`, `DMSetRegionDS()`
5319: @*/
5320: PetscErrorCode DMGetCellDS(DM dm, PetscInt point, PetscDS *prob)
5321: {
5322: PetscDS probDef = NULL;
5323: PetscInt s;
5329: *prob = NULL;
5330: for (s = 0; s < dm->Nds; ++s) {
5331: PetscInt val;
5333: if (!dm->probs[s].label) {
5334: probDef = dm->probs[s].ds;
5335: } else {
5336: DMLabelGetValue(dm->probs[s].label, point, &val);
5337: if (val >= 0) {
5338: *prob = dm->probs[s].ds;
5339: break;
5340: }
5341: }
5342: }
5343: if (!*prob) *prob = probDef;
5344: return 0;
5345: }
5347: /*@
5348: DMGetRegionDS - Get the PetscDS for a given mesh region, defined by a DMLabel
5350: Not collective
5352: Input Parameters:
5353: + dm - The DM
5354: - label - The DMLabel defining the mesh region, or NULL for the entire mesh
5356: Output Parameters:
5357: + fields - The IS containing the DM field numbers for the fields in this DS, or NULL
5358: - prob - The PetscDS defined on the given region, or NULL
5360: Note:
5361: If a non-NULL label is given, but there is no PetscDS on that specific label,
5362: the PetscDS for the full domain (if present) is returned. Returns with
5363: fields=NULL and prob=NULL if there is no PetscDS for the full domain.
5365: Level: advanced
5367: .seealso: `DMGetRegionNumDS()`, `DMSetRegionDS()`, `DMGetDS()`, `DMGetCellDS()`
5368: @*/
5369: PetscErrorCode DMGetRegionDS(DM dm, DMLabel label, IS *fields, PetscDS *ds)
5370: {
5371: PetscInt Nds = dm->Nds, s;
5375: if (fields) {
5377: *fields = NULL;
5378: }
5379: if (ds) {
5381: *ds = NULL;
5382: }
5383: for (s = 0; s < Nds; ++s) {
5384: if (dm->probs[s].label == label || !dm->probs[s].label) {
5385: if (fields) *fields = dm->probs[s].fields;
5386: if (ds) *ds = dm->probs[s].ds;
5387: if (dm->probs[s].label) return 0;
5388: }
5389: }
5390: return 0;
5391: }
5393: /*@
5394: DMSetRegionDS - Set the `PetscDS` for a given mesh region, defined by a `DMLabel`
5396: Collective on dm
5398: Input Parameters:
5399: + dm - The `DM`
5400: . label - The `DMLabel` defining the mesh region, or NULL for the entire mesh
5401: . fields - The IS containing the `DM` field numbers for the fields in this `PetscDS`, or NULL for all fields
5402: - prob - The `PetscDS` defined on the given region
5404: Note:
5405: If the label has a `PetscDS` defined, it will be replaced. Otherwise, it will be added to the `DM`. If the `PetscDS` is replaced,
5406: the fields argument is ignored.
5408: Level: advanced
5410: .seealso: `DMGetRegionDS()`, `DMSetRegionNumDS()`, `DMGetDS()`, `DMGetCellDS()`
5411: @*/
5412: PetscErrorCode DMSetRegionDS(DM dm, DMLabel label, IS fields, PetscDS ds)
5413: {
5414: PetscInt Nds = dm->Nds, s;
5419: for (s = 0; s < Nds; ++s) {
5420: if (dm->probs[s].label == label) {
5421: PetscDSDestroy(&dm->probs[s].ds);
5422: dm->probs[s].ds = ds;
5423: return 0;
5424: }
5425: }
5426: DMDSEnlarge_Static(dm, Nds + 1);
5427: PetscObjectReference((PetscObject)label);
5428: PetscObjectReference((PetscObject)fields);
5429: PetscObjectReference((PetscObject)ds);
5430: if (!label) {
5431: /* Put the NULL label at the front, so it is returned as the default */
5432: for (s = Nds - 1; s >= 0; --s) dm->probs[s + 1] = dm->probs[s];
5433: Nds = 0;
5434: }
5435: dm->probs[Nds].label = label;
5436: dm->probs[Nds].fields = fields;
5437: dm->probs[Nds].ds = ds;
5438: return 0;
5439: }
5441: /*@
5442: DMGetRegionNumDS - Get the PetscDS for a given mesh region, defined by the region number
5444: Not collective
5446: Input Parameters:
5447: + dm - The DM
5448: - num - The region number, in [0, Nds)
5450: Output Parameters:
5451: + label - The region label, or NULL
5452: . fields - The IS containing the DM field numbers for the fields in this DS, or NULL
5453: - ds - The PetscDS defined on the given region, or NULL
5455: Level: advanced
5457: .seealso: `DMGetRegionDS()`, `DMSetRegionDS()`, `DMGetDS()`, `DMGetCellDS()`
5458: @*/
5459: PetscErrorCode DMGetRegionNumDS(DM dm, PetscInt num, DMLabel *label, IS *fields, PetscDS *ds)
5460: {
5461: PetscInt Nds;
5464: DMGetNumDS(dm, &Nds);
5466: if (label) {
5468: *label = dm->probs[num].label;
5469: }
5470: if (fields) {
5472: *fields = dm->probs[num].fields;
5473: }
5474: if (ds) {
5476: *ds = dm->probs[num].ds;
5477: }
5478: return 0;
5479: }
5481: /*@
5482: DMSetRegionNumDS - Set the PetscDS for a given mesh region, defined by the region number
5484: Not collective
5486: Input Parameters:
5487: + dm - The DM
5488: . num - The region number, in [0, Nds)
5489: . label - The region label, or NULL
5490: . fields - The IS containing the DM field numbers for the fields in this DS, or NULL to prevent setting
5491: - ds - The PetscDS defined on the given region, or NULL to prevent setting
5493: Level: advanced
5495: .seealso: `DMGetRegionDS()`, `DMSetRegionDS()`, `DMGetDS()`, `DMGetCellDS()`
5496: @*/
5497: PetscErrorCode DMSetRegionNumDS(DM dm, PetscInt num, DMLabel label, IS fields, PetscDS ds)
5498: {
5499: PetscInt Nds;
5503: DMGetNumDS(dm, &Nds);
5505: PetscObjectReference((PetscObject)label);
5506: DMLabelDestroy(&dm->probs[num].label);
5507: dm->probs[num].label = label;
5508: if (fields) {
5510: PetscObjectReference((PetscObject)fields);
5511: ISDestroy(&dm->probs[num].fields);
5512: dm->probs[num].fields = fields;
5513: }
5514: if (ds) {
5516: PetscObjectReference((PetscObject)ds);
5517: PetscDSDestroy(&dm->probs[num].ds);
5518: dm->probs[num].ds = ds;
5519: }
5520: return 0;
5521: }
5523: /*@
5524: DMFindRegionNum - Find the region number for a given PetscDS, or -1 if it is not found.
5526: Not collective
5528: Input Parameters:
5529: + dm - The DM
5530: - ds - The PetscDS defined on the given region
5532: Output Parameter:
5533: . num - The region number, in [0, Nds), or -1 if not found
5535: Level: advanced
5537: .seealso: `DMGetRegionNumDS()`, `DMGetRegionDS()`, `DMSetRegionDS()`, `DMGetDS()`, `DMGetCellDS()`
5538: @*/
5539: PetscErrorCode DMFindRegionNum(DM dm, PetscDS ds, PetscInt *num)
5540: {
5541: PetscInt Nds, n;
5546: DMGetNumDS(dm, &Nds);
5547: for (n = 0; n < Nds; ++n)
5548: if (ds == dm->probs[n].ds) break;
5549: if (n >= Nds) *num = -1;
5550: else *num = n;
5551: return 0;
5552: }
5554: /*@C
5555: DMCreateFEDefault - Create a `PetscFE` based on the celltype for the mesh
5557: Not collective
5559: Input Parameters:
5560: + dm - The `DM`
5561: . Nc - The number of components for the field
5562: . prefix - The options prefix for the output `PetscFE`, or NULL
5563: - qorder - The quadrature order or `PETSC_DETERMINE` to use `PetscSpace` polynomial degree
5565: Output Parameter:
5566: . fem - The `PetscFE`
5568: Note:
5569: This is a convenience method that just calls `PetscFECreateByCell()` underneath.
5571: Level: intermediate
5573: .seealso: `PetscFECreateByCell()`, `DMAddField()`, `DMCreateDS()`, `DMGetCellDS()`, `DMGetRegionDS()`
5574: @*/
5575: PetscErrorCode DMCreateFEDefault(DM dm, PetscInt Nc, const char prefix[], PetscInt qorder, PetscFE *fem)
5576: {
5577: DMPolytopeType ct;
5578: PetscInt dim, cStart;
5585: DMGetDimension(dm, &dim);
5586: DMPlexGetHeightStratum(dm, 0, &cStart, NULL);
5587: DMPlexGetCellType(dm, cStart, &ct);
5588: PetscFECreateByCell(PETSC_COMM_SELF, dim, Nc, ct, prefix, qorder, fem);
5589: return 0;
5590: }
5592: /*@
5593: DMCreateDS - Create the discrete systems for the `DM` based upon the fields added to the `DM`
5595: Collective on dm
5597: Input Parameter:
5598: . dm - The `DM`
5600: Options Database Keys:
5601: . -dm_petscds_view - View all the `PetscDS` objects in this `DM`
5603: Note:
5604: If the label has a `PetscDS` defined, it will be replaced. Otherwise, it will be added to the `DM`.
5606: Level: intermediate
5608: .seealso: `DMSetField`, `DMAddField()`, `DMGetDS()`, `DMGetCellDS()`, `DMGetRegionDS()`, `DMSetRegionDS()`
5609: @*/
5610: PetscErrorCode DMCreateDS(DM dm)
5611: {
5612: MPI_Comm comm;
5613: PetscDS dsDef;
5614: DMLabel *labelSet;
5615: PetscInt dE, Nf = dm->Nf, f, s, Nl, l, Ndef, k;
5616: PetscBool doSetup = PETSC_TRUE, flg;
5619: if (!dm->fields) return 0;
5620: PetscObjectGetComm((PetscObject)dm, &comm);
5621: DMGetCoordinateDim(dm, &dE);
5622: /* Determine how many regions we have */
5623: PetscMalloc1(Nf, &labelSet);
5624: Nl = 0;
5625: Ndef = 0;
5626: for (f = 0; f < Nf; ++f) {
5627: DMLabel label = dm->fields[f].label;
5628: PetscInt l;
5630: #ifdef PETSC_HAVE_LIBCEED
5631: /* Move CEED context to discretizations */
5632: {
5633: PetscClassId id;
5635: PetscObjectGetClassId(dm->fields[f].disc, &id);
5636: if (id == PETSCFE_CLASSID) {
5637: Ceed ceed;
5639: DMGetCeed(dm, &ceed);
5640: PetscFESetCeed((PetscFE)dm->fields[f].disc, ceed);
5641: }
5642: }
5643: #endif
5644: if (!label) {
5645: ++Ndef;
5646: continue;
5647: }
5648: for (l = 0; l < Nl; ++l)
5649: if (label == labelSet[l]) break;
5650: if (l < Nl) continue;
5651: labelSet[Nl++] = label;
5652: }
5653: /* Create default DS if there are no labels to intersect with */
5654: DMGetRegionDS(dm, NULL, NULL, &dsDef);
5655: if (!dsDef && Ndef && !Nl) {
5656: IS fields;
5657: PetscInt *fld, nf;
5659: for (f = 0, nf = 0; f < Nf; ++f)
5660: if (!dm->fields[f].label) ++nf;
5662: PetscMalloc1(nf, &fld);
5663: for (f = 0, nf = 0; f < Nf; ++f)
5664: if (!dm->fields[f].label) fld[nf++] = f;
5665: ISCreate(PETSC_COMM_SELF, &fields);
5666: PetscObjectSetOptionsPrefix((PetscObject)fields, "dm_fields_");
5667: ISSetType(fields, ISGENERAL);
5668: ISGeneralSetIndices(fields, nf, fld, PETSC_OWN_POINTER);
5670: PetscDSCreate(PETSC_COMM_SELF, &dsDef);
5671: DMSetRegionDS(dm, NULL, fields, dsDef);
5672: PetscDSDestroy(&dsDef);
5673: ISDestroy(&fields);
5674: }
5675: DMGetRegionDS(dm, NULL, NULL, &dsDef);
5676: if (dsDef) PetscDSSetCoordinateDimension(dsDef, dE);
5677: /* Intersect labels with default fields */
5678: if (Ndef && Nl) {
5679: DM plex;
5680: DMLabel cellLabel;
5681: IS fieldIS, allcellIS, defcellIS = NULL;
5682: PetscInt *fields;
5683: const PetscInt *cells;
5684: PetscInt depth, nf = 0, n, c;
5686: DMConvert(dm, DMPLEX, &plex);
5687: DMPlexGetDepth(plex, &depth);
5688: DMGetStratumIS(plex, "dim", depth, &allcellIS);
5689: if (!allcellIS) DMGetStratumIS(plex, "depth", depth, &allcellIS);
5690: /* TODO This looks like it only works for one label */
5691: for (l = 0; l < Nl; ++l) {
5692: DMLabel label = labelSet[l];
5693: IS pointIS;
5695: ISDestroy(&defcellIS);
5696: DMLabelGetStratumIS(label, 1, &pointIS);
5697: ISDifference(allcellIS, pointIS, &defcellIS);
5698: ISDestroy(&pointIS);
5699: }
5700: ISDestroy(&allcellIS);
5702: DMLabelCreate(PETSC_COMM_SELF, "defaultCells", &cellLabel);
5703: ISGetLocalSize(defcellIS, &n);
5704: ISGetIndices(defcellIS, &cells);
5705: for (c = 0; c < n; ++c) DMLabelSetValue(cellLabel, cells[c], 1);
5706: ISRestoreIndices(defcellIS, &cells);
5707: ISDestroy(&defcellIS);
5708: DMPlexLabelComplete(plex, cellLabel);
5710: PetscMalloc1(Ndef, &fields);
5711: for (f = 0; f < Nf; ++f)
5712: if (!dm->fields[f].label) fields[nf++] = f;
5713: ISCreate(PETSC_COMM_SELF, &fieldIS);
5714: PetscObjectSetOptionsPrefix((PetscObject)fieldIS, "dm_fields_");
5715: ISSetType(fieldIS, ISGENERAL);
5716: ISGeneralSetIndices(fieldIS, nf, fields, PETSC_OWN_POINTER);
5718: PetscDSCreate(PETSC_COMM_SELF, &dsDef);
5719: DMSetRegionDS(dm, cellLabel, fieldIS, dsDef);
5720: PetscDSSetCoordinateDimension(dsDef, dE);
5721: DMLabelDestroy(&cellLabel);
5722: PetscDSDestroy(&dsDef);
5723: ISDestroy(&fieldIS);
5724: DMDestroy(&plex);
5725: }
5726: /* Create label DSes
5727: - WE ONLY SUPPORT IDENTICAL OR DISJOINT LABELS
5728: */
5729: /* TODO Should check that labels are disjoint */
5730: for (l = 0; l < Nl; ++l) {
5731: DMLabel label = labelSet[l];
5732: PetscDS ds;
5733: IS fields;
5734: PetscInt *fld, nf;
5736: PetscDSCreate(PETSC_COMM_SELF, &ds);
5737: for (f = 0, nf = 0; f < Nf; ++f)
5738: if (label == dm->fields[f].label || !dm->fields[f].label) ++nf;
5739: PetscMalloc1(nf, &fld);
5740: for (f = 0, nf = 0; f < Nf; ++f)
5741: if (label == dm->fields[f].label || !dm->fields[f].label) fld[nf++] = f;
5742: ISCreate(PETSC_COMM_SELF, &fields);
5743: PetscObjectSetOptionsPrefix((PetscObject)fields, "dm_fields_");
5744: ISSetType(fields, ISGENERAL);
5745: ISGeneralSetIndices(fields, nf, fld, PETSC_OWN_POINTER);
5746: DMSetRegionDS(dm, label, fields, ds);
5747: ISDestroy(&fields);
5748: PetscDSSetCoordinateDimension(ds, dE);
5749: {
5750: DMPolytopeType ct;
5751: PetscInt lStart, lEnd;
5752: PetscBool isCohesiveLocal = PETSC_FALSE, isCohesive;
5754: DMLabelGetBounds(label, &lStart, &lEnd);
5755: if (lStart >= 0) {
5756: DMPlexGetCellType(dm, lStart, &ct);
5757: switch (ct) {
5758: case DM_POLYTOPE_POINT_PRISM_TENSOR:
5759: case DM_POLYTOPE_SEG_PRISM_TENSOR:
5760: case DM_POLYTOPE_TRI_PRISM_TENSOR:
5761: case DM_POLYTOPE_QUAD_PRISM_TENSOR:
5762: isCohesiveLocal = PETSC_TRUE;
5763: break;
5764: default:
5765: break;
5766: }
5767: }
5768: MPI_Allreduce(&isCohesiveLocal, &isCohesive, 1, MPIU_BOOL, MPI_LOR, comm);
5769: for (f = 0, nf = 0; f < Nf; ++f) {
5770: if (label == dm->fields[f].label || !dm->fields[f].label) {
5771: if (label == dm->fields[f].label) {
5772: PetscDSSetDiscretization(ds, nf, NULL);
5773: PetscDSSetCohesive(ds, nf, isCohesive);
5774: }
5775: ++nf;
5776: }
5777: }
5778: }
5779: PetscDSDestroy(&ds);
5780: }
5781: PetscFree(labelSet);
5782: /* Set fields in DSes */
5783: for (s = 0; s < dm->Nds; ++s) {
5784: PetscDS ds = dm->probs[s].ds;
5785: IS fields = dm->probs[s].fields;
5786: const PetscInt *fld;
5787: PetscInt nf, dsnf;
5788: PetscBool isCohesive;
5790: PetscDSGetNumFields(ds, &dsnf);
5791: PetscDSIsCohesive(ds, &isCohesive);
5792: ISGetLocalSize(fields, &nf);
5793: ISGetIndices(fields, &fld);
5794: for (f = 0; f < nf; ++f) {
5795: PetscObject disc = dm->fields[fld[f]].disc;
5796: PetscBool isCohesiveField;
5797: PetscClassId id;
5799: /* Handle DS with no fields */
5800: if (dsnf) PetscDSGetCohesive(ds, f, &isCohesiveField);
5801: /* If this is a cohesive cell, then regular fields need the lower dimensional discretization */
5802: if (isCohesive && !isCohesiveField) PetscFEGetHeightSubspace((PetscFE)disc, 1, (PetscFE *)&disc);
5803: PetscDSSetDiscretization(ds, f, disc);
5804: /* We allow people to have placeholder fields and construct the Section by hand */
5805: PetscObjectGetClassId(disc, &id);
5806: if ((id != PETSCFE_CLASSID) && (id != PETSCFV_CLASSID)) doSetup = PETSC_FALSE;
5807: }
5808: ISRestoreIndices(fields, &fld);
5809: }
5810: /* Allow k-jet tabulation */
5811: PetscOptionsGetInt(NULL, ((PetscObject)dm)->prefix, "-dm_ds_jet_degree", &k, &flg);
5812: if (flg) {
5813: for (s = 0; s < dm->Nds; ++s) {
5814: PetscDS ds = dm->probs[s].ds;
5815: PetscInt Nf, f;
5817: PetscDSGetNumFields(ds, &Nf);
5818: for (f = 0; f < Nf; ++f) PetscDSSetJetDegree(ds, f, k);
5819: }
5820: }
5821: /* Setup DSes */
5822: if (doSetup) {
5823: for (s = 0; s < dm->Nds; ++s) PetscDSSetUp(dm->probs[s].ds);
5824: }
5825: return 0;
5826: }
5828: /*@
5829: DMComputeExactSolution - Compute the exact solution for a given `DM`, using the `PetscDS` information.
5831: Collective on `DM`
5833: Input Parameters:
5834: + dm - The `DM`
5835: - time - The time
5837: Output Parameters:
5838: + u - The vector will be filled with exact solution values, or NULL
5839: - u_t - The vector will be filled with the time derivative of exact solution values, or NULL
5841: Note:
5842: The user must call `PetscDSSetExactSolution()` before using this routine
5844: Level: developer
5846: .seealso: `PetscDSSetExactSolution()`
5847: @*/
5848: PetscErrorCode DMComputeExactSolution(DM dm, PetscReal time, Vec u, Vec u_t)
5849: {
5850: PetscErrorCode (**exacts)(PetscInt, PetscReal, const PetscReal x[], PetscInt, PetscScalar *u, void *ctx);
5851: void **ectxs;
5852: PetscInt Nf, Nds, s;
5857: DMGetNumFields(dm, &Nf);
5858: PetscMalloc2(Nf, &exacts, Nf, &ectxs);
5859: DMGetNumDS(dm, &Nds);
5860: for (s = 0; s < Nds; ++s) {
5861: PetscDS ds;
5862: DMLabel label;
5863: IS fieldIS;
5864: const PetscInt *fields, id = 1;
5865: PetscInt dsNf, f;
5867: DMGetRegionNumDS(dm, s, &label, &fieldIS, &ds);
5868: PetscDSGetNumFields(ds, &dsNf);
5869: ISGetIndices(fieldIS, &fields);
5870: PetscArrayzero(exacts, Nf);
5871: PetscArrayzero(ectxs, Nf);
5872: if (u) {
5873: for (f = 0; f < dsNf; ++f) {
5874: const PetscInt field = fields[f];
5875: PetscDSGetExactSolution(ds, field, &exacts[field], &ectxs[field]);
5876: }
5877: ISRestoreIndices(fieldIS, &fields);
5878: if (label) {
5879: DMProjectFunctionLabel(dm, time, label, 1, &id, 0, NULL, exacts, ectxs, INSERT_ALL_VALUES, u);
5880: } else {
5881: DMProjectFunction(dm, time, exacts, ectxs, INSERT_ALL_VALUES, u);
5882: }
5883: }
5884: if (u_t) {
5885: PetscArrayzero(exacts, Nf);
5886: PetscArrayzero(ectxs, Nf);
5887: for (f = 0; f < dsNf; ++f) {
5888: const PetscInt field = fields[f];
5889: PetscDSGetExactSolutionTimeDerivative(ds, field, &exacts[field], &ectxs[field]);
5890: }
5891: ISRestoreIndices(fieldIS, &fields);
5892: if (label) {
5893: DMProjectFunctionLabel(dm, time, label, 1, &id, 0, NULL, exacts, ectxs, INSERT_ALL_VALUES, u_t);
5894: } else {
5895: DMProjectFunction(dm, time, exacts, ectxs, INSERT_ALL_VALUES, u_t);
5896: }
5897: }
5898: }
5899: if (u) {
5900: PetscObjectSetName((PetscObject)u, "Exact Solution");
5901: PetscObjectSetOptionsPrefix((PetscObject)u, "exact_");
5902: }
5903: if (u_t) {
5904: PetscObjectSetName((PetscObject)u, "Exact Solution Time Derivative");
5905: PetscObjectSetOptionsPrefix((PetscObject)u_t, "exact_t_");
5906: }
5907: PetscFree2(exacts, ectxs);
5908: return 0;
5909: }
5911: PetscErrorCode DMTransferDS_Internal(DM dm, DMLabel label, IS fields, PetscDS ds)
5912: {
5913: PetscDS dsNew;
5914: DSBoundary b;
5915: PetscInt cdim, Nf, f, d;
5916: PetscBool isCohesive;
5917: void *ctx;
5919: PetscDSCreate(PetscObjectComm((PetscObject)ds), &dsNew);
5920: PetscDSCopyConstants(ds, dsNew);
5921: PetscDSCopyExactSolutions(ds, dsNew);
5922: PetscDSSelectDiscretizations(ds, PETSC_DETERMINE, NULL, dsNew);
5923: PetscDSCopyEquations(ds, dsNew);
5924: PetscDSGetNumFields(ds, &Nf);
5925: for (f = 0; f < Nf; ++f) {
5926: PetscDSGetContext(ds, f, &ctx);
5927: PetscDSSetContext(dsNew, f, ctx);
5928: PetscDSGetCohesive(ds, f, &isCohesive);
5929: PetscDSSetCohesive(dsNew, f, isCohesive);
5930: PetscDSGetJetDegree(ds, f, &d);
5931: PetscDSSetJetDegree(dsNew, f, d);
5932: }
5933: if (Nf) {
5934: PetscDSGetCoordinateDimension(ds, &cdim);
5935: PetscDSSetCoordinateDimension(dsNew, cdim);
5936: }
5937: PetscDSCopyBoundary(ds, PETSC_DETERMINE, NULL, dsNew);
5938: for (b = dsNew->boundary; b; b = b->next) {
5939: DMGetLabel(dm, b->lname, &b->label);
5940: /* Do not check if label exists here, since p4est calls this for the reference tree which does not have the labels */
5942: }
5944: DMSetRegionDS(dm, label, fields, dsNew);
5945: PetscDSDestroy(&dsNew);
5946: return 0;
5947: }
5949: /*@
5950: DMCopyDS - Copy the discrete systems for the `DM` into another `DM`
5952: Collective on dm
5954: Input Parameter:
5955: . dm - The `DM`
5957: Output Parameter:
5958: . newdm - The `DM`
5960: Level: advanced
5962: .seealso: `DMCopyFields()`, `DMAddField()`, `DMGetDS()`, `DMGetCellDS()`, `DMGetRegionDS()`, `DMSetRegionDS()`
5963: @*/
5964: PetscErrorCode DMCopyDS(DM dm, DM newdm)
5965: {
5966: PetscInt Nds, s;
5968: if (dm == newdm) return 0;
5969: DMGetNumDS(dm, &Nds);
5970: DMClearDS(newdm);
5971: for (s = 0; s < Nds; ++s) {
5972: DMLabel label;
5973: IS fields;
5974: PetscDS ds, newds;
5975: PetscInt Nbd, bd;
5977: DMGetRegionNumDS(dm, s, &label, &fields, &ds);
5978: /* TODO: We need to change all keys from labels in the old DM to labels in the new DM */
5979: DMTransferDS_Internal(newdm, label, fields, ds);
5980: /* Commplete new labels in the new DS */
5981: DMGetRegionDS(newdm, label, NULL, &newds);
5982: PetscDSGetNumBoundary(newds, &Nbd);
5983: for (bd = 0; bd < Nbd; ++bd) {
5984: PetscWeakForm wf;
5985: DMLabel label;
5986: PetscInt field;
5988: PetscDSGetBoundary(newds, bd, &wf, NULL, NULL, &label, NULL, NULL, &field, NULL, NULL, NULL, NULL, NULL);
5989: PetscWeakFormReplaceLabel(wf, label);
5990: }
5991: }
5992: DMCompleteBCLabels_Internal(newdm);
5993: return 0;
5994: }
5996: /*@
5997: DMCopyDisc - Copy the fields and discrete systems for the `DM` into another `DM`
5999: Collective on dm
6001: Input Parameter:
6002: . dm - The `DM`
6004: Output Parameter:
6005: . newdm - The `DM`
6007: Level: advanced
6009: Developer Note:
6010: Really ugly name, nothing in PETSc is called a `Disc` plus it is an ugly abbreviation
6012: .seealso: `DMCopyFields()`, `DMCopyDS()`
6013: @*/
6014: PetscErrorCode DMCopyDisc(DM dm, DM newdm)
6015: {
6016: DMCopyFields(dm, newdm);
6017: DMCopyDS(dm, newdm);
6018: return 0;
6019: }
6021: /*@
6022: DMGetDimension - Return the topological dimension of the `DM`
6024: Not collective
6026: Input Parameter:
6027: . dm - The `DM`
6029: Output Parameter:
6030: . dim - The topological dimension
6032: Level: beginner
6034: .seealso: `DMSetDimension()`, `DMCreate()`
6035: @*/
6036: PetscErrorCode DMGetDimension(DM dm, PetscInt *dim)
6037: {
6040: *dim = dm->dim;
6041: return 0;
6042: }
6044: /*@
6045: DMSetDimension - Set the topological dimension of the `DM`
6047: Collective on dm
6049: Input Parameters:
6050: + dm - The `DM`
6051: - dim - The topological dimension
6053: Level: beginner
6055: .seealso: `DMGetDimension()`, `DMCreate()`
6056: @*/
6057: PetscErrorCode DMSetDimension(DM dm, PetscInt dim)
6058: {
6059: PetscDS ds;
6060: PetscInt Nds, n;
6064: dm->dim = dim;
6065: if (dm->dim >= 0) {
6066: DMGetNumDS(dm, &Nds);
6067: for (n = 0; n < Nds; ++n) {
6068: DMGetRegionNumDS(dm, n, NULL, NULL, &ds);
6069: if (ds->dimEmbed < 0) PetscDSSetCoordinateDimension(ds, dim);
6070: }
6071: }
6072: return 0;
6073: }
6075: /*@
6076: DMGetDimPoints - Get the half-open interval for all points of a given dimension
6078: Collective on dm
6080: Input Parameters:
6081: + dm - the `DM`
6082: - dim - the dimension
6084: Output Parameters:
6085: + pStart - The first point of the given dimension
6086: - pEnd - The first point following points of the given dimension
6088: Note:
6089: The points are vertices in the Hasse diagram encoding the topology. This is explained in
6090: https://arxiv.org/abs/0908.4427. If no points exist of this dimension in the storage scheme,
6091: then the interval is empty.
6093: Level: intermediate
6095: .seealso: `DMPLEX`, `DMPlexGetDepthStratum()`, `DMPlexGetHeightStratum()`
6096: @*/
6097: PetscErrorCode DMGetDimPoints(DM dm, PetscInt dim, PetscInt *pStart, PetscInt *pEnd)
6098: {
6099: PetscInt d;
6102: DMGetDimension(dm, &d);
6104: PetscUseTypeMethod(dm, getdimpoints, dim, pStart, pEnd);
6105: return 0;
6106: }
6108: /*@
6109: DMGetOutputDM - Retrieve the `DM` associated with the layout for output
6111: Collective on dm
6113: Input Parameter:
6114: . dm - The original `DM`
6116: Output Parameter:
6117: . odm - The `DM` which provides the layout for output
6119: Level: intermediate
6121: Note:
6122: In some situations the vector obtained with `DMCreateGlobalVector()` excludes points for degrees of freedom that are associated with fixed (Dirichelet) boundary
6123: conditions since the algebraic solver does not solve for those variables. The output `DM` includes these excluded points and its global vector contains the
6124: locations for those dof so that they can be output to a file or other viewer along with the unconstrained dof.
6126: .seealso: `VecView()`, `DMGetGlobalSection()`, `DMCreateGlobalVector()`, `PetscSectionHasConstraints()`, `DMSetGlobalSection()`
6127: @*/
6128: PetscErrorCode DMGetOutputDM(DM dm, DM *odm)
6129: {
6130: PetscSection section;
6131: PetscBool hasConstraints, ghasConstraints;
6135: DMGetLocalSection(dm, §ion);
6136: PetscSectionHasConstraints(section, &hasConstraints);
6137: MPI_Allreduce(&hasConstraints, &ghasConstraints, 1, MPIU_BOOL, MPI_LOR, PetscObjectComm((PetscObject)dm));
6138: if (!ghasConstraints) {
6139: *odm = dm;
6140: return 0;
6141: }
6142: if (!dm->dmBC) {
6143: PetscSection newSection, gsection;
6144: PetscSF sf;
6146: DMClone(dm, &dm->dmBC);
6147: DMCopyDisc(dm, dm->dmBC);
6148: PetscSectionClone(section, &newSection);
6149: DMSetLocalSection(dm->dmBC, newSection);
6150: PetscSectionDestroy(&newSection);
6151: DMGetPointSF(dm->dmBC, &sf);
6152: PetscSectionCreateGlobalSection(section, sf, PETSC_TRUE, PETSC_FALSE, &gsection);
6153: DMSetGlobalSection(dm->dmBC, gsection);
6154: PetscSectionDestroy(&gsection);
6155: }
6156: *odm = dm->dmBC;
6157: return 0;
6158: }
6160: /*@
6161: DMGetOutputSequenceNumber - Retrieve the sequence number/value for output
6163: Input Parameter:
6164: . dm - The original `DM`
6166: Output Parameters:
6167: + num - The output sequence number
6168: - val - The output sequence value
6170: Level: intermediate
6172: Note:
6173: This is intended for output that should appear in sequence, for instance
6174: a set of timesteps in an `PETSCVIEWERHDF5` file, or a set of realizations of a stochastic system.
6176: Developer Note:
6177: The `DM` serves as a convenient place to store the current iteration value. The iteration is not
6178: not directly related to the `DM`.
6180: .seealso: `VecView()`
6181: @*/
6182: PetscErrorCode DMGetOutputSequenceNumber(DM dm, PetscInt *num, PetscReal *val)
6183: {
6185: if (num) {
6187: *num = dm->outputSequenceNum;
6188: }
6189: if (val) {
6191: *val = dm->outputSequenceVal;
6192: }
6193: return 0;
6194: }
6196: /*@
6197: DMSetOutputSequenceNumber - Set the sequence number/value for output
6199: Input Parameters:
6200: + dm - The original `DM`
6201: . num - The output sequence number
6202: - val - The output sequence value
6204: Level: intermediate
6206: Note:
6207: This is intended for output that should appear in sequence, for instance
6208: a set of timesteps in an `PETSCVIEWERHDF5` file, or a set of realizations of a stochastic system.
6210: .seealso: `VecView()`
6211: @*/
6212: PetscErrorCode DMSetOutputSequenceNumber(DM dm, PetscInt num, PetscReal val)
6213: {
6215: dm->outputSequenceNum = num;
6216: dm->outputSequenceVal = val;
6217: return 0;
6218: }
6220: /*@C
6221: DMOutputSequenceLoad - Retrieve the sequence value from a `PetscViewer`
6223: Input Parameters:
6224: + dm - The original `DM`
6225: . name - The sequence name
6226: - num - The output sequence number
6228: Output Parameter:
6229: . val - The output sequence value
6231: Level: intermediate
6233: Note:
6234: This is intended for output that should appear in sequence, for instance
6235: a set of timesteps in an `PETSCVIEWERHDF5` file, or a set of realizations of a stochastic system.
6237: Developer Note:
6238: It is unclear at the user API level why a `DM` is needed as input
6240: .seealso: `DMGetOutputSequenceNumber()`, `DMSetOutputSequenceNumber()`, `VecView()`
6241: @*/
6242: PetscErrorCode DMOutputSequenceLoad(DM dm, PetscViewer viewer, const char *name, PetscInt num, PetscReal *val)
6243: {
6244: PetscBool ishdf5;
6249: PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERHDF5, &ishdf5);
6250: if (ishdf5) {
6251: #if defined(PETSC_HAVE_HDF5)
6252: PetscScalar value;
6254: DMSequenceLoad_HDF5_Internal(dm, name, num, &value, viewer);
6255: *val = PetscRealPart(value);
6256: #endif
6257: } else SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Invalid viewer; open viewer with PetscViewerHDF5Open()");
6258: return 0;
6259: }
6261: /*@
6262: DMGetUseNatural - Get the flag for creating a mapping to the natural order when a `DM` is (re)distributed in parallel
6264: Not collective
6266: Input Parameter:
6267: . dm - The `DM`
6269: Output Parameter:
6270: . useNatural - `PETSC_TRUE` to build the mapping to a natural order during distribution
6272: Level: beginner
6274: .seealso: `DMSetUseNatural()`, `DMCreate()`
6275: @*/
6276: PetscErrorCode DMGetUseNatural(DM dm, PetscBool *useNatural)
6277: {
6280: *useNatural = dm->useNatural;
6281: return 0;
6282: }
6284: /*@
6285: DMSetUseNatural - Set the flag for creating a mapping to the natural order when a `DM` is (re)distributed in parallel
6287: Collective on dm
6289: Input Parameters:
6290: + dm - The `DM`
6291: - useNatural - `PETSC_TRUE` to build the mapping to a natural order during distribution
6293: Note:
6294: This also causes the map to be build after `DMCreateSubDM()` and `DMCreateSuperDM()`
6296: Level: beginner
6298: .seealso: `DMGetUseNatural()`, `DMCreate()`, `DMPlexDistribute()`, `DMCreateSubDM()`, `DMCreateSuperDM()`
6299: @*/
6300: PetscErrorCode DMSetUseNatural(DM dm, PetscBool useNatural)
6301: {
6304: dm->useNatural = useNatural;
6305: return 0;
6306: }
6308: /*@C
6309: DMCreateLabel - Create a label of the given name if it does not already exist in the `DM`
6311: Not Collective
6313: Input Parameters:
6314: + dm - The `DM` object
6315: - name - The label name
6317: Level: intermediate
6319: .seealso: `DMLabelCreate()`, `DMHasLabel()`, `DMGetLabelValue()`, `DMSetLabelValue()`, `DMGetStratumIS()`
6320: @*/
6321: PetscErrorCode DMCreateLabel(DM dm, const char name[])
6322: {
6323: PetscBool flg;
6324: DMLabel label;
6328: DMHasLabel(dm, name, &flg);
6329: if (!flg) {
6330: DMLabelCreate(PETSC_COMM_SELF, name, &label);
6331: DMAddLabel(dm, label);
6332: DMLabelDestroy(&label);
6333: }
6334: return 0;
6335: }
6337: /*@C
6338: DMCreateLabelAtIndex - Create a label of the given name at the given index. If it already exists in the `DM`, move it to this index.
6340: Not Collective
6342: Input Parameters:
6343: + dm - The `DM` object
6344: . l - The index for the label
6345: - name - The label name
6347: Level: intermediate
6349: .seealso: `DMCreateLabel()`, `DMLabelCreate()`, `DMHasLabel()`, `DMGetLabelValue()`, `DMSetLabelValue()`, `DMGetStratumIS()`
6350: @*/
6351: PetscErrorCode DMCreateLabelAtIndex(DM dm, PetscInt l, const char name[])
6352: {
6353: DMLabelLink orig, prev = NULL;
6354: DMLabel label;
6355: PetscInt Nl, m;
6356: PetscBool flg, match;
6357: const char *lname;
6361: DMHasLabel(dm, name, &flg);
6362: if (!flg) {
6363: DMLabelCreate(PETSC_COMM_SELF, name, &label);
6364: DMAddLabel(dm, label);
6365: DMLabelDestroy(&label);
6366: }
6367: DMGetNumLabels(dm, &Nl);
6369: for (m = 0, orig = dm->labels; m < Nl; ++m, prev = orig, orig = orig->next) {
6370: PetscObjectGetName((PetscObject)orig->label, &lname);
6371: PetscStrcmp(name, lname, &match);
6372: if (match) break;
6373: }
6374: if (m == l) return 0;
6375: if (!m) dm->labels = orig->next;
6376: else prev->next = orig->next;
6377: if (!l) {
6378: orig->next = dm->labels;
6379: dm->labels = orig;
6380: } else {
6381: for (m = 0, prev = dm->labels; m < l - 1; ++m, prev = prev->next)
6382: ;
6383: orig->next = prev->next;
6384: prev->next = orig;
6385: }
6386: return 0;
6387: }
6389: /*@C
6390: DMGetLabelValue - Get the value in a `DMLabel` for the given point, with -1 as the default
6392: Not Collective
6394: Input Parameters:
6395: + dm - The `DM` object
6396: . name - The label name
6397: - point - The mesh point
6399: Output Parameter:
6400: . value - The label value for this point, or -1 if the point is not in the label
6402: Level: beginner
6404: .seealso: `DMLabelGetValue()`, `DMSetLabelValue()`, `DMGetStratumIS()`
6405: @*/
6406: PetscErrorCode DMGetLabelValue(DM dm, const char name[], PetscInt point, PetscInt *value)
6407: {
6408: DMLabel label;
6412: DMGetLabel(dm, name, &label);
6414: DMLabelGetValue(label, point, value);
6415: return 0;
6416: }
6418: /*@C
6419: DMSetLabelValue - Add a point to a `DMLabel` with given value
6421: Not Collective
6423: Input Parameters:
6424: + dm - The `DM` object
6425: . name - The label name
6426: . point - The mesh point
6427: - value - The label value for this point
6429: Output Parameter:
6431: Level: beginner
6433: .seealso: `DMLabelSetValue()`, `DMGetStratumIS()`, `DMClearLabelValue()`
6434: @*/
6435: PetscErrorCode DMSetLabelValue(DM dm, const char name[], PetscInt point, PetscInt value)
6436: {
6437: DMLabel label;
6441: DMGetLabel(dm, name, &label);
6442: if (!label) {
6443: DMCreateLabel(dm, name);
6444: DMGetLabel(dm, name, &label);
6445: }
6446: DMLabelSetValue(label, point, value);
6447: return 0;
6448: }
6450: /*@C
6451: DMClearLabelValue - Remove a point from a `DMLabel` with given value
6453: Not Collective
6455: Input Parameters:
6456: + dm - The `DM` object
6457: . name - The label name
6458: . point - The mesh point
6459: - value - The label value for this point
6461: Level: beginner
6463: .seealso: `DMLabelClearValue()`, `DMSetLabelValue()`, `DMGetStratumIS()`
6464: @*/
6465: PetscErrorCode DMClearLabelValue(DM dm, const char name[], PetscInt point, PetscInt value)
6466: {
6467: DMLabel label;
6471: DMGetLabel(dm, name, &label);
6472: if (!label) return 0;
6473: DMLabelClearValue(label, point, value);
6474: return 0;
6475: }
6477: /*@C
6478: DMGetLabelSize - Get the value of `DMLabelGetNumValues()` of a `DMLabel` in the `DM`
6480: Not Collective
6482: Input Parameters:
6483: + dm - The `DM` object
6484: - name - The label name
6486: Output Parameter:
6487: . size - The number of different integer ids, or 0 if the label does not exist
6489: Level: beginner
6491: Developer Note:
6492: This should be renamed to something like `DMGetLabelNumValues()` or removed.
6494: .seealso: `DMLabelGetNumValues()`, `DMSetLabelValue()`, `DMGetLabel()`
6495: @*/
6496: PetscErrorCode DMGetLabelSize(DM dm, const char name[], PetscInt *size)
6497: {
6498: DMLabel label;
6503: DMGetLabel(dm, name, &label);
6504: *size = 0;
6505: if (!label) return 0;
6506: DMLabelGetNumValues(label, size);
6507: return 0;
6508: }
6510: /*@C
6511: DMGetLabelIdIS - Get the `DMLabelGetValueIS()` from a `DMLabel` in the `DM`
6513: Not Collective
6515: Input Parameters:
6516: + mesh - The `DM` object
6517: - name - The label name
6519: Output Parameter:
6520: . ids - The integer ids, or NULL if the label does not exist
6522: Level: beginner
6524: .seealso: `DMLabelGetValueIS()`, `DMGetLabelSize()`
6525: @*/
6526: PetscErrorCode DMGetLabelIdIS(DM dm, const char name[], IS *ids)
6527: {
6528: DMLabel label;
6533: DMGetLabel(dm, name, &label);
6534: *ids = NULL;
6535: if (label) {
6536: DMLabelGetValueIS(label, ids);
6537: } else {
6538: /* returning an empty IS */
6539: ISCreateGeneral(PETSC_COMM_SELF, 0, NULL, PETSC_USE_POINTER, ids);
6540: }
6541: return 0;
6542: }
6544: /*@C
6545: DMGetStratumSize - Get the number of points in a label stratum
6547: Not Collective
6549: Input Parameters:
6550: + dm - The `DM` object
6551: . name - The label name
6552: - value - The stratum value
6554: Output Parameter:
6555: . size - The number of points, also called the stratum size
6557: Level: beginner
6559: .seealso: `DMLabelGetStratumSize()`, `DMGetLabelSize()`, `DMGetLabelIds()`
6560: @*/
6561: PetscErrorCode DMGetStratumSize(DM dm, const char name[], PetscInt value, PetscInt *size)
6562: {
6563: DMLabel label;
6568: DMGetLabel(dm, name, &label);
6569: *size = 0;
6570: if (!label) return 0;
6571: DMLabelGetStratumSize(label, value, size);
6572: return 0;
6573: }
6575: /*@C
6576: DMGetStratumIS - Get the points in a label stratum
6578: Not Collective
6580: Input Parameters:
6581: + dm - The `DM` object
6582: . name - The label name
6583: - value - The stratum value
6585: Output Parameter:
6586: . points - The stratum points, or NULL if the label does not exist or does not have that value
6588: Level: beginner
6590: .seealso: `DMLabelGetStratumIS()`, `DMGetStratumSize()`
6591: @*/
6592: PetscErrorCode DMGetStratumIS(DM dm, const char name[], PetscInt value, IS *points)
6593: {
6594: DMLabel label;
6599: DMGetLabel(dm, name, &label);
6600: *points = NULL;
6601: if (!label) return 0;
6602: DMLabelGetStratumIS(label, value, points);
6603: return 0;
6604: }
6606: /*@C
6607: DMSetStratumIS - Set the points in a label stratum
6609: Not Collective
6611: Input Parameters:
6612: + dm - The `DM` object
6613: . name - The label name
6614: . value - The stratum value
6615: - points - The stratum points
6617: Level: beginner
6619: .seealso: `DMLabel`, `DMClearLabelStratum()`, `DMLabelClearStratum()`, `DMLabelSetStratumIS()`, `DMGetStratumSize()`
6620: @*/
6621: PetscErrorCode DMSetStratumIS(DM dm, const char name[], PetscInt value, IS points)
6622: {
6623: DMLabel label;
6628: DMGetLabel(dm, name, &label);
6629: if (!label) return 0;
6630: DMLabelSetStratumIS(label, value, points);
6631: return 0;
6632: }
6634: /*@C
6635: DMClearLabelStratum - Remove all points from a stratum from a `DMLabel`
6637: Not Collective
6639: Input Parameters:
6640: + dm - The `DM` object
6641: . name - The label name
6642: - value - The label value for this point
6644: Output Parameter:
6646: Level: beginner
6648: .seealso: `DMLabel`, `DMLabelClearStratum()`, `DMSetLabelValue()`, `DMGetStratumIS()`, `DMClearLabelValue()`
6649: @*/
6650: PetscErrorCode DMClearLabelStratum(DM dm, const char name[], PetscInt value)
6651: {
6652: DMLabel label;
6656: DMGetLabel(dm, name, &label);
6657: if (!label) return 0;
6658: DMLabelClearStratum(label, value);
6659: return 0;
6660: }
6662: /*@
6663: DMGetNumLabels - Return the number of labels defined by on the `DM`
6665: Not Collective
6667: Input Parameter:
6668: . dm - The `DM` object
6670: Output Parameter:
6671: . numLabels - the number of Labels
6673: Level: intermediate
6675: .seealso: `DMLabel`, `DMGetLabelByNum()`, `DMGetLabelName()`, `DMGetLabelValue()`, `DMSetLabelValue()`, `DMGetStratumIS()`
6676: @*/
6677: PetscErrorCode DMGetNumLabels(DM dm, PetscInt *numLabels)
6678: {
6679: DMLabelLink next = dm->labels;
6680: PetscInt n = 0;
6684: while (next) {
6685: ++n;
6686: next = next->next;
6687: }
6688: *numLabels = n;
6689: return 0;
6690: }
6692: /*@C
6693: DMGetLabelName - Return the name of nth label
6695: Not Collective
6697: Input Parameters:
6698: + dm - The `DM` object
6699: - n - the label number
6701: Output Parameter:
6702: . name - the label name
6704: Level: intermediate
6706: Developer Note:
6707: Some of the functions that appropriate on labels using their number have the suffix ByNum, others do not.
6709: .seealso: `DMLabel`, `DMGetLabelByNum()`, `DMGetLabel()`, `DMGetLabelValue()`, `DMSetLabelValue()`, `DMGetStratumIS()`
6710: @*/
6711: PetscErrorCode DMGetLabelName(DM dm, PetscInt n, const char **name)
6712: {
6713: DMLabelLink next = dm->labels;
6714: PetscInt l = 0;
6718: while (next) {
6719: if (l == n) {
6720: PetscObjectGetName((PetscObject)next->label, name);
6721: return 0;
6722: }
6723: ++l;
6724: next = next->next;
6725: }
6726: SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Label %" PetscInt_FMT " does not exist in this DM", n);
6727: }
6729: /*@C
6730: DMHasLabel - Determine whether the `DM` has a label of a given name
6732: Not Collective
6734: Input Parameters:
6735: + dm - The `DM` object
6736: - name - The label name
6738: Output Parameter:
6739: . hasLabel - `PETSC_TRUE` if the label is present
6741: Level: intermediate
6743: .seealso: `DMLabel`, `DMGetLabel()`, `DMGetLabelByNum()`, `DMCreateLabel()`, `DMGetLabelValue()`, `DMSetLabelValue()`, `DMGetStratumIS()`
6744: @*/
6745: PetscErrorCode DMHasLabel(DM dm, const char name[], PetscBool *hasLabel)
6746: {
6747: DMLabelLink next = dm->labels;
6748: const char *lname;
6753: *hasLabel = PETSC_FALSE;
6754: while (next) {
6755: PetscObjectGetName((PetscObject)next->label, &lname);
6756: PetscStrcmp(name, lname, hasLabel);
6757: if (*hasLabel) break;
6758: next = next->next;
6759: }
6760: return 0;
6761: }
6763: /*@C
6764: DMGetLabel - Return the label of a given name, or NULL, from a `DM`
6766: Not Collective
6768: Input Parameters:
6769: + dm - The `DM` object
6770: - name - The label name
6772: Output Parameter:
6773: . label - The `DMLabel`, or NULL if the label is absent
6775: Default labels in a `DMPLEX`:
6776: + "depth" - Holds the depth (co-dimension) of each mesh point
6777: . "celltype" - Holds the topological type of each cell
6778: . "ghost" - If the DM is distributed with overlap, this marks the cells and faces in the overlap
6779: . "Cell Sets" - Mirrors the cell sets defined by GMsh and ExodusII
6780: . "Face Sets" - Mirrors the face sets defined by GMsh and ExodusII
6781: - "Vertex Sets" - Mirrors the vertex sets defined by GMsh
6783: Level: intermediate
6785: .seealso: `DMLabel`, `DMHasLabel()`, `DMGetLabelByNum()`, `DMAddLabel()`, `DMCreateLabel()`, `DMHasLabel()`, `DMPlexGetDepthLabel()`, `DMPlexGetCellType()`
6786: @*/
6787: PetscErrorCode DMGetLabel(DM dm, const char name[], DMLabel *label)
6788: {
6789: DMLabelLink next = dm->labels;
6790: PetscBool hasLabel;
6791: const char *lname;
6796: *label = NULL;
6797: while (next) {
6798: PetscObjectGetName((PetscObject)next->label, &lname);
6799: PetscStrcmp(name, lname, &hasLabel);
6800: if (hasLabel) {
6801: *label = next->label;
6802: break;
6803: }
6804: next = next->next;
6805: }
6806: return 0;
6807: }
6809: /*@C
6810: DMGetLabelByNum - Return the nth label on a `DM`
6812: Not Collective
6814: Input Parameters:
6815: + dm - The `DM` object
6816: - n - the label number
6818: Output Parameter:
6819: . label - the label
6821: Level: intermediate
6823: .seealso: `DMLabel`, `DMAddLabel()`, `DMGetLabelValue()`, `DMSetLabelValue()`, `DMGetStratumIS()`
6824: @*/
6825: PetscErrorCode DMGetLabelByNum(DM dm, PetscInt n, DMLabel *label)
6826: {
6827: DMLabelLink next = dm->labels;
6828: PetscInt l = 0;
6832: while (next) {
6833: if (l == n) {
6834: *label = next->label;
6835: return 0;
6836: }
6837: ++l;
6838: next = next->next;
6839: }
6840: SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Label %" PetscInt_FMT " does not exist in this DM", n);
6841: }
6843: /*@C
6844: DMAddLabel - Add the label to this `DM`
6846: Not Collective
6848: Input Parameters:
6849: + dm - The `DM` object
6850: - label - The `DMLabel`
6852: Level: developer
6854: .seealso: `DMLabel`, `DMLabel`, `DMCreateLabel()`, `DMHasLabel()`, `DMGetLabelValue()`, `DMSetLabelValue()`, `DMGetStratumIS()`
6855: @*/
6856: PetscErrorCode DMAddLabel(DM dm, DMLabel label)
6857: {
6858: DMLabelLink l, *p, tmpLabel;
6859: PetscBool hasLabel;
6860: const char *lname;
6861: PetscBool flg;
6864: PetscObjectGetName((PetscObject)label, &lname);
6865: DMHasLabel(dm, lname, &hasLabel);
6867: PetscCalloc1(1, &tmpLabel);
6868: tmpLabel->label = label;
6869: tmpLabel->output = PETSC_TRUE;
6870: for (p = &dm->labels; (l = *p); p = &l->next) { }
6871: *p = tmpLabel;
6872: PetscObjectReference((PetscObject)label);
6873: PetscStrcmp(lname, "depth", &flg);
6874: if (flg) dm->depthLabel = label;
6875: PetscStrcmp(lname, "celltype", &flg);
6876: if (flg) dm->celltypeLabel = label;
6877: return 0;
6878: }
6880: /*@C
6881: DMSetLabel - Replaces the label of a given name, or ignores it if the name is not present
6883: Not Collective
6885: Input Parameters:
6886: + dm - The `DM` object
6887: - label - The `DMLabel`, having the same name, to substitute
6889: Default labels in a `DMPLEX`:
6890: + "depth" - Holds the depth (co-dimension) of each mesh point
6891: . "celltype" - Holds the topological type of each cell
6892: . "ghost" - If the DM is distributed with overlap, this marks the cells and faces in the overlap
6893: . "Cell Sets" - Mirrors the cell sets defined by GMsh and ExodusII
6894: . "Face Sets" - Mirrors the face sets defined by GMsh and ExodusII
6895: - "Vertex Sets" - Mirrors the vertex sets defined by GMsh
6897: Level: intermediate
6899: .seealso: `DMLabel`, `DMCreateLabel()`, `DMHasLabel()`, `DMPlexGetDepthLabel()`, `DMPlexGetCellType()`
6900: @*/
6901: PetscErrorCode DMSetLabel(DM dm, DMLabel label)
6902: {
6903: DMLabelLink next = dm->labels;
6904: PetscBool hasLabel, flg;
6905: const char *name, *lname;
6909: PetscObjectGetName((PetscObject)label, &name);
6910: while (next) {
6911: PetscObjectGetName((PetscObject)next->label, &lname);
6912: PetscStrcmp(name, lname, &hasLabel);
6913: if (hasLabel) {
6914: PetscObjectReference((PetscObject)label);
6915: PetscStrcmp(lname, "depth", &flg);
6916: if (flg) dm->depthLabel = label;
6917: PetscStrcmp(lname, "celltype", &flg);
6918: if (flg) dm->celltypeLabel = label;
6919: DMLabelDestroy(&next->label);
6920: next->label = label;
6921: break;
6922: }
6923: next = next->next;
6924: }
6925: return 0;
6926: }
6928: /*@C
6929: DMRemoveLabel - Remove the label given by name from this `DM`
6931: Not Collective
6933: Input Parameters:
6934: + dm - The `DM` object
6935: - name - The label name
6937: Output Parameter:
6938: . label - The `DMLabel`, or NULL if the label is absent. Pass in NULL to call `DMLabelDestroy()` on the label, otherwise the
6939: caller is responsible for calling `DMLabelDestroy()`.
6941: Level: developer
6943: .seealso: `DMLabel`, `DMCreateLabel()`, `DMHasLabel()`, `DMGetLabel()`, `DMGetLabelValue()`, `DMSetLabelValue()`, `DMLabelDestroy()`, `DMRemoveLabelBySelf()`
6944: @*/
6945: PetscErrorCode DMRemoveLabel(DM dm, const char name[], DMLabel *label)
6946: {
6947: DMLabelLink link, *pnext;
6948: PetscBool hasLabel;
6949: const char *lname;
6953: if (label) {
6955: *label = NULL;
6956: }
6957: for (pnext = &dm->labels; (link = *pnext); pnext = &link->next) {
6958: PetscObjectGetName((PetscObject)link->label, &lname);
6959: PetscStrcmp(name, lname, &hasLabel);
6960: if (hasLabel) {
6961: *pnext = link->next; /* Remove from list */
6962: PetscStrcmp(name, "depth", &hasLabel);
6963: if (hasLabel) dm->depthLabel = NULL;
6964: PetscStrcmp(name, "celltype", &hasLabel);
6965: if (hasLabel) dm->celltypeLabel = NULL;
6966: if (label) *label = link->label;
6967: else DMLabelDestroy(&link->label);
6968: PetscFree(link);
6969: break;
6970: }
6971: }
6972: return 0;
6973: }
6975: /*@
6976: DMRemoveLabelBySelf - Remove the label from this `DM`
6978: Not Collective
6980: Input Parameters:
6981: + dm - The `DM` object
6982: . label - The `DMLabel` to be removed from the `DM`
6983: - failNotFound - Should it fail if the label is not found in the DM?
6985: Level: developer
6987: Note:
6988: Only exactly the same instance is removed if found, name match is ignored.
6989: If the `DM` has an exclusive reference to the label, the label gets destroyed and
6990: *label nullified.
6992: .seealso: `DMLabel`, `DMCreateLabel()`, `DMHasLabel()`, `DMGetLabel()` `DMGetLabelValue()`, `DMSetLabelValue()`, `DMLabelDestroy()`, `DMRemoveLabel()`
6993: @*/
6994: PetscErrorCode DMRemoveLabelBySelf(DM dm, DMLabel *label, PetscBool failNotFound)
6995: {
6996: DMLabelLink link, *pnext;
6997: PetscBool hasLabel = PETSC_FALSE;
7001: if (!*label && !failNotFound) return 0;
7004: for (pnext = &dm->labels; (link = *pnext); pnext = &link->next) {
7005: if (*label == link->label) {
7006: hasLabel = PETSC_TRUE;
7007: *pnext = link->next; /* Remove from list */
7008: if (*label == dm->depthLabel) dm->depthLabel = NULL;
7009: if (*label == dm->celltypeLabel) dm->celltypeLabel = NULL;
7010: if (((PetscObject)link->label)->refct < 2) *label = NULL; /* nullify if exclusive reference */
7011: DMLabelDestroy(&link->label);
7012: PetscFree(link);
7013: break;
7014: }
7015: }
7017: return 0;
7018: }
7020: /*@C
7021: DMGetLabelOutput - Get the output flag for a given label
7023: Not Collective
7025: Input Parameters:
7026: + dm - The `DM` object
7027: - name - The label name
7029: Output Parameter:
7030: . output - The flag for output
7032: Level: developer
7034: .seealso: `DMLabel`, `DMSetLabelOutput()`, `DMCreateLabel()`, `DMHasLabel()`, `DMGetLabelValue()`, `DMSetLabelValue()`, `DMGetStratumIS()`
7035: @*/
7036: PetscErrorCode DMGetLabelOutput(DM dm, const char name[], PetscBool *output)
7037: {
7038: DMLabelLink next = dm->labels;
7039: const char *lname;
7044: while (next) {
7045: PetscBool flg;
7047: PetscObjectGetName((PetscObject)next->label, &lname);
7048: PetscStrcmp(name, lname, &flg);
7049: if (flg) {
7050: *output = next->output;
7051: return 0;
7052: }
7053: next = next->next;
7054: }
7055: SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "No label named %s was present in this dm", name);
7056: }
7058: /*@C
7059: DMSetLabelOutput - Set if a given label should be saved to a `PetscViewer` in calls to `DMView()`
7061: Not Collective
7063: Input Parameters:
7064: + dm - The `DM` object
7065: . name - The label name
7066: - output - `PETSC_TRUE` to save the label to the viewer
7068: Level: developer
7070: .seealso: `DMLabel`, `DMGetOutputFlag()`, `DMGetLabelOutput()`, `DMCreateLabel()`, `DMHasLabel()`, `DMGetLabelValue()`, `DMSetLabelValue()`, `DMGetStratumIS()`
7071: @*/
7072: PetscErrorCode DMSetLabelOutput(DM dm, const char name[], PetscBool output)
7073: {
7074: DMLabelLink next = dm->labels;
7075: const char *lname;
7079: while (next) {
7080: PetscBool flg;
7082: PetscObjectGetName((PetscObject)next->label, &lname);
7083: PetscStrcmp(name, lname, &flg);
7084: if (flg) {
7085: next->output = output;
7086: return 0;
7087: }
7088: next = next->next;
7089: }
7090: SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "No label named %s was present in this dm", name);
7091: }
7093: /*@
7094: DMCopyLabels - Copy labels from one `DM` mesh to another `DM` with a superset of the points
7096: Collective on dmA
7098: Input Parameters:
7099: + dmA - The `DM` object with initial labels
7100: . dmB - The `DM` object to which labels are copied
7101: . mode - Copy labels by pointers (`PETSC_OWN_POINTER`) or duplicate them (`PETSC_COPY_VALUES`)
7102: . all - Copy all labels including "depth", "dim", and "celltype" (`PETSC_TRUE`) which are otherwise ignored (`PETSC_FALSE`)
7103: - emode - How to behave when a `DMLabel` in the source and destination `DM`s with the same name is encountered (see `DMCopyLabelsMode`)
7105: Level: intermediate
7107: Note:
7108: This is typically used when interpolating or otherwise adding to a mesh, or testing.
7110: .seealso: `DMLabel`, `DMAddLabel()`, `DMCopyLabelsMode`
7111: @*/
7112: PetscErrorCode DMCopyLabels(DM dmA, DM dmB, PetscCopyMode mode, PetscBool all, DMCopyLabelsMode emode)
7113: {
7114: DMLabel label, labelNew, labelOld;
7115: const char *name;
7116: PetscBool flg;
7117: DMLabelLink link;
7124: if (dmA == dmB) return 0;
7125: for (link = dmA->labels; link; link = link->next) {
7126: label = link->label;
7127: PetscObjectGetName((PetscObject)label, &name);
7128: if (!all) {
7129: PetscStrcmp(name, "depth", &flg);
7130: if (flg) continue;
7131: PetscStrcmp(name, "dim", &flg);
7132: if (flg) continue;
7133: PetscStrcmp(name, "celltype", &flg);
7134: if (flg) continue;
7135: }
7136: DMGetLabel(dmB, name, &labelOld);
7137: if (labelOld) {
7138: switch (emode) {
7139: case DM_COPY_LABELS_KEEP:
7140: continue;
7141: case DM_COPY_LABELS_REPLACE:
7142: DMRemoveLabelBySelf(dmB, &labelOld, PETSC_TRUE);
7143: break;
7144: case DM_COPY_LABELS_FAIL:
7145: SETERRQ(PetscObjectComm((PetscObject)dmA), PETSC_ERR_ARG_OUTOFRANGE, "Label %s already exists in destination DM", name);
7146: default:
7147: SETERRQ(PetscObjectComm((PetscObject)dmA), PETSC_ERR_ARG_OUTOFRANGE, "Unhandled DMCopyLabelsMode %d", (int)emode);
7148: }
7149: }
7150: if (mode == PETSC_COPY_VALUES) {
7151: DMLabelDuplicate(label, &labelNew);
7152: } else {
7153: labelNew = label;
7154: }
7155: DMAddLabel(dmB, labelNew);
7156: if (mode == PETSC_COPY_VALUES) DMLabelDestroy(&labelNew);
7157: }
7158: return 0;
7159: }
7161: /*@C
7162: DMCompareLabels - Compare labels of two `DMPLEX` meshes
7164: Collective
7166: Input Parameters:
7167: + dm0 - First `DM` object
7168: - dm1 - Second `DM` object
7170: Output Parameters
7171: + equal - (Optional) Flag whether labels of dm0 and dm1 are the same
7172: - message - (Optional) Message describing the difference, or NULL if there is no difference
7174: Level: intermediate
7176: Notes:
7177: The output flag equal will be the same on all processes.
7179: If equal is passed as NULL and difference is found, an error is thrown on all processes.
7181: Make sure to pass equal is NULL on all processes or none of them.
7183: The output message is set independently on each rank.
7185: message must be freed with `PetscFree()`
7187: If message is passed as NULL and a difference is found, the difference description is printed to stderr in synchronized manner.
7189: Make sure to pass message as NULL on all processes or no processes.
7191: Labels are matched by name. If the number of labels and their names are equal,
7192: `DMLabelCompare()` is used to compare each pair of labels with the same name.
7194: Fortran Note:
7195: This function is not available from Fortran.
7197: .seealso: `DMLabel`, `DMAddLabel()`, `DMCopyLabelsMode`, `DMLabelCompare()`
7198: @*/
7199: PetscErrorCode DMCompareLabels(DM dm0, DM dm1, PetscBool *equal, char **message)
7200: {
7201: PetscInt n, i;
7202: char msg[PETSC_MAX_PATH_LEN] = "";
7203: PetscBool eq;
7204: MPI_Comm comm;
7205: PetscMPIInt rank;
7212: PetscObjectGetComm((PetscObject)dm0, &comm);
7213: MPI_Comm_rank(comm, &rank);
7214: {
7215: PetscInt n1;
7217: DMGetNumLabels(dm0, &n);
7218: DMGetNumLabels(dm1, &n1);
7219: eq = (PetscBool)(n == n1);
7220: if (!eq) PetscSNPrintf(msg, sizeof(msg), "Number of labels in dm0 = %" PetscInt_FMT " != %" PetscInt_FMT " = Number of labels in dm1", n, n1);
7221: MPI_Allreduce(MPI_IN_PLACE, &eq, 1, MPIU_BOOL, MPI_LAND, comm);
7222: if (!eq) goto finish;
7223: }
7224: for (i = 0; i < n; i++) {
7225: DMLabel l0, l1;
7226: const char *name;
7227: char *msgInner;
7229: /* Ignore label order */
7230: DMGetLabelByNum(dm0, i, &l0);
7231: PetscObjectGetName((PetscObject)l0, &name);
7232: DMGetLabel(dm1, name, &l1);
7233: if (!l1) {
7234: PetscSNPrintf(msg, sizeof(msg), "Label \"%s\" (#%" PetscInt_FMT " in dm0) not found in dm1", name, i);
7235: eq = PETSC_FALSE;
7236: break;
7237: }
7238: DMLabelCompare(comm, l0, l1, &eq, &msgInner);
7239: PetscStrncpy(msg, msgInner, sizeof(msg));
7240: PetscFree(msgInner);
7241: if (!eq) break;
7242: }
7243: MPI_Allreduce(MPI_IN_PLACE, &eq, 1, MPIU_BOOL, MPI_LAND, comm);
7244: finish:
7245: /* If message output arg not set, print to stderr */
7246: if (message) {
7247: *message = NULL;
7248: if (msg[0]) PetscStrallocpy(msg, message);
7249: } else {
7250: if (msg[0]) PetscSynchronizedFPrintf(comm, PETSC_STDERR, "[%d] %s\n", rank, msg);
7251: PetscSynchronizedFlush(comm, PETSC_STDERR);
7252: }
7253: /* If same output arg not ser and labels are not equal, throw error */
7254: if (equal) *equal = eq;
7256: return 0;
7257: }
7259: PetscErrorCode DMSetLabelValue_Fast(DM dm, DMLabel *label, const char name[], PetscInt point, PetscInt value)
7260: {
7262: if (!*label) {
7263: DMCreateLabel(dm, name);
7264: DMGetLabel(dm, name, label);
7265: }
7266: DMLabelSetValue(*label, point, value);
7267: return 0;
7268: }
7270: /*
7271: Many mesh programs, such as Triangle and TetGen, allow only a single label for each mesh point. Therefore, we would
7272: like to encode all label IDs using a single, universal label. We can do this by assigning an integer to every
7273: (label, id) pair in the DM.
7275: However, a mesh point can have multiple labels, so we must separate all these values. We will assign a bit range to
7276: each label.
7277: */
7278: PetscErrorCode DMUniversalLabelCreate(DM dm, DMUniversalLabel *universal)
7279: {
7280: DMUniversalLabel ul;
7281: PetscBool *active;
7282: PetscInt pStart, pEnd, p, Nl, l, m;
7284: PetscMalloc1(1, &ul);
7285: DMLabelCreate(PETSC_COMM_SELF, "universal", &ul->label);
7286: DMGetNumLabels(dm, &Nl);
7287: PetscCalloc1(Nl, &active);
7288: ul->Nl = 0;
7289: for (l = 0; l < Nl; ++l) {
7290: PetscBool isdepth, iscelltype;
7291: const char *name;
7293: DMGetLabelName(dm, l, &name);
7294: PetscStrncmp(name, "depth", 6, &isdepth);
7295: PetscStrncmp(name, "celltype", 9, &iscelltype);
7296: active[l] = !(isdepth || iscelltype) ? PETSC_TRUE : PETSC_FALSE;
7297: if (active[l]) ++ul->Nl;
7298: }
7299: PetscCalloc5(ul->Nl, &ul->names, ul->Nl, &ul->indices, ul->Nl + 1, &ul->offsets, ul->Nl + 1, &ul->bits, ul->Nl, &ul->masks);
7300: ul->Nv = 0;
7301: for (l = 0, m = 0; l < Nl; ++l) {
7302: DMLabel label;
7303: PetscInt nv;
7304: const char *name;
7306: if (!active[l]) continue;
7307: DMGetLabelName(dm, l, &name);
7308: DMGetLabelByNum(dm, l, &label);
7309: DMLabelGetNumValues(label, &nv);
7310: PetscStrallocpy(name, &ul->names[m]);
7311: ul->indices[m] = l;
7312: ul->Nv += nv;
7313: ul->offsets[m + 1] = nv;
7314: ul->bits[m + 1] = PetscCeilReal(PetscLog2Real(nv + 1));
7315: ++m;
7316: }
7317: for (l = 1; l <= ul->Nl; ++l) {
7318: ul->offsets[l] = ul->offsets[l - 1] + ul->offsets[l];
7319: ul->bits[l] = ul->bits[l - 1] + ul->bits[l];
7320: }
7321: for (l = 0; l < ul->Nl; ++l) {
7322: PetscInt b;
7324: ul->masks[l] = 0;
7325: for (b = ul->bits[l]; b < ul->bits[l + 1]; ++b) ul->masks[l] |= 1 << b;
7326: }
7327: PetscMalloc1(ul->Nv, &ul->values);
7328: for (l = 0, m = 0; l < Nl; ++l) {
7329: DMLabel label;
7330: IS valueIS;
7331: const PetscInt *varr;
7332: PetscInt nv, v;
7334: if (!active[l]) continue;
7335: DMGetLabelByNum(dm, l, &label);
7336: DMLabelGetNumValues(label, &nv);
7337: DMLabelGetValueIS(label, &valueIS);
7338: ISGetIndices(valueIS, &varr);
7339: for (v = 0; v < nv; ++v) ul->values[ul->offsets[m] + v] = varr[v];
7340: ISRestoreIndices(valueIS, &varr);
7341: ISDestroy(&valueIS);
7342: PetscSortInt(nv, &ul->values[ul->offsets[m]]);
7343: ++m;
7344: }
7345: DMPlexGetChart(dm, &pStart, &pEnd);
7346: for (p = pStart; p < pEnd; ++p) {
7347: PetscInt uval = 0;
7348: PetscBool marked = PETSC_FALSE;
7350: for (l = 0, m = 0; l < Nl; ++l) {
7351: DMLabel label;
7352: PetscInt val, defval, loc, nv;
7354: if (!active[l]) continue;
7355: DMGetLabelByNum(dm, l, &label);
7356: DMLabelGetValue(label, p, &val);
7357: DMLabelGetDefaultValue(label, &defval);
7358: if (val == defval) {
7359: ++m;
7360: continue;
7361: }
7362: nv = ul->offsets[m + 1] - ul->offsets[m];
7363: marked = PETSC_TRUE;
7364: PetscFindInt(val, nv, &ul->values[ul->offsets[m]], &loc);
7366: uval += (loc + 1) << ul->bits[m];
7367: ++m;
7368: }
7369: if (marked) DMLabelSetValue(ul->label, p, uval);
7370: }
7371: PetscFree(active);
7372: *universal = ul;
7373: return 0;
7374: }
7376: PetscErrorCode DMUniversalLabelDestroy(DMUniversalLabel *universal)
7377: {
7378: PetscInt l;
7380: for (l = 0; l < (*universal)->Nl; ++l) PetscFree((*universal)->names[l]);
7381: DMLabelDestroy(&(*universal)->label);
7382: PetscFree5((*universal)->names, (*universal)->indices, (*universal)->offsets, (*universal)->bits, (*universal)->masks);
7383: PetscFree((*universal)->values);
7384: PetscFree(*universal);
7385: *universal = NULL;
7386: return 0;
7387: }
7389: PetscErrorCode DMUniversalLabelGetLabel(DMUniversalLabel ul, DMLabel *ulabel)
7390: {
7392: *ulabel = ul->label;
7393: return 0;
7394: }
7396: PetscErrorCode DMUniversalLabelCreateLabels(DMUniversalLabel ul, PetscBool preserveOrder, DM dm)
7397: {
7398: PetscInt Nl = ul->Nl, l;
7401: for (l = 0; l < Nl; ++l) {
7402: if (preserveOrder) DMCreateLabelAtIndex(dm, ul->indices[l], ul->names[l]);
7403: else DMCreateLabel(dm, ul->names[l]);
7404: }
7405: if (preserveOrder) {
7406: for (l = 0; l < ul->Nl; ++l) {
7407: const char *name;
7408: PetscBool match;
7410: DMGetLabelName(dm, ul->indices[l], &name);
7411: PetscStrcmp(name, ul->names[l], &match);
7413: }
7414: }
7415: return 0;
7416: }
7418: PetscErrorCode DMUniversalLabelSetLabelValue(DMUniversalLabel ul, DM dm, PetscBool useIndex, PetscInt p, PetscInt value)
7419: {
7420: PetscInt l;
7422: for (l = 0; l < ul->Nl; ++l) {
7423: DMLabel label;
7424: PetscInt lval = (value & ul->masks[l]) >> ul->bits[l];
7426: if (lval) {
7427: if (useIndex) DMGetLabelByNum(dm, ul->indices[l], &label);
7428: else DMGetLabel(dm, ul->names[l], &label);
7429: DMLabelSetValue(label, p, ul->values[ul->offsets[l] + lval - 1]);
7430: }
7431: }
7432: return 0;
7433: }
7435: /*@
7436: DMGetCoarseDM - Get the coarse `DM`from which this `DM` was obtained by refinement
7438: Not collective
7440: Input Parameter:
7441: . dm - The `DM` object
7443: Output Parameter:
7444: . cdm - The coarse `DM`
7446: Level: intermediate
7448: .seealso: `DMSetCoarseDM()`, `DMCoarsen()`
7449: @*/
7450: PetscErrorCode DMGetCoarseDM(DM dm, DM *cdm)
7451: {
7454: *cdm = dm->coarseMesh;
7455: return 0;
7456: }
7458: /*@
7459: DMSetCoarseDM - Set the coarse `DM` from which this `DM` was obtained by refinement
7461: Input Parameters:
7462: + dm - The `DM` object
7463: - cdm - The coarse `DM`
7465: Level: intermediate
7467: Note:
7468: Normally this is set automatically by `DMRefine()`
7470: .seealso: `DMGetCoarseDM()`, `DMCoarsen()`, `DMSetRefine()`, `DMSetFineDM()`
7471: @*/
7472: PetscErrorCode DMSetCoarseDM(DM dm, DM cdm)
7473: {
7476: if (dm == cdm) cdm = NULL;
7477: PetscObjectReference((PetscObject)cdm);
7478: DMDestroy(&dm->coarseMesh);
7479: dm->coarseMesh = cdm;
7480: return 0;
7481: }
7483: /*@
7484: DMGetFineDM - Get the fine mesh from which this `DM` was obtained by coarsening
7486: Input Parameter:
7487: . dm - The `DM` object
7489: Output Parameter:
7490: . fdm - The fine `DM`
7492: Level: intermediate
7494: .seealso: `DMSetFineDM()`, `DMCoarsen()`, `DMRefine()`
7495: @*/
7496: PetscErrorCode DMGetFineDM(DM dm, DM *fdm)
7497: {
7500: *fdm = dm->fineMesh;
7501: return 0;
7502: }
7504: /*@
7505: DMSetFineDM - Set the fine mesh from which this was obtained by coarsening
7507: Input Parameters:
7508: + dm - The `DM` object
7509: - fdm - The fine `DM`
7511: Level: developer
7513: Note:
7514: Normally this is set automatically by `DMCoarsen()`
7516: .seealso: `DMGetFineDM()`, `DMCoarsen()`, `DMRefine()`
7517: @*/
7518: PetscErrorCode DMSetFineDM(DM dm, DM fdm)
7519: {
7522: if (dm == fdm) fdm = NULL;
7523: PetscObjectReference((PetscObject)fdm);
7524: DMDestroy(&dm->fineMesh);
7525: dm->fineMesh = fdm;
7526: return 0;
7527: }
7529: /*@C
7530: DMAddBoundary - Add a boundary condition to a model represented by a `DM`
7532: Collective on dm
7534: Input Parameters:
7535: + dm - The `DM`, with a `PetscDS` that matches the problem being constrained
7536: . type - The type of condition, e.g. `DM_BC_ESSENTIAL_ANALYTIC`, `DM_BC_ESSENTIAL_FIELD` (Dirichlet), or `DM_BC_NATURAL` (Neumann)
7537: . name - The BC name
7538: . label - The label defining constrained points
7539: . Nv - The number of `DMLabel` values for constrained points
7540: . values - An array of values for constrained points
7541: . field - The field to constrain
7542: . Nc - The number of constrained field components (0 will constrain all fields)
7543: . comps - An array of constrained component numbers
7544: . bcFunc - A pointwise function giving boundary values
7545: . bcFunc_t - A pointwise function giving the time deriative of the boundary values, or NULL
7546: - ctx - An optional user context for bcFunc
7548: Output Parameter:
7549: . bd - (Optional) Boundary number
7551: Options Database Keys:
7552: + -bc_<boundary name> <num> - Overrides the boundary ids
7553: - -bc_<boundary name>_comp <num> - Overrides the boundary components
7555: Notes:
7556: Both bcFunc abd bcFunc_t will depend on the boundary condition type. If the type if `DM_BC_ESSENTIAL`, then the calling sequence is:
7558: $ bcFunc(PetscInt dim, PetscReal time, const PetscReal x[], PetscInt Nc, PetscScalar bcval[])
7560: If the type is `DM_BC_ESSENTIAL_FIELD` or other _FIELD value, then the calling sequence is:
7562: $ bcFunc(PetscInt dim, PetscInt Nf, PetscInt NfAux,
7563: $ const PetscInt uOff[], const PetscInt uOff_x[], const PetscScalar u[], const PetscScalar u_t[], const PetscScalar u_x[],
7564: $ const PetscInt aOff[], const PetscInt aOff_x[], const PetscScalar a[], const PetscScalar a_t[], const PetscScalar a_x[],
7565: $ PetscReal time, const PetscReal x[], PetscScalar bcval[])
7567: + dim - the spatial dimension
7568: . Nf - the number of fields
7569: . uOff - the offset into u[] and u_t[] for each field
7570: . uOff_x - the offset into u_x[] for each field
7571: . u - each field evaluated at the current point
7572: . u_t - the time derivative of each field evaluated at the current point
7573: . u_x - the gradient of each field evaluated at the current point
7574: . aOff - the offset into a[] and a_t[] for each auxiliary field
7575: . aOff_x - the offset into a_x[] for each auxiliary field
7576: . a - each auxiliary field evaluated at the current point
7577: . a_t - the time derivative of each auxiliary field evaluated at the current point
7578: . a_x - the gradient of auxiliary each field evaluated at the current point
7579: . t - current time
7580: . x - coordinates of the current point
7581: . numConstants - number of constant parameters
7582: . constants - constant parameters
7583: - bcval - output values at the current point
7585: Level: intermediate
7587: .seealso: `DSGetBoundary()`, `PetscDSAddBoundary()`
7588: @*/
7589: PetscErrorCode DMAddBoundary(DM dm, DMBoundaryConditionType type, const char name[], DMLabel label, PetscInt Nv, const PetscInt values[], PetscInt field, PetscInt Nc, const PetscInt comps[], void (*bcFunc)(void), void (*bcFunc_t)(void), void *ctx, PetscInt *bd)
7590: {
7591: PetscDS ds;
7600: DMGetDS(dm, &ds);
7601: /* Complete label */
7602: if (label) {
7603: PetscObject obj;
7604: PetscClassId id;
7606: DMGetField(dm, field, NULL, &obj);
7607: PetscObjectGetClassId(obj, &id);
7608: if (id == PETSCFE_CLASSID) {
7609: DM plex;
7611: DMConvert(dm, DMPLEX, &plex);
7612: if (plex) DMPlexLabelComplete(plex, label);
7613: DMDestroy(&plex);
7614: }
7615: }
7616: PetscDSAddBoundary(ds, type, name, label, Nv, values, field, Nc, comps, bcFunc, bcFunc_t, ctx, bd);
7617: return 0;
7618: }
7620: /* TODO Remove this since now the structures are the same */
7621: static PetscErrorCode DMPopulateBoundary(DM dm)
7622: {
7623: PetscDS ds;
7624: DMBoundary *lastnext;
7625: DSBoundary dsbound;
7627: DMGetDS(dm, &ds);
7628: dsbound = ds->boundary;
7629: if (dm->boundary) {
7630: DMBoundary next = dm->boundary;
7632: /* quick check to see if the PetscDS has changed */
7633: if (next->dsboundary == dsbound) return 0;
7634: /* the PetscDS has changed: tear down and rebuild */
7635: while (next) {
7636: DMBoundary b = next;
7638: next = b->next;
7639: PetscFree(b);
7640: }
7641: dm->boundary = NULL;
7642: }
7644: lastnext = &(dm->boundary);
7645: while (dsbound) {
7646: DMBoundary dmbound;
7648: PetscNew(&dmbound);
7649: dmbound->dsboundary = dsbound;
7650: dmbound->label = dsbound->label;
7651: /* push on the back instead of the front so that it is in the same order as in the PetscDS */
7652: *lastnext = dmbound;
7653: lastnext = &(dmbound->next);
7654: dsbound = dsbound->next;
7655: }
7656: return 0;
7657: }
7659: /* TODO: missing manual page */
7660: PetscErrorCode DMIsBoundaryPoint(DM dm, PetscInt point, PetscBool *isBd)
7661: {
7662: DMBoundary b;
7666: *isBd = PETSC_FALSE;
7667: DMPopulateBoundary(dm);
7668: b = dm->boundary;
7669: while (b && !(*isBd)) {
7670: DMLabel label = b->label;
7671: DSBoundary dsb = b->dsboundary;
7672: PetscInt i;
7674: if (label) {
7675: for (i = 0; i < dsb->Nv && !(*isBd); ++i) DMLabelStratumHasPoint(label, dsb->values[i], point, isBd);
7676: }
7677: b = b->next;
7678: }
7679: return 0;
7680: }
7682: /*@C
7683: DMProjectFunction - This projects the given function into the function space provided by a `DM`, putting the coefficients in a global vector.
7685: Collective on dm
7687: Input Parameters:
7688: + dm - The `DM`
7689: . time - The time
7690: . funcs - The coordinate functions to evaluate, one per field
7691: . ctxs - Optional array of contexts to pass to each coordinate function. ctxs itself may be null.
7692: - mode - The insertion mode for values
7694: Output Parameter:
7695: . X - vector
7697: Calling sequence of func:
7698: $ func(PetscInt dim, PetscReal time, const PetscReal x[], PetscInt Nc, PetscScalar u[], void *ctx);
7700: + dim - The spatial dimension
7701: . time - The time at which to sample
7702: . x - The coordinates
7703: . Nc - The number of components
7704: . u - The output field values
7705: - ctx - optional user-defined function context
7707: Level: developer
7709: Developer Notes:
7710: This API is specific to only particular usage of `DM`
7712: The notes need to provide some information about what has to be provided to the `DM` to be able to perform the computation.
7714: .seealso: `DMProjectFunctionLocal()`, `DMProjectFunctionLabel()`, `DMComputeL2Diff()`
7715: @*/
7716: PetscErrorCode DMProjectFunction(DM dm, PetscReal time, PetscErrorCode (**funcs)(PetscInt, PetscReal, const PetscReal[], PetscInt, PetscScalar *, void *), void **ctxs, InsertMode mode, Vec X)
7717: {
7718: Vec localX;
7721: DMGetLocalVector(dm, &localX);
7722: DMProjectFunctionLocal(dm, time, funcs, ctxs, mode, localX);
7723: DMLocalToGlobalBegin(dm, localX, mode, X);
7724: DMLocalToGlobalEnd(dm, localX, mode, X);
7725: DMRestoreLocalVector(dm, &localX);
7726: return 0;
7727: }
7729: /*@C
7730: DMProjectFunctionLocal - This projects the given function into the function space provided by a `DM`, putting the coefficients in a local vector.
7732: Not collective
7734: Input Parameters:
7735: + dm - The `DM`
7736: . time - The time
7737: . funcs - The coordinate functions to evaluate, one per field
7738: . ctxs - Optional array of contexts to pass to each coordinate function. ctxs itself may be null.
7739: - mode - The insertion mode for values
7741: Output Parameter:
7742: . localX - vector
7744: Calling sequence of func:
7745: $ func(PetscInt dim, PetscReal time, const PetscReal x[], PetscInt Nc, PetscScalar u[], void *ctx);
7747: + dim - The spatial dimension
7748: . x - The coordinates
7749: . Nc - The number of components
7750: . u - The output field values
7751: - ctx - optional user-defined function context
7753: Level: developer
7755: Developer Notes:
7756: This API is specific to only particular usage of `DM`
7758: The notes need to provide some information about what has to be provided to the `DM` to be able to perform the computation.
7760: .seealso: `DMProjectFunction()`, `DMProjectFunctionLabel()`, `DMComputeL2Diff()`
7761: @*/
7762: PetscErrorCode DMProjectFunctionLocal(DM dm, PetscReal time, PetscErrorCode (**funcs)(PetscInt, PetscReal, const PetscReal[], PetscInt, PetscScalar *, void *), void **ctxs, InsertMode mode, Vec localX)
7763: {
7766: (dm->ops->projectfunctionlocal)(dm, time, funcs, ctxs, mode, localX);
7767: return 0;
7768: }
7770: /*@C
7771: 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.
7773: Collective on dm
7775: Input Parameters:
7776: + dm - The `DM`
7777: . time - The time
7778: . label - The `DMLabel` selecting the portion of the mesh for projection
7779: . funcs - The coordinate functions to evaluate, one per field
7780: . ctxs - Optional array of contexts to pass to each coordinate function. ctxs may be null.
7781: - mode - The insertion mode for values
7783: Output Parameter:
7784: . X - vector
7786: Calling sequence of func:
7787: $ func(PetscInt dim, PetscReal time, const PetscReal x[], PetscInt Nc, PetscScalar u[], void *ctx);
7789: + dim - The spatial dimension
7790: . x - The coordinates
7791: . Nc - The number of components
7792: . u - The output field values
7793: - ctx - optional user-defined function context
7795: Level: developer
7797: Developer Notes:
7798: This API is specific to only particular usage of `DM`
7800: The notes need to provide some information about what has to be provided to the `DM` to be able to perform the computation.
7802: .seealso: `DMProjectFunction()`, `DMProjectFunctionLocal()`, `DMProjectFunctionLabelLocal()`, `DMComputeL2Diff()`
7803: @*/
7804: PetscErrorCode DMProjectFunctionLabel(DM dm, PetscReal time, DMLabel label, PetscInt numIds, const PetscInt ids[], PetscInt Nc, const PetscInt comps[], PetscErrorCode (**funcs)(PetscInt, PetscReal, const PetscReal[], PetscInt, PetscScalar *, void *), void **ctxs, InsertMode mode, Vec X)
7805: {
7806: Vec localX;
7809: DMGetLocalVector(dm, &localX);
7810: DMProjectFunctionLabelLocal(dm, time, label, numIds, ids, Nc, comps, funcs, ctxs, mode, localX);
7811: DMLocalToGlobalBegin(dm, localX, mode, X);
7812: DMLocalToGlobalEnd(dm, localX, mode, X);
7813: DMRestoreLocalVector(dm, &localX);
7814: return 0;
7815: }
7817: /*@C
7818: 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.
7820: Not collective
7822: Input Parameters:
7823: + dm - The `DM`
7824: . time - The time
7825: . label - The `DMLabel` selecting the portion of the mesh for projection
7826: . funcs - The coordinate functions to evaluate, one per field
7827: . ctxs - Optional array of contexts to pass to each coordinate function. ctxs itself may be null.
7828: - mode - The insertion mode for values
7830: Output Parameter:
7831: . localX - vector
7833: Calling sequence of func:
7834: $ func(PetscInt dim, PetscReal time, const PetscReal x[], PetscInt Nc, PetscScalar u[], void *ctx);
7836: + dim - The spatial dimension
7837: . x - The coordinates
7838: . Nc - The number of components
7839: . u - The output field values
7840: - ctx - optional user-defined function context
7842: Level: developer
7844: Developer Notes:
7845: This API is specific to only particular usage of `DM`
7847: The notes need to provide some information about what has to be provided to the `DM` to be able to perform the computation.
7849: .seealso: `DMProjectFunction()`, `DMProjectFunctionLocal()`, `DMProjectFunctionLabel()`, `DMComputeL2Diff()`
7850: @*/
7851: PetscErrorCode DMProjectFunctionLabelLocal(DM dm, PetscReal time, DMLabel label, PetscInt numIds, const PetscInt ids[], PetscInt Nc, const PetscInt comps[], PetscErrorCode (**funcs)(PetscInt, PetscReal, const PetscReal[], PetscInt, PetscScalar *, void *), void **ctxs, InsertMode mode, Vec localX)
7852: {
7855: (dm->ops->projectfunctionlabellocal)(dm, time, label, numIds, ids, Nc, comps, funcs, ctxs, mode, localX);
7856: return 0;
7857: }
7859: /*@C
7860: 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.
7862: Not collective
7864: Input Parameters:
7865: + dm - The `DM`
7866: . time - The time
7867: . localU - The input field vector
7868: . funcs - The functions to evaluate, one per field
7869: - mode - The insertion mode for values
7871: Output Parameter:
7872: . localX - The output vector
7874: Calling sequence of func:
7875: $ func(PetscInt dim, PetscInt Nf, PetscInt NfAux,
7876: $ const PetscInt uOff[], const PetscInt uOff_x[], const PetscScalar u[], const PetscScalar u_t[], const PetscScalar u_x[],
7877: $ const PetscInt aOff[], const PetscInt aOff_x[], const PetscScalar a[], const PetscScalar a_t[], const PetscScalar a_x[],
7878: $ PetscReal t, const PetscReal x[], PetscInt numConstants, const PetscScalar constants[], PetscScalar f[]);
7880: + dim - The spatial dimension
7881: . Nf - The number of input fields
7882: . NfAux - The number of input auxiliary fields
7883: . uOff - The offset of each field in u[]
7884: . uOff_x - The offset of each field in u_x[]
7885: . u - The field values at this point in space
7886: . u_t - The field time derivative at this point in space (or NULL)
7887: . u_x - The field derivatives at this point in space
7888: . aOff - The offset of each auxiliary field in u[]
7889: . aOff_x - The offset of each auxiliary field in u_x[]
7890: . a - The auxiliary field values at this point in space
7891: . a_t - The auxiliary field time derivative at this point in space (or NULL)
7892: . a_x - The auxiliary field derivatives at this point in space
7893: . t - The current time
7894: . x - The coordinates of this point
7895: . numConstants - The number of constants
7896: . constants - The value of each constant
7897: - f - The value of the function at this point in space
7899: Note:
7900: 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.
7901: 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
7902: a subdomain. You can also output a different number of fields than the input, with different discretizations. Last the auxiliary `DM`, attached to the
7903: auxiliary field vector, which is attached to dm, can also be different. It can have a different topology, number of fields, and discretizations.
7905: Level: intermediate
7907: Developer Notes:
7908: This API is specific to only particular usage of `DM`
7910: The notes need to provide some information about what has to be provided to the `DM` to be able to perform the computation.
7912: .seealso: `DMProjectField()`, `DMProjectFieldLabelLocal()`, `DMProjectFunction()`, `DMComputeL2Diff()`
7913: @*/
7914: PetscErrorCode DMProjectFieldLocal(DM dm, PetscReal time, Vec localU, void (**funcs)(PetscInt, PetscInt, PetscInt, const PetscInt[], const PetscInt[], const PetscScalar[], const PetscScalar[], const PetscScalar[], const PetscInt[], const PetscInt[], const PetscScalar[], const PetscScalar[], const PetscScalar[], PetscReal, const PetscReal[], PetscInt, const PetscScalar[], PetscScalar[]), InsertMode mode, Vec localX)
7915: {
7919: (dm->ops->projectfieldlocal)(dm, time, localU, funcs, mode, localX);
7920: return 0;
7921: }
7923: /*@C
7924: 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.
7926: Not collective
7928: Input Parameters:
7929: + dm - The `DM`
7930: . time - The time
7931: . label - The `DMLabel` marking the portion of the domain to output
7932: . numIds - The number of label ids to use
7933: . ids - The label ids to use for marking
7934: . Nc - The number of components to set in the output, or `PETSC_DETERMINE` for all components
7935: . comps - The components to set in the output, or NULL for all components
7936: . localU - The input field vector
7937: . funcs - The functions to evaluate, one per field
7938: - mode - The insertion mode for values
7940: Output Parameter:
7941: . localX - The output vector
7943: Calling sequence of func:
7944: $ func(PetscInt dim, PetscInt Nf, PetscInt NfAux,
7945: $ const PetscInt uOff[], const PetscInt uOff_x[], const PetscScalar u[], const PetscScalar u_t[], const PetscScalar u_x[],
7946: $ const PetscInt aOff[], const PetscInt aOff_x[], const PetscScalar a[], const PetscScalar a_t[], const PetscScalar a_x[],
7947: $ PetscReal t, const PetscReal x[], PetscInt numConstants, const PetscScalar constants[], PetscScalar f[]);
7949: + dim - The spatial dimension
7950: . Nf - The number of input fields
7951: . NfAux - The number of input auxiliary fields
7952: . uOff - The offset of each field in u[]
7953: . uOff_x - The offset of each field in u_x[]
7954: . u - The field values at this point in space
7955: . u_t - The field time derivative at this point in space (or NULL)
7956: . u_x - The field derivatives at this point in space
7957: . aOff - The offset of each auxiliary field in u[]
7958: . aOff_x - The offset of each auxiliary field in u_x[]
7959: . a - The auxiliary field values at this point in space
7960: . a_t - The auxiliary field time derivative at this point in space (or NULL)
7961: . a_x - The auxiliary field derivatives at this point in space
7962: . t - The current time
7963: . x - The coordinates of this point
7964: . numConstants - The number of constants
7965: . constants - The value of each constant
7966: - f - The value of the function at this point in space
7968: Note:
7969: 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.
7970: 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
7971: a subdomain. You can also output a different number of fields than the input, with different discretizations. Last the auxiliary `DM`, attached to the
7972: auxiliary field vector, which is attached to dm, can also be different. It can have a different topology, number of fields, and discretizations.
7974: Level: intermediate
7976: Developer Notes:
7977: This API is specific to only particular usage of `DM`
7979: The notes need to provide some information about what has to be provided to the `DM` to be able to perform the computation.
7981: .seealso: `DMProjectField()`, `DMProjectFieldLabel()`, `DMProjectFunction()`, `DMComputeL2Diff()`
7982: @*/
7983: PetscErrorCode DMProjectFieldLabelLocal(DM dm, PetscReal time, DMLabel label, PetscInt numIds, const PetscInt ids[], PetscInt Nc, const PetscInt comps[], Vec localU, void (**funcs)(PetscInt, PetscInt, PetscInt, const PetscInt[], const PetscInt[], const PetscScalar[], const PetscScalar[], const PetscScalar[], const PetscInt[], const PetscInt[], const PetscScalar[], const PetscScalar[], const PetscScalar[], PetscReal, const PetscReal[], PetscInt, const PetscScalar[], PetscScalar[]), InsertMode mode, Vec localX)
7984: {
7988: (dm->ops->projectfieldlabellocal)(dm, time, label, numIds, ids, Nc, comps, localU, funcs, mode, localX);
7989: return 0;
7990: }
7992: /*@C
7993: 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.
7995: Not collective
7997: Input Parameters:
7998: + dm - The `DM`
7999: . time - The time
8000: . label - The `DMLabel` marking the portion of the domain to output
8001: . numIds - The number of label ids to use
8002: . ids - The label ids to use for marking
8003: . Nc - The number of components to set in the output, or `PETSC_DETERMINE` for all components
8004: . comps - The components to set in the output, or NULL for all components
8005: . U - The input field vector
8006: . funcs - The functions to evaluate, one per field
8007: - mode - The insertion mode for values
8009: Output Parameter:
8010: . X - The output vector
8012: Calling sequence of func:
8013: $ func(PetscInt dim, PetscInt Nf, PetscInt NfAux,
8014: $ const PetscInt uOff[], const PetscInt uOff_x[], const PetscScalar u[], const PetscScalar u_t[], const PetscScalar u_x[],
8015: $ const PetscInt aOff[], const PetscInt aOff_x[], const PetscScalar a[], const PetscScalar a_t[], const PetscScalar a_x[],
8016: $ PetscReal t, const PetscReal x[], PetscInt numConstants, const PetscScalar constants[], PetscScalar f[]);
8018: + dim - The spatial dimension
8019: . Nf - The number of input fields
8020: . NfAux - The number of input auxiliary fields
8021: . uOff - The offset of each field in u[]
8022: . uOff_x - The offset of each field in u_x[]
8023: . u - The field values at this point in space
8024: . u_t - The field time derivative at this point in space (or NULL)
8025: . u_x - The field derivatives at this point in space
8026: . aOff - The offset of each auxiliary field in u[]
8027: . aOff_x - The offset of each auxiliary field in u_x[]
8028: . a - The auxiliary field values at this point in space
8029: . a_t - The auxiliary field time derivative at this point in space (or NULL)
8030: . a_x - The auxiliary field derivatives at this point in space
8031: . t - The current time
8032: . x - The coordinates of this point
8033: . numConstants - The number of constants
8034: . constants - The value of each constant
8035: - f - The value of the function at this point in space
8037: Note:
8038: 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.
8039: 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
8040: a subdomain. You can also output a different number of fields than the input, with different discretizations. Last the auxiliary `DM`, attached to the
8041: auxiliary field vector, which is attached to dm, can also be different. It can have a different topology, number of fields, and discretizations.
8043: Level: intermediate
8045: Developer Notes:
8046: This API is specific to only particular usage of `DM`
8048: The notes need to provide some information about what has to be provided to the `DM` to be able to perform the computation.
8050: .seealso: `DMProjectField()`, `DMProjectFieldLabelLocal()`, `DMProjectFunction()`, `DMComputeL2Diff()`
8051: @*/
8052: PetscErrorCode DMProjectFieldLabel(DM dm, PetscReal time, DMLabel label, PetscInt numIds, const PetscInt ids[], PetscInt Nc, const PetscInt comps[], Vec U, void (**funcs)(PetscInt, PetscInt, PetscInt, const PetscInt[], const PetscInt[], const PetscScalar[], const PetscScalar[], const PetscScalar[], const PetscInt[], const PetscInt[], const PetscScalar[], const PetscScalar[], const PetscScalar[], PetscReal, const PetscReal[], PetscInt, const PetscScalar[], PetscScalar[]), InsertMode mode, Vec X)
8053: {
8054: DM dmIn;
8055: Vec localU, localX;
8058: VecGetDM(U, &dmIn);
8059: DMGetLocalVector(dmIn, &localU);
8060: DMGetLocalVector(dm, &localX);
8061: DMGlobalToLocalBegin(dmIn, U, mode, localU);
8062: DMGlobalToLocalEnd(dmIn, U, mode, localU);
8063: DMProjectFieldLabelLocal(dm, time, label, numIds, ids, Nc, comps, localU, funcs, mode, localX);
8064: DMLocalToGlobalBegin(dm, localX, mode, X);
8065: DMLocalToGlobalEnd(dm, localX, mode, X);
8066: DMRestoreLocalVector(dm, &localX);
8067: DMRestoreLocalVector(dmIn, &localU);
8068: return 0;
8069: }
8071: /*@C
8072: 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.
8074: Not collective
8076: Input Parameters:
8077: + dm - The `DM`
8078: . time - The time
8079: . label - The `DMLabel` marking the portion of the domain boundary to output
8080: . numIds - The number of label ids to use
8081: . ids - The label ids to use for marking
8082: . Nc - The number of components to set in the output, or `PETSC_DETERMINE` for all components
8083: . comps - The components to set in the output, or NULL for all components
8084: . localU - The input field vector
8085: . funcs - The functions to evaluate, one per field
8086: - mode - The insertion mode for values
8088: Output Parameter:
8089: . localX - The output vector
8091: Calling sequence of func:
8092: $ func(PetscInt dim, PetscInt Nf, PetscInt NfAux,
8093: $ const PetscInt uOff[], const PetscInt uOff_x[], const PetscScalar u[], const PetscScalar u_t[], const PetscScalar u_x[],
8094: $ const PetscInt aOff[], const PetscInt aOff_x[], const PetscScalar a[], const PetscScalar a_t[], const PetscScalar a_x[],
8095: $ PetscReal t, const PetscReal x[], PetscInt numConstants, const PetscScalar constants[], PetscScalar f[]);
8097: + dim - The spatial dimension
8098: . Nf - The number of input fields
8099: . NfAux - The number of input auxiliary fields
8100: . uOff - The offset of each field in u[]
8101: . uOff_x - The offset of each field in u_x[]
8102: . u - The field values at this point in space
8103: . u_t - The field time derivative at this point in space (or NULL)
8104: . u_x - The field derivatives at this point in space
8105: . aOff - The offset of each auxiliary field in u[]
8106: . aOff_x - The offset of each auxiliary field in u_x[]
8107: . a - The auxiliary field values at this point in space
8108: . a_t - The auxiliary field time derivative at this point in space (or NULL)
8109: . a_x - The auxiliary field derivatives at this point in space
8110: . t - The current time
8111: . x - The coordinates of this point
8112: . n - The face normal
8113: . numConstants - The number of constants
8114: . constants - The value of each constant
8115: - f - The value of the function at this point in space
8117: Note:
8118: 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.
8119: 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
8120: a subdomain. You can also output a different number of fields than the input, with different discretizations. Last the auxiliary `DM`, attached to the
8121: auxiliary field vector, which is attached to dm, can also be different. It can have a different topology, number of fields, and discretizations.
8123: Level: intermediate
8125: Developer Notes:
8126: This API is specific to only particular usage of `DM`
8128: The notes need to provide some information about what has to be provided to the `DM` to be able to perform the computation.
8130: .seealso: `DMProjectField()`, `DMProjectFieldLabelLocal()`, `DMProjectFunction()`, `DMComputeL2Diff()`
8131: @*/
8132: PetscErrorCode DMProjectBdFieldLabelLocal(DM dm, PetscReal time, DMLabel label, PetscInt numIds, const PetscInt ids[], PetscInt Nc, const PetscInt comps[], Vec localU, void (**funcs)(PetscInt, PetscInt, PetscInt, const PetscInt[], const PetscInt[], const PetscScalar[], const PetscScalar[], const PetscScalar[], const PetscInt[], const PetscInt[], const PetscScalar[], const PetscScalar[], const PetscScalar[], PetscReal, const PetscReal[], const PetscReal[], PetscInt, const PetscScalar[], PetscScalar[]), InsertMode mode, Vec localX)
8133: {
8137: (dm->ops->projectbdfieldlabellocal)(dm, time, label, numIds, ids, Nc, comps, localU, funcs, mode, localX);
8138: return 0;
8139: }
8141: /*@C
8142: DMComputeL2Diff - This function computes the L_2 difference between a function u and an FEM interpolant solution u_h.
8144: Collective on dm
8146: Input Parameters:
8147: + dm - The `DM`
8148: . time - The time
8149: . funcs - The functions to evaluate for each field component
8150: . ctxs - Optional array of contexts to pass to each function, or NULL.
8151: - X - The coefficient vector u_h, a global vector
8153: Output Parameter:
8154: . diff - The diff ||u - u_h||_2
8156: Level: developer
8158: Developer Notes:
8159: This API is specific to only particular usage of `DM`
8161: The notes need to provide some information about what has to be provided to the `DM` to be able to perform the computation.
8163: .seealso: `DMProjectFunction()`, `DMComputeL2FieldDiff()`, `DMComputeL2GradientDiff()`
8164: @*/
8165: PetscErrorCode DMComputeL2Diff(DM dm, PetscReal time, PetscErrorCode (**funcs)(PetscInt, PetscReal, const PetscReal[], PetscInt, PetscScalar *, void *), void **ctxs, Vec X, PetscReal *diff)
8166: {
8169: (dm->ops->computel2diff)(dm, time, funcs, ctxs, X, diff);
8170: return 0;
8171: }
8173: /*@C
8174: DMComputeL2GradientDiff - This function computes the L_2 difference between the gradient of a function u and an FEM interpolant solution grad u_h.
8176: Collective on dm
8178: Input Parameters:
8179: + dm - The `DM`
8180: , time - The time
8181: . funcs - The gradient functions to evaluate for each field component
8182: . ctxs - Optional array of contexts to pass to each function, or NULL.
8183: . X - The coefficient vector u_h, a global vector
8184: - n - The vector to project along
8186: Output Parameter:
8187: . diff - The diff ||(grad u - grad u_h) . n||_2
8189: Level: developer
8191: Developer Notes:
8192: This API is specific to only particular usage of `DM`
8194: The notes need to provide some information about what has to be provided to the `DM` to be able to perform the computation.
8196: .seealso: `DMProjectFunction()`, `DMComputeL2Diff()`, `DMComputeL2FieldDiff()`
8197: @*/
8198: 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)
8199: {
8202: (dm->ops->computel2gradientdiff)(dm, time, funcs, ctxs, X, n, diff);
8203: return 0;
8204: }
8206: /*@C
8207: DMComputeL2FieldDiff - This function computes the L_2 difference between a function u and an FEM interpolant solution u_h, separated into field components.
8209: Collective on dm
8211: Input Parameters:
8212: + dm - The `DM`
8213: . time - The time
8214: . funcs - The functions to evaluate for each field component
8215: . ctxs - Optional array of contexts to pass to each function, or NULL.
8216: - X - The coefficient vector u_h, a global vector
8218: Output Parameter:
8219: . diff - The array of differences, ||u^f - u^f_h||_2
8221: Level: developer
8223: Developer Notes:
8224: This API is specific to only particular usage of `DM`
8226: The notes need to provide some information about what has to be provided to the `DM` to be able to perform the computation.
8228: .seealso: `DMProjectFunction()`, `DMComputeL2FieldDiff()`, `DMComputeL2GradientDiff()`
8229: @*/
8230: PetscErrorCode DMComputeL2FieldDiff(DM dm, PetscReal time, PetscErrorCode (**funcs)(PetscInt, PetscReal, const PetscReal[], PetscInt, PetscScalar *, void *), void **ctxs, Vec X, PetscReal diff[])
8231: {
8234: (dm->ops->computel2fielddiff)(dm, time, funcs, ctxs, X, diff);
8235: return 0;
8236: }
8238: /*@C
8239: DMGetNeighbors - Gets an array containing the MPI ranks of all the processes neighbors
8241: Not Collective
8243: Input Parameter:
8244: . dm - The `DM`
8246: Output Parameters:
8247: + nranks - the number of neighbours
8248: - ranks - the neighbors ranks
8250: Note:
8251: Do not free the array, it is freed when the `DM` is destroyed.
8253: Level: beginner
8255: .seealso: `DMDAGetNeighbors()`, `PetscSFGetRootRanks()`
8256: @*/
8257: PetscErrorCode DMGetNeighbors(DM dm, PetscInt *nranks, const PetscMPIInt *ranks[])
8258: {
8260: (dm->ops->getneighbors)(dm, nranks, ranks);
8261: return 0;
8262: }
8264: #include <petsc/private/matimpl.h>
8266: /*
8267: Converts the input vector to a ghosted vector and then calls the standard coloring code.
8268: This has be a different function because it requires DM which is not defined in the Mat library
8269: */
8270: PetscErrorCode MatFDColoringApply_AIJDM(Mat J, MatFDColoring coloring, Vec x1, void *sctx)
8271: {
8272: if (coloring->ctype == IS_COLORING_LOCAL) {
8273: Vec x1local;
8274: DM dm;
8275: MatGetDM(J, &dm);
8277: DMGetLocalVector(dm, &x1local);
8278: DMGlobalToLocalBegin(dm, x1, INSERT_VALUES, x1local);
8279: DMGlobalToLocalEnd(dm, x1, INSERT_VALUES, x1local);
8280: x1 = x1local;
8281: }
8282: MatFDColoringApply_AIJ(J, coloring, x1, sctx);
8283: if (coloring->ctype == IS_COLORING_LOCAL) {
8284: DM dm;
8285: MatGetDM(J, &dm);
8286: DMRestoreLocalVector(dm, &x1);
8287: }
8288: return 0;
8289: }
8291: /*@
8292: MatFDColoringUseDM - allows a `MatFDColoring` object to use the `DM` associated with the matrix to compute a `IS_COLORING_LOCAL` coloring
8294: Input Parameter:
8295: . coloring - the `MatFDColoring` object
8297: Developer Note:
8298: this routine exists because the PETSc `Mat` library does not know about the `DM` objects
8300: Level: advanced
8302: .seealso: `MatFDColoring`, `MatFDColoringCreate()`, `ISColoringType`
8303: @*/
8304: PetscErrorCode MatFDColoringUseDM(Mat coloring, MatFDColoring fdcoloring)
8305: {
8306: coloring->ops->fdcoloringapply = MatFDColoringApply_AIJDM;
8307: return 0;
8308: }
8310: /*@
8311: DMGetCompatibility - determine if two `DM`s are compatible
8313: Collective
8315: Input Parameters:
8316: + dm1 - the first `DM`
8317: - dm2 - the second `DM`
8319: Output Parameters:
8320: + compatible - whether or not the two `DM`s are compatible
8321: - set - whether or not the compatible value was actually determined and set
8323: Notes:
8324: Two `DM`s are deemed compatible if they represent the same parallel decomposition
8325: of the same topology. This implies that the section (field data) on one
8326: "makes sense" with respect to the topology and parallel decomposition of the other.
8327: Loosely speaking, compatible `DM`s represent the same domain and parallel
8328: decomposition, but hold different data.
8330: Typically, one would confirm compatibility if intending to simultaneously iterate
8331: over a pair of vectors obtained from different `DM`s.
8333: For example, two `DMDA` objects are compatible if they have the same local
8334: and global sizes and the same stencil width. They can have different numbers
8335: of degrees of freedom per node. Thus, one could use the node numbering from
8336: either `DM` in bounds for a loop over vectors derived from either `DM`.
8338: Consider the operation of summing data living on a 2-dof `DMDA` to data living
8339: on a 1-dof `DMDA`, which should be compatible, as in the following snippet.
8340: .vb
8341: ...
8342: DMGetCompatibility(da1,da2,&compatible,&set);
8343: if (set && compatible) {
8344: DMDAVecGetArrayDOF(da1,vec1,&arr1);
8345: DMDAVecGetArrayDOF(da2,vec2,&arr2);
8346: DMDAGetCorners(da1,&x,&y,NULL,&m,&n,NULL);
8347: for (j=y; j<y+n; ++j) {
8348: for (i=x; i<x+m, ++i) {
8349: arr1[j][i][0] = arr2[j][i][0] + arr2[j][i][1];
8350: }
8351: }
8352: DMDAVecRestoreArrayDOF(da1,vec1,&arr1);
8353: DMDAVecRestoreArrayDOF(da2,vec2,&arr2);
8354: } else {
8355: SETERRQ(PetscObjectComm((PetscObject)da1,PETSC_ERR_ARG_INCOMP,"DMDA objects incompatible");
8356: }
8357: ...
8358: .ve
8360: Checking compatibility might be expensive for a given implementation of `DM`,
8361: or might be impossible to unambiguously confirm or deny. For this reason,
8362: this function may decline to determine compatibility, and hence users should
8363: always check the "set" output parameter.
8365: A `DM` is always compatible with itself.
8367: In the current implementation, `DM`s which live on "unequal" communicators
8368: (MPI_UNEQUAL in the terminology of MPI_Comm_compare()) are always deemed
8369: incompatible.
8371: This function is labeled "Collective," as information about all subdomains
8372: is required on each rank. However, in `DM` implementations which store all this
8373: information locally, this function may be merely "Logically Collective".
8375: Developer Note:
8376: Compatibility is assumed to be a symmetric concept; `DM` A is compatible with `DM` B
8377: iff B is compatible with A. Thus, this function checks the implementations
8378: of both dm and dmc (if they are of different types), attempting to determine
8379: compatibility. It is left to `DM` implementers to ensure that symmetry is
8380: preserved. The simplest way to do this is, when implementing type-specific
8381: logic for this function, is to check for existing logic in the implementation
8382: of other `DM` types and let *set = PETSC_FALSE if found.
8384: Level: advanced
8386: .seealso: `DM`, `DMDACreateCompatibleDMDA()`, `DMStagCreateCompatibleDMStag()`
8387: @*/
8388: PetscErrorCode DMGetCompatibility(DM dm1, DM dm2, PetscBool *compatible, PetscBool *set)
8389: {
8390: PetscMPIInt compareResult;
8391: DMType type, type2;
8392: PetscBool sameType;
8397: /* Declare a DM compatible with itself */
8398: if (dm1 == dm2) {
8399: *set = PETSC_TRUE;
8400: *compatible = PETSC_TRUE;
8401: return 0;
8402: }
8404: /* Declare a DM incompatible with a DM that lives on an "unequal"
8405: communicator. Note that this does not preclude compatibility with
8406: DMs living on "congruent" or "similar" communicators, but this must be
8407: determined by the implementation-specific logic */
8408: MPI_Comm_compare(PetscObjectComm((PetscObject)dm1), PetscObjectComm((PetscObject)dm2), &compareResult);
8409: if (compareResult == MPI_UNEQUAL) {
8410: *set = PETSC_TRUE;
8411: *compatible = PETSC_FALSE;
8412: return 0;
8413: }
8415: /* Pass to the implementation-specific routine, if one exists. */
8416: if (dm1->ops->getcompatibility) {
8417: PetscUseTypeMethod(dm1, getcompatibility, dm2, compatible, set);
8418: if (*set) return 0;
8419: }
8421: /* If dm1 and dm2 are of different types, then attempt to check compatibility
8422: with an implementation of this function from dm2 */
8423: DMGetType(dm1, &type);
8424: DMGetType(dm2, &type2);
8425: PetscStrcmp(type, type2, &sameType);
8426: if (!sameType && dm2->ops->getcompatibility) {
8427: PetscUseTypeMethod(dm2, getcompatibility, dm1, compatible, set); /* Note argument order */
8428: } else {
8429: *set = PETSC_FALSE;
8430: }
8431: return 0;
8432: }
8434: /*@C
8435: DMMonitorSet - Sets an additional monitor function that is to be used after a solve to monitor discretization performance.
8437: Logically Collective on dm
8439: Input Parameters:
8440: + DM - the `DM`
8441: . f - the monitor function
8442: . mctx - [optional] user-defined context for private data for the monitor routine (use NULL if no context is desired)
8443: - monitordestroy - [optional] routine that frees monitor context (may be NULL)
8445: Options Database Keys:
8446: - -dm_monitor_cancel - cancels all monitors that have been hardwired into a code by calls to `DMMonitorSet()`, but
8447: does not cancel those set via the options database.
8449: Note:
8450: Several different monitoring routines may be set by calling
8451: `DMMonitorSet()` multiple times or with `DMMonitorSetFromOptions()`; all will be called in the
8452: order in which they were set.
8454: Fortran Note:
8455: Only a single monitor function can be set for each `DM` object
8457: Developer Note:
8458: This API has a generic name but seems specific to a very particular aspect of the use of `DM`
8460: Level: intermediate
8462: .seealso: `DMMonitorCancel()`, `DMMonitorSetFromOptions()`, `DMMonitor()`
8463: @*/
8464: PetscErrorCode DMMonitorSet(DM dm, PetscErrorCode (*f)(DM, void *), void *mctx, PetscErrorCode (*monitordestroy)(void **))
8465: {
8466: PetscInt m;
8469: for (m = 0; m < dm->numbermonitors; ++m) {
8470: PetscBool identical;
8472: PetscMonitorCompare((PetscErrorCode(*)(void))f, mctx, monitordestroy, (PetscErrorCode(*)(void))dm->monitor[m], dm->monitorcontext[m], dm->monitordestroy[m], &identical);
8473: if (identical) return 0;
8474: }
8476: dm->monitor[dm->numbermonitors] = f;
8477: dm->monitordestroy[dm->numbermonitors] = monitordestroy;
8478: dm->monitorcontext[dm->numbermonitors++] = (void *)mctx;
8479: return 0;
8480: }
8482: /*@
8483: DMMonitorCancel - Clears all the monitor functions for a `DM` object.
8485: Logically Collective on dm
8487: Input Parameter:
8488: . dm - the DM
8490: Options Database Key:
8491: . -dm_monitor_cancel - cancels all monitors that have been hardwired
8492: into a code by calls to `DMonitorSet()`, but does not cancel those
8493: set via the options database
8495: Note:
8496: There is no way to clear one specific monitor from a `DM` object.
8498: Level: intermediate
8500: .seealso: `DMMonitorSet()`, `DMMonitorSetFromOptions()`, `DMMonitor()`
8501: @*/
8502: PetscErrorCode DMMonitorCancel(DM dm)
8503: {
8504: PetscInt m;
8507: for (m = 0; m < dm->numbermonitors; ++m) {
8508: if (dm->monitordestroy[m]) (*dm->monitordestroy[m])(&dm->monitorcontext[m]);
8509: }
8510: dm->numbermonitors = 0;
8511: return 0;
8512: }
8514: /*@C
8515: DMMonitorSetFromOptions - Sets a monitor function and viewer appropriate for the type indicated by the user
8517: Collective on dm
8519: Input Parameters:
8520: + dm - `DM` object you wish to monitor
8521: . name - the monitor type one is seeking
8522: . help - message indicating what monitoring is done
8523: . manual - manual page for the monitor
8524: . monitor - the monitor function
8525: - 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
8527: Output Parameter:
8528: . flg - Flag set if the monitor was created
8530: Level: developer
8532: .seealso: `PetscOptionsGetViewer()`, `PetscOptionsGetReal()`, `PetscOptionsHasName()`, `PetscOptionsGetString()`,
8533: `PetscOptionsGetIntArray()`, `PetscOptionsGetRealArray()`, `PetscOptionsBool()`
8534: `PetscOptionsInt()`, `PetscOptionsString()`, `PetscOptionsReal()`, `PetscOptionsBool()`,
8535: `PetscOptionsName()`, `PetscOptionsBegin()`, `PetscOptionsEnd()`, `PetscOptionsHeadBegin()`,
8536: `PetscOptionsStringArray()`, `PetscOptionsRealArray()`, `PetscOptionsScalar()`,
8537: `PetscOptionsBoolGroupBegin()`, `PetscOptionsBoolGroup()`, `PetscOptionsBoolGroupEnd()`,
8538: `PetscOptionsFList()`, `PetscOptionsEList()`, `DMMonitor()`, `DMMonitorSet()`
8539: @*/
8540: PetscErrorCode DMMonitorSetFromOptions(DM dm, const char name[], const char help[], const char manual[], PetscErrorCode (*monitor)(DM, void *), PetscErrorCode (*monitorsetup)(DM, PetscViewerAndFormat *), PetscBool *flg)
8541: {
8542: PetscViewer viewer;
8543: PetscViewerFormat format;
8546: PetscOptionsGetViewer(PetscObjectComm((PetscObject)dm), ((PetscObject)dm)->options, ((PetscObject)dm)->prefix, name, &viewer, &format, flg);
8547: if (*flg) {
8548: PetscViewerAndFormat *vf;
8550: PetscViewerAndFormatCreate(viewer, format, &vf);
8551: PetscObjectDereference((PetscObject)viewer);
8552: if (monitorsetup) (*monitorsetup)(dm, vf);
8553: DMMonitorSet(dm, (PetscErrorCode(*)(DM, void *))monitor, vf, (PetscErrorCode(*)(void **))PetscViewerAndFormatDestroy);
8554: }
8555: return 0;
8556: }
8558: /*@
8559: DMMonitor - runs the user provided monitor routines, if they exist
8561: Collective on dm
8563: Input Parameters:
8564: . dm - The `DM`
8566: Level: developer
8568: Question:
8569: Note should indicate when during the life of the `DM` the monitor is run. It appears to be related to the discretization process seems rather specialized
8570: since some `DM` have no concept of discretization
8572: .seealso: `DMMonitorSet()`, `DMMonitorSetFromOptions()`
8573: @*/
8574: PetscErrorCode DMMonitor(DM dm)
8575: {
8576: PetscInt m;
8578: if (!dm) return 0;
8580: for (m = 0; m < dm->numbermonitors; ++m) (*dm->monitor[m])(dm, dm->monitorcontext[m]);
8581: return 0;
8582: }
8584: /*@
8585: DMComputeError - Computes the error assuming the user has provided the exact solution functions
8587: Collective on dm
8589: Input Parameters:
8590: + dm - The `DM`
8591: - sol - The solution vector
8593: Input/Output Parameter:
8594: . errors - An array of length Nf, the number of fields, or NULL for no output; on output
8595: contains the error in each field
8597: Output Parameter:
8598: . errorVec - A vector to hold the cellwise error (may be NULL)
8600: Note:
8601: The exact solutions come from the `PetscDS` object, and the time comes from `DMGetOutputSequenceNumber()`.
8603: Level: developer
8605: .seealso: `DMMonitorSet()`, `DMGetRegionNumDS()`, `PetscDSGetExactSolution()`, `DMGetOutputSequenceNumber()`
8606: @*/
8607: PetscErrorCode DMComputeError(DM dm, Vec sol, PetscReal errors[], Vec *errorVec)
8608: {
8609: PetscErrorCode (**exactSol)(PetscInt, PetscReal, const PetscReal[], PetscInt, PetscScalar[], void *);
8610: void **ctxs;
8611: PetscReal time;
8612: PetscInt Nf, f, Nds, s;
8614: DMGetNumFields(dm, &Nf);
8615: PetscCalloc2(Nf, &exactSol, Nf, &ctxs);
8616: DMGetNumDS(dm, &Nds);
8617: for (s = 0; s < Nds; ++s) {
8618: PetscDS ds;
8619: DMLabel label;
8620: IS fieldIS;
8621: const PetscInt *fields;
8622: PetscInt dsNf;
8624: DMGetRegionNumDS(dm, s, &label, &fieldIS, &ds);
8625: PetscDSGetNumFields(ds, &dsNf);
8626: if (fieldIS) ISGetIndices(fieldIS, &fields);
8627: for (f = 0; f < dsNf; ++f) {
8628: const PetscInt field = fields[f];
8629: PetscDSGetExactSolution(ds, field, &exactSol[field], &ctxs[field]);
8630: }
8631: if (fieldIS) ISRestoreIndices(fieldIS, &fields);
8632: }
8634: DMGetOutputSequenceNumber(dm, NULL, &time);
8635: if (errors) DMComputeL2FieldDiff(dm, time, exactSol, ctxs, sol, errors);
8636: if (errorVec) {
8637: DM edm;
8638: DMPolytopeType ct;
8639: PetscBool simplex;
8640: PetscInt dim, cStart, Nf;
8642: DMClone(dm, &edm);
8643: DMGetDimension(edm, &dim);
8644: DMPlexGetHeightStratum(dm, 0, &cStart, NULL);
8645: DMPlexGetCellType(dm, cStart, &ct);
8646: simplex = DMPolytopeTypeGetNumVertices(ct) == DMPolytopeTypeGetDim(ct) + 1 ? PETSC_TRUE : PETSC_FALSE;
8647: DMGetNumFields(dm, &Nf);
8648: for (f = 0; f < Nf; ++f) {
8649: PetscFE fe, efe;
8650: PetscQuadrature q;
8651: const char *name;
8653: DMGetField(dm, f, NULL, (PetscObject *)&fe);
8654: PetscFECreateLagrange(PETSC_COMM_SELF, dim, Nf, simplex, 0, PETSC_DETERMINE, &efe);
8655: PetscObjectGetName((PetscObject)fe, &name);
8656: PetscObjectSetName((PetscObject)efe, name);
8657: PetscFEGetQuadrature(fe, &q);
8658: PetscFESetQuadrature(efe, q);
8659: DMSetField(edm, f, NULL, (PetscObject)efe);
8660: PetscFEDestroy(&efe);
8661: }
8662: DMCreateDS(edm);
8664: DMCreateGlobalVector(edm, errorVec);
8665: PetscObjectSetName((PetscObject)*errorVec, "Error");
8666: DMPlexComputeL2DiffVec(dm, time, exactSol, ctxs, sol, *errorVec);
8667: DMDestroy(&edm);
8668: }
8669: PetscFree2(exactSol, ctxs);
8670: return 0;
8671: }
8673: /*@
8674: DMGetNumAuxiliaryVec - Get the number of auxiliary vectors associated with this `DM`
8676: Not collective
8678: Input Parameter:
8679: . dm - The `DM`
8681: Output Parameter:
8682: . numAux - The number of auxiliary data vectors
8684: Level: advanced
8686: .seealso: `DMSetAuxiliaryVec()`, `DMGetAuxiliaryLabels()`, `DMGetAuxiliaryVec()`, `DMSetAuxiliaryVec()`
8687: @*/
8688: PetscErrorCode DMGetNumAuxiliaryVec(DM dm, PetscInt *numAux)
8689: {
8691: PetscHMapAuxGetSize(dm->auxData, numAux);
8692: return 0;
8693: }
8695: /*@
8696: DMGetAuxiliaryVec - Get the auxiliary vector for region specified by the given label and value, and equation part
8698: Not collective
8700: Input Parameters:
8701: + dm - The `DM`
8702: . label - The `DMLabel`
8703: . value - The label value indicating the region
8704: - part - The equation part, or 0 if unused
8706: Output Parameter:
8707: . aux - The `Vec` holding auxiliary field data
8709: Note:
8710: If no auxiliary vector is found for this (label, value), (NULL, 0, 0) is checked as well.
8712: Level: advanced
8714: .seealso: `DMSetAuxiliaryVec()`, `DMGetNumAuxiliaryVec()`, `DMGetAuxiliaryLabels()`
8715: @*/
8716: PetscErrorCode DMGetAuxiliaryVec(DM dm, DMLabel label, PetscInt value, PetscInt part, Vec *aux)
8717: {
8718: PetscHashAuxKey key, wild = {NULL, 0, 0};
8719: PetscBool has;
8723: key.label = label;
8724: key.value = value;
8725: key.part = part;
8726: PetscHMapAuxHas(dm->auxData, key, &has);
8727: if (has) PetscHMapAuxGet(dm->auxData, key, aux);
8728: else PetscHMapAuxGet(dm->auxData, wild, aux);
8729: return 0;
8730: }
8732: /*@
8733: DMSetAuxiliaryVec - Set an auxiliary vector for region specified by the given label and value, and equation part
8735: Not collective because auxilary vectors are not parallel
8737: Input Parameters:
8738: + dm - The `DM`
8739: . label - The `DMLabel`
8740: . value - The label value indicating the region
8741: . part - The equation part, or 0 if unused
8742: - aux - The `Vec` holding auxiliary field data
8744: Level: advanced
8746: .seealso: `DMGetAuxiliaryVec()`, `DMGetAuxiliaryLabels()`, `DMCopyAuxiliaryVec()`
8747: @*/
8748: PetscErrorCode DMSetAuxiliaryVec(DM dm, DMLabel label, PetscInt value, PetscInt part, Vec aux)
8749: {
8750: Vec old;
8751: PetscHashAuxKey key;
8755: key.label = label;
8756: key.value = value;
8757: key.part = part;
8758: PetscHMapAuxGet(dm->auxData, key, &old);
8759: PetscObjectReference((PetscObject)aux);
8760: PetscObjectDereference((PetscObject)old);
8761: if (!aux) PetscHMapAuxDel(dm->auxData, key);
8762: else PetscHMapAuxSet(dm->auxData, key, aux);
8763: return 0;
8764: }
8766: /*@C
8767: DMGetAuxiliaryLabels - Get the labels, values, and parts for all auxiliary vectors in this `DM`
8769: Not collective
8771: Input Parameter:
8772: . dm - The `DM`
8774: Output Parameters:
8775: + labels - The `DMLabel`s for each `Vec`
8776: . values - The label values for each `Vec`
8777: - parts - The equation parts for each `Vec`
8779: Note:
8780: The arrays passed in must be at least as large as `DMGetNumAuxiliaryVec()`.
8782: Level: advanced
8784: .seealso: `DMGetNumAuxiliaryVec()`, `DMGetAuxiliaryVec()`, `DMGetNumAuxiliaryVec()`, `DMSetAuxiliaryVec()`, DMCopyAuxiliaryVec()`
8785: @*/
8786: PetscErrorCode DMGetAuxiliaryLabels(DM dm, DMLabel labels[], PetscInt values[], PetscInt parts[])
8787: {
8788: PetscHashAuxKey *keys;
8789: PetscInt n, i, off = 0;
8795: DMGetNumAuxiliaryVec(dm, &n);
8796: PetscMalloc1(n, &keys);
8797: PetscHMapAuxGetKeys(dm->auxData, &off, keys);
8798: for (i = 0; i < n; ++i) {
8799: labels[i] = keys[i].label;
8800: values[i] = keys[i].value;
8801: parts[i] = keys[i].part;
8802: }
8803: PetscFree(keys);
8804: return 0;
8805: }
8807: /*@
8808: DMCopyAuxiliaryVec - Copy the auxiliary vector data on a `DM` to a new `DM`
8810: Not collective
8812: Input Parameter:
8813: . dm - The `DM`
8815: Output Parameter:
8816: . dmNew - The new `DM`, now with the same auxiliary data
8818: Level: advanced
8820: Note:
8821: This is a shallow copy of the auxiliary vectors
8823: .seealso: `DMGetNumAuxiliaryVec()`, `DMGetAuxiliaryVec()`, `DMSetAuxiliaryVec()`
8824: @*/
8825: PetscErrorCode DMCopyAuxiliaryVec(DM dm, DM dmNew)
8826: {
8828: PetscHMapAuxDestroy(&dmNew->auxData);
8829: PetscHMapAuxDuplicate(dm->auxData, &dmNew->auxData);
8830: return 0;
8831: }
8833: /*@C
8834: DMPolytopeMatchOrientation - Determine an orientation (transformation) that takes the source face arrangement to the target face arrangement
8836: Not collective
8838: Input Parameters:
8839: + ct - The `DMPolytopeType`
8840: . sourceCone - The source arrangement of faces
8841: - targetCone - The target arrangement of faces
8843: Output Parameters:
8844: + ornt - The orientation (transformation) which will take the source arrangement to the target arrangement
8845: - found - Flag indicating that a suitable orientation was found
8847: Level: advanced
8849: Note:
8850: An arrangement is a face order combined with an orientation for each face
8852: Each orientation (transformation) is labeled with an integer from negative `DMPolytopeTypeGetNumArrangments(ct)`/2 to `DMPolytopeTypeGetNumArrangments(ct)`/2
8853: that labels each arrangement (face ordering plus orientation for each face).
8855: See `DMPolytopeMatchVertexOrientation()` to find a new vertex orientation that takes the source vertex arrangement to the target vertex arrangement
8857: .seealso: `DMPolytopeGetOrientation()`, `DMPolytopeMatchVertexOrientation()`, `DMPolytopeGetVertexOrientation()`
8858: @*/
8859: PetscErrorCode DMPolytopeMatchOrientation(DMPolytopeType ct, const PetscInt sourceCone[], const PetscInt targetCone[], PetscInt *ornt, PetscBool *found)
8860: {
8861: const PetscInt cS = DMPolytopeTypeGetConeSize(ct);
8862: const PetscInt nO = DMPolytopeTypeGetNumArrangments(ct) / 2;
8863: PetscInt o, c;
8865: if (!nO) {
8866: *ornt = 0;
8867: *found = PETSC_TRUE;
8868: return 0;
8869: }
8870: for (o = -nO; o < nO; ++o) {
8871: const PetscInt *arr = DMPolytopeTypeGetArrangment(ct, o);
8873: for (c = 0; c < cS; ++c)
8874: if (sourceCone[arr[c * 2]] != targetCone[c]) break;
8875: if (c == cS) {
8876: *ornt = o;
8877: break;
8878: }
8879: }
8880: *found = o == nO ? PETSC_FALSE : PETSC_TRUE;
8881: return 0;
8882: }
8884: /*@C
8885: DMPolytopeGetOrientation - Determine an orientation (transformation) that takes the source face arrangement to the target face arrangement
8887: Not collective
8889: Input Parameters:
8890: + ct - The `DMPolytopeType`
8891: . sourceCone - The source arrangement of faces
8892: - targetCone - The target arrangement of faces
8894: Output Parameters:
8895: . ornt - The orientation (transformation) which will take the source arrangement to the target arrangement
8897: Level: advanced
8899: Note:
8900: This function is the same as `DMPolytopeMatchOrientation()` except it will generate an error if no suitable orientation can be found.
8902: Developer Note:
8903: It is unclear why this function needs to exist since one can simply call `DMPolytopeMatchOrientation()` and error if none is found
8905: .seealso: `DMPolytopeType`, `DMPolytopeMatchOrientation()`, `DMPolytopeGetVertexOrientation()`, `DMPolytopeMatchVertexOrientation()`
8906: @*/
8907: PetscErrorCode DMPolytopeGetOrientation(DMPolytopeType ct, const PetscInt sourceCone[], const PetscInt targetCone[], PetscInt *ornt)
8908: {
8909: PetscBool found;
8911: DMPolytopeMatchOrientation(ct, sourceCone, targetCone, ornt, &found);
8913: return 0;
8914: }
8916: /*@C
8917: DMPolytopeMatchVertexOrientation - Determine an orientation (transformation) that takes the source vertex arrangement to the target vertex arrangement
8919: Not collective
8921: Input Parameters:
8922: + ct - The `DMPolytopeType`
8923: . sourceVert - The source arrangement of vertices
8924: - targetVert - The target arrangement of vertices
8926: Output Parameters:
8927: + ornt - The orientation (transformation) which will take the source arrangement to the target arrangement
8928: - found - Flag indicating that a suitable orientation was found
8930: Level: advanced
8932: Note:
8933: An arrangement is a vertex order
8935: Each orientation (transformation) is labeled with an integer from negative `DMPolytopeTypeGetNumArrangments(ct)`/2 to `DMPolytopeTypeGetNumArrangments(ct)`/2
8936: that labels each arrangement (vertex ordering).
8938: See `DMPolytopeMatchOrientation()` to find a new face orientation that takes the source face arrangement to the target face arrangement
8940: .seealso: `DMPolytopeType`, `DMPolytopeGetOrientation()`, `DMPolytopeMatchOrientation()`, `DMPolytopeTypeGetNumVertices()`, `DMPolytopeTypeGetVertexArrangment()`
8941: @*/
8942: PetscErrorCode DMPolytopeMatchVertexOrientation(DMPolytopeType ct, const PetscInt sourceVert[], const PetscInt targetVert[], PetscInt *ornt, PetscBool *found)
8943: {
8944: const PetscInt cS = DMPolytopeTypeGetNumVertices(ct);
8945: const PetscInt nO = DMPolytopeTypeGetNumArrangments(ct) / 2;
8946: PetscInt o, c;
8948: if (!nO) {
8949: *ornt = 0;
8950: *found = PETSC_TRUE;
8951: return 0;
8952: }
8953: for (o = -nO; o < nO; ++o) {
8954: const PetscInt *arr = DMPolytopeTypeGetVertexArrangment(ct, o);
8956: for (c = 0; c < cS; ++c)
8957: if (sourceVert[arr[c]] != targetVert[c]) break;
8958: if (c == cS) {
8959: *ornt = o;
8960: break;
8961: }
8962: }
8963: *found = o == nO ? PETSC_FALSE : PETSC_TRUE;
8964: return 0;
8965: }
8967: /*@C
8968: DMPolytopeGetVertexOrientation - Determine an orientation (transformation) that takes the source vertex arrangement to the target vertex arrangement
8970: Not collective
8972: Input Parameters:
8973: + ct - The `DMPolytopeType`
8974: . sourceCone - The source arrangement of vertices
8975: - targetCone - The target arrangement of vertices
8977: Output Parameters:
8978: . ornt - The orientation (transformation) which will take the source arrangement to the target arrangement
8980: Level: advanced
8982: Note:
8983: This function is the same as `DMPolytopeMatchVertexOrientation()` except it errors if not orientation is possible.
8985: Developer Note:
8986: It is unclear why this function needs to exist since one can simply call `DMPolytopeMatchVertexOrientation()` and error if none is found
8988: .seealso: `DMPolytopeType`, `DMPolytopeMatchVertexOrientation()`, `DMPolytopeGetOrientation()`
8989: @*/
8990: PetscErrorCode DMPolytopeGetVertexOrientation(DMPolytopeType ct, const PetscInt sourceCone[], const PetscInt targetCone[], PetscInt *ornt)
8991: {
8992: PetscBool found;
8994: DMPolytopeMatchVertexOrientation(ct, sourceCone, targetCone, ornt, &found);
8996: return 0;
8997: }
8999: /*@C
9000: DMPolytopeInCellTest - Check whether a point lies inside the reference cell of given type
9002: Not collective
9004: Input Parameters:
9005: + ct - The `DMPolytopeType`
9006: - point - Coordinates of the point
9008: Output Parameters:
9009: . inside - Flag indicating whether the point is inside the reference cell of given type
9011: Level: advanced
9013: .seealso: `DM`, `DMPolytopeType`, `DMLocatePoints()`
9014: @*/
9015: PetscErrorCode DMPolytopeInCellTest(DMPolytopeType ct, const PetscReal point[], PetscBool *inside)
9016: {
9017: PetscReal sum = 0.0;
9018: PetscInt d;
9020: *inside = PETSC_TRUE;
9021: switch (ct) {
9022: case DM_POLYTOPE_TRIANGLE:
9023: case DM_POLYTOPE_TETRAHEDRON:
9024: for (d = 0; d < DMPolytopeTypeGetDim(ct); ++d) {
9025: if (point[d] < -1.0) {
9026: *inside = PETSC_FALSE;
9027: break;
9028: }
9029: sum += point[d];
9030: }
9031: if (sum > PETSC_SMALL) {
9032: *inside = PETSC_FALSE;
9033: break;
9034: }
9035: break;
9036: case DM_POLYTOPE_QUADRILATERAL:
9037: case DM_POLYTOPE_HEXAHEDRON:
9038: for (d = 0; d < DMPolytopeTypeGetDim(ct); ++d)
9039: if (PetscAbsReal(point[d]) > 1. + PETSC_SMALL) {
9040: *inside = PETSC_FALSE;
9041: break;
9042: }
9043: break;
9044: default:
9045: SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Unsupported polytope type %s", DMPolytopeTypes[ct]);
9046: }
9047: return 0;
9048: }