Actual source code: plexfem.c
1: #include <petsc/private/dmpleximpl.h>
2: #include <petscsf.h>
4: #include <petscblaslapack.h>
5: #include <petsc/private/hashsetij.h>
6: #include <petsc/private/petscfeimpl.h>
7: #include <petsc/private/petscfvimpl.h>
9: PetscBool Clementcite = PETSC_FALSE;
10: const char ClementCitation[] = "@article{clement1975approximation,\n"
11: " title = {Approximation by finite element functions using local regularization},\n"
12: " author = {Philippe Cl{\\'e}ment},\n"
13: " journal = {Revue fran{\\c{c}}aise d'automatique, informatique, recherche op{\\'e}rationnelle. Analyse num{\\'e}rique},\n"
14: " volume = {9},\n"
15: " number = {R2},\n"
16: " pages = {77--84},\n"
17: " year = {1975}\n}\n";
19: static PetscErrorCode DMPlexConvertPlex(DM dm, DM *plex, PetscBool copy)
20: {
21: PetscBool isPlex;
23: PetscFunctionBegin;
24: PetscCall(PetscObjectTypeCompare((PetscObject)dm, DMPLEX, &isPlex));
25: if (isPlex) {
26: *plex = dm;
27: PetscCall(PetscObjectReference((PetscObject)dm));
28: } else {
29: PetscCall(PetscObjectQuery((PetscObject)dm, "dm_plex", (PetscObject *)plex));
30: if (!*plex) {
31: PetscCall(DMConvert(dm, DMPLEX, plex));
32: PetscCall(PetscObjectCompose((PetscObject)dm, "dm_plex", (PetscObject)*plex));
33: } else {
34: PetscCall(PetscObjectReference((PetscObject)*plex));
35: }
36: if (copy) {
37: DMSubDomainHookLink link;
39: PetscCall(DMCopyDS(dm, PETSC_DETERMINE, PETSC_DETERMINE, *plex));
40: PetscCall(DMCopyAuxiliaryVec(dm, *plex));
41: /* Run the subdomain hook (this will copy the DMSNES/DMTS) */
42: for (link = dm->subdomainhook; link; link = link->next) {
43: if (link->ddhook) PetscCall((*link->ddhook)(dm, *plex, link->ctx));
44: }
45: }
46: }
47: PetscFunctionReturn(PETSC_SUCCESS);
48: }
50: static PetscErrorCode PetscContainerCtxDestroy_PetscFEGeom(PetscCtxRt ctx)
51: {
52: PetscFEGeom *geom = *(PetscFEGeom **)ctx;
54: PetscFunctionBegin;
55: PetscCall(PetscFEGeomDestroy(&geom));
56: PetscFunctionReturn(PETSC_SUCCESS);
57: }
59: static PetscErrorCode DMPlexGetFEGeom(DMField coordField, IS pointIS, PetscQuadrature quad, PetscFEGeomMode mode, PetscFEGeom **geom)
60: {
61: char composeStr[33] = {0};
62: PetscObjectId id;
63: PetscContainer container;
65: PetscFunctionBegin;
66: PetscCall(PetscObjectGetId((PetscObject)quad, &id));
67: PetscCall(PetscSNPrintf(composeStr, 32, "DMPlexGetFEGeom_%" PetscInt64_FMT "\n", id));
68: PetscCall(PetscObjectQuery((PetscObject)pointIS, composeStr, (PetscObject *)&container));
69: if (container) {
70: PetscCall(PetscContainerGetPointer(container, geom));
71: } else {
72: PetscCall(DMFieldCreateFEGeom(coordField, pointIS, quad, mode, geom));
73: PetscCall(PetscContainerCreate(PETSC_COMM_SELF, &container));
74: PetscCall(PetscContainerSetPointer(container, (void *)*geom));
75: PetscCall(PetscContainerSetCtxDestroy(container, PetscContainerCtxDestroy_PetscFEGeom));
76: PetscCall(PetscObjectCompose((PetscObject)pointIS, composeStr, (PetscObject)container));
77: PetscCall(PetscContainerDestroy(&container));
78: }
79: PetscFunctionReturn(PETSC_SUCCESS);
80: }
82: static PetscErrorCode DMPlexRestoreFEGeom(DMField coordField, IS pointIS, PetscQuadrature quad, PetscFEGeomMode mode, PetscFEGeom **geom)
83: {
84: PetscFunctionBegin;
85: *geom = NULL;
86: PetscFunctionReturn(PETSC_SUCCESS);
87: }
89: /*@
90: DMPlexGetScale - Get the scale for the specified fundamental unit
92: Not Collective
94: Input Parameters:
95: + dm - the `DM`
96: - unit - The SI unit
98: Output Parameter:
99: . scale - The value used to scale all quantities with this unit
101: Level: advanced
103: .seealso: [](ch_unstructured), `DM`, `DMPLEX`, `DMPlexSetScale()`, `PetscUnit`
104: @*/
105: PetscErrorCode DMPlexGetScale(DM dm, PetscUnit unit, PetscReal *scale)
106: {
107: DM_Plex *mesh = (DM_Plex *)dm->data;
109: PetscFunctionBegin;
111: PetscAssertPointer(scale, 3);
112: *scale = mesh->scale[unit];
113: PetscFunctionReturn(PETSC_SUCCESS);
114: }
116: /*@
117: DMPlexSetScale - Set the scale for the specified fundamental unit
119: Not Collective
121: Input Parameters:
122: + dm - the `DM`
123: . unit - The SI unit
124: - scale - The value used to scale all quantities with this unit
126: Level: advanced
128: .seealso: [](ch_unstructured), `DM`, `DMPLEX`, `DMPlexGetScale()`, `PetscUnit`
129: @*/
130: PetscErrorCode DMPlexSetScale(DM dm, PetscUnit unit, PetscReal scale)
131: {
132: DM_Plex *mesh = (DM_Plex *)dm->data;
134: PetscFunctionBegin;
136: mesh->scale[unit] = scale;
137: PetscFunctionReturn(PETSC_SUCCESS);
138: }
140: PetscErrorCode DMPlexGetUseCeed_Plex(DM dm, PetscBool *useCeed)
141: {
142: DM_Plex *mesh = (DM_Plex *)dm->data;
144: PetscFunctionBegin;
145: *useCeed = mesh->useCeed;
146: PetscFunctionReturn(PETSC_SUCCESS);
147: }
148: PetscErrorCode DMPlexSetUseCeed_Plex(DM dm, PetscBool useCeed)
149: {
150: DM_Plex *mesh = (DM_Plex *)dm->data;
152: PetscFunctionBegin;
153: mesh->useCeed = useCeed;
154: PetscFunctionReturn(PETSC_SUCCESS);
155: }
157: /*@
158: DMPlexGetUseCeed - Get flag for using the LibCEED backend
160: Not collective
162: Input Parameter:
163: . dm - The `DM`
165: Output Parameter:
166: . useCeed - The flag
168: Level: intermediate
170: .seealso: `DMPlexSetUseCeed()`
171: @*/
172: PetscErrorCode DMPlexGetUseCeed(DM dm, PetscBool *useCeed)
173: {
174: PetscFunctionBegin;
176: PetscAssertPointer(useCeed, 2);
177: *useCeed = PETSC_FALSE;
178: PetscTryMethod(dm, "DMPlexGetUseCeed_C", (DM, PetscBool *), (dm, useCeed));
179: PetscFunctionReturn(PETSC_SUCCESS);
180: }
182: /*@
183: DMPlexSetUseCeed - Set flag for using the LibCEED backend
185: Not collective
187: Input Parameters:
188: + dm - The `DM`
189: - useCeed - The flag
191: Level: intermediate
193: .seealso: `DMPlexGetUseCeed()`
194: @*/
195: PetscErrorCode DMPlexSetUseCeed(DM dm, PetscBool useCeed)
196: {
197: PetscFunctionBegin;
200: PetscUseMethod(dm, "DMPlexSetUseCeed_C", (DM, PetscBool), (dm, useCeed));
201: PetscFunctionReturn(PETSC_SUCCESS);
202: }
204: /*@
205: DMPlexGetUseMatClosurePermutation - Get flag for using a closure permutation for matrix insertion
207: Not collective
209: Input Parameter:
210: . dm - The `DM`
212: Output Parameter:
213: . useClPerm - The flag
215: Level: intermediate
217: .seealso: `DMPlexSetUseMatClosurePermutation()`
218: @*/
219: PetscErrorCode DMPlexGetUseMatClosurePermutation(DM dm, PetscBool *useClPerm)
220: {
221: DM_Plex *mesh = (DM_Plex *)dm->data;
223: PetscFunctionBegin;
225: PetscAssertPointer(useClPerm, 2);
226: *useClPerm = mesh->useMatClPerm;
227: PetscFunctionReturn(PETSC_SUCCESS);
228: }
230: /*@
231: DMPlexSetUseMatClosurePermutation - Set flag for using a closure permutation for matrix insertion
233: Not collective
235: Input Parameters:
236: + dm - The `DM`
237: - useClPerm - The flag
239: Level: intermediate
241: .seealso: `DMPlexGetUseMatClosurePermutation()`
242: @*/
243: PetscErrorCode DMPlexSetUseMatClosurePermutation(DM dm, PetscBool useClPerm)
244: {
245: DM_Plex *mesh = (DM_Plex *)dm->data;
247: PetscFunctionBegin;
250: mesh->useMatClPerm = useClPerm;
251: PetscFunctionReturn(PETSC_SUCCESS);
252: }
254: static PetscErrorCode DMPlexProjectRigidBody_Private(PetscInt dim, PetscReal t, const PetscReal X[], PetscInt Nc, PetscScalar *mode, PetscCtx ctx)
255: {
256: const PetscInt eps[3][3][3] = {
257: {{0, 0, 0}, {0, 0, 1}, {0, -1, 0}},
258: {{0, 0, -1}, {0, 0, 0}, {1, 0, 0} },
259: {{0, 1, 0}, {-1, 0, 0}, {0, 0, 0} }
260: };
261: PetscInt *ctxInt = (PetscInt *)ctx;
262: PetscInt dim2 = ctxInt[0];
263: PetscInt d = ctxInt[1];
264: PetscInt i, j, k = dim > 2 ? d - dim : d;
266: PetscFunctionBegin;
267: PetscCheck(dim == dim2, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Input dimension %" PetscInt_FMT " does not match context dimension %" PetscInt_FMT, dim, dim2);
268: for (i = 0; i < dim; i++) mode[i] = 0.;
269: if (d < dim) {
270: mode[d] = 1.; /* Translation along axis d */
271: } else {
272: for (i = 0; i < dim; i++) {
273: for (j = 0; j < dim; j++) mode[j] += eps[i][j][k] * X[i]; /* Rotation about axis d */
274: }
275: }
276: PetscFunctionReturn(PETSC_SUCCESS);
277: }
279: /*@
280: DMPlexCreateRigidBody - For the default global section, create rigid body modes by function space interpolation
282: Collective
284: Input Parameters:
285: + dm - the `DM`
286: - field - The field number for the rigid body space, or 0 for the default
288: Output Parameter:
289: . sp - the null space
291: Level: advanced
293: Note:
294: This is necessary to provide a suitable coarse space for algebraic multigrid
296: .seealso: [](ch_unstructured), `DM`, `DMPLEX`, `MatNullSpaceCreate()`, `PCGAMG`
297: @*/
298: PetscErrorCode DMPlexCreateRigidBody(DM dm, PetscInt field, MatNullSpace *sp)
299: {
300: PetscErrorCode (**func)(PetscInt, PetscReal, const PetscReal *, PetscInt, PetscScalar *, void *);
301: MPI_Comm comm;
302: Vec mode[6];
303: PetscSection section, globalSection;
304: PetscInt dim, dimEmbed, Nf, n, m, mmin, d, i, j;
305: void **ctxs;
307: PetscFunctionBegin;
308: PetscCall(PetscObjectGetComm((PetscObject)dm, &comm));
309: PetscCall(DMGetDimension(dm, &dim));
310: PetscCall(DMGetCoordinateDim(dm, &dimEmbed));
311: PetscCall(DMGetNumFields(dm, &Nf));
312: PetscCheck(!Nf || !(field < 0 || field >= Nf), comm, PETSC_ERR_ARG_OUTOFRANGE, "Field %" PetscInt_FMT " is not in [0, %" PetscInt_FMT ")", field, Nf);
313: if (dim == 1 && Nf < 2) {
314: PetscCall(MatNullSpaceCreate(comm, PETSC_TRUE, 0, NULL, sp));
315: PetscFunctionReturn(PETSC_SUCCESS);
316: }
317: PetscCall(DMGetLocalSection(dm, §ion));
318: PetscCall(DMGetGlobalSection(dm, &globalSection));
319: PetscCall(PetscSectionGetConstrainedStorageSize(globalSection, &n));
320: PetscCall(PetscCalloc2(Nf, &func, Nf, &ctxs));
321: m = (dim * (dim + 1)) / 2;
322: PetscCall(VecCreate(comm, &mode[0]));
323: PetscCall(VecSetType(mode[0], dm->vectype));
324: PetscCall(VecSetSizes(mode[0], n, PETSC_DETERMINE));
325: PetscCall(VecSetUp(mode[0]));
326: PetscCall(VecGetSize(mode[0], &n));
327: mmin = PetscMin(m, n);
328: func[field] = DMPlexProjectRigidBody_Private;
329: for (i = 1; i < m; ++i) PetscCall(VecDuplicate(mode[0], &mode[i]));
330: for (d = 0; d < m; d++) {
331: PetscInt ctx[2];
333: ctxs[field] = (void *)(&ctx[0]);
334: ctx[0] = dimEmbed;
335: ctx[1] = d;
336: PetscCall(DMProjectFunction(dm, 0.0, func, ctxs, INSERT_VALUES, mode[d]));
337: }
338: /* Orthonormalize system */
339: for (i = 0; i < mmin; ++i) {
340: PetscScalar dots[6];
341: PetscReal norm;
343: PetscCall(VecNormalize(mode[i], &norm));
344: if (PetscAbsReal(norm) <= PETSC_SQRT_MACHINE_EPSILON) {
345: PetscCall(VecDestroy(&mode[i]));
346: if (i < mmin - 1) {
347: for (j = i; j < mmin - 1; j++) mode[j] = mode[j + 1];
348: mode[mmin - 1] = NULL;
349: }
350: m--;
351: mmin--;
352: i--;
353: continue;
354: }
355: PetscCall(VecMDot(mode[i], mmin - i - 1, mode + i + 1, dots + i + 1));
356: for (j = i + 1; j < mmin; ++j) {
357: dots[j] *= -1.0;
358: PetscCall(VecAXPY(mode[j], dots[j], mode[i]));
359: }
360: }
361: PetscCall(MatNullSpaceCreate(comm, PETSC_FALSE, mmin, mode, sp));
362: for (i = 0; i < m; ++i) PetscCall(VecDestroy(&mode[i]));
363: PetscCall(PetscFree2(func, ctxs));
364: PetscFunctionReturn(PETSC_SUCCESS);
365: }
367: /*@
368: DMPlexCreateRigidBodies - For the default global section, create rigid body modes by function space interpolation
370: Collective
372: Input Parameters:
373: + dm - the `DM`
374: . nb - The number of bodies
375: . label - The `DMLabel` marking each domain
376: . nids - The number of ids per body
377: - ids - An array of the label ids in sequence for each domain
379: Output Parameter:
380: . sp - the null space
382: Level: advanced
384: Note:
385: This is necessary to provide a suitable coarse space for algebraic multigrid
387: .seealso: [](ch_unstructured), `DM`, `DMPLEX`, `MatNullSpaceCreate()`
388: @*/
389: PetscErrorCode DMPlexCreateRigidBodies(DM dm, PetscInt nb, DMLabel label, const PetscInt nids[], const PetscInt ids[], MatNullSpace *sp)
390: {
391: MPI_Comm comm;
392: PetscSection section, globalSection;
393: Vec *mode;
394: PetscScalar *dots;
395: PetscInt dim, dimEmbed, n, m, b, d, i, j, off;
397: PetscFunctionBegin;
398: PetscCall(PetscObjectGetComm((PetscObject)dm, &comm));
399: PetscCall(DMGetDimension(dm, &dim));
400: PetscCall(DMGetCoordinateDim(dm, &dimEmbed));
401: PetscCall(DMGetLocalSection(dm, §ion));
402: PetscCall(DMGetGlobalSection(dm, &globalSection));
403: PetscCall(PetscSectionGetConstrainedStorageSize(globalSection, &n));
404: m = nb * (dim * (dim + 1)) / 2;
405: PetscCall(PetscMalloc2(m, &mode, m, &dots));
406: PetscCall(VecCreate(comm, &mode[0]));
407: PetscCall(VecSetSizes(mode[0], n, PETSC_DETERMINE));
408: PetscCall(VecSetUp(mode[0]));
409: for (i = 1; i < m; ++i) PetscCall(VecDuplicate(mode[0], &mode[i]));
410: for (b = 0, off = 0; b < nb; ++b) {
411: for (d = 0; d < m / nb; ++d) {
412: PetscInt ctx[2];
413: PetscErrorCode (*func)(PetscInt, PetscReal, const PetscReal *, PetscInt, PetscScalar *, void *) = DMPlexProjectRigidBody_Private;
414: void *voidctx = (void *)(&ctx[0]);
416: ctx[0] = dimEmbed;
417: ctx[1] = d;
418: PetscCall(DMProjectFunctionLabel(dm, 0.0, label, nids[b], &ids[off], 0, NULL, &func, &voidctx, INSERT_VALUES, mode[d]));
419: off += nids[b];
420: }
421: }
422: /* Orthonormalize system */
423: for (i = 0; i < m; ++i) {
424: PetscScalar dots[6];
426: PetscCall(VecNormalize(mode[i], NULL));
427: PetscCall(VecMDot(mode[i], m - i - 1, mode + i + 1, dots + i + 1));
428: for (j = i + 1; j < m; ++j) {
429: dots[j] *= -1.0;
430: PetscCall(VecAXPY(mode[j], dots[j], mode[i]));
431: }
432: }
433: PetscCall(MatNullSpaceCreate(comm, PETSC_FALSE, m, mode, sp));
434: for (i = 0; i < m; ++i) PetscCall(VecDestroy(&mode[i]));
435: PetscCall(PetscFree2(mode, dots));
436: PetscFunctionReturn(PETSC_SUCCESS);
437: }
439: /*@
440: DMPlexSetMaxProjectionHeight - In DMPlexProjectXXXLocal() functions, the projected values of a basis function's dofs
441: are computed by associating the basis function with one of the mesh points in its transitively-closed support, and
442: evaluating the dual space basis of that point.
444: Input Parameters:
445: + dm - the `DMPLEX` object
446: - height - the maximum projection height >= 0
448: Level: advanced
450: Notes:
451: A basis function is associated with the point in its transitively-closed support whose mesh
452: height is highest (w.r.t. DAG height), but not greater than the maximum projection height,
453: which is set with this function. By default, the maximum projection height is zero, which
454: means that only mesh cells are used to project basis functions. A height of one, for
455: example, evaluates a cell-interior basis functions using its cells dual space basis, but all
456: other basis functions with the dual space basis of a face.
458: .seealso: [](ch_unstructured), `DM`, `DMPLEX`, `DMPlexGetMaxProjectionHeight()`, `DMProjectFunctionLocal()`, `DMProjectFunctionLabelLocal()`
459: @*/
460: PetscErrorCode DMPlexSetMaxProjectionHeight(DM dm, PetscInt height)
461: {
462: DM_Plex *plex = (DM_Plex *)dm->data;
464: PetscFunctionBegin;
466: plex->maxProjectionHeight = height;
467: PetscFunctionReturn(PETSC_SUCCESS);
468: }
470: /*@
471: DMPlexGetMaxProjectionHeight - Get the maximum height (w.r.t. DAG) of mesh points used to evaluate dual bases in
472: DMPlexProjectXXXLocal() functions.
474: Input Parameter:
475: . dm - the `DMPLEX` object
477: Output Parameter:
478: . height - the maximum projection height
480: Level: intermediate
482: .seealso: [](ch_unstructured), `DM`, `DMPLEX`, `DMPlexSetMaxProjectionHeight()`, `DMProjectFunctionLocal()`, `DMProjectFunctionLabelLocal()`
483: @*/
484: PetscErrorCode DMPlexGetMaxProjectionHeight(DM dm, PetscInt *height)
485: {
486: DM_Plex *plex = (DM_Plex *)dm->data;
488: PetscFunctionBegin;
490: *height = plex->maxProjectionHeight;
491: PetscFunctionReturn(PETSC_SUCCESS);
492: }
494: typedef struct {
495: PetscReal alpha; /* The first Euler angle, and in 2D the only one */
496: PetscReal beta; /* The second Euler angle */
497: PetscReal gamma; /* The third Euler angle */
498: PetscInt dim; /* The dimension of R */
499: PetscScalar *R; /* The rotation matrix, transforming a vector in the local basis to the global basis */
500: PetscScalar *RT; /* The transposed rotation matrix, transforming a vector in the global basis to the local basis */
501: } RotCtx;
503: /*
504: Note: Following https://en.wikipedia.org/wiki/Euler_angles, we will specify Euler angles by extrinsic rotations, meaning that
505: we rotate with respect to a fixed initial coordinate system, the local basis (x-y-z). The global basis (X-Y-Z) is reached as follows:
506: $ The XYZ system rotates about the z axis by alpha. The X axis is now at angle alpha with respect to the x axis.
507: $ The XYZ system rotates again about the x axis by beta. The Z axis is now at angle beta with respect to the z axis.
508: $ The XYZ system rotates a third time about the z axis by gamma.
509: */
510: static PetscErrorCode DMPlexBasisTransformSetUp_Rotation_Internal(DM dm, PetscCtx ctx)
511: {
512: RotCtx *rc = (RotCtx *)ctx;
513: PetscInt dim = rc->dim;
514: PetscReal c1, s1, c2, s2, c3, s3;
516: PetscFunctionBegin;
517: PetscCall(PetscMalloc2(PetscSqr(dim), &rc->R, PetscSqr(dim), &rc->RT));
518: switch (dim) {
519: case 2:
520: c1 = PetscCosReal(rc->alpha);
521: s1 = PetscSinReal(rc->alpha);
522: rc->R[0] = c1;
523: rc->R[1] = s1;
524: rc->R[2] = -s1;
525: rc->R[3] = c1;
526: PetscCall(PetscArraycpy(rc->RT, rc->R, PetscSqr(dim)));
527: DMPlex_Transpose2D_Internal(rc->RT);
528: break;
529: case 3:
530: c1 = PetscCosReal(rc->alpha);
531: s1 = PetscSinReal(rc->alpha);
532: c2 = PetscCosReal(rc->beta);
533: s2 = PetscSinReal(rc->beta);
534: c3 = PetscCosReal(rc->gamma);
535: s3 = PetscSinReal(rc->gamma);
536: rc->R[0] = c1 * c3 - c2 * s1 * s3;
537: rc->R[1] = c3 * s1 + c1 * c2 * s3;
538: rc->R[2] = s2 * s3;
539: rc->R[3] = -c1 * s3 - c2 * c3 * s1;
540: rc->R[4] = c1 * c2 * c3 - s1 * s3;
541: rc->R[5] = c3 * s2;
542: rc->R[6] = s1 * s2;
543: rc->R[7] = -c1 * s2;
544: rc->R[8] = c2;
545: PetscCall(PetscArraycpy(rc->RT, rc->R, PetscSqr(dim)));
546: DMPlex_Transpose3D_Internal(rc->RT);
547: break;
548: default:
549: SETERRQ(PetscObjectComm((PetscObject)dm), PETSC_ERR_ARG_OUTOFRANGE, "Dimension %" PetscInt_FMT " not supported", dim);
550: }
551: PetscFunctionReturn(PETSC_SUCCESS);
552: }
554: static PetscErrorCode DMPlexBasisTransformDestroy_Rotation_Internal(DM dm, PetscCtx ctx)
555: {
556: RotCtx *rc = (RotCtx *)ctx;
558: PetscFunctionBegin;
559: PetscCall(PetscFree2(rc->R, rc->RT));
560: PetscCall(PetscFree(rc));
561: PetscFunctionReturn(PETSC_SUCCESS);
562: }
564: static PetscErrorCode DMPlexBasisTransformGetMatrix_Rotation_Internal(DM dm, const PetscReal x[], PetscBool l2g, const PetscScalar **A, PetscCtx ctx)
565: {
566: RotCtx *rc = (RotCtx *)ctx;
568: PetscFunctionBeginHot;
569: PetscAssertPointer(ctx, 5);
570: if (l2g) {
571: *A = rc->R;
572: } else {
573: *A = rc->RT;
574: }
575: PetscFunctionReturn(PETSC_SUCCESS);
576: }
578: PetscErrorCode DMPlexBasisTransformApplyReal_Internal(DM dm, const PetscReal x[], PetscBool l2g, PetscInt dim, const PetscReal *y, PetscReal *z, PetscCtx ctx)
579: {
580: PetscFunctionBegin;
581: #if defined(PETSC_USE_COMPLEX)
582: switch (dim) {
583: case 2: {
584: PetscScalar yt[2] = {y[0], y[1]}, zt[2] = {0.0, 0.0};
586: PetscCall(DMPlexBasisTransformApply_Internal(dm, x, l2g, dim, yt, zt, ctx));
587: z[0] = PetscRealPart(zt[0]);
588: z[1] = PetscRealPart(zt[1]);
589: } break;
590: case 3: {
591: PetscScalar yt[3] = {y[0], y[1], y[2]}, zt[3] = {0.0, 0.0, 0.0};
593: PetscCall(DMPlexBasisTransformApply_Internal(dm, x, l2g, dim, yt, zt, ctx));
594: z[0] = PetscRealPart(zt[0]);
595: z[1] = PetscRealPart(zt[1]);
596: z[2] = PetscRealPart(zt[2]);
597: } break;
598: }
599: #else
600: PetscCall(DMPlexBasisTransformApply_Internal(dm, x, l2g, dim, y, z, ctx));
601: #endif
602: PetscFunctionReturn(PETSC_SUCCESS);
603: }
605: PetscErrorCode DMPlexBasisTransformApply_Internal(DM dm, const PetscReal x[], PetscBool l2g, PetscInt dim, const PetscScalar *y, PetscScalar *z, PetscCtx ctx)
606: {
607: const PetscScalar *A;
609: PetscFunctionBeginHot;
610: PetscCall((*dm->transformGetMatrix)(dm, x, l2g, &A, ctx));
611: switch (dim) {
612: case 2:
613: DMPlex_Mult2D_Internal(A, 1, y, z);
614: break;
615: case 3:
616: DMPlex_Mult3D_Internal(A, 1, y, z);
617: break;
618: }
619: PetscFunctionReturn(PETSC_SUCCESS);
620: }
622: static PetscErrorCode DMPlexBasisTransformField_Internal(DM dm, DM tdm, Vec tv, PetscInt p, PetscInt f, PetscBool l2g, PetscScalar *a)
623: {
624: PetscSection ts;
625: const PetscScalar *ta, *tva;
626: PetscInt dof;
628: PetscFunctionBeginHot;
629: PetscCall(DMGetLocalSection(tdm, &ts));
630: PetscCall(PetscSectionGetFieldDof(ts, p, f, &dof));
631: PetscCall(VecGetArrayRead(tv, &ta));
632: PetscCall(DMPlexPointLocalFieldRead(tdm, p, f, ta, &tva));
633: if (l2g) {
634: switch (dof) {
635: case 4:
636: DMPlex_Mult2D_Internal(tva, 1, a, a);
637: break;
638: case 9:
639: DMPlex_Mult3D_Internal(tva, 1, a, a);
640: break;
641: }
642: } else {
643: switch (dof) {
644: case 4:
645: DMPlex_MultTranspose2D_Internal(tva, 1, a, a);
646: break;
647: case 9:
648: DMPlex_MultTranspose3D_Internal(tva, 1, a, a);
649: break;
650: }
651: }
652: PetscCall(VecRestoreArrayRead(tv, &ta));
653: PetscFunctionReturn(PETSC_SUCCESS);
654: }
656: static PetscErrorCode DMPlexBasisTransformFieldTensor_Internal(DM dm, DM tdm, Vec tv, PetscInt pf, PetscInt f, PetscInt pg, PetscInt g, PetscBool l2g, PetscInt lda, PetscScalar *a)
657: {
658: PetscSection s, ts;
659: const PetscScalar *ta, *tvaf, *tvag;
660: PetscInt fdof, gdof, fpdof, gpdof;
662: PetscFunctionBeginHot;
663: PetscCall(DMGetLocalSection(dm, &s));
664: PetscCall(DMGetLocalSection(tdm, &ts));
665: PetscCall(PetscSectionGetFieldDof(s, pf, f, &fpdof));
666: PetscCall(PetscSectionGetFieldDof(s, pg, g, &gpdof));
667: PetscCall(PetscSectionGetFieldDof(ts, pf, f, &fdof));
668: PetscCall(PetscSectionGetFieldDof(ts, pg, g, &gdof));
669: PetscCall(VecGetArrayRead(tv, &ta));
670: PetscCall(DMPlexPointLocalFieldRead(tdm, pf, f, ta, &tvaf));
671: PetscCall(DMPlexPointLocalFieldRead(tdm, pg, g, ta, &tvag));
672: if (l2g) {
673: switch (fdof) {
674: case 4:
675: DMPlex_MatMult2D_Internal(tvaf, gpdof, lda, a, a);
676: break;
677: case 9:
678: DMPlex_MatMult3D_Internal(tvaf, gpdof, lda, a, a);
679: break;
680: }
681: switch (gdof) {
682: case 4:
683: DMPlex_MatMultTransposeLeft2D_Internal(tvag, fpdof, lda, a, a);
684: break;
685: case 9:
686: DMPlex_MatMultTransposeLeft3D_Internal(tvag, fpdof, lda, a, a);
687: break;
688: }
689: } else {
690: switch (fdof) {
691: case 4:
692: DMPlex_MatMultTranspose2D_Internal(tvaf, gpdof, lda, a, a);
693: break;
694: case 9:
695: DMPlex_MatMultTranspose3D_Internal(tvaf, gpdof, lda, a, a);
696: break;
697: }
698: switch (gdof) {
699: case 4:
700: DMPlex_MatMultLeft2D_Internal(tvag, fpdof, lda, a, a);
701: break;
702: case 9:
703: DMPlex_MatMultLeft3D_Internal(tvag, fpdof, lda, a, a);
704: break;
705: }
706: }
707: PetscCall(VecRestoreArrayRead(tv, &ta));
708: PetscFunctionReturn(PETSC_SUCCESS);
709: }
711: PetscErrorCode DMPlexBasisTransformPoint_Internal(DM dm, DM tdm, Vec tv, PetscInt p, PetscBool fieldActive[], PetscBool l2g, PetscScalar *a)
712: {
713: PetscSection s;
714: PetscSection clSection;
715: IS clPoints;
716: const PetscInt *clp;
717: PetscInt *points = NULL;
718: PetscInt Nf, f, Np, cp, dof, d = 0;
720: PetscFunctionBegin;
721: PetscCall(DMGetLocalSection(dm, &s));
722: PetscCall(PetscSectionGetNumFields(s, &Nf));
723: PetscCall(DMPlexGetCompressedClosure(dm, s, p, 0, &Np, &points, &clSection, &clPoints, &clp));
724: for (f = 0; f < Nf; ++f) {
725: for (cp = 0; cp < Np * 2; cp += 2) {
726: PetscCall(PetscSectionGetFieldDof(s, points[cp], f, &dof));
727: if (!dof) continue;
728: if (fieldActive[f]) PetscCall(DMPlexBasisTransformField_Internal(dm, tdm, tv, points[cp], f, l2g, &a[d]));
729: d += dof;
730: }
731: }
732: PetscCall(DMPlexRestoreCompressedClosure(dm, s, p, &Np, &points, &clSection, &clPoints, &clp));
733: PetscFunctionReturn(PETSC_SUCCESS);
734: }
736: PetscErrorCode DMPlexBasisTransformPointTensor_Internal(DM dm, DM tdm, Vec tv, PetscInt p, PetscBool l2g, PetscInt lda, PetscScalar *a)
737: {
738: PetscSection s;
739: PetscSection clSection;
740: IS clPoints;
741: const PetscInt *clp;
742: PetscInt *points = NULL;
743: PetscInt Nf, f, g, Np, cpf, cpg, fdof, gdof, r, c = 0;
745: PetscFunctionBegin;
746: PetscCall(DMGetLocalSection(dm, &s));
747: PetscCall(PetscSectionGetNumFields(s, &Nf));
748: PetscCall(DMPlexGetCompressedClosure(dm, s, p, 0, &Np, &points, &clSection, &clPoints, &clp));
749: for (f = 0, r = 0; f < Nf; ++f) {
750: for (cpf = 0; cpf < Np * 2; cpf += 2) {
751: PetscCall(PetscSectionGetFieldDof(s, points[cpf], f, &fdof));
752: for (g = 0, c = 0; g < Nf; ++g) {
753: for (cpg = 0; cpg < Np * 2; cpg += 2) {
754: PetscCall(PetscSectionGetFieldDof(s, points[cpg], g, &gdof));
755: PetscCall(DMPlexBasisTransformFieldTensor_Internal(dm, tdm, tv, points[cpf], f, points[cpg], g, l2g, lda, &a[r * lda + c]));
756: c += gdof;
757: }
758: }
759: PetscCheck(c == lda, PETSC_COMM_SELF, PETSC_ERR_PLIB, "Invalid number of columns %" PetscInt_FMT " should be %" PetscInt_FMT, c, lda);
760: r += fdof;
761: }
762: }
763: PetscCheck(r == lda, PETSC_COMM_SELF, PETSC_ERR_PLIB, "Invalid number of rows %" PetscInt_FMT " should be %" PetscInt_FMT, c, lda);
764: PetscCall(DMPlexRestoreCompressedClosure(dm, s, p, &Np, &points, &clSection, &clPoints, &clp));
765: PetscFunctionReturn(PETSC_SUCCESS);
766: }
768: static PetscErrorCode DMPlexBasisTransform_Internal(DM dm, Vec lv, PetscBool l2g)
769: {
770: DM tdm;
771: Vec tv;
772: PetscSection ts, s;
773: const PetscScalar *ta;
774: PetscScalar *a, *va;
775: PetscInt pStart, pEnd, p, Nf, f;
777: PetscFunctionBegin;
778: PetscCall(DMGetBasisTransformDM_Internal(dm, &tdm));
779: PetscCall(DMGetBasisTransformVec_Internal(dm, &tv));
780: PetscCall(DMGetLocalSection(tdm, &ts));
781: PetscCall(DMGetLocalSection(dm, &s));
782: PetscCall(PetscSectionGetChart(s, &pStart, &pEnd));
783: PetscCall(PetscSectionGetNumFields(s, &Nf));
784: PetscCall(VecGetArray(lv, &a));
785: PetscCall(VecGetArrayRead(tv, &ta));
786: for (p = pStart; p < pEnd; ++p) {
787: for (f = 0; f < Nf; ++f) {
788: PetscCall(DMPlexPointLocalFieldRef(dm, p, f, a, &va));
789: PetscCall(DMPlexBasisTransformField_Internal(dm, tdm, tv, p, f, l2g, va));
790: }
791: }
792: PetscCall(VecRestoreArray(lv, &a));
793: PetscCall(VecRestoreArrayRead(tv, &ta));
794: PetscFunctionReturn(PETSC_SUCCESS);
795: }
797: /*@
798: DMPlexGlobalToLocalBasis - Transform the values in the given local vector from the global basis to the local basis
800: Input Parameters:
801: + dm - The `DM`
802: - lv - A local vector with values in the global basis
804: Output Parameter:
805: . lv - A local vector with values in the local basis
807: Level: developer
809: Note:
810: This method is only intended to be called inside `DMGlobalToLocal()`. It is unlikely that a user will have a local vector full of coefficients for the global basis unless they are reimplementing GlobalToLocal.
812: .seealso: [](ch_unstructured), `DM`, `DMPLEX`, `DMPlexLocalToGlobalBasis()`, `DMGetLocalSection()`, `DMPlexCreateBasisRotation()`
813: @*/
814: PetscErrorCode DMPlexGlobalToLocalBasis(DM dm, Vec lv)
815: {
816: PetscFunctionBegin;
819: PetscCall(DMPlexBasisTransform_Internal(dm, lv, PETSC_FALSE));
820: PetscFunctionReturn(PETSC_SUCCESS);
821: }
823: /*@
824: DMPlexLocalToGlobalBasis - Transform the values in the given local vector from the local basis to the global basis
826: Input Parameters:
827: + dm - The `DM`
828: - lv - A local vector with values in the local basis
830: Output Parameter:
831: . lv - A local vector with values in the global basis
833: Level: developer
835: Note:
836: This method is only intended to be called inside `DMGlobalToLocal()`. It is unlikely that a user would want a local vector full of coefficients for the global basis unless they are reimplementing GlobalToLocal.
838: .seealso: [](ch_unstructured), `DM`, `DMPLEX`, `DMPlexGlobalToLocalBasis()`, `DMGetLocalSection()`, `DMPlexCreateBasisRotation()`
839: @*/
840: PetscErrorCode DMPlexLocalToGlobalBasis(DM dm, Vec lv)
841: {
842: PetscFunctionBegin;
845: PetscCall(DMPlexBasisTransform_Internal(dm, lv, PETSC_TRUE));
846: PetscFunctionReturn(PETSC_SUCCESS);
847: }
849: /*@
850: DMPlexCreateBasisRotation - Create an internal transformation from the global basis, used to specify boundary conditions
851: and global solutions, to a local basis, appropriate for discretization integrals and assembly.
853: Input Parameters:
854: + dm - The `DM`
855: . alpha - The first Euler angle, and in 2D the only one
856: . beta - The second Euler angle
857: - gamma - The third Euler angle
859: Level: developer
861: Note:
862: Following https://en.wikipedia.org/wiki/Euler_angles, we will specify Euler angles by extrinsic rotations, meaning that
863: we rotate with respect to a fixed initial coordinate system, the local basis (x-y-z). The global basis (X-Y-Z) is reached as follows
864: .vb
865: The XYZ system rotates about the z axis by alpha. The X axis is now at angle alpha with respect to the x axis.
866: The XYZ system rotates again about the x axis by beta. The Z axis is now at angle beta with respect to the z axis.
867: The XYZ system rotates a third time about the z axis by gamma.
868: .ve
870: .seealso: [](ch_unstructured), `DM`, `DMPLEX`, `DMPlexGlobalToLocalBasis()`, `DMPlexLocalToGlobalBasis()`
871: @*/
872: PetscErrorCode DMPlexCreateBasisRotation(DM dm, PetscReal alpha, PetscReal beta, PetscReal gamma)
873: {
874: RotCtx *rc;
875: PetscInt cdim;
877: PetscFunctionBegin;
878: PetscCall(DMGetCoordinateDim(dm, &cdim));
879: PetscCall(PetscMalloc1(1, &rc));
880: dm->transformCtx = rc;
881: dm->transformSetUp = DMPlexBasisTransformSetUp_Rotation_Internal;
882: dm->transformDestroy = DMPlexBasisTransformDestroy_Rotation_Internal;
883: dm->transformGetMatrix = DMPlexBasisTransformGetMatrix_Rotation_Internal;
884: rc->dim = cdim;
885: rc->alpha = alpha;
886: rc->beta = beta;
887: rc->gamma = gamma;
888: PetscCall((*dm->transformSetUp)(dm, dm->transformCtx));
889: PetscCall(DMConstructBasisTransform_Internal(dm));
890: PetscFunctionReturn(PETSC_SUCCESS);
891: }
893: /*@C
894: DMPlexInsertBoundaryValuesEssential - Insert boundary values into a local vector using a function of the coordinates
896: Input Parameters:
897: + dm - The `DM`, with a `PetscDS` that matches the problem being constrained
898: . time - The time
899: . field - The field to constrain
900: . Nc - The number of constrained field components, or 0 for all components
901: . comps - An array of constrained component numbers, or `NULL` for all components
902: . label - The `DMLabel` defining constrained points
903: . numids - The number of `DMLabel` ids for constrained points
904: . ids - An array of ids for constrained points
905: . func - A pointwise function giving boundary values
906: - ctx - An optional application context for `bcFunc`
908: Output Parameter:
909: . locX - A local vector to receives the boundary values
911: Level: developer
913: .seealso: [](ch_unstructured), `DM`, `DMPLEX`, `DMLabel`, `DMPlexInsertBoundaryValuesEssentialField()`, `DMPlexInsertBoundaryValuesEssentialBdField()`, `DMAddBoundary()`
914: @*/
915: PetscErrorCode DMPlexInsertBoundaryValuesEssential(DM dm, PetscReal time, PetscInt field, PetscInt Nc, const PetscInt comps[], DMLabel label, PetscInt numids, const PetscInt ids[], PetscErrorCode (*func)(PetscInt, PetscReal, const PetscReal[], PetscInt, PetscScalar *, void *), PetscCtx ctx, Vec locX)
916: {
917: PetscErrorCode (**funcs)(PetscInt, PetscReal, const PetscReal x[], PetscInt, PetscScalar *u, PetscCtx ctx);
918: void **ctxs;
919: PetscInt numFields;
921: PetscFunctionBegin;
922: PetscCall(DMGetNumFields(dm, &numFields));
923: PetscCall(PetscCalloc2(numFields, &funcs, numFields, &ctxs));
924: funcs[field] = func;
925: ctxs[field] = ctx;
926: PetscCall(DMProjectFunctionLabelLocal(dm, time, label, numids, ids, Nc, comps, funcs, ctxs, INSERT_BC_VALUES, locX));
927: PetscCall(PetscFree2(funcs, ctxs));
928: PetscFunctionReturn(PETSC_SUCCESS);
929: }
931: /*@C
932: DMPlexInsertBoundaryValuesEssentialField - Insert boundary values into a local vector using a function of the coordinates and field data
934: Input Parameters:
935: + dm - The `DM`, with a `PetscDS` that matches the problem being constrained
936: . time - The time
937: . locU - A local vector with the input solution values
938: . field - The field to constrain
939: . Nc - The number of constrained field components, or 0 for all components
940: . comps - An array of constrained component numbers, or `NULL` for all components
941: . label - The `DMLabel` defining constrained points
942: . numids - The number of `DMLabel` ids for constrained points
943: . ids - An array of ids for constrained points
944: . func - A pointwise function giving boundary values
945: - ctx - An optional application context for `bcFunc`
947: Output Parameter:
948: . locX - A local vector to receives the boundary values
950: Level: developer
952: .seealso: [](ch_unstructured), `DM`, `DMPLEX`, `DMPlexInsertBoundaryValuesEssential()`, `DMPlexInsertBoundaryValuesEssentialBdField()`, `DMAddBoundary()`
953: @*/
954: PetscErrorCode DMPlexInsertBoundaryValuesEssentialField(DM dm, PetscReal time, Vec locU, PetscInt field, PetscInt Nc, const PetscInt comps[], DMLabel label, PetscInt numids, const PetscInt ids[], void (*func)(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[]), PetscCtx ctx, Vec locX)
955: {
956: 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[]);
957: void **ctxs;
958: PetscInt numFields;
960: PetscFunctionBegin;
961: PetscCall(DMGetNumFields(dm, &numFields));
962: PetscCall(PetscCalloc2(numFields, &funcs, numFields, &ctxs));
963: funcs[field] = func;
964: ctxs[field] = ctx;
965: PetscCall(DMProjectFieldLabelLocal(dm, time, label, numids, ids, Nc, comps, locU, funcs, INSERT_BC_VALUES, locX));
966: PetscCall(PetscFree2(funcs, ctxs));
967: PetscFunctionReturn(PETSC_SUCCESS);
968: }
970: /*@C
971: DMPlexInsertBoundaryValuesEssentialBdField - Insert boundary values into a local vector using a function of the coordinates and boundary field data
973: Collective
975: Input Parameters:
976: + dm - The `DM`, with a `PetscDS` that matches the problem being constrained
977: . time - The time
978: . locU - A local vector with the input solution values
979: . field - The field to constrain
980: . Nc - The number of constrained field components, or 0 for all components
981: . comps - An array of constrained component numbers, or `NULL` for all components
982: . label - The `DMLabel` defining constrained points
983: . numids - The number of `DMLabel` ids for constrained points
984: . ids - An array of ids for constrained points
985: . func - A pointwise function giving boundary values, the calling sequence is given in `DMProjectBdFieldLabelLocal()`
986: - ctx - An optional application context for `func`
988: Output Parameter:
989: . locX - A local vector to receive the boundary values
991: Level: developer
993: .seealso: [](ch_unstructured), `DM`, `DMPLEX`, `DMProjectBdFieldLabelLocal()`, `DMPlexInsertBoundaryValuesEssential()`, `DMPlexInsertBoundaryValuesEssentialField()`, `DMAddBoundary()`
994: @*/
995: PetscErrorCode DMPlexInsertBoundaryValuesEssentialBdField(DM dm, PetscReal time, Vec locU, PetscInt field, PetscInt Nc, const PetscInt comps[], DMLabel label, PetscInt numids, const PetscInt ids[], void (*func)(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[]), PetscCtx ctx, Vec locX)
996: {
997: 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[]);
998: void **ctxs;
999: PetscInt numFields;
1001: PetscFunctionBegin;
1002: PetscCall(DMGetNumFields(dm, &numFields));
1003: PetscCall(PetscCalloc2(numFields, &funcs, numFields, &ctxs));
1004: funcs[field] = func;
1005: ctxs[field] = ctx;
1006: PetscCall(DMProjectBdFieldLabelLocal(dm, time, label, numids, ids, Nc, comps, locU, funcs, INSERT_BC_VALUES, locX));
1007: PetscCall(PetscFree2(funcs, ctxs));
1008: PetscFunctionReturn(PETSC_SUCCESS);
1009: }
1011: /*@C
1012: DMPlexInsertBoundaryValuesRiemann - Insert boundary values into a local vector
1014: Input Parameters:
1015: + dm - The `DM`, with a `PetscDS` that matches the problem being constrained
1016: . time - The time
1017: . faceGeometry - A vector with the FVM face geometry information
1018: . cellGeometry - A vector with the FVM cell geometry information
1019: . Grad - A vector with the FVM cell gradient information
1020: . field - The field to constrain
1021: . Nc - The number of constrained field components, or 0 for all components
1022: . comps - An array of constrained component numbers, or `NULL` for all components
1023: . label - The `DMLabel` defining constrained points
1024: . numids - The number of `DMLabel` ids for constrained points
1025: . ids - An array of ids for constrained points
1026: . func - A pointwise function giving boundary values
1027: - ctx - An optional application context for bcFunc
1029: Output Parameter:
1030: . locX - A local vector to receives the boundary values
1032: Level: developer
1034: Note:
1035: This implementation currently ignores the numcomps/comps argument from `DMAddBoundary()`
1037: .seealso: [](ch_unstructured), `DM`, `DMPLEX`, `DMPlexInsertBoundaryValuesEssential()`, `DMPlexInsertBoundaryValuesEssentialField()`, `DMAddBoundary()`
1038: @*/
1039: PetscErrorCode DMPlexInsertBoundaryValuesRiemann(DM dm, PetscReal time, Vec faceGeometry, Vec cellGeometry, Vec Grad, PetscInt field, PetscInt Nc, const PetscInt comps[], DMLabel label, PetscInt numids, const PetscInt ids[], PetscErrorCode (*func)(PetscReal, const PetscReal *, const PetscReal *, const PetscScalar *, PetscScalar *, void *), PetscCtx ctx, Vec locX)
1040: {
1041: PetscDS prob;
1042: PetscSF sf;
1043: DM dmFace, dmCell, dmGrad;
1044: const PetscScalar *facegeom, *cellgeom = NULL, *grad;
1045: const PetscInt *leaves;
1046: PetscScalar *x, *fx;
1047: PetscInt dim, nleaves, loc, fStart, fEnd, pdim, i;
1048: PetscErrorCode ierru = PETSC_SUCCESS;
1050: PetscFunctionBegin;
1051: PetscCall(DMGetPointSF(dm, &sf));
1052: PetscCall(PetscSFGetGraph(sf, NULL, &nleaves, &leaves, NULL));
1053: nleaves = PetscMax(0, nleaves);
1054: PetscCall(DMGetDimension(dm, &dim));
1055: PetscCall(DMPlexGetHeightStratum(dm, 1, &fStart, &fEnd));
1056: PetscCall(DMGetDS(dm, &prob));
1057: PetscCall(VecGetDM(faceGeometry, &dmFace));
1058: PetscCall(VecGetArrayRead(faceGeometry, &facegeom));
1059: if (cellGeometry) {
1060: PetscCall(VecGetDM(cellGeometry, &dmCell));
1061: PetscCall(VecGetArrayRead(cellGeometry, &cellgeom));
1062: }
1063: if (Grad) {
1064: PetscFV fv;
1066: PetscCall(PetscDSGetDiscretization(prob, field, (PetscObject *)&fv));
1067: PetscCall(VecGetDM(Grad, &dmGrad));
1068: PetscCall(VecGetArrayRead(Grad, &grad));
1069: PetscCall(PetscFVGetNumComponents(fv, &pdim));
1070: PetscCall(DMGetWorkArray(dm, pdim, MPIU_SCALAR, &fx));
1071: }
1072: PetscCall(VecGetArray(locX, &x));
1073: for (i = 0; i < numids; ++i) {
1074: IS faceIS;
1075: const PetscInt *faces;
1076: PetscInt numFaces, f;
1078: PetscCall(DMLabelGetStratumIS(label, ids[i], &faceIS));
1079: if (!faceIS) continue; /* No points with that id on this process */
1080: PetscCall(ISGetLocalSize(faceIS, &numFaces));
1081: PetscCall(ISGetIndices(faceIS, &faces));
1082: for (f = 0; f < numFaces; ++f) {
1083: const PetscInt face = faces[f], *cells;
1084: PetscFVFaceGeom *fg;
1086: if ((face < fStart) || (face >= fEnd)) continue; /* Refinement adds non-faces to labels */
1087: PetscCall(PetscFindInt(face, nleaves, (PetscInt *)leaves, &loc));
1088: if (loc >= 0) continue;
1089: PetscCall(DMPlexPointLocalRead(dmFace, face, facegeom, &fg));
1090: PetscCall(DMPlexGetSupport(dm, face, &cells));
1091: if (Grad) {
1092: PetscFVCellGeom *cg;
1093: PetscScalar *cx, *cgrad;
1094: PetscScalar *xG;
1095: PetscReal dx[3];
1096: PetscInt d;
1098: PetscCall(DMPlexPointLocalRead(dmCell, cells[0], cellgeom, &cg));
1099: PetscCall(DMPlexPointLocalRead(dm, cells[0], x, &cx));
1100: PetscCall(DMPlexPointLocalRead(dmGrad, cells[0], grad, &cgrad));
1101: PetscCall(DMPlexPointLocalFieldRef(dm, cells[1], field, x, &xG));
1102: DMPlex_WaxpyD_Internal(dim, -1, cg->centroid, fg->centroid, dx);
1103: for (d = 0; d < pdim; ++d) fx[d] = cx[d] + DMPlex_DotD_Internal(dim, &cgrad[d * dim], dx);
1104: PetscCall((*func)(time, fg->centroid, fg->normal, fx, xG, ctx));
1105: } else {
1106: PetscScalar *xI;
1107: PetscScalar *xG;
1109: PetscCall(DMPlexPointLocalRead(dm, cells[0], x, &xI));
1110: PetscCall(DMPlexPointLocalFieldRef(dm, cells[1], field, x, &xG));
1111: ierru = (*func)(time, fg->centroid, fg->normal, xI, xG, ctx);
1112: if (ierru) {
1113: PetscCall(ISRestoreIndices(faceIS, &faces));
1114: PetscCall(ISDestroy(&faceIS));
1115: goto cleanup;
1116: }
1117: }
1118: }
1119: PetscCall(ISRestoreIndices(faceIS, &faces));
1120: PetscCall(ISDestroy(&faceIS));
1121: }
1122: cleanup:
1123: PetscCall(VecRestoreArray(locX, &x));
1124: if (Grad) {
1125: PetscCall(DMRestoreWorkArray(dm, pdim, MPIU_SCALAR, &fx));
1126: PetscCall(VecRestoreArrayRead(Grad, &grad));
1127: }
1128: if (cellGeometry) PetscCall(VecRestoreArrayRead(cellGeometry, &cellgeom));
1129: PetscCall(VecRestoreArrayRead(faceGeometry, &facegeom));
1130: PetscCall(ierru);
1131: PetscFunctionReturn(PETSC_SUCCESS);
1132: }
1134: static PetscErrorCode zero(PetscInt dim, PetscReal time, const PetscReal x[], PetscInt Nc, PetscScalar *u, PetscCtx ctx)
1135: {
1136: PetscInt c;
1137: for (c = 0; c < Nc; ++c) u[c] = 0.0;
1138: return PETSC_SUCCESS;
1139: }
1141: PetscErrorCode DMPlexInsertBoundaryValues_Plex(DM dm, PetscBool insertEssential, Vec locX, PetscReal time, Vec faceGeomFVM, Vec cellGeomFVM, Vec gradFVM)
1142: {
1143: PetscObject isZero;
1144: PetscDS prob;
1145: PetscInt numBd, b;
1147: PetscFunctionBegin;
1148: PetscCall(DMGetDS(dm, &prob));
1149: PetscCall(PetscDSGetNumBoundary(prob, &numBd));
1150: PetscCall(PetscObjectQuery((PetscObject)locX, "__Vec_bc_zero__", &isZero));
1151: PetscCall(PetscDSUpdateBoundaryLabels(prob, dm));
1152: for (b = 0; b < numBd; ++b) {
1153: PetscWeakForm wf;
1154: DMBoundaryConditionType type;
1155: const char *name;
1156: DMLabel label;
1157: PetscInt field, Nc;
1158: const PetscInt *comps;
1159: PetscObject obj;
1160: PetscClassId id;
1161: PetscVoidFn *bvfunc;
1162: PetscInt numids;
1163: const PetscInt *ids;
1164: void *ctx;
1166: PetscCall(PetscDSGetBoundary(prob, b, &wf, &type, &name, &label, &numids, &ids, &field, &Nc, &comps, &bvfunc, NULL, &ctx));
1167: if (insertEssential != (type & DM_BC_ESSENTIAL)) continue;
1168: PetscCall(DMGetField(dm, field, NULL, &obj));
1169: PetscCall(PetscObjectGetClassId(obj, &id));
1170: if (id == PETSCFE_CLASSID) {
1171: switch (type) {
1172: /* for FEM, there is no insertion to be done for non-essential boundary conditions */
1173: case DM_BC_ESSENTIAL: {
1174: PetscSimplePointFn *func = (PetscSimplePointFn *)bvfunc;
1176: if (isZero) func = zero;
1177: PetscCall(DMPlexLabelAddCells(dm, label));
1178: PetscCall(DMPlexInsertBoundaryValuesEssential(dm, time, field, Nc, comps, label, numids, ids, func, ctx, locX));
1179: PetscCall(DMPlexLabelClearCells(dm, label));
1180: } break;
1181: case DM_BC_ESSENTIAL_FIELD: {
1182: PetscPointFn *func = (PetscPointFn *)bvfunc;
1184: PetscCall(DMPlexLabelAddCells(dm, label));
1185: PetscCall(DMPlexInsertBoundaryValuesEssentialField(dm, time, locX, field, Nc, comps, label, numids, ids, func, ctx, locX));
1186: PetscCall(DMPlexLabelClearCells(dm, label));
1187: } break;
1188: default:
1189: break;
1190: }
1191: } else if (id == PETSCFV_CLASSID) {
1192: {
1193: PetscErrorCode (*func)(PetscReal, const PetscReal *, const PetscReal *, const PetscScalar *, PetscScalar *, void *) = (PetscErrorCode (*)(PetscReal, const PetscReal *, const PetscReal *, const PetscScalar *, PetscScalar *, void *))bvfunc;
1195: if (!faceGeomFVM) continue;
1196: PetscCall(DMPlexInsertBoundaryValuesRiemann(dm, time, faceGeomFVM, cellGeomFVM, gradFVM, field, Nc, comps, label, numids, ids, func, ctx, locX));
1197: }
1198: } else SETERRQ(PetscObjectComm((PetscObject)dm), PETSC_ERR_ARG_WRONG, "Unknown discretization type for field %" PetscInt_FMT, field);
1199: }
1200: PetscFunctionReturn(PETSC_SUCCESS);
1201: }
1203: PetscErrorCode DMPlexInsertTimeDerivativeBoundaryValues_Plex(DM dm, PetscBool insertEssential, Vec locX, PetscReal time, Vec faceGeomFVM, Vec cellGeomFVM, Vec gradFVM)
1204: {
1205: PetscObject isZero;
1206: PetscDS prob;
1207: PetscInt numBd, b;
1209: PetscFunctionBegin;
1210: if (!locX) PetscFunctionReturn(PETSC_SUCCESS);
1211: PetscCall(DMGetDS(dm, &prob));
1212: PetscCall(PetscDSGetNumBoundary(prob, &numBd));
1213: PetscCall(PetscObjectQuery((PetscObject)locX, "__Vec_bc_zero__", &isZero));
1214: for (b = 0; b < numBd; ++b) {
1215: PetscWeakForm wf;
1216: DMBoundaryConditionType type;
1217: const char *name;
1218: DMLabel label;
1219: PetscInt field, Nc;
1220: const PetscInt *comps;
1221: PetscObject obj;
1222: PetscClassId id;
1223: PetscInt numids;
1224: const PetscInt *ids;
1225: PetscVoidFn *bvfunc;
1226: void *ctx;
1228: PetscCall(PetscDSGetBoundary(prob, b, &wf, &type, &name, &label, &numids, &ids, &field, &Nc, &comps, NULL, &bvfunc, &ctx));
1229: if (insertEssential != (type & DM_BC_ESSENTIAL)) continue;
1230: PetscCall(DMGetField(dm, field, NULL, &obj));
1231: PetscCall(PetscObjectGetClassId(obj, &id));
1232: if (id == PETSCFE_CLASSID) {
1233: switch (type) {
1234: /* for FEM, there is no insertion to be done for non-essential boundary conditions */
1235: case DM_BC_ESSENTIAL: {
1236: PetscSimplePointFn *func_t = (PetscSimplePointFn *)bvfunc;
1238: if (isZero) func_t = zero;
1239: PetscCall(DMPlexLabelAddCells(dm, label));
1240: PetscCall(DMPlexInsertBoundaryValuesEssential(dm, time, field, Nc, comps, label, numids, ids, func_t, ctx, locX));
1241: PetscCall(DMPlexLabelClearCells(dm, label));
1242: } break;
1243: case DM_BC_ESSENTIAL_FIELD: {
1244: PetscPointFn *func_t = (PetscPointFn *)bvfunc;
1246: PetscCall(DMPlexLabelAddCells(dm, label));
1247: PetscCall(DMPlexInsertBoundaryValuesEssentialField(dm, time, locX, field, Nc, comps, label, numids, ids, func_t, ctx, locX));
1248: PetscCall(DMPlexLabelClearCells(dm, label));
1249: } break;
1250: default:
1251: break;
1252: }
1253: } else SETERRQ(PetscObjectComm((PetscObject)dm), PETSC_ERR_ARG_WRONG, "Unknown discretization type for field %" PetscInt_FMT, field);
1254: }
1255: PetscFunctionReturn(PETSC_SUCCESS);
1256: }
1258: PetscErrorCode DMPlexInsertBounds_Plex(DM dm, PetscBool lower, PetscReal time, Vec locB)
1259: {
1260: PetscDS ds;
1261: PetscInt numBd;
1263: PetscFunctionBegin;
1264: PetscCall(DMGetDS(dm, &ds));
1265: PetscCall(PetscDSGetNumBoundary(ds, &numBd));
1266: PetscCall(PetscDSUpdateBoundaryLabels(ds, dm));
1267: for (PetscInt b = 0; b < numBd; ++b) {
1268: PetscWeakForm wf;
1269: DMBoundaryConditionType type;
1270: const char *name;
1271: DMLabel label;
1272: PetscInt numids;
1273: const PetscInt *ids;
1274: PetscInt field, Nc;
1275: const PetscInt *comps;
1276: PetscVoidFn *bvfunc;
1277: void *ctx;
1279: PetscCall(PetscDSGetBoundary(ds, b, &wf, &type, &name, &label, &numids, &ids, &field, &Nc, &comps, &bvfunc, NULL, &ctx));
1280: if (lower && type != DM_BC_LOWER_BOUND) continue;
1281: if (!lower && type != DM_BC_UPPER_BOUND) continue;
1282: PetscCall(DMPlexLabelAddCells(dm, label));
1283: {
1284: PetscErrorCode (**funcs)(PetscInt, PetscReal, const PetscReal x[], PetscInt, PetscScalar *u, PetscCtx ctx);
1285: void **ctxs;
1286: PetscInt Nf;
1288: PetscCall(DMGetNumFields(dm, &Nf));
1289: PetscCall(PetscCalloc2(Nf, &funcs, Nf, &ctxs));
1290: funcs[field] = (PetscSimplePointFn *)bvfunc;
1291: ctxs[field] = ctx;
1292: PetscCall(DMProjectFunctionLabelLocal(dm, time, label, numids, ids, Nc, comps, funcs, ctxs, INSERT_ALL_VALUES, locB));
1293: PetscCall(PetscFree2(funcs, ctxs));
1294: }
1295: PetscCall(DMPlexLabelClearCells(dm, label));
1296: }
1297: PetscFunctionReturn(PETSC_SUCCESS);
1298: }
1300: /*@
1301: DMPlexInsertBoundaryValues - Puts coefficients which represent boundary values into the local solution vector
1303: Not Collective
1305: Input Parameters:
1306: + dm - The `DM`
1307: . insertEssential - Should I insert essential (e.g. Dirichlet) or inessential (e.g. Neumann) boundary conditions
1308: . time - The time
1309: . faceGeomFVM - Face geometry data for FV discretizations
1310: . cellGeomFVM - Cell geometry data for FV discretizations
1311: - gradFVM - Gradient reconstruction data for FV discretizations
1313: Output Parameter:
1314: . locX - Solution updated with boundary values
1316: Level: intermediate
1318: .seealso: [](ch_unstructured), `DM`, `DMPLEX`, `DMProjectFunctionLabelLocal()`, `DMAddBoundary()`
1319: @*/
1320: PetscErrorCode DMPlexInsertBoundaryValues(DM dm, PetscBool insertEssential, Vec locX, PetscReal time, Vec faceGeomFVM, Vec cellGeomFVM, Vec gradFVM)
1321: {
1322: PetscFunctionBegin;
1328: PetscTryMethod(dm, "DMPlexInsertBoundaryValues_C", (DM, PetscBool, Vec, PetscReal, Vec, Vec, Vec), (dm, insertEssential, locX, time, faceGeomFVM, cellGeomFVM, gradFVM));
1329: PetscFunctionReturn(PETSC_SUCCESS);
1330: }
1332: /*@
1333: DMPlexInsertTimeDerivativeBoundaryValues - Puts coefficients which represent boundary values of the time derivative into the local solution vector
1335: Input Parameters:
1336: + dm - The `DM`
1337: . insertEssential - Should I insert essential (e.g. Dirichlet) or inessential (e.g. Neumann) boundary conditions
1338: . time - The time
1339: . faceGeomFVM - Face geometry data for FV discretizations
1340: . cellGeomFVM - Cell geometry data for FV discretizations
1341: - gradFVM - Gradient reconstruction data for FV discretizations
1343: Output Parameter:
1344: . locX_t - Solution updated with boundary values
1346: Level: developer
1348: .seealso: [](ch_unstructured), `DM`, `DMPLEX`, `DMProjectFunctionLabelLocal()`
1349: @*/
1350: PetscErrorCode DMPlexInsertTimeDerivativeBoundaryValues(DM dm, PetscBool insertEssential, Vec locX_t, PetscReal time, Vec faceGeomFVM, Vec cellGeomFVM, Vec gradFVM)
1351: {
1352: PetscFunctionBegin;
1358: PetscTryMethod(dm, "DMPlexInsertTimeDerivativeBoundaryValues_C", (DM, PetscBool, Vec, PetscReal, Vec, Vec, Vec), (dm, insertEssential, locX_t, time, faceGeomFVM, cellGeomFVM, gradFVM));
1359: PetscFunctionReturn(PETSC_SUCCESS);
1360: }
1362: /*@
1363: DMPlexInsertBounds - Puts coefficients which represent solution bounds into the local bounds vector
1365: Not Collective
1367: Input Parameters:
1368: + dm - The `DM`
1369: . lower - If `PETSC_TRUE` use `DM_BC_LOWER_BOUND` conditions, otherwise use `DM_BC_UPPER_BOUND`
1370: - time - The time
1372: Output Parameter:
1373: . locB - Bounds vector updated with new bounds
1375: Level: intermediate
1377: .seealso: [](ch_unstructured), `DM`, `DMPLEX`, `DMProjectFunctionLabelLocal()`, `PetscDSAddBoundary()`
1378: @*/
1379: PetscErrorCode DMPlexInsertBounds(DM dm, PetscBool lower, PetscReal time, Vec locB)
1380: {
1381: PetscFunctionBegin;
1384: PetscTryMethod(dm, "DMPlexInsertBounds_C", (DM, PetscBool, PetscReal, Vec), (dm, lower, time, locB));
1385: PetscFunctionReturn(PETSC_SUCCESS);
1386: }
1388: // Handle non-essential (e.g. outflow) boundary values
1389: PetscErrorCode DMPlexInsertBoundaryValuesFVM(DM dm, PetscFV fv, Vec locX, PetscReal time, Vec *locGradient)
1390: {
1391: DM dmGrad;
1392: Vec cellGeometryFVM, faceGeometryFVM, locGrad = NULL;
1394: PetscFunctionBegin;
1398: if (locGradient) {
1399: PetscAssertPointer(locGradient, 5);
1400: *locGradient = NULL;
1401: }
1402: PetscCall(DMPlexGetGeometryFVM(dm, &faceGeometryFVM, &cellGeometryFVM, NULL));
1403: /* Reconstruct and limit cell gradients */
1404: PetscCall(DMPlexGetGradientDM(dm, fv, &dmGrad));
1405: if (dmGrad) {
1406: Vec grad;
1407: PetscInt fStart, fEnd;
1409: PetscCall(DMPlexGetHeightStratum(dm, 1, &fStart, &fEnd));
1410: PetscCall(DMGetGlobalVector(dmGrad, &grad));
1411: PetscCall(DMPlexReconstructGradients_Internal(dm, fv, fStart, fEnd, faceGeometryFVM, cellGeometryFVM, locX, grad));
1412: /* Communicate gradient values */
1413: PetscCall(DMGetLocalVector(dmGrad, &locGrad));
1414: PetscCall(DMGlobalToLocalBegin(dmGrad, grad, INSERT_VALUES, locGrad));
1415: PetscCall(DMGlobalToLocalEnd(dmGrad, grad, INSERT_VALUES, locGrad));
1416: PetscCall(DMRestoreGlobalVector(dmGrad, &grad));
1417: }
1418: PetscCall(DMPlexInsertBoundaryValues(dm, PETSC_FALSE, locX, time, faceGeometryFVM, cellGeometryFVM, locGrad));
1419: if (locGradient) *locGradient = locGrad;
1420: else if (locGrad) PetscCall(DMRestoreLocalVector(dmGrad, &locGrad));
1421: PetscFunctionReturn(PETSC_SUCCESS);
1422: }
1424: PetscErrorCode DMComputeL2Diff_Plex(DM dm, PetscReal time, PetscErrorCode (**funcs)(PetscInt, PetscReal, const PetscReal[], PetscInt, PetscScalar *, void *), void **ctxs, Vec X, PetscReal *diff)
1425: {
1426: Vec localX;
1428: PetscFunctionBegin;
1429: PetscCall(DMGetLocalVector(dm, &localX));
1430: PetscCall(DMPlexInsertBoundaryValues(dm, PETSC_TRUE, localX, time, NULL, NULL, NULL));
1431: PetscCall(DMGlobalToLocalBegin(dm, X, INSERT_VALUES, localX));
1432: PetscCall(DMGlobalToLocalEnd(dm, X, INSERT_VALUES, localX));
1433: PetscCall(DMPlexComputeL2DiffLocal(dm, time, funcs, ctxs, localX, diff));
1434: PetscCall(DMRestoreLocalVector(dm, &localX));
1435: PetscFunctionReturn(PETSC_SUCCESS);
1436: }
1438: /*@C
1439: DMPlexComputeL2DiffLocal - This function computes the L_2 difference between a function u and an FEM interpolant solution u_h.
1441: Collective
1443: Input Parameters:
1444: + dm - The `DM`
1445: . time - The time
1446: . funcs - The functions to evaluate for each field component
1447: . ctxs - Optional array of contexts to pass to each function, or `NULL`.
1448: - localX - The coefficient vector u_h, a local vector
1450: Output Parameter:
1451: . diff - The diff ||u - u_h||_2
1453: Level: developer
1455: .seealso: [](ch_unstructured), `DM`, `DMPLEX`, `DMProjectFunction()`, `DMComputeL2FieldDiff()`, `DMComputeL2GradientDiff()`
1456: @*/
1457: PetscErrorCode DMPlexComputeL2DiffLocal(DM dm, PetscReal time, PetscErrorCode (**funcs)(PetscInt, PetscReal, const PetscReal[], PetscInt, PetscScalar *, void *), void **ctxs, Vec localX, PetscReal *diff)
1458: {
1459: const PetscInt debug = ((DM_Plex *)dm->data)->printL2;
1460: DM tdm;
1461: Vec tv;
1462: PetscSection section;
1463: PetscQuadrature quad;
1464: PetscFEGeom fegeom;
1465: PetscScalar *funcVal, *interpolant;
1466: PetscReal *coords, *gcoords;
1467: PetscReal localDiff = 0.0;
1468: const PetscReal *quadWeights;
1469: PetscInt dim, coordDim, numFields, numComponents = 0, qNc, Nq, cellHeight, cStart, cEnd, c, field, fieldOffset;
1470: PetscBool transform;
1472: PetscFunctionBegin;
1473: PetscCall(DMGetDimension(dm, &dim));
1474: PetscCall(DMGetCoordinateDim(dm, &coordDim));
1475: fegeom.dimEmbed = coordDim;
1476: PetscCall(DMGetLocalSection(dm, §ion));
1477: PetscCall(PetscSectionGetNumFields(section, &numFields));
1478: PetscCall(DMGetBasisTransformDM_Internal(dm, &tdm));
1479: PetscCall(DMGetBasisTransformVec_Internal(dm, &tv));
1480: PetscCall(DMHasBasisTransform(dm, &transform));
1481: PetscCheck(numFields, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Number of fields is zero!");
1482: for (field = 0; field < numFields; ++field) {
1483: PetscObject obj;
1484: PetscClassId id;
1485: PetscInt Nc;
1487: PetscCall(DMGetField(dm, field, NULL, &obj));
1488: PetscCall(PetscObjectGetClassId(obj, &id));
1489: if (id == PETSCFE_CLASSID) {
1490: PetscFE fe = (PetscFE)obj;
1492: PetscCall(PetscFEGetQuadrature(fe, &quad));
1493: PetscCall(PetscFEGetNumComponents(fe, &Nc));
1494: } else if (id == PETSCFV_CLASSID) {
1495: PetscFV fv = (PetscFV)obj;
1497: PetscCall(PetscFVGetQuadrature(fv, &quad));
1498: PetscCall(PetscFVGetNumComponents(fv, &Nc));
1499: } else SETERRQ(PetscObjectComm((PetscObject)dm), PETSC_ERR_ARG_WRONG, "Unknown discretization type for field %" PetscInt_FMT, field);
1500: numComponents += Nc;
1501: }
1502: PetscCall(PetscQuadratureGetData(quad, NULL, &qNc, &Nq, NULL, &quadWeights));
1503: PetscCheck(!(qNc != 1) || !(qNc != numComponents), PetscObjectComm((PetscObject)dm), PETSC_ERR_ARG_SIZ, "Quadrature components %" PetscInt_FMT " != %" PetscInt_FMT " field components", qNc, numComponents);
1504: PetscCall(PetscMalloc6(numComponents, &funcVal, numComponents, &interpolant, coordDim * (Nq + 1), &coords, Nq, &fegeom.detJ, coordDim * coordDim * Nq, &fegeom.J, coordDim * coordDim * Nq, &fegeom.invJ));
1505: PetscCall(DMPlexGetVTKCellHeight(dm, &cellHeight));
1506: PetscCall(DMPlexGetSimplexOrBoxCells(dm, cellHeight, &cStart, &cEnd));
1507: for (c = cStart; c < cEnd; ++c) {
1508: PetscScalar *x = NULL;
1509: PetscReal elemDiff = 0.0;
1510: PetscInt qc = 0;
1512: PetscCall(DMPlexComputeCellGeometryFEM(dm, c, quad, coords, fegeom.J, fegeom.invJ, fegeom.detJ));
1513: PetscCall(DMPlexVecGetOrientedClosure(dm, NULL, PETSC_FALSE, localX, c, 0, NULL, &x));
1515: for (field = 0, fieldOffset = 0; field < numFields; ++field) {
1516: PetscObject obj;
1517: PetscClassId id;
1518: void *const ctx = ctxs ? ctxs[field] : NULL;
1519: PetscInt Nb, Nc, q, fc;
1521: PetscCall(DMGetField(dm, field, NULL, &obj));
1522: PetscCall(PetscObjectGetClassId(obj, &id));
1523: if (id == PETSCFE_CLASSID) {
1524: PetscCall(PetscFEGetNumComponents((PetscFE)obj, &Nc));
1525: PetscCall(PetscFEGetDimension((PetscFE)obj, &Nb));
1526: } else if (id == PETSCFV_CLASSID) {
1527: PetscCall(PetscFVGetNumComponents((PetscFV)obj, &Nc));
1528: Nb = 1;
1529: } else SETERRQ(PetscObjectComm((PetscObject)dm), PETSC_ERR_ARG_WRONG, "Unknown discretization type for field %" PetscInt_FMT, field);
1530: if (debug) {
1531: char title[1024];
1532: PetscCall(PetscSNPrintf(title, 1023, "Solution for Field %" PetscInt_FMT, field));
1533: PetscCall(DMPrintCellVector(c, title, Nb, &x[fieldOffset]));
1534: }
1535: for (q = 0; q < Nq; ++q) {
1536: PetscFEGeom qgeom;
1537: PetscErrorCode ierr;
1539: qgeom.dimEmbed = fegeom.dimEmbed;
1540: qgeom.J = &fegeom.J[q * coordDim * coordDim];
1541: qgeom.invJ = &fegeom.invJ[q * coordDim * coordDim];
1542: qgeom.detJ = &fegeom.detJ[q];
1543: PetscCheck(fegeom.detJ[q] > 0.0, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Invalid determinant %g for element %" PetscInt_FMT ", point %" PetscInt_FMT, (double)fegeom.detJ[q], c, q);
1544: if (transform) {
1545: gcoords = &coords[coordDim * Nq];
1546: PetscCall(DMPlexBasisTransformApplyReal_Internal(dm, &coords[coordDim * q], PETSC_TRUE, coordDim, &coords[coordDim * q], gcoords, dm->transformCtx));
1547: } else {
1548: gcoords = &coords[coordDim * q];
1549: }
1550: PetscCall(PetscArrayzero(funcVal, Nc));
1551: ierr = (*funcs[field])(coordDim, time, gcoords, Nc, funcVal, ctx);
1552: if (ierr) {
1553: PetscCall(DMPlexVecRestoreClosure(dm, NULL, localX, c, NULL, &x));
1554: PetscCall(DMRestoreLocalVector(dm, &localX));
1555: PetscCall(PetscFree6(funcVal, interpolant, coords, fegeom.detJ, fegeom.J, fegeom.invJ));
1556: }
1557: if (transform) PetscCall(DMPlexBasisTransformApply_Internal(dm, &coords[coordDim * q], PETSC_FALSE, Nc, funcVal, funcVal, dm->transformCtx));
1558: if (id == PETSCFE_CLASSID) PetscCall(PetscFEInterpolate_Static((PetscFE)obj, &x[fieldOffset], &qgeom, q, interpolant));
1559: else if (id == PETSCFV_CLASSID) PetscCall(PetscFVInterpolate_Static((PetscFV)obj, &x[fieldOffset], q, interpolant));
1560: else SETERRQ(PetscObjectComm((PetscObject)dm), PETSC_ERR_ARG_WRONG, "Unknown discretization type for field %" PetscInt_FMT, field);
1561: for (fc = 0; fc < Nc; ++fc) {
1562: const PetscReal wt = quadWeights[q * qNc + (qNc == 1 ? 0 : qc + fc)];
1563: if (debug)
1564: PetscCall(PetscPrintf(PETSC_COMM_SELF, " elem %" PetscInt_FMT " field %" PetscInt_FMT ",%" PetscInt_FMT " point %g %g %g diff %g (%g, %g)\n", c, field, fc, (double)(coordDim > 0 ? coords[coordDim * q] : 0), (double)(coordDim > 1 ? coords[coordDim * q + 1] : 0), (double)(coordDim > 2 ? coords[coordDim * q + 2] : 0),
1565: (double)(PetscSqr(PetscRealPart(interpolant[fc] - funcVal[fc])) * wt * fegeom.detJ[q]), (double)PetscRealPart(interpolant[fc]), (double)PetscRealPart(funcVal[fc])));
1566: elemDiff += PetscSqr(PetscRealPart(interpolant[fc] - funcVal[fc])) * wt * fegeom.detJ[q];
1567: }
1568: }
1569: fieldOffset += Nb;
1570: qc += Nc;
1571: }
1572: PetscCall(DMPlexVecRestoreClosure(dm, NULL, localX, c, NULL, &x));
1573: if (debug) PetscCall(PetscPrintf(PETSC_COMM_SELF, " elem %" PetscInt_FMT " diff %g\n", c, (double)elemDiff));
1574: localDiff += elemDiff;
1575: }
1576: PetscCall(PetscFree6(funcVal, interpolant, coords, fegeom.detJ, fegeom.J, fegeom.invJ));
1577: PetscCallMPI(MPIU_Allreduce(&localDiff, diff, 1, MPIU_REAL, MPIU_SUM, PetscObjectComm((PetscObject)dm)));
1578: *diff = PetscSqrtReal(*diff);
1579: PetscFunctionReturn(PETSC_SUCCESS);
1580: }
1582: PetscErrorCode DMComputeL2GradientDiff_Plex(DM dm, PetscReal time, PetscErrorCode (**funcs)(PetscInt, PetscReal, const PetscReal[], const PetscReal[], PetscInt, PetscScalar *, void *), void **ctxs, Vec X, const PetscReal n[], PetscReal *diff)
1583: {
1584: const PetscInt debug = ((DM_Plex *)dm->data)->printL2;
1585: DM tdm;
1586: PetscSection section;
1587: PetscQuadrature quad;
1588: Vec localX, tv;
1589: PetscScalar *funcVal, *interpolant;
1590: const PetscReal *quadWeights;
1591: PetscFEGeom fegeom;
1592: PetscReal *coords, *gcoords;
1593: PetscReal localDiff = 0.0;
1594: PetscInt dim, coordDim, qNc = 0, Nq = 0, numFields, numComponents = 0, cStart, cEnd, c, field, fieldOffset;
1595: PetscBool transform;
1597: PetscFunctionBegin;
1598: PetscCall(DMGetDimension(dm, &dim));
1599: PetscCall(DMGetCoordinateDim(dm, &coordDim));
1600: fegeom.dimEmbed = coordDim;
1601: PetscCall(DMGetLocalSection(dm, §ion));
1602: PetscCall(PetscSectionGetNumFields(section, &numFields));
1603: PetscCall(DMGetLocalVector(dm, &localX));
1604: PetscCall(DMGlobalToLocalBegin(dm, X, INSERT_VALUES, localX));
1605: PetscCall(DMGlobalToLocalEnd(dm, X, INSERT_VALUES, localX));
1606: PetscCall(DMGetBasisTransformDM_Internal(dm, &tdm));
1607: PetscCall(DMGetBasisTransformVec_Internal(dm, &tv));
1608: PetscCall(DMHasBasisTransform(dm, &transform));
1609: for (field = 0; field < numFields; ++field) {
1610: PetscFE fe;
1611: PetscInt Nc;
1613: PetscCall(DMGetField(dm, field, NULL, (PetscObject *)&fe));
1614: PetscCall(PetscFEGetQuadrature(fe, &quad));
1615: PetscCall(PetscFEGetNumComponents(fe, &Nc));
1616: numComponents += Nc;
1617: }
1618: PetscCall(PetscQuadratureGetData(quad, NULL, &qNc, &Nq, NULL, &quadWeights));
1619: PetscCheck(!(qNc != 1) || !(qNc != numComponents), PetscObjectComm((PetscObject)dm), PETSC_ERR_ARG_SIZ, "Quadrature components %" PetscInt_FMT " != %" PetscInt_FMT " field components", qNc, numComponents);
1620: /* PetscCall(DMProjectFunctionLocal(dm, fe, funcs, INSERT_BC_VALUES, localX)); */
1621: PetscCall(PetscMalloc6(numComponents, &funcVal, coordDim * (Nq + 1), &coords, coordDim * coordDim * Nq, &fegeom.J, coordDim * coordDim * Nq, &fegeom.invJ, numComponents * coordDim, &interpolant, Nq, &fegeom.detJ));
1622: PetscCall(DMPlexGetSimplexOrBoxCells(dm, 0, &cStart, &cEnd));
1623: for (c = cStart; c < cEnd; ++c) {
1624: PetscScalar *x = NULL;
1625: PetscReal elemDiff = 0.0;
1626: PetscInt qc = 0;
1628: PetscCall(DMPlexComputeCellGeometryFEM(dm, c, quad, coords, fegeom.J, fegeom.invJ, fegeom.detJ));
1629: PetscCall(DMPlexVecGetOrientedClosure(dm, NULL, PETSC_FALSE, localX, c, 0, NULL, &x));
1631: for (field = 0, fieldOffset = 0; field < numFields; ++field) {
1632: PetscFE fe;
1633: void *const ctx = ctxs ? ctxs[field] : NULL;
1634: PetscInt Nb, Nc, q, fc;
1636: PetscCall(DMGetField(dm, field, NULL, (PetscObject *)&fe));
1637: PetscCall(PetscFEGetDimension(fe, &Nb));
1638: PetscCall(PetscFEGetNumComponents(fe, &Nc));
1639: if (debug) {
1640: char title[1024];
1641: PetscCall(PetscSNPrintf(title, 1023, "Solution for Field %" PetscInt_FMT, field));
1642: PetscCall(DMPrintCellVector(c, title, Nb, &x[fieldOffset]));
1643: }
1644: for (q = 0; q < Nq; ++q) {
1645: PetscFEGeom qgeom;
1646: PetscErrorCode ierr;
1648: qgeom.dimEmbed = fegeom.dimEmbed;
1649: qgeom.J = &fegeom.J[q * coordDim * coordDim];
1650: qgeom.invJ = &fegeom.invJ[q * coordDim * coordDim];
1651: qgeom.detJ = &fegeom.detJ[q];
1652: PetscCheck(fegeom.detJ[q] > 0.0, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Invalid determinant %g for element %" PetscInt_FMT ", quadrature points %" PetscInt_FMT, (double)fegeom.detJ[q], c, q);
1653: if (transform) {
1654: gcoords = &coords[coordDim * Nq];
1655: PetscCall(DMPlexBasisTransformApplyReal_Internal(dm, &coords[coordDim * q], PETSC_TRUE, coordDim, &coords[coordDim * q], gcoords, dm->transformCtx));
1656: } else {
1657: gcoords = &coords[coordDim * q];
1658: }
1659: PetscCall(PetscArrayzero(funcVal, Nc));
1660: ierr = (*funcs[field])(coordDim, time, gcoords, n, Nc, funcVal, ctx);
1661: if (ierr) {
1662: PetscCall(DMPlexVecRestoreClosure(dm, NULL, localX, c, NULL, &x));
1663: PetscCall(DMRestoreLocalVector(dm, &localX));
1664: PetscCall(PetscFree6(funcVal, coords, fegeom.J, fegeom.invJ, interpolant, fegeom.detJ));
1665: }
1666: if (transform) PetscCall(DMPlexBasisTransformApply_Internal(dm, &coords[coordDim * q], PETSC_FALSE, Nc, funcVal, funcVal, dm->transformCtx));
1667: PetscCall(PetscFEInterpolateGradient_Static(fe, 1, &x[fieldOffset], &qgeom, q, interpolant));
1668: /* Overwrite with the dot product if the normal is given */
1669: if (n) {
1670: for (fc = 0; fc < Nc; ++fc) {
1671: PetscScalar sum = 0.0;
1672: PetscInt d;
1673: for (d = 0; d < dim; ++d) sum += interpolant[fc * dim + d] * n[d];
1674: interpolant[fc] = sum;
1675: }
1676: }
1677: for (fc = 0; fc < Nc; ++fc) {
1678: const PetscReal wt = quadWeights[q * qNc + (qNc == 1 ? 0 : qc + fc)];
1679: if (debug) PetscCall(PetscPrintf(PETSC_COMM_SELF, " elem %" PetscInt_FMT " fieldDer %" PetscInt_FMT ",%" PetscInt_FMT " diff %g\n", c, field, fc, (double)(PetscSqr(PetscRealPart(interpolant[fc] - funcVal[fc])) * wt * fegeom.detJ[q])));
1680: elemDiff += PetscSqr(PetscRealPart(interpolant[fc] - funcVal[fc])) * wt * fegeom.detJ[q];
1681: }
1682: }
1683: fieldOffset += Nb;
1684: qc += Nc;
1685: }
1686: PetscCall(DMPlexVecRestoreClosure(dm, NULL, localX, c, NULL, &x));
1687: if (debug) PetscCall(PetscPrintf(PETSC_COMM_SELF, " elem %" PetscInt_FMT " diff %g\n", c, (double)elemDiff));
1688: localDiff += elemDiff;
1689: }
1690: PetscCall(PetscFree6(funcVal, coords, fegeom.J, fegeom.invJ, interpolant, fegeom.detJ));
1691: PetscCall(DMRestoreLocalVector(dm, &localX));
1692: PetscCallMPI(MPIU_Allreduce(&localDiff, diff, 1, MPIU_REAL, MPIU_SUM, PetscObjectComm((PetscObject)dm)));
1693: *diff = PetscSqrtReal(*diff);
1694: PetscFunctionReturn(PETSC_SUCCESS);
1695: }
1697: PetscErrorCode DMComputeL2FieldDiff_Plex(DM dm, PetscReal time, PetscErrorCode (**funcs)(PetscInt, PetscReal, const PetscReal[], PetscInt, PetscScalar *, void *), void **ctxs, Vec X, PetscReal *diff)
1698: {
1699: const PetscInt debug = ((DM_Plex *)dm->data)->printL2;
1700: DM tdm;
1701: DMLabel depthLabel;
1702: PetscSection section;
1703: Vec localX, tv;
1704: PetscReal *localDiff;
1705: PetscInt dim, depth, dE, Nf, f, Nds, s;
1706: PetscBool transform;
1708: PetscFunctionBegin;
1709: PetscCall(DMGetDimension(dm, &dim));
1710: PetscCall(DMGetCoordinateDim(dm, &dE));
1711: PetscCall(DMGetLocalSection(dm, §ion));
1712: PetscCall(DMGetLocalVector(dm, &localX));
1713: PetscCall(DMGetBasisTransformDM_Internal(dm, &tdm));
1714: PetscCall(DMGetBasisTransformVec_Internal(dm, &tv));
1715: PetscCall(DMHasBasisTransform(dm, &transform));
1716: PetscCall(DMGetNumFields(dm, &Nf));
1717: PetscCall(DMPlexGetDepthLabel(dm, &depthLabel));
1718: PetscCall(DMLabelGetNumValues(depthLabel, &depth));
1720: PetscCall(VecSet(localX, 0.0));
1721: PetscCall(DMGlobalToLocalBegin(dm, X, INSERT_VALUES, localX));
1722: PetscCall(DMGlobalToLocalEnd(dm, X, INSERT_VALUES, localX));
1723: PetscCall(DMProjectFunctionLocal(dm, time, funcs, ctxs, INSERT_BC_VALUES, localX));
1724: PetscCall(DMGetNumDS(dm, &Nds));
1725: PetscCall(PetscCalloc1(Nf, &localDiff));
1726: for (s = 0; s < Nds; ++s) {
1727: PetscDS ds;
1728: DMLabel label;
1729: IS fieldIS, pointIS;
1730: const PetscInt *fields, *points = NULL;
1731: PetscQuadrature quad;
1732: const PetscReal *quadPoints, *quadWeights;
1733: PetscFEGeom fegeom;
1734: PetscReal *coords, *gcoords;
1735: PetscScalar *funcVal, *interpolant;
1736: PetscBool isCohesive;
1737: PetscInt qNc, Nq, totNc, cStart = 0, cEnd, c, dsNf;
1739: PetscCall(DMGetRegionNumDS(dm, s, &label, &fieldIS, &ds, NULL));
1740: PetscCall(ISGetIndices(fieldIS, &fields));
1741: PetscCall(PetscDSIsCohesive(ds, &isCohesive));
1742: PetscCall(PetscDSGetNumFields(ds, &dsNf));
1743: PetscCall(PetscDSGetTotalComponents(ds, &totNc));
1744: PetscCall(PetscDSGetQuadrature(ds, &quad));
1745: PetscCall(PetscQuadratureGetData(quad, NULL, &qNc, &Nq, &quadPoints, &quadWeights));
1746: PetscCheck(!(qNc != 1) || !(qNc != totNc), PETSC_COMM_SELF, PETSC_ERR_ARG_SIZ, "Quadrature components %" PetscInt_FMT " != %" PetscInt_FMT " field components", qNc, totNc);
1747: PetscCall(PetscCalloc6(totNc, &funcVal, totNc, &interpolant, dE * (Nq + 1), &coords, Nq, &fegeom.detJ, dE * dE * Nq, &fegeom.J, dE * dE * Nq, &fegeom.invJ));
1748: if (!label) {
1749: PetscCall(DMPlexGetSimplexOrBoxCells(dm, 0, &cStart, &cEnd));
1750: } else {
1751: PetscCall(DMLabelGetStratumIS(label, 1, &pointIS));
1752: PetscCall(ISGetLocalSize(pointIS, &cEnd));
1753: PetscCall(ISGetIndices(pointIS, &points));
1754: }
1755: for (c = cStart; c < cEnd; ++c) {
1756: const PetscInt cell = points ? points[c] : c;
1757: PetscScalar *x = NULL;
1758: const PetscInt *cone;
1759: PetscInt qc = 0, fOff = 0, dep;
1761: PetscCall(DMLabelGetValue(depthLabel, cell, &dep));
1762: if (dep != depth - 1) continue;
1763: if (isCohesive) {
1764: PetscCall(DMPlexGetCone(dm, cell, &cone));
1765: PetscCall(DMPlexComputeCellGeometryFEM(dm, cone[0], quad, coords, fegeom.J, fegeom.invJ, fegeom.detJ));
1766: } else {
1767: PetscCall(DMPlexComputeCellGeometryFEM(dm, cell, quad, coords, fegeom.J, fegeom.invJ, fegeom.detJ));
1768: }
1769: PetscCall(DMPlexVecGetOrientedClosure(dm, NULL, PETSC_FALSE, localX, cell, 0, NULL, &x));
1770: for (f = 0; f < dsNf; ++f) {
1771: PetscObject obj;
1772: PetscClassId id;
1773: void *const ctx = ctxs ? ctxs[fields[f]] : NULL;
1774: PetscInt Nb, Nc, q, fc;
1775: PetscReal elemDiff = 0.0;
1776: PetscBool cohesive;
1778: PetscCall(PetscDSGetCohesive(ds, f, &cohesive));
1779: PetscCall(PetscDSGetDiscretization(ds, f, &obj));
1780: PetscCall(PetscObjectGetClassId(obj, &id));
1781: if (id == PETSCFE_CLASSID) {
1782: PetscCall(PetscFEGetNumComponents((PetscFE)obj, &Nc));
1783: PetscCall(PetscFEGetDimension((PetscFE)obj, &Nb));
1784: } else if (id == PETSCFV_CLASSID) {
1785: PetscCall(PetscFVGetNumComponents((PetscFV)obj, &Nc));
1786: Nb = 1;
1787: } else SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Unknown discretization type for field %" PetscInt_FMT, fields[f]);
1788: if (isCohesive && !cohesive) {
1789: fOff += Nb * 2;
1790: qc += Nc;
1791: continue;
1792: }
1793: if (debug) {
1794: char title[1024];
1795: PetscCall(PetscSNPrintf(title, 1023, "Solution for Field %" PetscInt_FMT, fields[f]));
1796: PetscCall(DMPrintCellVector(cell, title, Nb, &x[fOff]));
1797: }
1798: for (q = 0; q < Nq; ++q) {
1799: PetscFEGeom qgeom;
1800: PetscErrorCode ierr;
1802: qgeom.dimEmbed = fegeom.dimEmbed;
1803: qgeom.J = &fegeom.J[q * dE * dE];
1804: qgeom.invJ = &fegeom.invJ[q * dE * dE];
1805: qgeom.detJ = &fegeom.detJ[q];
1806: PetscCheck(fegeom.detJ[q] > 0.0, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Invalid determinant %g for cell %" PetscInt_FMT ", quadrature point %" PetscInt_FMT, (double)fegeom.detJ[q], cell, q);
1807: if (transform) {
1808: gcoords = &coords[dE * Nq];
1809: PetscCall(DMPlexBasisTransformApplyReal_Internal(dm, &coords[dE * q], PETSC_TRUE, dE, &coords[dE * q], gcoords, dm->transformCtx));
1810: } else {
1811: gcoords = &coords[dE * q];
1812: }
1813: for (fc = 0; fc < Nc; ++fc) funcVal[fc] = 0.;
1814: ierr = (*funcs[fields[f]])(dE, time, gcoords, Nc, funcVal, ctx);
1815: if (ierr) {
1816: PetscCall(DMPlexVecRestoreClosure(dm, NULL, localX, cell, NULL, &x));
1817: PetscCall(DMRestoreLocalVector(dm, &localX));
1818: PetscCall(PetscFree6(funcVal, interpolant, coords, fegeom.detJ, fegeom.J, fegeom.invJ));
1819: }
1820: if (transform) PetscCall(DMPlexBasisTransformApply_Internal(dm, &coords[dE * q], PETSC_FALSE, Nc, funcVal, funcVal, dm->transformCtx));
1821: /* Call once for each face, except for lagrange field */
1822: if (id == PETSCFE_CLASSID) PetscCall(PetscFEInterpolate_Static((PetscFE)obj, &x[fOff], &qgeom, q, interpolant));
1823: else if (id == PETSCFV_CLASSID) PetscCall(PetscFVInterpolate_Static((PetscFV)obj, &x[fOff], q, interpolant));
1824: else SETERRQ(PetscObjectComm((PetscObject)dm), PETSC_ERR_ARG_WRONG, "Unknown discretization type for field %" PetscInt_FMT, fields[f]);
1825: for (fc = 0; fc < Nc; ++fc) {
1826: const PetscReal wt = quadWeights[q * qNc + (qNc == 1 ? 0 : qc + fc)];
1827: if (debug)
1828: PetscCall(PetscPrintf(PETSC_COMM_SELF, " cell %" PetscInt_FMT " field %" PetscInt_FMT ",%" PetscInt_FMT " point %g %g %g diff %g\n", cell, fields[f], fc, (double)(dE > 0 ? coords[dE * q] : 0), (double)(dE > 1 ? coords[dE * q + 1] : 0), (double)(dE > 2 ? coords[dE * q + 2] : 0),
1829: (double)(PetscSqr(PetscRealPart(interpolant[fc] - funcVal[fc])) * wt * fegeom.detJ[q])));
1830: elemDiff += PetscSqr(PetscRealPart(interpolant[fc] - funcVal[fc])) * wt * fegeom.detJ[q];
1831: }
1832: }
1833: fOff += Nb;
1834: qc += Nc;
1835: localDiff[fields[f]] += elemDiff;
1836: if (debug) PetscCall(PetscPrintf(PETSC_COMM_SELF, " cell %" PetscInt_FMT " field %" PetscInt_FMT " cum diff %g\n", cell, fields[f], (double)localDiff[fields[f]]));
1837: }
1838: PetscCall(DMPlexVecRestoreClosure(dm, NULL, localX, cell, NULL, &x));
1839: }
1840: if (label) {
1841: PetscCall(ISRestoreIndices(pointIS, &points));
1842: PetscCall(ISDestroy(&pointIS));
1843: }
1844: PetscCall(ISRestoreIndices(fieldIS, &fields));
1845: PetscCall(PetscFree6(funcVal, interpolant, coords, fegeom.detJ, fegeom.J, fegeom.invJ));
1846: }
1847: PetscCall(DMRestoreLocalVector(dm, &localX));
1848: PetscCallMPI(MPIU_Allreduce(localDiff, diff, Nf, MPIU_REAL, MPIU_SUM, PetscObjectComm((PetscObject)dm)));
1849: PetscCall(PetscFree(localDiff));
1850: for (f = 0; f < Nf; ++f) diff[f] = PetscSqrtReal(diff[f]);
1851: PetscFunctionReturn(PETSC_SUCCESS);
1852: }
1854: /*@C
1855: DMPlexComputeL2DiffVec - This function computes the cellwise L_2 difference between a function u and an FEM interpolant solution u_h, and stores it in a Vec.
1857: Collective
1859: Input Parameters:
1860: + dm - The `DM`
1861: . time - The time
1862: . funcs - The functions to evaluate for each field component: `NULL` means that component does not contribute to error calculation
1863: . ctxs - Optional array of contexts to pass to each function, or `NULL`.
1864: - X - The coefficient vector u_h
1866: Output Parameter:
1867: . D - A `Vec` which holds the difference ||u - u_h||_2 for each cell
1869: Level: developer
1871: .seealso: [](ch_unstructured), `DM`, `DMPLEX`, `DMProjectFunction()`, `DMComputeL2Diff()`, `DMPlexComputeL2FieldDiff()`, `DMComputeL2GradientDiff()`
1872: @*/
1873: PetscErrorCode DMPlexComputeL2DiffVec(DM dm, PetscReal time, PetscErrorCode (**funcs)(PetscInt, PetscReal, const PetscReal[], PetscInt, PetscScalar *, void *), void **ctxs, Vec X, Vec D)
1874: {
1875: PetscSection section;
1876: PetscQuadrature quad;
1877: Vec localX;
1878: PetscFEGeom fegeom;
1879: PetscScalar *funcVal, *interpolant;
1880: PetscReal *coords;
1881: const PetscReal *quadPoints, *quadWeights;
1882: PetscInt dim, coordDim, numFields, numComponents = 0, qNc, Nq, cStart, cEnd, c, field, fieldOffset;
1884: PetscFunctionBegin;
1885: PetscCall(VecSet(D, 0.0));
1886: PetscCall(DMGetDimension(dm, &dim));
1887: PetscCall(DMGetCoordinateDim(dm, &coordDim));
1888: PetscCall(DMGetLocalSection(dm, §ion));
1889: PetscCall(PetscSectionGetNumFields(section, &numFields));
1890: PetscCall(DMGetLocalVector(dm, &localX));
1891: PetscCall(DMProjectFunctionLocal(dm, time, funcs, ctxs, INSERT_BC_VALUES, localX));
1892: PetscCall(DMGlobalToLocalBegin(dm, X, INSERT_VALUES, localX));
1893: PetscCall(DMGlobalToLocalEnd(dm, X, INSERT_VALUES, localX));
1894: for (field = 0; field < numFields; ++field) {
1895: PetscObject obj;
1896: PetscClassId id;
1897: PetscInt Nc;
1899: PetscCall(DMGetField(dm, field, NULL, &obj));
1900: PetscCall(PetscObjectGetClassId(obj, &id));
1901: if (id == PETSCFE_CLASSID) {
1902: PetscFE fe = (PetscFE)obj;
1904: PetscCall(PetscFEGetQuadrature(fe, &quad));
1905: PetscCall(PetscFEGetNumComponents(fe, &Nc));
1906: } else if (id == PETSCFV_CLASSID) {
1907: PetscFV fv = (PetscFV)obj;
1909: PetscCall(PetscFVGetQuadrature(fv, &quad));
1910: PetscCall(PetscFVGetNumComponents(fv, &Nc));
1911: } else SETERRQ(PetscObjectComm((PetscObject)dm), PETSC_ERR_ARG_WRONG, "Unknown discretization type for field %" PetscInt_FMT, field);
1912: numComponents += Nc;
1913: }
1914: PetscCall(PetscQuadratureGetData(quad, NULL, &qNc, &Nq, &quadPoints, &quadWeights));
1915: PetscCheck(!(qNc != 1) || !(qNc != numComponents), PetscObjectComm((PetscObject)dm), PETSC_ERR_ARG_SIZ, "Quadrature components %" PetscInt_FMT " != %" PetscInt_FMT " field components", qNc, numComponents);
1916: PetscCall(PetscMalloc6(numComponents, &funcVal, numComponents, &interpolant, coordDim * Nq, &coords, Nq, &fegeom.detJ, coordDim * coordDim * Nq, &fegeom.J, coordDim * coordDim * Nq, &fegeom.invJ));
1917: PetscCall(DMPlexGetSimplexOrBoxCells(dm, 0, &cStart, &cEnd));
1918: for (c = cStart; c < cEnd; ++c) {
1919: PetscScalar *x = NULL;
1920: PetscScalar elemDiff = 0.0;
1921: PetscInt qc = 0;
1923: PetscCall(DMPlexComputeCellGeometryFEM(dm, c, quad, coords, fegeom.J, fegeom.invJ, fegeom.detJ));
1924: PetscCall(DMPlexVecGetOrientedClosure(dm, NULL, PETSC_FALSE, localX, c, 0, NULL, &x));
1926: for (field = 0, fieldOffset = 0; field < numFields; ++field) {
1927: PetscObject obj;
1928: PetscClassId id;
1929: void *const ctx = ctxs ? ctxs[field] : NULL;
1930: PetscInt Nb, Nc, q, fc;
1932: PetscCall(DMGetField(dm, field, NULL, &obj));
1933: PetscCall(PetscObjectGetClassId(obj, &id));
1934: if (id == PETSCFE_CLASSID) {
1935: PetscCall(PetscFEGetNumComponents((PetscFE)obj, &Nc));
1936: PetscCall(PetscFEGetDimension((PetscFE)obj, &Nb));
1937: } else if (id == PETSCFV_CLASSID) {
1938: PetscCall(PetscFVGetNumComponents((PetscFV)obj, &Nc));
1939: Nb = 1;
1940: } else SETERRQ(PetscObjectComm((PetscObject)dm), PETSC_ERR_ARG_WRONG, "Unknown discretization type for field %" PetscInt_FMT, field);
1941: if (funcs[field]) {
1942: for (q = 0; q < Nq; ++q) {
1943: PetscFEGeom qgeom;
1945: qgeom.dimEmbed = fegeom.dimEmbed;
1946: qgeom.J = &fegeom.J[q * coordDim * coordDim];
1947: qgeom.invJ = &fegeom.invJ[q * coordDim * coordDim];
1948: qgeom.detJ = &fegeom.detJ[q];
1949: PetscCheck(fegeom.detJ[q] > 0.0, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Invalid determinant %g for element %" PetscInt_FMT ", quadrature points %" PetscInt_FMT, (double)fegeom.detJ[q], c, q);
1950: PetscCall((*funcs[field])(coordDim, time, &coords[q * coordDim], Nc, funcVal, ctx));
1951: #if defined(needs_fix_with_return_code_argument)
1952: if (ierr) {
1953: PetscCall(DMPlexVecRestoreClosure(dm, NULL, localX, c, NULL, &x));
1954: PetscCall(PetscFree6(funcVal, interpolant, coords, fegeom.detJ, fegeom.J, fegeom.invJ));
1955: PetscCall(DMRestoreLocalVector(dm, &localX));
1956: }
1957: #endif
1958: if (id == PETSCFE_CLASSID) PetscCall(PetscFEInterpolate_Static((PetscFE)obj, &x[fieldOffset], &qgeom, q, interpolant));
1959: else if (id == PETSCFV_CLASSID) PetscCall(PetscFVInterpolate_Static((PetscFV)obj, &x[fieldOffset], q, interpolant));
1960: else SETERRQ(PetscObjectComm((PetscObject)dm), PETSC_ERR_ARG_WRONG, "Unknown discretization type for field %" PetscInt_FMT, field);
1961: for (fc = 0; fc < Nc; ++fc) {
1962: const PetscReal wt = quadWeights[q * qNc + (qNc == 1 ? 0 : qc + fc)];
1963: elemDiff += PetscSqr(PetscRealPart(interpolant[fc] - funcVal[fc])) * wt * fegeom.detJ[q];
1964: }
1965: }
1966: }
1967: fieldOffset += Nb;
1968: qc += Nc;
1969: }
1970: PetscCall(DMPlexVecRestoreClosure(dm, NULL, localX, c, NULL, &x));
1971: PetscCall(VecSetValue(D, c - cStart, elemDiff, INSERT_VALUES));
1972: }
1973: PetscCall(PetscFree6(funcVal, interpolant, coords, fegeom.detJ, fegeom.J, fegeom.invJ));
1974: PetscCall(DMRestoreLocalVector(dm, &localX));
1975: PetscCall(VecSqrtAbs(D));
1976: PetscFunctionReturn(PETSC_SUCCESS);
1977: }
1979: /*@
1980: DMPlexComputeL2FluxDiffVecLocal - This function computes the integral of the difference between the gradient of field `f`in `u` and field `mf` in `mu`
1982: Collective
1984: Input Parameters:
1985: + lu - The local `Vec` containing the primal solution
1986: . f - The field number for the potential
1987: . lmu - The local `Vec` containing the mixed solution
1988: - mf - The field number for the flux
1990: Output Parameter:
1991: . eFlux - A global `Vec` which holds $||\nabla u_f - \mu_{mf}||$
1993: Level: advanced
1995: Notes:
1996: We assume that the `DM` for each solution has the same topology, geometry, and quadrature.
1998: This is usually used to get an error estimate for the primal solution, using the flux from a mixed solution.
2000: .seealso: [](ch_unstructured), `DM`, `DMPLEX`, `DMPlexComputeL2FluxDiffVec()`, `DMProjectFunction()`, `DMComputeL2Diff()`, `DMPlexComputeL2FieldDiff()`, `DMComputeL2GradientDiff()`
2001: @*/
2002: PetscErrorCode DMPlexComputeL2FluxDiffVecLocal(Vec lu, PetscInt f, Vec lmu, PetscInt mf, Vec eFlux)
2003: {
2004: DM dm, mdm, edm;
2005: PetscFE fe, mfe;
2006: PetscFEGeom fegeom;
2007: PetscQuadrature quad;
2008: const PetscReal *quadWeights;
2009: PetscReal *coords;
2010: PetscScalar *interpolant, *minterpolant, *earray;
2011: PetscInt cdim, mcdim, cStart, cEnd, Nc, mNc, qNc, Nq;
2012: MPI_Comm comm;
2014: PetscFunctionBegin;
2015: PetscCall(VecGetDM(lu, &dm));
2016: PetscCall(VecGetDM(lmu, &mdm));
2017: PetscCall(VecGetDM(eFlux, &edm));
2018: PetscCall(PetscObjectGetComm((PetscObject)dm, &comm));
2019: PetscCall(VecSet(eFlux, 0.0));
2021: // Check if the both problems are on the same mesh
2022: PetscCall(DMGetCoordinateDim(dm, &cdim));
2023: PetscCall(DMGetCoordinateDim(mdm, &mcdim));
2024: PetscCheck(cdim == mcdim, comm, PETSC_ERR_ARG_SIZ, "primal coordinate Dim %" PetscInt_FMT " != %" PetscInt_FMT " mixed coordinate Dim", cdim, mcdim);
2025: fegeom.dimEmbed = cdim;
2027: PetscCall(DMGetField(dm, f, NULL, (PetscObject *)&fe));
2028: PetscCall(DMGetField(mdm, mf, NULL, (PetscObject *)&mfe));
2029: PetscCall(PetscFEGetNumComponents(fe, &Nc));
2030: PetscCall(PetscFEGetNumComponents(mfe, &mNc));
2031: PetscCall(PetscFEGetQuadrature(fe, &quad));
2032: PetscCall(PetscQuadratureGetData(quad, NULL, &qNc, &Nq, NULL, &quadWeights));
2033: PetscCheck(qNc == 1 || qNc == mNc, comm, PETSC_ERR_ARG_SIZ, "Quadrature components %" PetscInt_FMT " != %" PetscInt_FMT " field components", qNc, mNc);
2035: PetscCall(DMPlexGetSimplexOrBoxCells(dm, 0, &cStart, &cEnd));
2036: PetscCall(VecGetArrayWrite(eFlux, &earray));
2037: PetscCall(PetscMalloc6(Nc * cdim, &interpolant, mNc * cdim, &minterpolant, cdim * (Nq + 1), &coords, cdim * cdim * Nq, &fegeom.J, cdim * cdim * Nq, &fegeom.invJ, Nq, &fegeom.detJ));
2038: for (PetscInt c = cStart; c < cEnd; ++c) {
2039: PetscScalar *x = NULL;
2040: PetscScalar *mx = NULL;
2041: PetscScalar *eval = NULL;
2042: PetscReal fluxElemDiff = 0.0;
2044: PetscCall(DMPlexComputeCellGeometryFEM(dm, c, quad, coords, fegeom.J, fegeom.invJ, fegeom.detJ));
2045: PetscCall(DMPlexVecGetClosure(dm, NULL, lu, c, NULL, &x));
2046: PetscCall(DMPlexVecGetClosure(mdm, NULL, lmu, c, NULL, &mx));
2048: for (PetscInt q = 0; q < Nq; ++q) {
2049: PetscFEGeom qgeom;
2051: qgeom.dimEmbed = fegeom.dimEmbed;
2052: qgeom.J = &fegeom.J[q * cdim * cdim];
2053: qgeom.invJ = &fegeom.invJ[q * cdim * cdim];
2054: qgeom.detJ = &fegeom.detJ[q];
2056: PetscCheck(fegeom.detJ[q] > 0.0, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Invalid determinant %g for element %" PetscInt_FMT ", quadrature points %" PetscInt_FMT, (double)fegeom.detJ[q], c, q);
2058: PetscCall(PetscFEInterpolate_Static(mfe, &mx[0], &qgeom, q, minterpolant));
2059: PetscCall(PetscFEInterpolateGradient_Static(fe, 1, &x[0], &qgeom, q, interpolant));
2061: /* Now take the elementwise difference and store that in a vector. */
2062: for (PetscInt fc = 0; fc < mNc; ++fc) {
2063: const PetscReal wt = quadWeights[q * qNc + (qNc == 1 ? 0 : fc)];
2064: fluxElemDiff += PetscSqr(PetscRealPart(interpolant[fc] - minterpolant[fc])) * wt * fegeom.detJ[q];
2065: }
2066: }
2067: PetscCall(DMPlexVecRestoreClosure(dm, NULL, lu, c, NULL, &x));
2068: PetscCall(DMPlexVecRestoreClosure(mdm, NULL, lmu, c, NULL, &mx));
2069: PetscCall(DMPlexPointGlobalRef(edm, c, earray, (void *)&eval));
2070: if (eval) eval[0] = fluxElemDiff;
2071: }
2072: PetscCall(PetscFree6(interpolant, minterpolant, coords, fegeom.detJ, fegeom.J, fegeom.invJ));
2073: PetscCall(VecRestoreArrayWrite(eFlux, &earray));
2075: PetscCall(VecAssemblyBegin(eFlux));
2076: PetscCall(VecAssemblyEnd(eFlux));
2077: PetscCall(VecSqrtAbs(eFlux));
2078: PetscFunctionReturn(PETSC_SUCCESS);
2079: }
2081: /*@
2082: DMPlexComputeL2FluxDiffVec - This function computes the integral of the difference between the gradient of field `f`in `u` and field `mf` in `mu`
2084: Collective
2086: Input Parameters:
2087: + u - The global `Vec` containing the primal solution
2088: . f - The field number for the potential
2089: . mu - The global `Vec` containing the mixed solution
2090: - mf - The field number for the flux
2092: Output Parameter:
2093: . eFlux - A global `Vec` which holds $||\nabla u_f - \mu_{mf}||$
2095: Level: advanced
2097: Notes:
2098: We assume that the `DM` for each solution has the same topology, geometry, and quadrature.
2100: This is usually used to get an error estimate for the primal solution, using the flux from a mixed solution.
2102: .seealso: [](ch_unstructured), `DM`, `DMPLEX`, `DMPlexComputeL2FluxDiffVecLocal()`, `DMProjectFunction()`, `DMComputeL2Diff()`, `DMPlexComputeL2FieldDiff()`, `DMComputeL2GradientDiff()`
2103: @*/
2104: PetscErrorCode DMPlexComputeL2FluxDiffVec(Vec u, PetscInt f, Vec mu, PetscInt mf, Vec eFlux)
2105: {
2106: DM dm, mdm;
2107: Vec lu, lmu;
2109: PetscFunctionBegin;
2110: PetscCall(VecGetDM(u, &dm));
2111: PetscCall(DMGetLocalVector(dm, &lu));
2112: PetscCall(DMGlobalToLocal(dm, u, INSERT_VALUES, lu));
2113: PetscCall(DMPlexInsertBoundaryValues(dm, PETSC_TRUE, lu, 0.0, NULL, NULL, NULL));
2115: PetscCall(VecGetDM(mu, &mdm));
2116: PetscCall(DMGetLocalVector(mdm, &lmu));
2117: PetscCall(DMGlobalToLocal(mdm, mu, INSERT_VALUES, lmu));
2118: PetscCall(DMPlexInsertBoundaryValues(mdm, PETSC_TRUE, lmu, 0.0, NULL, NULL, NULL));
2120: PetscCall(DMPlexComputeL2FluxDiffVecLocal(lu, f, lmu, mf, eFlux));
2122: PetscCall(DMRestoreLocalVector(dm, &lu));
2123: PetscCall(DMRestoreLocalVector(mdm, &lmu));
2124: PetscFunctionReturn(PETSC_SUCCESS);
2125: }
2127: /*@
2128: DMPlexComputeClementInterpolant - This function computes the L2 projection of the cellwise values of a function u onto P1
2130: Collective
2132: Input Parameters:
2133: + dm - The `DM`
2134: - locX - The coefficient vector u_h
2136: Output Parameter:
2137: . locC - A `Vec` which holds the Clement interpolant of the function
2139: Level: developer
2141: Note:
2142: $ u_h(v_i) = \sum_{T_i \in support(v_i)} |T_i| u_h(T_i) / \sum_{T_i \in support(v_i)} |T_i| $ where $ |T_i| $ is the cell volume
2144: .seealso: [](ch_unstructured), `DM`, `DMPLEX`, `DMProjectFunction()`, `DMComputeL2Diff()`, `DMPlexComputeL2FieldDiff()`, `DMComputeL2GradientDiff()`
2145: @*/
2146: PetscErrorCode DMPlexComputeClementInterpolant(DM dm, Vec locX, Vec locC)
2147: {
2148: PetscInt debug = ((DM_Plex *)dm->data)->printFEM;
2149: DM dmc;
2150: PetscQuadrature quad;
2151: PetscScalar *interpolant, *valsum;
2152: PetscFEGeom fegeom;
2153: PetscReal *coords;
2154: const PetscReal *quadPoints, *quadWeights;
2155: PetscInt dim, cdim, Nf, f, Nc = 0, Nq, qNc, cStart, cEnd, vStart, vEnd, v;
2157: PetscFunctionBegin;
2158: PetscCall(PetscCitationsRegister(ClementCitation, &Clementcite));
2159: PetscCall(VecGetDM(locC, &dmc));
2160: PetscCall(VecSet(locC, 0.0));
2161: PetscCall(DMGetDimension(dm, &dim));
2162: PetscCall(DMGetCoordinateDim(dm, &cdim));
2163: fegeom.dimEmbed = cdim;
2164: PetscCall(DMGetNumFields(dm, &Nf));
2165: PetscCheck(Nf > 0, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Number of fields is zero!");
2166: for (f = 0; f < Nf; ++f) {
2167: PetscObject obj;
2168: PetscClassId id;
2169: PetscInt fNc;
2171: PetscCall(DMGetField(dm, f, NULL, &obj));
2172: PetscCall(PetscObjectGetClassId(obj, &id));
2173: if (id == PETSCFE_CLASSID) {
2174: PetscFE fe = (PetscFE)obj;
2176: PetscCall(PetscFEGetQuadrature(fe, &quad));
2177: PetscCall(PetscFEGetNumComponents(fe, &fNc));
2178: } else if (id == PETSCFV_CLASSID) {
2179: PetscFV fv = (PetscFV)obj;
2181: PetscCall(PetscFVGetQuadrature(fv, &quad));
2182: PetscCall(PetscFVGetNumComponents(fv, &fNc));
2183: } else SETERRQ(PetscObjectComm((PetscObject)dm), PETSC_ERR_ARG_WRONG, "Unknown discretization type for field %" PetscInt_FMT, f);
2184: Nc += fNc;
2185: }
2186: PetscCall(PetscQuadratureGetData(quad, NULL, &qNc, &Nq, &quadPoints, &quadWeights));
2187: PetscCheck(qNc == 1, PetscObjectComm((PetscObject)dm), PETSC_ERR_ARG_SIZ, "Quadrature components %" PetscInt_FMT " > 1", qNc);
2188: PetscCall(PetscMalloc6(Nc * 2, &valsum, Nc, &interpolant, cdim * Nq, &coords, Nq, &fegeom.detJ, cdim * cdim * Nq, &fegeom.J, cdim * cdim * Nq, &fegeom.invJ));
2189: PetscCall(DMPlexGetDepthStratum(dm, 0, &vStart, &vEnd));
2190: PetscCall(DMPlexGetSimplexOrBoxCells(dm, 0, &cStart, &cEnd));
2191: for (v = vStart; v < vEnd; ++v) {
2192: PetscScalar volsum = 0.0;
2193: PetscInt *star = NULL;
2194: PetscInt starSize, st, fc;
2196: PetscCall(PetscArrayzero(valsum, Nc));
2197: PetscCall(DMPlexGetTransitiveClosure(dm, v, PETSC_FALSE, &starSize, &star));
2198: for (st = 0; st < starSize * 2; st += 2) {
2199: const PetscInt cell = star[st];
2200: PetscScalar *val = &valsum[Nc];
2201: PetscScalar *x = NULL;
2202: PetscReal vol = 0.0;
2203: PetscInt foff = 0;
2205: if ((cell < cStart) || (cell >= cEnd)) continue;
2206: PetscCall(DMPlexComputeCellGeometryFEM(dm, cell, quad, coords, fegeom.J, fegeom.invJ, fegeom.detJ));
2207: PetscCall(DMPlexVecGetClosure(dm, NULL, locX, cell, NULL, &x));
2208: for (f = 0; f < Nf; ++f) {
2209: PetscObject obj;
2210: PetscClassId id;
2211: PetscInt Nb, fNc, q;
2213: PetscCall(PetscArrayzero(val, Nc));
2214: PetscCall(DMGetField(dm, f, NULL, &obj));
2215: PetscCall(PetscObjectGetClassId(obj, &id));
2216: if (id == PETSCFE_CLASSID) {
2217: PetscCall(PetscFEGetNumComponents((PetscFE)obj, &fNc));
2218: PetscCall(PetscFEGetDimension((PetscFE)obj, &Nb));
2219: } else if (id == PETSCFV_CLASSID) {
2220: PetscCall(PetscFVGetNumComponents((PetscFV)obj, &fNc));
2221: Nb = 1;
2222: } else SETERRQ(PetscObjectComm((PetscObject)dm), PETSC_ERR_ARG_WRONG, "Unknown discretization type for field %" PetscInt_FMT, f);
2223: for (q = 0; q < Nq; ++q) {
2224: const PetscReal wt = quadWeights[q] * fegeom.detJ[q];
2225: PetscFEGeom qgeom;
2227: qgeom.dimEmbed = fegeom.dimEmbed;
2228: qgeom.J = &fegeom.J[q * cdim * cdim];
2229: qgeom.invJ = &fegeom.invJ[q * cdim * cdim];
2230: qgeom.detJ = &fegeom.detJ[q];
2231: PetscCheck(fegeom.detJ[q] > 0.0, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Invalid determinant %g for element %" PetscInt_FMT ", quadrature points %" PetscInt_FMT, (double)fegeom.detJ[q], cell, q);
2232: PetscCheck(id == PETSCFE_CLASSID, PetscObjectComm((PetscObject)dm), PETSC_ERR_ARG_WRONG, "Unknown discretization type for field %" PetscInt_FMT, f);
2233: PetscCall(PetscFEInterpolate_Static((PetscFE)obj, &x[foff], &qgeom, q, interpolant));
2234: for (fc = 0; fc < fNc; ++fc) val[foff + fc] += interpolant[fc] * wt;
2235: vol += wt;
2236: }
2237: foff += Nb;
2238: }
2239: PetscCall(DMPlexVecRestoreClosure(dm, NULL, locX, cell, NULL, &x));
2240: for (fc = 0; fc < Nc; ++fc) valsum[fc] += val[fc];
2241: volsum += vol;
2242: if (debug) {
2243: PetscCall(PetscPrintf(PETSC_COMM_SELF, "Vertex %" PetscInt_FMT " Cell %" PetscInt_FMT " value: [", v, cell));
2244: for (fc = 0; fc < Nc; ++fc) {
2245: if (fc) PetscCall(PetscPrintf(PETSC_COMM_SELF, ", "));
2246: PetscCall(PetscPrintf(PETSC_COMM_SELF, "%g", (double)PetscRealPart(val[fc])));
2247: }
2248: PetscCall(PetscPrintf(PETSC_COMM_SELF, "]\n"));
2249: }
2250: }
2251: for (fc = 0; fc < Nc; ++fc) valsum[fc] /= volsum;
2252: PetscCall(DMPlexRestoreTransitiveClosure(dm, v, PETSC_FALSE, &starSize, &star));
2253: PetscCall(DMPlexVecSetClosure(dmc, NULL, locC, v, valsum, INSERT_VALUES));
2254: }
2255: PetscCall(PetscFree6(valsum, interpolant, coords, fegeom.detJ, fegeom.J, fegeom.invJ));
2256: PetscFunctionReturn(PETSC_SUCCESS);
2257: }
2259: /*@
2260: DMPlexComputeGradientClementInterpolant - This function computes the L2 projection of the cellwise gradient of a function u onto P1
2262: Collective
2264: Input Parameters:
2265: + dm - The `DM`
2266: - locX - The coefficient vector u_h
2268: Output Parameter:
2269: . locC - A `Vec` which holds the Clement interpolant of the gradient
2271: Level: developer
2273: Note:
2274: $\nabla u_h(v_i) = \sum_{T_i \in support(v_i)} |T_i| \nabla u_h(T_i) / \sum_{T_i \in support(v_i)} |T_i| $ where $ |T_i| $ is the cell volume
2276: .seealso: [](ch_unstructured), `DM`, `DMPLEX`, `DMProjectFunction()`, `DMComputeL2Diff()`, `DMPlexComputeL2FieldDiff()`, `DMComputeL2GradientDiff()`
2277: @*/
2278: PetscErrorCode DMPlexComputeGradientClementInterpolant(DM dm, Vec locX, Vec locC)
2279: {
2280: DM_Plex *mesh = (DM_Plex *)dm->data;
2281: PetscInt debug = mesh->printFEM;
2282: DM dmC;
2283: PetscQuadrature quad;
2284: PetscScalar *interpolant, *gradsum;
2285: PetscFEGeom fegeom;
2286: PetscReal *coords;
2287: const PetscReal *quadPoints, *quadWeights;
2288: PetscInt dim, coordDim, numFields, numComponents = 0, qNc, Nq, cStart, cEnd, vStart, vEnd, v, field, fieldOffset;
2290: PetscFunctionBegin;
2291: PetscCall(PetscCitationsRegister(ClementCitation, &Clementcite));
2292: PetscCall(VecGetDM(locC, &dmC));
2293: PetscCall(VecSet(locC, 0.0));
2294: PetscCall(DMGetDimension(dm, &dim));
2295: PetscCall(DMGetCoordinateDim(dm, &coordDim));
2296: fegeom.dimEmbed = coordDim;
2297: PetscCall(DMGetNumFields(dm, &numFields));
2298: PetscCheck(numFields, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Number of fields is zero!");
2299: for (field = 0; field < numFields; ++field) {
2300: PetscObject obj;
2301: PetscClassId id;
2302: PetscInt Nc;
2304: PetscCall(DMGetField(dm, field, NULL, &obj));
2305: PetscCall(PetscObjectGetClassId(obj, &id));
2306: if (id == PETSCFE_CLASSID) {
2307: PetscFE fe = (PetscFE)obj;
2309: PetscCall(PetscFEGetQuadrature(fe, &quad));
2310: PetscCall(PetscFEGetNumComponents(fe, &Nc));
2311: } else if (id == PETSCFV_CLASSID) {
2312: PetscFV fv = (PetscFV)obj;
2314: PetscCall(PetscFVGetQuadrature(fv, &quad));
2315: PetscCall(PetscFVGetNumComponents(fv, &Nc));
2316: } else SETERRQ(PetscObjectComm((PetscObject)dm), PETSC_ERR_ARG_WRONG, "Unknown discretization type for field %" PetscInt_FMT, field);
2317: numComponents += Nc;
2318: }
2319: PetscCall(PetscQuadratureGetData(quad, NULL, &qNc, &Nq, &quadPoints, &quadWeights));
2320: PetscCheck(!(qNc != 1) || !(qNc != numComponents), PetscObjectComm((PetscObject)dm), PETSC_ERR_ARG_SIZ, "Quadrature components %" PetscInt_FMT " != %" PetscInt_FMT " field components", qNc, numComponents);
2321: PetscCall(PetscMalloc6(coordDim * numComponents * 2, &gradsum, coordDim * numComponents, &interpolant, coordDim * Nq, &coords, Nq, &fegeom.detJ, coordDim * coordDim * Nq, &fegeom.J, coordDim * coordDim * Nq, &fegeom.invJ));
2322: PetscCall(DMPlexGetDepthStratum(dm, 0, &vStart, &vEnd));
2323: PetscCall(DMPlexGetSimplexOrBoxCells(dm, 0, &cStart, &cEnd));
2324: for (v = vStart; v < vEnd; ++v) {
2325: PetscScalar volsum = 0.0;
2326: PetscInt *star = NULL;
2327: PetscInt starSize, st, d, fc;
2329: PetscCall(PetscArrayzero(gradsum, coordDim * numComponents));
2330: PetscCall(DMPlexGetTransitiveClosure(dm, v, PETSC_FALSE, &starSize, &star));
2331: for (st = 0; st < starSize * 2; st += 2) {
2332: const PetscInt cell = star[st];
2333: PetscScalar *grad = &gradsum[coordDim * numComponents];
2334: PetscScalar *x = NULL;
2335: PetscReal vol = 0.0;
2337: if ((cell < cStart) || (cell >= cEnd)) continue;
2338: PetscCall(DMPlexComputeCellGeometryFEM(dm, cell, quad, coords, fegeom.J, fegeom.invJ, fegeom.detJ));
2339: PetscCall(DMPlexVecGetClosure(dm, NULL, locX, cell, NULL, &x));
2340: for (field = 0, fieldOffset = 0; field < numFields; ++field) {
2341: PetscObject obj;
2342: PetscClassId id;
2343: PetscInt Nb, Nc, q, qc = 0;
2345: PetscCall(PetscArrayzero(grad, coordDim * numComponents));
2346: PetscCall(DMGetField(dm, field, NULL, &obj));
2347: PetscCall(PetscObjectGetClassId(obj, &id));
2348: if (id == PETSCFE_CLASSID) {
2349: PetscCall(PetscFEGetNumComponents((PetscFE)obj, &Nc));
2350: PetscCall(PetscFEGetDimension((PetscFE)obj, &Nb));
2351: } else if (id == PETSCFV_CLASSID) {
2352: PetscCall(PetscFVGetNumComponents((PetscFV)obj, &Nc));
2353: Nb = 1;
2354: } else SETERRQ(PetscObjectComm((PetscObject)dm), PETSC_ERR_ARG_WRONG, "Unknown discretization type for field %" PetscInt_FMT, field);
2355: for (q = 0; q < Nq; ++q) {
2356: PetscFEGeom qgeom;
2358: qgeom.dimEmbed = fegeom.dimEmbed;
2359: qgeom.J = &fegeom.J[q * coordDim * coordDim];
2360: qgeom.invJ = &fegeom.invJ[q * coordDim * coordDim];
2361: qgeom.detJ = &fegeom.detJ[q];
2362: PetscCheck(fegeom.detJ[q] > 0.0, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Invalid determinant %g for element %" PetscInt_FMT ", quadrature points %" PetscInt_FMT, (double)fegeom.detJ[q], cell, q);
2363: PetscCheck(id == PETSCFE_CLASSID, PetscObjectComm((PetscObject)dm), PETSC_ERR_ARG_WRONG, "Unknown discretization type for field %" PetscInt_FMT, field);
2364: PetscCall(PetscFEInterpolateGradient_Static((PetscFE)obj, 1, &x[fieldOffset], &qgeom, q, interpolant));
2365: for (fc = 0; fc < Nc; ++fc) {
2366: const PetscReal wt = quadWeights[q * qNc + qc];
2368: for (d = 0; d < coordDim; ++d) grad[fc * coordDim + d] += interpolant[fc * dim + d] * wt * fegeom.detJ[q];
2369: }
2370: vol += quadWeights[q * qNc] * fegeom.detJ[q];
2371: }
2372: fieldOffset += Nb;
2373: qc += Nc;
2374: }
2375: PetscCall(DMPlexVecRestoreClosure(dm, NULL, locX, cell, NULL, &x));
2376: for (fc = 0; fc < numComponents; ++fc) {
2377: for (d = 0; d < coordDim; ++d) gradsum[fc * coordDim + d] += grad[fc * coordDim + d];
2378: }
2379: volsum += vol;
2380: if (debug) {
2381: PetscCall(PetscPrintf(PETSC_COMM_SELF, "Vertex %" PetscInt_FMT " Cell %" PetscInt_FMT " gradient: [", v, cell));
2382: for (fc = 0; fc < numComponents; ++fc) {
2383: for (d = 0; d < coordDim; ++d) {
2384: if (fc || d > 0) PetscCall(PetscPrintf(PETSC_COMM_SELF, ", "));
2385: PetscCall(PetscPrintf(PETSC_COMM_SELF, "%g", (double)PetscRealPart(grad[fc * coordDim + d])));
2386: }
2387: }
2388: PetscCall(PetscPrintf(PETSC_COMM_SELF, "]\n"));
2389: }
2390: }
2391: for (fc = 0; fc < numComponents; ++fc) {
2392: for (d = 0; d < coordDim; ++d) gradsum[fc * coordDim + d] /= volsum;
2393: }
2394: PetscCall(DMPlexRestoreTransitiveClosure(dm, v, PETSC_FALSE, &starSize, &star));
2395: PetscCall(DMPlexVecSetClosure(dmC, NULL, locC, v, gradsum, INSERT_VALUES));
2396: }
2397: PetscCall(PetscFree6(gradsum, interpolant, coords, fegeom.detJ, fegeom.J, fegeom.invJ));
2398: PetscFunctionReturn(PETSC_SUCCESS);
2399: }
2401: PetscErrorCode DMPlexComputeIntegral_Internal(DM dm, Vec locX, PetscInt cStart, PetscInt cEnd, PetscScalar *cintegral, PetscCtx ctx)
2402: {
2403: DM dmAux = NULL, plexA = NULL;
2404: PetscDS prob, probAux = NULL;
2405: PetscSection section, sectionAux;
2406: Vec locA;
2407: PetscInt dim, numCells = cEnd - cStart, c, f;
2408: PetscBool useFVM = PETSC_FALSE;
2409: /* DS */
2410: PetscInt Nf, totDim, *uOff, *uOff_x, numConstants;
2411: PetscInt NfAux, totDimAux, *aOff;
2412: PetscScalar *u, *a = NULL;
2413: const PetscScalar *constants;
2414: /* Geometry */
2415: PetscFEGeom *cgeomFEM;
2416: DM dmGrad;
2417: PetscQuadrature affineQuad = NULL;
2418: Vec cellGeometryFVM = NULL, faceGeometryFVM = NULL, locGrad = NULL;
2419: PetscFVCellGeom *cgeomFVM;
2420: const PetscScalar *lgrad;
2421: PetscInt maxDegree;
2422: DMField coordField;
2423: IS cellIS;
2425: PetscFunctionBegin;
2426: PetscCall(DMGetDS(dm, &prob));
2427: PetscCall(DMGetDimension(dm, &dim));
2428: PetscCall(DMGetLocalSection(dm, §ion));
2429: PetscCall(DMGetNumFields(dm, &Nf));
2430: /* Determine which discretizations we have */
2431: for (f = 0; f < Nf; ++f) {
2432: PetscObject obj;
2433: PetscClassId id;
2435: PetscCall(PetscDSGetDiscretization(prob, f, &obj));
2436: PetscCall(PetscObjectGetClassId(obj, &id));
2437: if (id == PETSCFV_CLASSID) useFVM = PETSC_TRUE;
2438: }
2439: /* Read DS information */
2440: PetscCall(PetscDSGetTotalDimension(prob, &totDim));
2441: PetscCall(PetscDSGetComponentOffsets(prob, &uOff));
2442: PetscCall(PetscDSGetComponentDerivativeOffsets(prob, &uOff_x));
2443: PetscCall(ISCreateStride(PETSC_COMM_SELF, numCells, cStart, 1, &cellIS));
2444: PetscCall(PetscDSGetConstants(prob, &numConstants, &constants));
2445: /* Read Auxiliary DS information */
2446: PetscCall(DMGetAuxiliaryVec(dm, NULL, 0, 0, &locA));
2447: if (locA) {
2448: PetscCall(VecGetDM(locA, &dmAux));
2449: PetscCall(DMConvert(dmAux, DMPLEX, &plexA));
2450: PetscCall(DMGetDS(dmAux, &probAux));
2451: PetscCall(PetscDSGetNumFields(probAux, &NfAux));
2452: PetscCall(DMGetLocalSection(dmAux, §ionAux));
2453: PetscCall(PetscDSGetTotalDimension(probAux, &totDimAux));
2454: PetscCall(PetscDSGetComponentOffsets(probAux, &aOff));
2455: }
2456: /* Allocate data arrays */
2457: PetscCall(PetscCalloc1(numCells * totDim, &u));
2458: if (dmAux) PetscCall(PetscMalloc1(numCells * totDimAux, &a));
2459: /* Read out geometry */
2460: PetscCall(DMGetCoordinateField(dm, &coordField));
2461: PetscCall(DMFieldGetDegree(coordField, cellIS, NULL, &maxDegree));
2462: if (maxDegree <= 1) {
2463: PetscCall(DMFieldCreateDefaultQuadrature(coordField, cellIS, &affineQuad));
2464: if (affineQuad) PetscCall(DMFieldCreateFEGeom(coordField, cellIS, affineQuad, PETSC_FEGEOM_BASIC, &cgeomFEM));
2465: }
2466: if (useFVM) {
2467: PetscFV fv = NULL;
2468: Vec grad;
2469: PetscInt fStart, fEnd;
2470: PetscBool compGrad;
2472: for (f = 0; f < Nf; ++f) {
2473: PetscObject obj;
2474: PetscClassId id;
2476: PetscCall(PetscDSGetDiscretization(prob, f, &obj));
2477: PetscCall(PetscObjectGetClassId(obj, &id));
2478: if (id == PETSCFV_CLASSID) {
2479: fv = (PetscFV)obj;
2480: break;
2481: }
2482: }
2483: PetscCall(PetscFVGetComputeGradients(fv, &compGrad));
2484: PetscCall(PetscFVSetComputeGradients(fv, PETSC_TRUE));
2485: PetscCall(DMPlexComputeGeometryFVM(dm, &cellGeometryFVM, &faceGeometryFVM));
2486: PetscCall(DMPlexComputeGradientFVM(dm, fv, faceGeometryFVM, cellGeometryFVM, &dmGrad));
2487: PetscCall(PetscFVSetComputeGradients(fv, compGrad));
2488: PetscCall(VecGetArrayRead(cellGeometryFVM, (const PetscScalar **)&cgeomFVM));
2489: /* Reconstruct and limit cell gradients */
2490: PetscCall(DMPlexGetHeightStratum(dm, 1, &fStart, &fEnd));
2491: PetscCall(DMGetGlobalVector(dmGrad, &grad));
2492: PetscCall(DMPlexReconstructGradients_Internal(dm, fv, fStart, fEnd, faceGeometryFVM, cellGeometryFVM, locX, grad));
2493: /* Communicate gradient values */
2494: PetscCall(DMGetLocalVector(dmGrad, &locGrad));
2495: PetscCall(DMGlobalToLocalBegin(dmGrad, grad, INSERT_VALUES, locGrad));
2496: PetscCall(DMGlobalToLocalEnd(dmGrad, grad, INSERT_VALUES, locGrad));
2497: PetscCall(DMRestoreGlobalVector(dmGrad, &grad));
2498: /* Handle non-essential (e.g. outflow) boundary values */
2499: PetscCall(DMPlexInsertBoundaryValues(dm, PETSC_FALSE, locX, 0.0, faceGeometryFVM, cellGeometryFVM, locGrad));
2500: PetscCall(VecGetArrayRead(locGrad, &lgrad));
2501: }
2502: /* Read out data from inputs */
2503: for (c = cStart; c < cEnd; ++c) {
2504: PetscScalar *x = NULL;
2505: PetscInt i;
2507: PetscCall(DMPlexVecGetClosure(dm, section, locX, c, NULL, &x));
2508: for (i = 0; i < totDim; ++i) u[c * totDim + i] = x[i];
2509: PetscCall(DMPlexVecRestoreClosure(dm, section, locX, c, NULL, &x));
2510: if (dmAux) {
2511: PetscCall(DMPlexVecGetClosure(plexA, sectionAux, locA, c, NULL, &x));
2512: for (i = 0; i < totDimAux; ++i) a[c * totDimAux + i] = x[i];
2513: PetscCall(DMPlexVecRestoreClosure(plexA, sectionAux, locA, c, NULL, &x));
2514: }
2515: }
2516: /* Do integration for each field */
2517: for (f = 0; f < Nf; ++f) {
2518: PetscObject obj;
2519: PetscClassId id;
2520: PetscInt numChunks, numBatches, batchSize, numBlocks, blockSize, Ne, Nr, offset;
2522: PetscCall(PetscDSGetDiscretization(prob, f, &obj));
2523: PetscCall(PetscObjectGetClassId(obj, &id));
2524: if (id == PETSCFE_CLASSID) {
2525: PetscFE fe = (PetscFE)obj;
2526: PetscQuadrature q;
2527: PetscFEGeom *chunkGeom = NULL;
2528: PetscInt Nq, Nb;
2530: PetscCall(PetscFEGetTileSizes(fe, NULL, &numBlocks, NULL, &numBatches));
2531: PetscCall(PetscFEGetQuadrature(fe, &q));
2532: PetscCall(PetscQuadratureGetData(q, NULL, NULL, &Nq, NULL, NULL));
2533: PetscCall(PetscFEGetDimension(fe, &Nb));
2534: blockSize = Nb * Nq;
2535: batchSize = numBlocks * blockSize;
2536: PetscCall(PetscFESetTileSizes(fe, blockSize, numBlocks, batchSize, numBatches));
2537: numChunks = numCells / (numBatches * batchSize);
2538: Ne = numChunks * numBatches * batchSize;
2539: Nr = numCells % (numBatches * batchSize);
2540: offset = numCells - Nr;
2541: if (!affineQuad) PetscCall(DMFieldCreateFEGeom(coordField, cellIS, q, PETSC_FEGEOM_BASIC, &cgeomFEM));
2542: PetscCall(PetscFEGeomGetChunk(cgeomFEM, 0, offset, &chunkGeom));
2543: PetscCall(PetscFEIntegrate(prob, f, Ne, chunkGeom, u, probAux, a, cintegral));
2544: PetscCall(PetscFEGeomGetChunk(cgeomFEM, offset, numCells, &chunkGeom));
2545: PetscCall(PetscFEIntegrate(prob, f, Nr, chunkGeom, &u[offset * totDim], probAux, PetscSafePointerPlusOffset(a, offset * totDimAux), &cintegral[offset * Nf]));
2546: PetscCall(PetscFEGeomRestoreChunk(cgeomFEM, offset, numCells, &chunkGeom));
2547: if (!affineQuad) PetscCall(PetscFEGeomDestroy(&cgeomFEM));
2548: } else if (id == PETSCFV_CLASSID) {
2549: PetscInt foff;
2550: PetscPointFn *obj_func;
2552: PetscCall(PetscDSGetObjective(prob, f, &obj_func));
2553: PetscCall(PetscDSGetFieldOffset(prob, f, &foff));
2554: if (obj_func) {
2555: for (c = 0; c < numCells; ++c) {
2556: PetscScalar *u_x;
2557: PetscScalar lint = 0.;
2559: PetscCall(DMPlexPointLocalRead(dmGrad, c, lgrad, &u_x));
2560: obj_func(dim, Nf, NfAux, uOff, uOff_x, &u[totDim * c + foff], NULL, u_x, aOff, NULL, PetscSafePointerPlusOffset(a, totDimAux * c), NULL, NULL, 0.0, cgeomFVM[c].centroid, numConstants, constants, &lint);
2561: cintegral[c * Nf + f] += PetscRealPart(lint) * cgeomFVM[c].volume;
2562: }
2563: }
2564: } else SETERRQ(PetscObjectComm((PetscObject)dm), PETSC_ERR_ARG_WRONG, "Unknown discretization type for field %" PetscInt_FMT, f);
2565: }
2566: /* Cleanup data arrays */
2567: if (useFVM) {
2568: PetscCall(VecRestoreArrayRead(locGrad, &lgrad));
2569: PetscCall(VecRestoreArrayRead(cellGeometryFVM, (const PetscScalar **)&cgeomFVM));
2570: PetscCall(DMRestoreLocalVector(dmGrad, &locGrad));
2571: PetscCall(VecDestroy(&faceGeometryFVM));
2572: PetscCall(VecDestroy(&cellGeometryFVM));
2573: PetscCall(DMDestroy(&dmGrad));
2574: }
2575: if (dmAux) PetscCall(PetscFree(a));
2576: PetscCall(DMDestroy(&plexA));
2577: PetscCall(PetscFree(u));
2578: /* Cleanup */
2579: if (affineQuad) PetscCall(PetscFEGeomDestroy(&cgeomFEM));
2580: PetscCall(PetscQuadratureDestroy(&affineQuad));
2581: PetscCall(ISDestroy(&cellIS));
2582: PetscFunctionReturn(PETSC_SUCCESS);
2583: }
2585: /*@
2586: DMPlexComputeIntegralFEM - Form the integral over the domain from the global input X using pointwise functions specified by the user
2588: Input Parameters:
2589: + dm - The mesh
2590: . X - Global input vector
2591: - ctx - The application context
2593: Output Parameter:
2594: . integral - Integral for each field
2596: Level: developer
2598: .seealso: [](ch_unstructured), `DM`, `DMPLEX`, `DMPlexSNESComputeResidualFEM()`
2599: @*/
2600: PetscErrorCode DMPlexComputeIntegralFEM(DM dm, Vec X, PetscScalar *integral, PetscCtx ctx)
2601: {
2602: PetscInt printFEM;
2603: PetscScalar *cintegral, *lintegral;
2604: PetscInt Nf, f, cellHeight, cStart, cEnd, cell;
2605: Vec locX;
2607: PetscFunctionBegin;
2610: PetscAssertPointer(integral, 3);
2611: PetscCall(PetscLogEventBegin(DMPLEX_IntegralFEM, dm, 0, 0, 0));
2612: PetscCall(DMPlexConvertPlex(dm, &dm, PETSC_TRUE));
2613: PetscCall(DMGetNumFields(dm, &Nf));
2614: PetscCall(DMPlexGetVTKCellHeight(dm, &cellHeight));
2615: PetscCall(DMPlexGetSimplexOrBoxCells(dm, cellHeight, &cStart, &cEnd));
2616: /* TODO Introduce a loop over large chunks (right now this is a single chunk) */
2617: PetscCall(PetscCalloc2(Nf, &lintegral, (cEnd - cStart) * Nf, &cintegral));
2618: /* Get local solution with boundary values */
2619: PetscCall(DMGetLocalVector(dm, &locX));
2620: PetscCall(DMPlexInsertBoundaryValues(dm, PETSC_TRUE, locX, 0.0, NULL, NULL, NULL));
2621: PetscCall(DMGlobalToLocalBegin(dm, X, INSERT_VALUES, locX));
2622: PetscCall(DMGlobalToLocalEnd(dm, X, INSERT_VALUES, locX));
2623: PetscCall(DMPlexComputeIntegral_Internal(dm, locX, cStart, cEnd, cintegral, ctx));
2624: PetscCall(DMRestoreLocalVector(dm, &locX));
2625: printFEM = ((DM_Plex *)dm->data)->printFEM;
2626: /* Sum up values */
2627: for (cell = cStart; cell < cEnd; ++cell) {
2628: const PetscInt c = cell - cStart;
2630: if (printFEM > 1) PetscCall(DMPrintCellVector(cell, "Cell Integral", Nf, &cintegral[c * Nf]));
2631: for (f = 0; f < Nf; ++f) lintegral[f] += cintegral[c * Nf + f];
2632: }
2633: PetscCallMPI(MPIU_Allreduce(lintegral, integral, Nf, MPIU_SCALAR, MPIU_SUM, PetscObjectComm((PetscObject)dm)));
2634: if (printFEM) {
2635: PetscCall(PetscPrintf(PetscObjectComm((PetscObject)dm), "Integral:"));
2636: for (f = 0; f < Nf; ++f) PetscCall(PetscPrintf(PetscObjectComm((PetscObject)dm), " %g", (double)PetscRealPart(integral[f])));
2637: PetscCall(PetscPrintf(PetscObjectComm((PetscObject)dm), "\n"));
2638: }
2639: PetscCall(PetscFree2(lintegral, cintegral));
2640: PetscCall(PetscLogEventEnd(DMPLEX_IntegralFEM, dm, 0, 0, 0));
2641: PetscCall(DMDestroy(&dm));
2642: PetscFunctionReturn(PETSC_SUCCESS);
2643: }
2645: /*@
2646: DMPlexComputeCellwiseIntegralFEM - Form the vector of cellwise integrals F from the global input X using pointwise functions specified by the user
2648: Input Parameters:
2649: + dm - The mesh
2650: . X - Global input vector
2651: - ctx - The application context
2653: Output Parameter:
2654: . F - Cellwise integrals for each field
2656: Level: developer
2658: .seealso: [](ch_unstructured), `DM`, `DMPLEX`, `DMPlexSNESComputeResidualFEM()`
2659: @*/
2660: PetscErrorCode DMPlexComputeCellwiseIntegralFEM(DM dm, Vec X, Vec F, PetscCtx ctx)
2661: {
2662: PetscInt printFEM;
2663: DM dmF;
2664: PetscSection sectionF = NULL;
2665: PetscScalar *cintegral, *af;
2666: PetscInt Nf, f, cellHeight, cStart, cEnd, cell, n;
2667: Vec locX;
2669: PetscFunctionBegin;
2673: PetscCall(PetscLogEventBegin(DMPLEX_IntegralFEM, dm, 0, 0, 0));
2674: PetscCall(DMPlexConvertPlex(dm, &dm, PETSC_TRUE));
2675: PetscCall(DMGetNumFields(dm, &Nf));
2676: PetscCall(DMPlexGetVTKCellHeight(dm, &cellHeight));
2677: PetscCall(DMPlexGetSimplexOrBoxCells(dm, cellHeight, &cStart, &cEnd));
2678: /* TODO Introduce a loop over large chunks (right now this is a single chunk) */
2679: PetscCall(PetscCalloc1((cEnd - cStart) * Nf, &cintegral));
2680: /* Get local solution with boundary values */
2681: PetscCall(DMGetLocalVector(dm, &locX));
2682: PetscCall(DMPlexInsertBoundaryValues(dm, PETSC_TRUE, locX, 0.0, NULL, NULL, NULL));
2683: PetscCall(DMGlobalToLocalBegin(dm, X, INSERT_VALUES, locX));
2684: PetscCall(DMGlobalToLocalEnd(dm, X, INSERT_VALUES, locX));
2685: PetscCall(DMPlexComputeIntegral_Internal(dm, locX, cStart, cEnd, cintegral, ctx));
2686: PetscCall(DMRestoreLocalVector(dm, &locX));
2687: /* Put values in F */
2688: PetscCall(VecGetArray(F, &af));
2689: PetscCall(VecGetDM(F, &dmF));
2690: if (dmF) PetscCall(DMGetLocalSection(dmF, §ionF));
2691: PetscCall(VecGetLocalSize(F, &n));
2692: PetscCheck(n >= (cEnd - cStart) * Nf, PETSC_COMM_SELF, PETSC_ERR_ARG_SIZ, "Vector size %" PetscInt_FMT " < %" PetscInt_FMT, n, (cEnd - cStart) * Nf);
2693: printFEM = ((DM_Plex *)dm->data)->printFEM;
2694: for (cell = cStart; cell < cEnd; ++cell) {
2695: const PetscInt c = cell - cStart;
2696: PetscInt dof = Nf, off = c * Nf;
2698: if (printFEM > 1) PetscCall(DMPrintCellVector(cell, "Cell Integral", Nf, &cintegral[c * Nf]));
2699: if (sectionF) {
2700: PetscCall(PetscSectionGetDof(sectionF, cell, &dof));
2701: PetscCall(PetscSectionGetOffset(sectionF, cell, &off));
2702: }
2703: PetscCheck(dof == Nf, PETSC_COMM_SELF, PETSC_ERR_ARG_SIZ, "The number of cell dofs %" PetscInt_FMT " != %" PetscInt_FMT, dof, Nf);
2704: for (f = 0; f < Nf; ++f) af[off + f] = cintegral[c * Nf + f];
2705: }
2706: PetscCall(VecRestoreArray(F, &af));
2707: PetscCall(PetscFree(cintegral));
2708: PetscCall(PetscLogEventEnd(DMPLEX_IntegralFEM, dm, 0, 0, 0));
2709: PetscCall(DMDestroy(&dm));
2710: PetscFunctionReturn(PETSC_SUCCESS);
2711: }
2713: static PetscErrorCode DMPlexComputeBdIntegral_Internal(DM dm, Vec locX, IS pointIS, 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[]), PetscScalar *fintegral, PetscCtx ctx)
2714: {
2715: DM plex = NULL, plexA = NULL;
2716: DMEnclosureType encAux;
2717: PetscDS prob, probAux = NULL;
2718: PetscSection section, sectionAux = NULL;
2719: Vec locA = NULL;
2720: DMField coordField;
2721: PetscInt Nf, totDim, *uOff, *uOff_x;
2722: PetscInt NfAux = 0, totDimAux = 0, *aOff = NULL;
2723: PetscScalar *u, *a = NULL;
2724: const PetscScalar *constants;
2725: PetscInt numConstants, f;
2727: PetscFunctionBegin;
2728: PetscCall(DMGetCoordinateField(dm, &coordField));
2729: PetscCall(DMConvert(dm, DMPLEX, &plex));
2730: PetscCall(DMGetDS(dm, &prob));
2731: PetscCall(DMGetLocalSection(dm, §ion));
2732: PetscCall(PetscSectionGetNumFields(section, &Nf));
2733: /* Determine which discretizations we have */
2734: for (f = 0; f < Nf; ++f) {
2735: PetscObject obj;
2736: PetscClassId id;
2738: PetscCall(PetscDSGetDiscretization(prob, f, &obj));
2739: PetscCall(PetscObjectGetClassId(obj, &id));
2740: PetscCheck(id != PETSCFV_CLASSID, PetscObjectComm((PetscObject)dm), PETSC_ERR_SUP, "Not supported for FVM (field %" PetscInt_FMT ")", f);
2741: }
2742: /* Read DS information */
2743: PetscCall(PetscDSGetTotalDimension(prob, &totDim));
2744: PetscCall(PetscDSGetComponentOffsets(prob, &uOff));
2745: PetscCall(PetscDSGetComponentDerivativeOffsets(prob, &uOff_x));
2746: PetscCall(PetscDSGetConstants(prob, &numConstants, &constants));
2747: /* Read Auxiliary DS information */
2748: PetscCall(DMGetAuxiliaryVec(dm, NULL, 0, 0, &locA));
2749: if (locA) {
2750: DM dmAux;
2752: PetscCall(VecGetDM(locA, &dmAux));
2753: PetscCall(DMGetEnclosureRelation(dmAux, dm, &encAux));
2754: PetscCall(DMConvert(dmAux, DMPLEX, &plexA));
2755: PetscCall(DMGetDS(dmAux, &probAux));
2756: PetscCall(PetscDSGetNumFields(probAux, &NfAux));
2757: PetscCall(DMGetLocalSection(dmAux, §ionAux));
2758: PetscCall(PetscDSGetTotalDimension(probAux, &totDimAux));
2759: PetscCall(PetscDSGetComponentOffsets(probAux, &aOff));
2760: }
2761: /* Integrate over points */
2762: {
2763: PetscFEGeom *fgeom, *chunkGeom = NULL;
2764: PetscInt maxDegree;
2765: PetscQuadrature qGeom = NULL;
2766: const PetscInt *points;
2767: PetscInt numFaces, face, Nq, field;
2768: PetscInt numChunks, chunkSize, chunk, Nr, offset;
2770: PetscCall(ISGetLocalSize(pointIS, &numFaces));
2771: PetscCall(ISGetIndices(pointIS, &points));
2772: PetscCall(PetscCalloc2(numFaces * totDim, &u, (locA ? (size_t)numFaces * totDimAux : 0), &a));
2773: PetscCall(DMFieldGetDegree(coordField, pointIS, NULL, &maxDegree));
2774: for (face = 0; face < numFaces; ++face) {
2775: const PetscInt point = points[face], *support;
2776: PetscScalar *x = NULL;
2778: PetscCall(DMPlexGetSupport(dm, point, &support));
2779: PetscCall(DMPlexVecGetClosure(plex, section, locX, support[0], NULL, &x));
2780: for (PetscInt i = 0; i < totDim; ++i) u[face * totDim + i] = x[i];
2781: PetscCall(DMPlexVecRestoreClosure(plex, section, locX, support[0], NULL, &x));
2782: if (locA) {
2783: PetscInt subp;
2784: PetscCall(DMGetEnclosurePoint(plexA, dm, encAux, support[0], &subp));
2785: PetscCall(DMPlexVecGetClosure(plexA, sectionAux, locA, subp, NULL, &x));
2786: for (PetscInt i = 0; i < totDimAux; ++i) a[f * totDimAux + i] = x[i];
2787: PetscCall(DMPlexVecRestoreClosure(plexA, sectionAux, locA, subp, NULL, &x));
2788: }
2789: }
2790: for (field = 0; field < Nf; ++field) {
2791: PetscFE fe;
2793: PetscCall(PetscDSGetDiscretization(prob, field, (PetscObject *)&fe));
2794: if (maxDegree <= 1) PetscCall(DMFieldCreateDefaultQuadrature(coordField, pointIS, &qGeom));
2795: if (!qGeom) {
2796: PetscCall(PetscFEGetFaceQuadrature(fe, &qGeom));
2797: PetscCall(PetscObjectReference((PetscObject)qGeom));
2798: }
2799: PetscCall(PetscQuadratureGetData(qGeom, NULL, NULL, &Nq, NULL, NULL));
2800: PetscCall(DMPlexGetFEGeom(coordField, pointIS, qGeom, PETSC_FEGEOM_BOUNDARY, &fgeom));
2801: /* Get blocking */
2802: {
2803: PetscQuadrature q;
2804: PetscInt numBatches, batchSize, numBlocks, blockSize;
2805: PetscInt Nq, Nb;
2807: PetscCall(PetscFEGetTileSizes(fe, NULL, &numBlocks, NULL, &numBatches));
2808: PetscCall(PetscFEGetQuadrature(fe, &q));
2809: PetscCall(PetscQuadratureGetData(q, NULL, NULL, &Nq, NULL, NULL));
2810: PetscCall(PetscFEGetDimension(fe, &Nb));
2811: blockSize = Nb * Nq;
2812: batchSize = numBlocks * blockSize;
2813: chunkSize = numBatches * batchSize;
2814: PetscCall(PetscFESetTileSizes(fe, blockSize, numBlocks, batchSize, numBatches));
2815: numChunks = numFaces / chunkSize;
2816: Nr = numFaces % chunkSize;
2817: offset = numFaces - Nr;
2818: }
2819: /* Do integration for each field */
2820: for (chunk = 0; chunk < numChunks; ++chunk) {
2821: PetscCall(PetscFEGeomGetChunk(fgeom, chunk * chunkSize, (chunk + 1) * chunkSize, &chunkGeom));
2822: PetscCall(PetscFEIntegrateBd(prob, field, funcs[field], chunkSize, chunkGeom, &u[chunk * chunkSize * totDim], probAux, PetscSafePointerPlusOffset(a, chunk * chunkSize * totDimAux), &fintegral[chunk * chunkSize * Nf]));
2823: PetscCall(PetscFEGeomRestoreChunk(fgeom, 0, offset, &chunkGeom));
2824: }
2825: PetscCall(PetscFEGeomGetChunk(fgeom, offset, numFaces, &chunkGeom));
2826: PetscCall(PetscFEIntegrateBd(prob, field, funcs[field], Nr, chunkGeom, &u[offset * totDim], probAux, PetscSafePointerPlusOffset(a, offset * totDimAux), &fintegral[offset * Nf]));
2827: PetscCall(PetscFEGeomRestoreChunk(fgeom, offset, numFaces, &chunkGeom));
2828: /* Cleanup data arrays */
2829: PetscCall(DMPlexRestoreFEGeom(coordField, pointIS, qGeom, PETSC_FEGEOM_BOUNDARY, &fgeom));
2830: PetscCall(PetscQuadratureDestroy(&qGeom));
2831: }
2832: PetscCall(PetscFree2(u, a));
2833: PetscCall(ISRestoreIndices(pointIS, &points));
2834: }
2835: if (plex) PetscCall(DMDestroy(&plex));
2836: if (plexA) PetscCall(DMDestroy(&plexA));
2837: PetscFunctionReturn(PETSC_SUCCESS);
2838: }
2840: /*@C
2841: DMPlexComputeBdIntegral - Form the integral over the specified boundary from the global input X using pointwise functions specified by the user
2843: Input Parameters:
2844: + dm - The mesh
2845: . X - Global input vector
2846: . label - The boundary `DMLabel`
2847: . numVals - The number of label values to use, or `PETSC_DETERMINE` for all values
2848: . vals - The label values to use, or NULL for all values
2849: . funcs - The functions to integrate along the boundary for each field
2850: - ctx - The application context
2852: Output Parameter:
2853: . integral - Integral for each field
2855: Level: developer
2857: .seealso: [](ch_unstructured), `DM`, `DMPLEX`, `DMPlexComputeIntegralFEM()`, `DMPlexComputeBdResidualFEM()`
2858: @*/
2859: PetscErrorCode DMPlexComputeBdIntegral(DM dm, Vec X, DMLabel label, PetscInt numVals, const PetscInt vals[], 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[]), PetscScalar *integral, PetscCtx ctx)
2860: {
2861: Vec locX;
2862: PetscSection section;
2863: DMLabel depthLabel;
2864: IS facetIS;
2865: PetscInt dim, Nf, f, v;
2867: PetscFunctionBegin;
2871: if (vals) PetscAssertPointer(vals, 5);
2872: PetscAssertPointer(integral, 7);
2873: PetscCall(PetscLogEventBegin(DMPLEX_IntegralFEM, dm, 0, 0, 0));
2874: PetscCall(DMPlexGetDepthLabel(dm, &depthLabel));
2875: PetscCall(DMGetDimension(dm, &dim));
2876: PetscCall(DMLabelGetStratumIS(depthLabel, dim - 1, &facetIS));
2877: /* Filter out ghost facets (SF leaves) so that each boundary facet is only
2878: counted on one rank. Without this, shared facets at partition boundaries
2879: are integrated on multiple ranks, causing double-counting after MPI sum. */
2880: if (facetIS) {
2881: PetscSF sf;
2882: PetscInt nleaves;
2883: const PetscInt *leaves;
2885: PetscCall(DMGetPointSF(dm, &sf));
2886: PetscCall(PetscSFGetGraph(sf, NULL, &nleaves, &leaves, NULL));
2887: if (nleaves > 0 && leaves) {
2888: IS leafIS, ownedFacetIS;
2890: PetscCall(ISCreateGeneral(PETSC_COMM_SELF, nleaves, leaves, PETSC_USE_POINTER, &leafIS));
2891: PetscCall(ISDifference(facetIS, leafIS, &ownedFacetIS));
2892: PetscCall(ISDestroy(&leafIS));
2893: PetscCall(ISDestroy(&facetIS));
2894: facetIS = ownedFacetIS;
2895: }
2896: }
2897: PetscCall(DMGetLocalSection(dm, §ion));
2898: PetscCall(PetscSectionGetNumFields(section, &Nf));
2899: /* Get local solution with boundary values */
2900: PetscCall(DMGetLocalVector(dm, &locX));
2901: PetscCall(DMPlexInsertBoundaryValues(dm, PETSC_TRUE, locX, 0.0, NULL, NULL, NULL));
2902: PetscCall(DMGlobalToLocalBegin(dm, X, INSERT_VALUES, locX));
2903: PetscCall(DMGlobalToLocalEnd(dm, X, INSERT_VALUES, locX));
2904: /* Loop over label values */
2905: PetscCall(PetscArrayzero(integral, Nf));
2906: for (v = 0; v < numVals; ++v) {
2907: IS pointIS;
2908: PetscInt numFaces, face;
2909: PetscScalar *fintegral;
2911: PetscCall(DMLabelGetStratumIS(label, vals[v], &pointIS));
2912: if (!pointIS) continue; /* No points with that id on this process */
2913: {
2914: IS isectIS;
2916: /* TODO: Special cases of ISIntersect where it is quick to check a priori if one is a superset of the other */
2917: PetscCall(ISIntersect_Caching_Internal(facetIS, pointIS, &isectIS));
2918: PetscCall(ISDestroy(&pointIS));
2919: pointIS = isectIS;
2920: }
2921: PetscCall(ISGetLocalSize(pointIS, &numFaces));
2922: PetscCall(PetscCalloc1(numFaces * Nf, &fintegral));
2923: PetscCall(DMPlexComputeBdIntegral_Internal(dm, locX, pointIS, funcs, fintegral, ctx));
2924: /* Sum point contributions into integral */
2925: for (f = 0; f < Nf; ++f)
2926: for (face = 0; face < numFaces; ++face) integral[f] += fintegral[face * Nf + f];
2927: PetscCall(PetscFree(fintegral));
2928: PetscCall(ISDestroy(&pointIS));
2929: }
2930: PetscCall(DMRestoreLocalVector(dm, &locX));
2931: PetscCall(ISDestroy(&facetIS));
2932: PetscCall(PetscLogEventEnd(DMPLEX_IntegralFEM, dm, 0, 0, 0));
2933: PetscFunctionReturn(PETSC_SUCCESS);
2934: }
2936: /*@
2937: DMPlexComputeInterpolatorNested - Form the local portion of the interpolation matrix from the coarse `DM` to a uniformly refined `DM`.
2939: Input Parameters:
2940: + dmc - The coarse mesh
2941: . dmf - The fine mesh
2942: . isRefined - Flag indicating regular refinement, rather than the same topology
2943: - ctx - The application context
2945: Output Parameter:
2946: . In - The interpolation matrix
2948: Level: developer
2950: .seealso: [](ch_unstructured), `DM`, `DMPLEX`, `DMPlexComputeInterpolatorGeneral()`
2951: @*/
2952: PetscErrorCode DMPlexComputeInterpolatorNested(DM dmc, DM dmf, PetscBool isRefined, Mat In, PetscCtx ctx)
2953: {
2954: DM_Plex *mesh = (DM_Plex *)dmc->data;
2955: const char *name = "Interpolator";
2956: PetscFE *feRef;
2957: PetscFV *fvRef;
2958: PetscSection fsection, fglobalSection;
2959: PetscSection csection, cglobalSection;
2960: PetscScalar *elemMat;
2961: PetscInt dim, Nf, f, fieldI, fieldJ, offsetI, offsetJ, cStart, cEnd, c;
2962: PetscInt cTotDim = 0, rTotDim = 0;
2964: PetscFunctionBegin;
2965: PetscCall(PetscLogEventBegin(DMPLEX_InterpolatorFEM, dmc, dmf, 0, 0));
2966: PetscCall(DMGetDimension(dmf, &dim));
2967: PetscCall(DMGetLocalSection(dmf, &fsection));
2968: PetscCall(DMGetGlobalSection(dmf, &fglobalSection));
2969: PetscCall(DMGetLocalSection(dmc, &csection));
2970: PetscCall(DMGetGlobalSection(dmc, &cglobalSection));
2971: PetscCall(PetscSectionGetNumFields(fsection, &Nf));
2972: PetscCall(DMPlexGetSimplexOrBoxCells(dmc, 0, &cStart, &cEnd));
2973: PetscCall(PetscCalloc2(Nf, &feRef, Nf, &fvRef));
2974: for (f = 0; f < Nf; ++f) {
2975: PetscObject obj, objc;
2976: PetscClassId id, idc;
2977: PetscInt rNb = 0, Nc = 0, cNb = 0;
2979: PetscCall(DMGetField(dmf, f, NULL, &obj));
2980: PetscCall(PetscObjectGetClassId(obj, &id));
2981: if (id == PETSCFE_CLASSID) {
2982: PetscFE fe = (PetscFE)obj;
2984: if (isRefined) PetscCall(PetscFERefine(fe, &feRef[f]));
2985: else {
2986: PetscCall(PetscObjectReference((PetscObject)fe));
2987: feRef[f] = fe;
2988: }
2989: PetscCall(PetscFEGetDimension(feRef[f], &rNb));
2990: PetscCall(PetscFEGetNumComponents(fe, &Nc));
2991: } else if (id == PETSCFV_CLASSID) {
2992: PetscFV fv = (PetscFV)obj;
2993: PetscDualSpace Q;
2995: if (isRefined) PetscCall(PetscFVRefine(fv, &fvRef[f]));
2996: else {
2997: PetscCall(PetscObjectReference((PetscObject)fv));
2998: fvRef[f] = fv;
2999: }
3000: PetscCall(PetscFVGetDualSpace(fvRef[f], &Q));
3001: PetscCall(PetscDualSpaceGetDimension(Q, &rNb));
3002: PetscCall(PetscFVGetDualSpace(fv, &Q));
3003: PetscCall(PetscFVGetNumComponents(fv, &Nc));
3004: }
3005: PetscCall(DMGetField(dmc, f, NULL, &objc));
3006: PetscCall(PetscObjectGetClassId(objc, &idc));
3007: if (idc == PETSCFE_CLASSID) {
3008: PetscFE fe = (PetscFE)objc;
3010: PetscCall(PetscFEGetDimension(fe, &cNb));
3011: } else if (id == PETSCFV_CLASSID) {
3012: PetscFV fv = (PetscFV)obj;
3013: PetscDualSpace Q;
3015: PetscCall(PetscFVGetDualSpace(fv, &Q));
3016: PetscCall(PetscDualSpaceGetDimension(Q, &cNb));
3017: }
3018: rTotDim += rNb;
3019: cTotDim += cNb;
3020: }
3021: PetscCall(PetscMalloc1(rTotDim * cTotDim, &elemMat));
3022: PetscCall(PetscArrayzero(elemMat, rTotDim * cTotDim));
3023: for (fieldI = 0, offsetI = 0; fieldI < Nf; ++fieldI) {
3024: PetscDualSpace Qref;
3025: PetscQuadrature f;
3026: const PetscReal *qpoints, *qweights;
3027: PetscReal *points;
3028: PetscInt npoints = 0, Nc, Np, fpdim, i, k, p, d;
3030: /* Compose points from all dual basis functionals */
3031: if (feRef[fieldI]) {
3032: PetscCall(PetscFEGetDualSpace(feRef[fieldI], &Qref));
3033: PetscCall(PetscFEGetNumComponents(feRef[fieldI], &Nc));
3034: } else {
3035: PetscCall(PetscFVGetDualSpace(fvRef[fieldI], &Qref));
3036: PetscCall(PetscFVGetNumComponents(fvRef[fieldI], &Nc));
3037: }
3038: PetscCall(PetscDualSpaceGetDimension(Qref, &fpdim));
3039: for (i = 0; i < fpdim; ++i) {
3040: PetscCall(PetscDualSpaceGetFunctional(Qref, i, &f));
3041: PetscCall(PetscQuadratureGetData(f, NULL, NULL, &Np, NULL, NULL));
3042: npoints += Np;
3043: }
3044: PetscCall(PetscMalloc1(npoints * dim, &points));
3045: for (i = 0, k = 0; i < fpdim; ++i) {
3046: PetscCall(PetscDualSpaceGetFunctional(Qref, i, &f));
3047: PetscCall(PetscQuadratureGetData(f, NULL, NULL, &Np, &qpoints, NULL));
3048: for (p = 0; p < Np; ++p, ++k)
3049: for (d = 0; d < dim; ++d) points[k * dim + d] = qpoints[p * dim + d];
3050: }
3052: for (fieldJ = 0, offsetJ = 0; fieldJ < Nf; ++fieldJ) {
3053: PetscObject obj;
3054: PetscClassId id;
3055: PetscInt NcJ = 0, cpdim = 0, j, qNc;
3057: PetscCall(DMGetField(dmc, fieldJ, NULL, &obj));
3058: PetscCall(PetscObjectGetClassId(obj, &id));
3059: if (id == PETSCFE_CLASSID) {
3060: PetscFE fe = (PetscFE)obj;
3061: PetscTabulation T = NULL;
3063: /* Evaluate basis at points */
3064: PetscCall(PetscFEGetNumComponents(fe, &NcJ));
3065: PetscCall(PetscFEGetDimension(fe, &cpdim));
3066: /* For now, fields only interpolate themselves */
3067: if (fieldI == fieldJ) {
3068: PetscCheck(Nc == NcJ, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Number of components in fine space field %" PetscInt_FMT " does not match coarse field %" PetscInt_FMT, Nc, NcJ);
3069: PetscCall(PetscFECreateTabulation(fe, 1, npoints, points, 0, &T));
3070: for (i = 0, k = 0; i < fpdim; ++i) {
3071: PetscCall(PetscDualSpaceGetFunctional(Qref, i, &f));
3072: PetscCall(PetscQuadratureGetData(f, NULL, &qNc, &Np, NULL, &qweights));
3073: PetscCheck(qNc == NcJ, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Number of components in quadrature %" PetscInt_FMT " does not match coarse field %" PetscInt_FMT, qNc, NcJ);
3074: for (p = 0; p < Np; ++p, ++k) {
3075: for (j = 0; j < cpdim; ++j) {
3076: /*
3077: cTotDim: Total columns in element interpolation matrix, sum of number of dual basis functionals in each field
3078: offsetI, offsetJ: Offsets into the larger element interpolation matrix for different fields
3079: fpdim, i, cpdim, j: Dofs for fine and coarse grids, correspond to dual space basis functionals
3080: qNC, Nc, Ncj, c: Number of components in this field
3081: Np, p: Number of quad points in the fine grid functional i
3082: k: i*Np + p, overall point number for the interpolation
3083: */
3084: for (c = 0; c < Nc; ++c) elemMat[(offsetI + i) * cTotDim + offsetJ + j] += T->T[0][k * cpdim * NcJ + j * Nc + c] * qweights[p * qNc + c];
3085: }
3086: }
3087: }
3088: PetscCall(PetscTabulationDestroy(&T));
3089: }
3090: } else if (id == PETSCFV_CLASSID) {
3091: PetscFV fv = (PetscFV)obj;
3093: /* Evaluate constant function at points */
3094: PetscCall(PetscFVGetNumComponents(fv, &NcJ));
3095: cpdim = 1;
3096: /* For now, fields only interpolate themselves */
3097: if (fieldI == fieldJ) {
3098: PetscCheck(Nc == NcJ, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Number of components in fine space field %" PetscInt_FMT " does not match coarse field %" PetscInt_FMT, Nc, NcJ);
3099: for (i = 0, k = 0; i < fpdim; ++i) {
3100: PetscCall(PetscDualSpaceGetFunctional(Qref, i, &f));
3101: PetscCall(PetscQuadratureGetData(f, NULL, &qNc, &Np, NULL, &qweights));
3102: PetscCheck(qNc == NcJ, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Number of components in quadrature %" PetscInt_FMT " does not match coarse field %" PetscInt_FMT, qNc, NcJ);
3103: for (p = 0; p < Np; ++p, ++k) {
3104: for (j = 0; j < cpdim; ++j) {
3105: for (c = 0; c < Nc; ++c) elemMat[(offsetI + i) * cTotDim + offsetJ + j] += 1.0 * qweights[p * qNc + c];
3106: }
3107: }
3108: }
3109: }
3110: }
3111: offsetJ += cpdim;
3112: }
3113: offsetI += fpdim;
3114: PetscCall(PetscFree(points));
3115: }
3116: if (mesh->printFEM > 1) PetscCall(DMPrintCellMatrix(0, name, rTotDim, cTotDim, elemMat));
3117: /* Preallocate matrix */
3118: {
3119: Mat preallocator;
3120: PetscScalar *vals;
3121: PetscInt *cellCIndices, *cellFIndices;
3122: PetscInt locRows, locCols, cell;
3124: PetscCall(MatGetLocalSize(In, &locRows, &locCols));
3125: PetscCall(MatCreate(PetscObjectComm((PetscObject)In), &preallocator));
3126: PetscCall(MatSetType(preallocator, MATPREALLOCATOR));
3127: PetscCall(MatSetSizes(preallocator, locRows, locCols, PETSC_DETERMINE, PETSC_DETERMINE));
3128: PetscCall(MatSetUp(preallocator));
3129: PetscCall(PetscCalloc3(rTotDim * cTotDim, &vals, cTotDim, &cellCIndices, rTotDim, &cellFIndices));
3130: if (locRows || locCols) {
3131: for (cell = cStart; cell < cEnd; ++cell) {
3132: if (isRefined) {
3133: PetscCall(DMPlexMatGetClosureIndicesRefined(dmf, fsection, fglobalSection, dmc, csection, cglobalSection, cell, cellCIndices, cellFIndices));
3134: PetscCall(MatSetValues(preallocator, rTotDim, cellFIndices, cTotDim, cellCIndices, vals, INSERT_VALUES));
3135: } else {
3136: PetscCall(DMPlexMatSetClosureGeneral(dmf, fsection, fglobalSection, PETSC_FALSE, dmc, csection, cglobalSection, PETSC_FALSE, preallocator, cell, vals, INSERT_VALUES));
3137: }
3138: }
3139: }
3140: PetscCall(PetscFree3(vals, cellCIndices, cellFIndices));
3141: PetscCall(MatAssemblyBegin(preallocator, MAT_FINAL_ASSEMBLY));
3142: PetscCall(MatAssemblyEnd(preallocator, MAT_FINAL_ASSEMBLY));
3143: PetscCall(MatPreallocatorPreallocate(preallocator, PETSC_TRUE, In));
3144: PetscCall(MatDestroy(&preallocator));
3145: }
3146: /* Fill matrix */
3147: PetscCall(MatZeroEntries(In));
3148: for (c = cStart; c < cEnd; ++c) {
3149: if (isRefined) {
3150: PetscCall(DMPlexMatSetClosureRefined(dmf, fsection, fglobalSection, dmc, csection, cglobalSection, In, c, elemMat, INSERT_VALUES));
3151: } else {
3152: PetscCall(DMPlexMatSetClosureGeneral(dmf, fsection, fglobalSection, PETSC_FALSE, dmc, csection, cglobalSection, PETSC_FALSE, In, c, elemMat, INSERT_VALUES));
3153: }
3154: }
3155: for (f = 0; f < Nf; ++f) PetscCall(PetscFEDestroy(&feRef[f]));
3156: PetscCall(PetscFree2(feRef, fvRef));
3157: PetscCall(PetscFree(elemMat));
3158: PetscCall(MatAssemblyBegin(In, MAT_FINAL_ASSEMBLY));
3159: PetscCall(MatAssemblyEnd(In, MAT_FINAL_ASSEMBLY));
3160: if (mesh->printFEM > 1) {
3161: PetscCall(PetscPrintf(PetscObjectComm((PetscObject)In), "%s:\n", name));
3162: PetscCall(MatFilter(In, 1.0e-10, PETSC_FALSE, PETSC_FALSE));
3163: PetscCall(MatView(In, NULL));
3164: }
3165: PetscCall(PetscLogEventEnd(DMPLEX_InterpolatorFEM, dmc, dmf, 0, 0));
3166: PetscFunctionReturn(PETSC_SUCCESS);
3167: }
3169: PetscErrorCode DMPlexComputeMassMatrixNested(DM dmc, DM dmf, Mat mass, PetscCtx ctx)
3170: {
3171: SETERRQ(PetscObjectComm((PetscObject)dmc), PETSC_ERR_SUP, "Laziness");
3172: }
3174: /*@
3175: DMPlexComputeInterpolatorGeneral - Form the local portion of the interpolation matrix from the coarse `DM` to a non-nested fine `DM`.
3177: Input Parameters:
3178: + dmf - The fine mesh
3179: . dmc - The coarse mesh
3180: - ctx - The application context
3182: Output Parameter:
3183: . In - The interpolation matrix
3185: Level: developer
3187: .seealso: [](ch_unstructured), `DM`, `DMPLEX`, `DMPlexComputeInterpolatorNested()`
3188: @*/
3189: PetscErrorCode DMPlexComputeInterpolatorGeneral(DM dmc, DM dmf, Mat In, PetscCtx ctx)
3190: {
3191: DM_Plex *mesh = (DM_Plex *)dmf->data;
3192: const char *name = "Interpolator";
3193: PetscDS prob;
3194: Mat interp;
3195: PetscSection fsection, globalFSection;
3196: PetscSection csection, globalCSection;
3197: PetscInt locRows, locCols;
3198: PetscReal *x, *v0, *J, *invJ, detJ;
3199: PetscReal *v0c, *Jc, *invJc, detJc;
3200: PetscScalar *elemMat;
3201: PetscInt dim, Nf, field, totDim, cStart, cEnd, cell, ccell, s;
3203: PetscFunctionBegin;
3204: PetscCall(PetscLogEventBegin(DMPLEX_InterpolatorFEM, dmc, dmf, 0, 0));
3205: PetscCall(DMGetCoordinateDim(dmc, &dim));
3206: PetscCall(DMGetDS(dmc, &prob));
3207: PetscCall(PetscDSGetWorkspace(prob, &x, NULL, NULL, NULL, NULL));
3208: PetscCall(PetscDSGetNumFields(prob, &Nf));
3209: PetscCall(PetscMalloc3(dim, &v0, dim * dim, &J, dim * dim, &invJ));
3210: PetscCall(PetscMalloc3(dim, &v0c, dim * dim, &Jc, dim * dim, &invJc));
3211: PetscCall(DMGetLocalSection(dmf, &fsection));
3212: PetscCall(DMGetGlobalSection(dmf, &globalFSection));
3213: PetscCall(DMGetLocalSection(dmc, &csection));
3214: PetscCall(DMGetGlobalSection(dmc, &globalCSection));
3215: PetscCall(DMPlexGetSimplexOrBoxCells(dmf, 0, &cStart, &cEnd));
3216: PetscCall(PetscDSGetTotalDimension(prob, &totDim));
3217: PetscCall(PetscMalloc1(totDim, &elemMat));
3219: PetscCall(MatGetLocalSize(In, &locRows, &locCols));
3220: PetscCall(MatCreate(PetscObjectComm((PetscObject)In), &interp));
3221: PetscCall(MatSetType(interp, MATPREALLOCATOR));
3222: PetscCall(MatSetSizes(interp, locRows, locCols, PETSC_DETERMINE, PETSC_DETERMINE));
3223: PetscCall(MatSetUp(interp));
3224: for (s = 0; s < 2; ++s) {
3225: for (field = 0; field < Nf; ++field) {
3226: PetscObject obj;
3227: PetscClassId id;
3228: PetscDualSpace Q = NULL;
3229: PetscTabulation T = NULL;
3230: PetscQuadrature f;
3231: const PetscReal *qpoints, *qweights;
3232: PetscInt Nc, qNc, Np, fpdim, off, i, d;
3234: PetscCall(PetscDSGetFieldOffset(prob, field, &off));
3235: PetscCall(PetscDSGetDiscretization(prob, field, &obj));
3236: PetscCall(PetscObjectGetClassId(obj, &id));
3237: if (id == PETSCFE_CLASSID) {
3238: PetscFE fe = (PetscFE)obj;
3240: PetscCall(PetscFEGetDualSpace(fe, &Q));
3241: PetscCall(PetscFEGetNumComponents(fe, &Nc));
3242: if (s) PetscCall(PetscFECreateTabulation(fe, 1, 1, x, 0, &T));
3243: } else if (id == PETSCFV_CLASSID) {
3244: PetscFV fv = (PetscFV)obj;
3246: PetscCall(PetscFVGetDualSpace(fv, &Q));
3247: Nc = 1;
3248: } else SETERRQ(PetscObjectComm((PetscObject)dmc), PETSC_ERR_ARG_WRONG, "Unknown discretization type for field %" PetscInt_FMT, field);
3249: PetscCall(PetscDualSpaceGetDimension(Q, &fpdim));
3250: /* For each fine grid cell */
3251: for (cell = cStart; cell < cEnd; ++cell) {
3252: PetscInt *findices, *cindices;
3253: PetscInt numFIndices, numCIndices;
3255: PetscCall(DMPlexGetClosureIndices(dmf, fsection, globalFSection, cell, PETSC_FALSE, &numFIndices, &findices, NULL, NULL));
3256: PetscCall(DMPlexComputeCellGeometryFEM(dmf, cell, NULL, v0, J, invJ, &detJ));
3257: PetscCheck(numFIndices == totDim, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Number of fine indices %" PetscInt_FMT " != %" PetscInt_FMT " dual basis vecs", numFIndices, totDim);
3258: for (i = 0; i < fpdim; ++i) {
3259: Vec pointVec;
3260: PetscScalar *pV;
3261: PetscSF coarseCellSF = NULL;
3262: const PetscSFNode *coarseCells;
3263: PetscInt numCoarseCells, cpdim, row = findices[i + off], q, c, j;
3265: /* Get points from the dual basis functional quadrature */
3266: PetscCall(PetscDualSpaceGetFunctional(Q, i, &f));
3267: PetscCall(PetscQuadratureGetData(f, NULL, &qNc, &Np, &qpoints, &qweights));
3268: PetscCheck(qNc == Nc, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Number of components in quadrature %" PetscInt_FMT " does not match coarse field %" PetscInt_FMT, qNc, Nc);
3269: PetscCall(VecCreateSeq(PETSC_COMM_SELF, Np * dim, &pointVec));
3270: PetscCall(VecSetBlockSize(pointVec, dim));
3271: PetscCall(VecGetArray(pointVec, &pV));
3272: for (q = 0; q < Np; ++q) {
3273: const PetscReal xi0[3] = {-1., -1., -1.};
3275: /* Transform point to real space */
3276: CoordinatesRefToReal(dim, dim, xi0, v0, J, &qpoints[q * dim], x);
3277: for (d = 0; d < dim; ++d) pV[q * dim + d] = x[d];
3278: }
3279: PetscCall(VecRestoreArray(pointVec, &pV));
3280: /* Get set of coarse cells that overlap points (would like to group points by coarse cell) */
3281: /* OPT: Read this out from preallocation information */
3282: PetscCall(DMLocatePoints(dmc, pointVec, DM_POINTLOCATION_NEAREST, &coarseCellSF));
3283: /* Update preallocation info */
3284: PetscCall(PetscSFGetGraph(coarseCellSF, NULL, &numCoarseCells, NULL, &coarseCells));
3285: PetscCheck(numCoarseCells == Np, PETSC_COMM_SELF, PETSC_ERR_PLIB, "Not all closure points located");
3286: PetscCall(VecGetArray(pointVec, &pV));
3287: for (ccell = 0; ccell < numCoarseCells; ++ccell) {
3288: PetscReal pVReal[3];
3289: const PetscReal xi0[3] = {-1., -1., -1.};
3291: PetscCall(DMPlexGetClosureIndices(dmc, csection, globalCSection, coarseCells[ccell].index, PETSC_FALSE, &numCIndices, &cindices, NULL, NULL));
3292: if (id == PETSCFE_CLASSID) PetscCall(PetscFEGetDimension((PetscFE)obj, &cpdim));
3293: else cpdim = 1;
3295: if (s) {
3296: /* Transform points from real space to coarse reference space */
3297: PetscCall(DMPlexComputeCellGeometryFEM(dmc, coarseCells[ccell].index, NULL, v0c, Jc, invJc, &detJc));
3298: for (d = 0; d < dim; ++d) pVReal[d] = PetscRealPart(pV[ccell * dim + d]);
3299: CoordinatesRealToRef(dim, dim, xi0, v0c, invJc, pVReal, x);
3301: if (id == PETSCFE_CLASSID) {
3302: /* Evaluate coarse basis on contained point */
3303: PetscCall(PetscFEComputeTabulation((PetscFE)obj, 1, x, 0, T));
3304: PetscCall(PetscArrayzero(elemMat, cpdim));
3305: /* Get elemMat entries by multiplying by weight */
3306: for (j = 0; j < cpdim; ++j) {
3307: for (c = 0; c < Nc; ++c) elemMat[j] += T->T[0][j * Nc + c] * qweights[ccell * qNc + c];
3308: }
3309: } else {
3310: for (j = 0; j < cpdim; ++j) {
3311: for (c = 0; c < Nc; ++c) elemMat[j] += 1.0 * qweights[ccell * qNc + c];
3312: }
3313: }
3314: if (mesh->printFEM > 1) PetscCall(DMPrintCellMatrix(cell, name, 1, numCIndices, elemMat));
3315: }
3316: /* Update interpolator */
3317: PetscCheck(numCIndices == totDim, PETSC_COMM_SELF, PETSC_ERR_PLIB, "Number of element matrix columns %" PetscInt_FMT " != %" PetscInt_FMT, numCIndices, totDim);
3318: PetscCall(MatSetValues(interp, 1, &row, cpdim, &cindices[off], elemMat, INSERT_VALUES));
3319: PetscCall(DMPlexRestoreClosureIndices(dmc, csection, globalCSection, coarseCells[ccell].index, PETSC_FALSE, &numCIndices, &cindices, NULL, NULL));
3320: }
3321: PetscCall(VecRestoreArray(pointVec, &pV));
3322: PetscCall(PetscSFDestroy(&coarseCellSF));
3323: PetscCall(VecDestroy(&pointVec));
3324: }
3325: PetscCall(DMPlexRestoreClosureIndices(dmf, fsection, globalFSection, cell, PETSC_FALSE, &numFIndices, &findices, NULL, NULL));
3326: }
3327: if (s && id == PETSCFE_CLASSID) PetscCall(PetscTabulationDestroy(&T));
3328: }
3329: if (!s) {
3330: PetscCall(MatAssemblyBegin(interp, MAT_FINAL_ASSEMBLY));
3331: PetscCall(MatAssemblyEnd(interp, MAT_FINAL_ASSEMBLY));
3332: PetscCall(MatPreallocatorPreallocate(interp, PETSC_TRUE, In));
3333: PetscCall(MatDestroy(&interp));
3334: interp = In;
3335: }
3336: }
3337: PetscCall(PetscFree3(v0, J, invJ));
3338: PetscCall(PetscFree3(v0c, Jc, invJc));
3339: PetscCall(PetscFree(elemMat));
3340: PetscCall(MatAssemblyBegin(In, MAT_FINAL_ASSEMBLY));
3341: PetscCall(MatAssemblyEnd(In, MAT_FINAL_ASSEMBLY));
3342: PetscCall(PetscLogEventEnd(DMPLEX_InterpolatorFEM, dmc, dmf, 0, 0));
3343: PetscFunctionReturn(PETSC_SUCCESS);
3344: }
3346: /*@
3347: DMPlexComputeMassMatrixGeneral - Form the local portion of the mass matrix from the coarse `DM` to a non-nested fine `DM`.
3349: Input Parameters:
3350: + dmf - The fine mesh
3351: . dmc - The coarse mesh
3352: - ctx - The application context
3354: Output Parameter:
3355: . mass - The mass matrix
3357: Level: developer
3359: .seealso: [](ch_unstructured), `DM`, `DMPLEX`, `DMPlexComputeMassMatrixNested()`, `DMPlexComputeInterpolatorNested()`, `DMPlexComputeInterpolatorGeneral()`
3360: @*/
3361: PetscErrorCode DMPlexComputeMassMatrixGeneral(DM dmc, DM dmf, Mat mass, PetscCtx ctx)
3362: {
3363: DM_Plex *mesh = (DM_Plex *)dmf->data;
3364: const char *name = "Mass Matrix";
3365: PetscDS prob;
3366: PetscSection fsection, csection, globalFSection, globalCSection;
3367: PetscHSetIJ ht;
3368: PetscLayout rLayout;
3369: PetscInt *dnz, *onz;
3370: PetscInt locRows, rStart, rEnd;
3371: PetscReal *x, *v0, *J, *invJ, detJ;
3372: PetscReal *v0c, *Jc, *invJc, detJc;
3373: PetscScalar *elemMat;
3374: PetscInt dim, Nf, field, totDim, cStart, cEnd, cell, ccell;
3376: PetscFunctionBegin;
3377: PetscCall(DMGetCoordinateDim(dmc, &dim));
3378: PetscCall(DMGetDS(dmc, &prob));
3379: PetscCall(PetscDSGetWorkspace(prob, &x, NULL, NULL, NULL, NULL));
3380: PetscCall(PetscDSGetNumFields(prob, &Nf));
3381: PetscCall(PetscMalloc3(dim, &v0, dim * dim, &J, dim * dim, &invJ));
3382: PetscCall(PetscMalloc3(dim, &v0c, dim * dim, &Jc, dim * dim, &invJc));
3383: PetscCall(DMGetLocalSection(dmf, &fsection));
3384: PetscCall(DMGetGlobalSection(dmf, &globalFSection));
3385: PetscCall(DMGetLocalSection(dmc, &csection));
3386: PetscCall(DMGetGlobalSection(dmc, &globalCSection));
3387: PetscCall(DMPlexGetHeightStratum(dmf, 0, &cStart, &cEnd));
3388: PetscCall(PetscDSGetTotalDimension(prob, &totDim));
3389: PetscCall(PetscMalloc1(totDim, &elemMat));
3391: PetscCall(MatGetLocalSize(mass, &locRows, NULL));
3392: PetscCall(PetscLayoutCreate(PetscObjectComm((PetscObject)mass), &rLayout));
3393: PetscCall(PetscLayoutSetLocalSize(rLayout, locRows));
3394: PetscCall(PetscLayoutSetBlockSize(rLayout, 1));
3395: PetscCall(PetscLayoutSetUp(rLayout));
3396: PetscCall(PetscLayoutGetRange(rLayout, &rStart, &rEnd));
3397: PetscCall(PetscLayoutDestroy(&rLayout));
3398: PetscCall(PetscCalloc2(locRows, &dnz, locRows, &onz));
3399: PetscCall(PetscHSetIJCreate(&ht));
3400: for (field = 0; field < Nf; ++field) {
3401: PetscObject obj;
3402: PetscClassId id;
3403: PetscQuadrature quad;
3404: const PetscReal *qpoints;
3405: PetscInt Nq, Nc, i, d;
3407: PetscCall(PetscDSGetDiscretization(prob, field, &obj));
3408: PetscCall(PetscObjectGetClassId(obj, &id));
3409: if (id == PETSCFE_CLASSID) PetscCall(PetscFEGetQuadrature((PetscFE)obj, &quad));
3410: else PetscCall(PetscFVGetQuadrature((PetscFV)obj, &quad));
3411: PetscCall(PetscQuadratureGetData(quad, NULL, &Nc, &Nq, &qpoints, NULL));
3412: /* For each fine grid cell */
3413: for (cell = cStart; cell < cEnd; ++cell) {
3414: Vec pointVec;
3415: PetscScalar *pV;
3416: PetscSF coarseCellSF = NULL;
3417: const PetscSFNode *coarseCells;
3418: PetscInt numCoarseCells, q, c;
3419: PetscInt *findices, *cindices;
3420: PetscInt numFIndices, numCIndices;
3422: PetscCall(DMPlexGetClosureIndices(dmf, fsection, globalFSection, cell, PETSC_FALSE, &numFIndices, &findices, NULL, NULL));
3423: PetscCall(DMPlexComputeCellGeometryFEM(dmf, cell, NULL, v0, J, invJ, &detJ));
3424: /* Get points from the quadrature */
3425: PetscCall(VecCreateSeq(PETSC_COMM_SELF, Nq * dim, &pointVec));
3426: PetscCall(VecSetBlockSize(pointVec, dim));
3427: PetscCall(VecGetArray(pointVec, &pV));
3428: for (q = 0; q < Nq; ++q) {
3429: const PetscReal xi0[3] = {-1., -1., -1.};
3431: /* Transform point to real space */
3432: CoordinatesRefToReal(dim, dim, xi0, v0, J, &qpoints[q * dim], x);
3433: for (d = 0; d < dim; ++d) pV[q * dim + d] = x[d];
3434: }
3435: PetscCall(VecRestoreArray(pointVec, &pV));
3436: /* Get set of coarse cells that overlap points (would like to group points by coarse cell) */
3437: PetscCall(DMLocatePoints(dmc, pointVec, DM_POINTLOCATION_NEAREST, &coarseCellSF));
3438: PetscCall(PetscSFViewFromOptions(coarseCellSF, NULL, "-interp_sf_view"));
3439: /* Update preallocation info */
3440: PetscCall(PetscSFGetGraph(coarseCellSF, NULL, &numCoarseCells, NULL, &coarseCells));
3441: PetscCheck(numCoarseCells == Nq, PETSC_COMM_SELF, PETSC_ERR_PLIB, "Not all closure points located");
3442: {
3443: PetscHashIJKey key;
3444: PetscBool missing;
3446: for (i = 0; i < numFIndices; ++i) {
3447: key.i = findices[i];
3448: if (key.i >= 0) {
3449: /* Get indices for coarse elements */
3450: for (ccell = 0; ccell < numCoarseCells; ++ccell) {
3451: PetscCall(DMPlexGetClosureIndices(dmc, csection, globalCSection, coarseCells[ccell].index, PETSC_FALSE, &numCIndices, &cindices, NULL, NULL));
3452: for (c = 0; c < numCIndices; ++c) {
3453: key.j = cindices[c];
3454: if (key.j < 0) continue;
3455: PetscCall(PetscHSetIJQueryAdd(ht, key, &missing));
3456: if (missing) {
3457: if ((key.j >= rStart) && (key.j < rEnd)) ++dnz[key.i - rStart];
3458: else ++onz[key.i - rStart];
3459: }
3460: }
3461: PetscCall(DMPlexRestoreClosureIndices(dmc, csection, globalCSection, coarseCells[ccell].index, PETSC_FALSE, &numCIndices, &cindices, NULL, NULL));
3462: }
3463: }
3464: }
3465: }
3466: PetscCall(PetscSFDestroy(&coarseCellSF));
3467: PetscCall(VecDestroy(&pointVec));
3468: PetscCall(DMPlexRestoreClosureIndices(dmf, fsection, globalFSection, cell, PETSC_FALSE, &numFIndices, &findices, NULL, NULL));
3469: }
3470: }
3471: PetscCall(PetscHSetIJDestroy(&ht));
3472: PetscCall(MatXAIJSetPreallocation(mass, 1, dnz, onz, NULL, NULL));
3473: PetscCall(MatSetOption(mass, MAT_NEW_NONZERO_ALLOCATION_ERR, PETSC_TRUE));
3474: PetscCall(PetscFree2(dnz, onz));
3475: for (field = 0; field < Nf; ++field) {
3476: PetscObject obj;
3477: PetscClassId id;
3478: PetscTabulation T, Tfine;
3479: PetscQuadrature quad;
3480: const PetscReal *qpoints, *qweights;
3481: PetscInt Nq, Nc, i, d;
3483: PetscCall(PetscDSGetDiscretization(prob, field, &obj));
3484: PetscCall(PetscObjectGetClassId(obj, &id));
3485: if (id == PETSCFE_CLASSID) {
3486: PetscCall(PetscFEGetQuadrature((PetscFE)obj, &quad));
3487: PetscCall(PetscFEGetCellTabulation((PetscFE)obj, 1, &Tfine));
3488: PetscCall(PetscFECreateTabulation((PetscFE)obj, 1, 1, x, 0, &T));
3489: } else {
3490: PetscCall(PetscFVGetQuadrature((PetscFV)obj, &quad));
3491: }
3492: PetscCall(PetscQuadratureGetData(quad, NULL, &Nc, &Nq, &qpoints, &qweights));
3493: /* For each fine grid cell */
3494: for (cell = cStart; cell < cEnd; ++cell) {
3495: Vec pointVec;
3496: PetscScalar *pV;
3497: PetscSF coarseCellSF = NULL;
3498: const PetscSFNode *coarseCells;
3499: PetscInt numCoarseCells, cpdim, q, c, j;
3500: PetscInt *findices, *cindices;
3501: PetscInt numFIndices, numCIndices;
3503: PetscCall(DMPlexGetClosureIndices(dmf, fsection, globalFSection, cell, PETSC_FALSE, &numFIndices, &findices, NULL, NULL));
3504: PetscCall(DMPlexComputeCellGeometryFEM(dmf, cell, NULL, v0, J, invJ, &detJ));
3505: /* Get points from the quadrature */
3506: PetscCall(VecCreateSeq(PETSC_COMM_SELF, Nq * dim, &pointVec));
3507: PetscCall(VecSetBlockSize(pointVec, dim));
3508: PetscCall(VecGetArray(pointVec, &pV));
3509: for (q = 0; q < Nq; ++q) {
3510: const PetscReal xi0[3] = {-1., -1., -1.};
3512: /* Transform point to real space */
3513: CoordinatesRefToReal(dim, dim, xi0, v0, J, &qpoints[q * dim], x);
3514: for (d = 0; d < dim; ++d) pV[q * dim + d] = x[d];
3515: }
3516: PetscCall(VecRestoreArray(pointVec, &pV));
3517: /* Get set of coarse cells that overlap points (would like to group points by coarse cell) */
3518: PetscCall(DMLocatePoints(dmc, pointVec, DM_POINTLOCATION_NEAREST, &coarseCellSF));
3519: /* Update matrix */
3520: PetscCall(PetscSFGetGraph(coarseCellSF, NULL, &numCoarseCells, NULL, &coarseCells));
3521: PetscCheck(numCoarseCells == Nq, PETSC_COMM_SELF, PETSC_ERR_PLIB, "Not all closure points located");
3522: PetscCall(VecGetArray(pointVec, &pV));
3523: for (ccell = 0; ccell < numCoarseCells; ++ccell) {
3524: PetscReal pVReal[3];
3525: const PetscReal xi0[3] = {-1., -1., -1.};
3527: PetscCall(DMPlexGetClosureIndices(dmc, csection, globalCSection, coarseCells[ccell].index, PETSC_FALSE, &numCIndices, &cindices, NULL, NULL));
3528: /* Transform points from real space to coarse reference space */
3529: PetscCall(DMPlexComputeCellGeometryFEM(dmc, coarseCells[ccell].index, NULL, v0c, Jc, invJc, &detJc));
3530: for (d = 0; d < dim; ++d) pVReal[d] = PetscRealPart(pV[ccell * dim + d]);
3531: CoordinatesRealToRef(dim, dim, xi0, v0c, invJc, pVReal, x);
3533: if (id == PETSCFE_CLASSID) {
3534: PetscFE fe = (PetscFE)obj;
3536: /* Evaluate coarse basis on contained point */
3537: PetscCall(PetscFEGetDimension(fe, &cpdim));
3538: PetscCall(PetscFEComputeTabulation(fe, 1, x, 0, T));
3539: /* Get elemMat entries by multiplying by weight */
3540: for (i = 0; i < numFIndices; ++i) {
3541: PetscCall(PetscArrayzero(elemMat, cpdim));
3542: for (j = 0; j < cpdim; ++j) {
3543: for (c = 0; c < Nc; ++c) elemMat[j] += T->T[0][j * Nc + c] * Tfine->T[0][(ccell * numFIndices + i) * Nc + c] * qweights[ccell * Nc + c] * detJ;
3544: }
3545: /* Update interpolator */
3546: if (mesh->printFEM > 1) PetscCall(DMPrintCellMatrix(cell, name, 1, numCIndices, elemMat));
3547: PetscCheck(numCIndices == cpdim, PETSC_COMM_SELF, PETSC_ERR_PLIB, "Number of element matrix columns %" PetscInt_FMT " != %" PetscInt_FMT, numCIndices, cpdim);
3548: PetscCall(MatSetValues(mass, 1, &findices[i], numCIndices, cindices, elemMat, ADD_VALUES));
3549: }
3550: } else {
3551: cpdim = 1;
3552: for (i = 0; i < numFIndices; ++i) {
3553: PetscCall(PetscArrayzero(elemMat, cpdim));
3554: for (j = 0; j < cpdim; ++j) {
3555: for (c = 0; c < Nc; ++c) elemMat[j] += 1.0 * 1.0 * qweights[ccell * Nc + c] * detJ;
3556: }
3557: /* Update interpolator */
3558: if (mesh->printFEM > 1) PetscCall(DMPrintCellMatrix(cell, name, 1, numCIndices, elemMat));
3559: PetscCall(PetscPrintf(PETSC_COMM_SELF, "Nq: %" PetscInt_FMT " %" PetscInt_FMT " Nf: %" PetscInt_FMT " %" PetscInt_FMT " Nc: %" PetscInt_FMT " %" PetscInt_FMT "\n", ccell, Nq, i, numFIndices, j, numCIndices));
3560: PetscCheck(numCIndices == cpdim, PETSC_COMM_SELF, PETSC_ERR_PLIB, "Number of element matrix columns %" PetscInt_FMT " != %" PetscInt_FMT, numCIndices, cpdim);
3561: PetscCall(MatSetValues(mass, 1, &findices[i], numCIndices, cindices, elemMat, ADD_VALUES));
3562: }
3563: }
3564: PetscCall(DMPlexRestoreClosureIndices(dmc, csection, globalCSection, coarseCells[ccell].index, PETSC_FALSE, &numCIndices, &cindices, NULL, NULL));
3565: }
3566: PetscCall(VecRestoreArray(pointVec, &pV));
3567: PetscCall(PetscSFDestroy(&coarseCellSF));
3568: PetscCall(VecDestroy(&pointVec));
3569: PetscCall(DMPlexRestoreClosureIndices(dmf, fsection, globalFSection, cell, PETSC_FALSE, &numFIndices, &findices, NULL, NULL));
3570: }
3571: if (id == PETSCFE_CLASSID) PetscCall(PetscTabulationDestroy(&T));
3572: }
3573: PetscCall(PetscFree3(v0, J, invJ));
3574: PetscCall(PetscFree3(v0c, Jc, invJc));
3575: PetscCall(PetscFree(elemMat));
3576: PetscCall(MatAssemblyBegin(mass, MAT_FINAL_ASSEMBLY));
3577: PetscCall(MatAssemblyEnd(mass, MAT_FINAL_ASSEMBLY));
3578: PetscFunctionReturn(PETSC_SUCCESS);
3579: }
3581: /*@
3582: DMPlexComputeInjectorFEM - Compute a mapping from coarse unknowns to fine unknowns
3584: Input Parameters:
3585: + dmc - The coarse mesh
3586: . dmf - The fine mesh
3587: - ctx - The application context
3589: Output Parameter:
3590: . sc - The mapping
3592: Level: developer
3594: .seealso: [](ch_unstructured), `DM`, `DMPLEX`, `DMPlexComputeInterpolatorNested()`
3595: @*/
3596: PetscErrorCode DMPlexComputeInjectorFEM(DM dmc, DM dmf, VecScatter *sc, PetscCtx ctx)
3597: {
3598: PetscDS prob;
3599: PetscFE *feRef;
3600: PetscFV *fvRef;
3601: Vec fv, cv;
3602: IS fis, cis;
3603: PetscSection fsection, fglobalSection, csection, cglobalSection;
3604: PetscInt *cmap, *cellCIndices, *cellFIndices, *cindices, *findices;
3605: PetscInt cTotDim, fTotDim = 0, Nf, f, field, cStart, cEnd, c, dim, d, startC, endC, offsetC, offsetF, m;
3606: PetscBool *needAvg;
3608: PetscFunctionBegin;
3609: PetscCall(PetscLogEventBegin(DMPLEX_InjectorFEM, dmc, dmf, 0, 0));
3610: PetscCall(DMGetDimension(dmf, &dim));
3611: PetscCall(DMGetLocalSection(dmf, &fsection));
3612: PetscCall(DMGetGlobalSection(dmf, &fglobalSection));
3613: PetscCall(DMGetLocalSection(dmc, &csection));
3614: PetscCall(DMGetGlobalSection(dmc, &cglobalSection));
3615: PetscCall(PetscSectionGetNumFields(fsection, &Nf));
3616: PetscCall(DMPlexGetSimplexOrBoxCells(dmc, 0, &cStart, &cEnd));
3617: PetscCall(DMGetDS(dmc, &prob));
3618: PetscCall(PetscCalloc3(Nf, &feRef, Nf, &fvRef, Nf, &needAvg));
3619: for (f = 0; f < Nf; ++f) {
3620: PetscObject obj;
3621: PetscClassId id;
3622: PetscInt fNb = 0, Nc = 0;
3624: PetscCall(PetscDSGetDiscretization(prob, f, &obj));
3625: PetscCall(PetscObjectGetClassId(obj, &id));
3626: if (id == PETSCFE_CLASSID) {
3627: PetscFE fe = (PetscFE)obj;
3628: PetscSpace sp;
3629: PetscInt maxDegree;
3631: PetscCall(PetscFERefine(fe, &feRef[f]));
3632: PetscCall(PetscFEGetDimension(feRef[f], &fNb));
3633: PetscCall(PetscFEGetNumComponents(fe, &Nc));
3634: PetscCall(PetscFEGetBasisSpace(fe, &sp));
3635: PetscCall(PetscSpaceGetDegree(sp, NULL, &maxDegree));
3636: if (!maxDegree) needAvg[f] = PETSC_TRUE;
3637: } else if (id == PETSCFV_CLASSID) {
3638: PetscFV fv = (PetscFV)obj;
3639: PetscDualSpace Q;
3641: PetscCall(PetscFVRefine(fv, &fvRef[f]));
3642: PetscCall(PetscFVGetDualSpace(fvRef[f], &Q));
3643: PetscCall(PetscDualSpaceGetDimension(Q, &fNb));
3644: PetscCall(PetscFVGetNumComponents(fv, &Nc));
3645: needAvg[f] = PETSC_TRUE;
3646: }
3647: fTotDim += fNb;
3648: }
3649: PetscCall(PetscDSGetTotalDimension(prob, &cTotDim));
3650: PetscCall(PetscMalloc1(cTotDim, &cmap));
3651: for (field = 0, offsetC = 0, offsetF = 0; field < Nf; ++field) {
3652: PetscFE feC;
3653: PetscFV fvC;
3654: PetscDualSpace QF, QC;
3655: PetscInt order = -1, NcF, NcC, fpdim, cpdim;
3657: if (feRef[field]) {
3658: PetscCall(PetscDSGetDiscretization(prob, field, (PetscObject *)&feC));
3659: PetscCall(PetscFEGetNumComponents(feC, &NcC));
3660: PetscCall(PetscFEGetNumComponents(feRef[field], &NcF));
3661: PetscCall(PetscFEGetDualSpace(feRef[field], &QF));
3662: PetscCall(PetscDualSpaceGetOrder(QF, &order));
3663: PetscCall(PetscDualSpaceGetDimension(QF, &fpdim));
3664: PetscCall(PetscFEGetDualSpace(feC, &QC));
3665: PetscCall(PetscDualSpaceGetDimension(QC, &cpdim));
3666: } else {
3667: PetscCall(PetscDSGetDiscretization(prob, field, (PetscObject *)&fvC));
3668: PetscCall(PetscFVGetNumComponents(fvC, &NcC));
3669: PetscCall(PetscFVGetNumComponents(fvRef[field], &NcF));
3670: PetscCall(PetscFVGetDualSpace(fvRef[field], &QF));
3671: PetscCall(PetscDualSpaceGetDimension(QF, &fpdim));
3672: PetscCall(PetscFVGetDualSpace(fvC, &QC));
3673: PetscCall(PetscDualSpaceGetDimension(QC, &cpdim));
3674: }
3675: PetscCheck(NcF == NcC, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Number of components in fine space field %" PetscInt_FMT " does not match coarse field %" PetscInt_FMT, NcF, NcC);
3676: for (c = 0; c < cpdim; ++c) {
3677: PetscQuadrature cfunc;
3678: const PetscReal *cqpoints, *cqweights;
3679: PetscInt NqcC, NpC;
3680: PetscBool found = PETSC_FALSE;
3682: PetscCall(PetscDualSpaceGetFunctional(QC, c, &cfunc));
3683: PetscCall(PetscQuadratureGetData(cfunc, NULL, &NqcC, &NpC, &cqpoints, &cqweights));
3684: PetscCheck(NqcC == NcC, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Number of quadrature components %" PetscInt_FMT " must match number of field components %" PetscInt_FMT, NqcC, NcC);
3685: PetscCheck(NpC == 1 || !feRef[field], PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Do not know how to do injection for moments");
3686: for (f = 0; f < fpdim; ++f) {
3687: PetscQuadrature ffunc;
3688: const PetscReal *fqpoints, *fqweights;
3689: PetscReal sum = 0.0;
3690: PetscInt NqcF, NpF;
3692: PetscCall(PetscDualSpaceGetFunctional(QF, f, &ffunc));
3693: PetscCall(PetscQuadratureGetData(ffunc, NULL, &NqcF, &NpF, &fqpoints, &fqweights));
3694: PetscCheck(NqcF == NcF, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Number of quadrature components %" PetscInt_FMT " must match number of field components %" PetscInt_FMT, NqcF, NcF);
3695: if (NpC != NpF) continue;
3696: for (d = 0; d < dim; ++d) sum += PetscAbsReal(cqpoints[d] - fqpoints[d]);
3697: if (sum > 1.0e-9) continue;
3698: for (d = 0; d < NcC; ++d) sum += PetscAbsReal(cqweights[d] * fqweights[d]);
3699: if (sum < 1.0e-9) continue;
3700: cmap[offsetC + c] = offsetF + f;
3701: found = PETSC_TRUE;
3702: break;
3703: }
3704: if (!found) {
3705: /* TODO We really want the average here, but some asshole put VecScatter in the interface */
3706: PetscCheck(fvRef[field] || (feRef[field] && order == 0), PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Could not locate matching functional for injection");
3707: cmap[offsetC + c] = offsetF + 0;
3708: }
3709: }
3710: offsetC += cpdim;
3711: offsetF += fpdim;
3712: }
3713: for (f = 0; f < Nf; ++f) {
3714: PetscCall(PetscFEDestroy(&feRef[f]));
3715: PetscCall(PetscFVDestroy(&fvRef[f]));
3716: }
3717: PetscCall(PetscFree3(feRef, fvRef, needAvg));
3719: PetscCall(DMGetGlobalVector(dmf, &fv));
3720: PetscCall(DMGetGlobalVector(dmc, &cv));
3721: PetscCall(VecGetOwnershipRange(cv, &startC, &endC));
3722: PetscCall(PetscSectionGetConstrainedStorageSize(cglobalSection, &m));
3723: PetscCall(PetscMalloc2(cTotDim, &cellCIndices, fTotDim, &cellFIndices));
3724: PetscCall(PetscMalloc1(m, &cindices));
3725: PetscCall(PetscMalloc1(m, &findices));
3726: for (d = 0; d < m; ++d) cindices[d] = findices[d] = -1;
3727: for (c = cStart; c < cEnd; ++c) {
3728: PetscCall(DMPlexMatGetClosureIndicesRefined(dmf, fsection, fglobalSection, dmc, csection, cglobalSection, c, cellCIndices, cellFIndices));
3729: for (d = 0; d < cTotDim; ++d) {
3730: if ((cellCIndices[d] < startC) || (cellCIndices[d] >= endC)) continue;
3731: PetscCheck(!(findices[cellCIndices[d] - startC] >= 0) || !(findices[cellCIndices[d] - startC] != cellFIndices[cmap[d]]), PETSC_COMM_SELF, PETSC_ERR_PLIB, "Cell %" PetscInt_FMT " Coarse dof %" PetscInt_FMT " maps to both %" PetscInt_FMT " and %" PetscInt_FMT, c, cindices[cellCIndices[d] - startC], findices[cellCIndices[d] - startC], cellFIndices[cmap[d]]);
3732: cindices[cellCIndices[d] - startC] = cellCIndices[d];
3733: findices[cellCIndices[d] - startC] = cellFIndices[cmap[d]];
3734: }
3735: }
3736: PetscCall(PetscFree(cmap));
3737: PetscCall(PetscFree2(cellCIndices, cellFIndices));
3739: PetscCall(ISCreateGeneral(PETSC_COMM_SELF, m, cindices, PETSC_OWN_POINTER, &cis));
3740: PetscCall(ISCreateGeneral(PETSC_COMM_SELF, m, findices, PETSC_OWN_POINTER, &fis));
3741: PetscCall(VecScatterCreate(cv, cis, fv, fis, sc));
3742: PetscCall(ISDestroy(&cis));
3743: PetscCall(ISDestroy(&fis));
3744: PetscCall(DMRestoreGlobalVector(dmf, &fv));
3745: PetscCall(DMRestoreGlobalVector(dmc, &cv));
3746: PetscCall(PetscLogEventEnd(DMPLEX_InjectorFEM, dmc, dmf, 0, 0));
3747: PetscFunctionReturn(PETSC_SUCCESS);
3748: }
3750: /*@C
3751: DMPlexGetCellFields - Retrieve the field values values for a chunk of cells
3753: Input Parameters:
3754: + dm - The `DM`
3755: . cellIS - The cells to include
3756: . locX - A local vector with the solution fields
3757: . locX_t - A local vector with solution field time derivatives, or `NULL`
3758: - locA - A local vector with auxiliary fields, or `NULL`
3760: Output Parameters:
3761: + u - The field coefficients
3762: . u_t - The fields derivative coefficients
3763: - a - The auxiliary field coefficients
3765: Level: developer
3767: .seealso: [](ch_unstructured), `DM`, `DMPLEX`, `DMPlexGetFaceFields()`
3768: @*/
3769: PetscErrorCode DMPlexGetCellFields(DM dm, IS cellIS, Vec locX, PeOp Vec locX_t, PeOp Vec locA, PetscScalar *u[], PetscScalar *u_t[], PetscScalar *a[])
3770: {
3771: DM plex, plexA = NULL;
3772: DMEnclosureType encAux;
3773: PetscSection section, sectionAux;
3774: PetscDS prob;
3775: const PetscInt *cells;
3776: PetscInt cStart, cEnd, numCells, totDim, totDimAux, c;
3778: PetscFunctionBegin;
3783: PetscAssertPointer(u, 6);
3784: PetscAssertPointer(u_t, 7);
3785: PetscAssertPointer(a, 8);
3786: PetscCall(DMPlexConvertPlex(dm, &plex, PETSC_FALSE));
3787: PetscCall(ISGetPointRange(cellIS, &cStart, &cEnd, &cells));
3788: PetscCall(DMGetLocalSection(dm, §ion));
3789: PetscCall(DMGetCellDS(dm, cells ? cells[cStart] : cStart, &prob, NULL));
3790: PetscCall(PetscDSGetTotalDimension(prob, &totDim));
3791: if (locA) {
3792: DM dmAux;
3793: PetscDS probAux;
3795: PetscCall(VecGetDM(locA, &dmAux));
3796: PetscCall(DMGetEnclosureRelation(dmAux, dm, &encAux));
3797: PetscCall(DMPlexConvertPlex(dmAux, &plexA, PETSC_FALSE));
3798: PetscCall(DMGetLocalSection(dmAux, §ionAux));
3799: PetscCall(DMGetDS(dmAux, &probAux));
3800: PetscCall(PetscDSGetTotalDimension(probAux, &totDimAux));
3801: }
3802: numCells = cEnd - cStart;
3803: PetscCall(DMGetWorkArray(dm, numCells * totDim, MPIU_SCALAR, u));
3804: if (locX_t) PetscCall(DMGetWorkArray(dm, numCells * totDim, MPIU_SCALAR, u_t));
3805: else *u_t = NULL;
3806: if (locA) PetscCall(DMGetWorkArray(dm, numCells * totDimAux, MPIU_SCALAR, a));
3807: else *a = NULL;
3808: for (c = cStart; c < cEnd; ++c) {
3809: const PetscInt cell = cells ? cells[c] : c;
3810: const PetscInt cind = c - cStart;
3811: PetscScalar *x = NULL, *x_t = NULL, *ul = *u, *ul_t = *u_t, *al = *a;
3812: PetscInt i;
3814: PetscCall(DMPlexVecGetClosure(plex, section, locX, cell, NULL, &x));
3815: for (i = 0; i < totDim; ++i) ul[cind * totDim + i] = x[i];
3816: PetscCall(DMPlexVecRestoreClosure(plex, section, locX, cell, NULL, &x));
3817: if (locX_t) {
3818: PetscCall(DMPlexVecGetClosure(plex, section, locX_t, cell, NULL, &x_t));
3819: for (i = 0; i < totDim; ++i) ul_t[cind * totDim + i] = x_t[i];
3820: PetscCall(DMPlexVecRestoreClosure(plex, section, locX_t, cell, NULL, &x_t));
3821: }
3822: if (locA) {
3823: PetscInt subcell;
3824: PetscCall(DMGetEnclosurePoint(plexA, dm, encAux, cell, &subcell));
3825: PetscCall(DMPlexVecGetClosure(plexA, sectionAux, locA, subcell, NULL, &x));
3826: for (i = 0; i < totDimAux; ++i) al[cind * totDimAux + i] = x[i];
3827: PetscCall(DMPlexVecRestoreClosure(plexA, sectionAux, locA, subcell, NULL, &x));
3828: }
3829: }
3830: PetscCall(DMDestroy(&plex));
3831: if (locA) PetscCall(DMDestroy(&plexA));
3832: PetscCall(ISRestorePointRange(cellIS, &cStart, &cEnd, &cells));
3833: PetscFunctionReturn(PETSC_SUCCESS);
3834: }
3836: /*@C
3837: DMPlexRestoreCellFields - Restore the field values values for a chunk of cells
3839: Input Parameters:
3840: + dm - The `DM`
3841: . cellIS - The cells to include
3842: . locX - A local vector with the solution fields
3843: . locX_t - A local vector with solution field time derivatives, or `NULL`
3844: - locA - A local vector with auxiliary fields, or `NULL`
3846: Output Parameters:
3847: + u - The field coefficients
3848: . u_t - The fields derivative coefficients
3849: - a - The auxiliary field coefficients
3851: Level: developer
3853: .seealso: [](ch_unstructured), `DM`, `DMPLEX`, `DMPlexGetFaceFields()`
3854: @*/
3855: PetscErrorCode DMPlexRestoreCellFields(DM dm, IS cellIS, Vec locX, PeOp Vec locX_t, PeOp Vec locA, PetscScalar *u[], PetscScalar *u_t[], PetscScalar *a[])
3856: {
3857: PetscFunctionBegin;
3858: PetscCall(DMRestoreWorkArray(dm, 0, MPIU_SCALAR, u));
3859: if (locX_t) PetscCall(DMRestoreWorkArray(dm, 0, MPIU_SCALAR, u_t));
3860: if (locA) PetscCall(DMRestoreWorkArray(dm, 0, MPIU_SCALAR, a));
3861: PetscFunctionReturn(PETSC_SUCCESS);
3862: }
3864: static PetscErrorCode DMPlexGetHybridCellFields(DM dm, IS cellIS, Vec locX, Vec locX_t, Vec locA, PetscScalar **u, PetscScalar **u_t, PetscScalar **a)
3865: {
3866: DM plex, plexA = NULL;
3867: DMEnclosureType encAux;
3868: PetscSection section, sectionAux;
3869: PetscDS ds, dsIn;
3870: const PetscInt *cells;
3871: PetscInt cStart, cEnd, numCells, c, totDim, totDimAux, Nf, f;
3873: PetscFunctionBegin;
3879: PetscAssertPointer(u, 6);
3880: PetscAssertPointer(u_t, 7);
3881: PetscAssertPointer(a, 8);
3882: PetscCall(ISGetPointRange(cellIS, &cStart, &cEnd, &cells));
3883: numCells = cEnd - cStart;
3884: PetscCall(DMPlexConvertPlex(dm, &plex, PETSC_FALSE));
3885: PetscCall(DMGetLocalSection(dm, §ion));
3886: PetscCall(DMGetCellDS(dm, cells ? cells[cStart] : cStart, &ds, &dsIn));
3887: PetscCall(PetscDSGetNumFields(dsIn, &Nf));
3888: PetscCall(PetscDSGetTotalDimension(dsIn, &totDim));
3889: if (locA) {
3890: DM dmAux;
3891: PetscDS probAux;
3893: PetscCall(VecGetDM(locA, &dmAux));
3894: PetscCall(DMGetEnclosureRelation(dmAux, dm, &encAux));
3895: PetscCall(DMPlexConvertPlex(dmAux, &plexA, PETSC_FALSE));
3896: PetscCall(DMGetLocalSection(dmAux, §ionAux));
3897: PetscCall(DMGetDS(dmAux, &probAux));
3898: PetscCall(PetscDSGetTotalDimension(probAux, &totDimAux));
3899: }
3900: PetscCall(DMGetWorkArray(dm, numCells * totDim, MPIU_SCALAR, u));
3901: if (locX_t) PetscCall(DMGetWorkArray(dm, numCells * totDim, MPIU_SCALAR, u_t));
3902: else {
3903: *u_t = NULL;
3904: }
3905: if (locA) PetscCall(DMGetWorkArray(dm, numCells * totDimAux, MPIU_SCALAR, a));
3906: else {
3907: *a = NULL;
3908: }
3909: // Loop over cohesive cells
3910: for (c = cStart; c < cEnd; ++c) {
3911: const PetscInt cell = cells ? cells[c] : c;
3912: const PetscInt cind = c - cStart;
3913: PetscScalar *xf = NULL, *xc = NULL, *x = NULL, *xf_t = NULL, *xc_t = NULL;
3914: PetscScalar *ul = &(*u)[cind * totDim], *ul_t = PetscSafePointerPlusOffset(*u_t, cind * totDim);
3915: const PetscInt *cone, *ornt;
3916: PetscInt Nx = 0, Nxf, s;
3918: PetscCall(DMPlexGetCone(dm, cell, &cone));
3919: PetscCall(DMPlexGetConeOrientation(dm, cell, &ornt));
3920: // Put in cohesive unknowns
3921: PetscCall(DMPlexVecGetClosure(plex, section, locX, cell, &Nxf, &xf));
3922: if (locX_t) PetscCall(DMPlexVecGetClosure(plex, section, locX_t, cell, NULL, &xf_t));
3923: for (f = 0; f < Nf; ++f) {
3924: PetscInt fdofIn, foff, foffIn;
3925: PetscBool cohesive;
3927: PetscCall(PetscDSGetCohesive(dsIn, f, &cohesive));
3928: if (!cohesive) continue;
3929: PetscCall(PetscDSGetFieldSize(dsIn, f, &fdofIn));
3930: PetscCall(PetscDSGetFieldOffsetCohesive(ds, f, &foff));
3931: PetscCall(PetscDSGetFieldOffsetCohesive(dsIn, f, &foffIn));
3932: for (PetscInt i = 0; i < fdofIn; ++i) ul[foffIn + i] = xf[foff + i];
3933: if (locX_t)
3934: for (PetscInt i = 0; i < fdofIn; ++i) ul_t[foffIn + i] = xf_t[foff + i];
3935: Nx += fdofIn;
3936: }
3937: PetscCall(DMPlexVecRestoreClosure(plex, section, locX, cell, &Nxf, &xf));
3938: if (locX_t) PetscCall(DMPlexVecRestoreClosure(plex, section, locX_t, cell, NULL, &xf_t));
3939: // Loop over sides of surface
3940: for (s = 0; s < 2; ++s) {
3941: const PetscInt *support;
3942: const PetscInt face = cone[s];
3943: PetscDS dsC;
3944: PetscInt ssize, ncell, Nxc;
3946: // I don't think I need the face to have 0 orientation in the hybrid cell
3947: //PetscCheck(!ornt[s], PETSC_COMM_SELF, PETSC_ERR_SUP, "Face %" PetscInt_FMT " in hybrid cell %" PetscInt_FMT " has orientation %" PetscInt_FMT " != 0", face, cell, ornt[s]);
3948: PetscCall(DMPlexGetSupport(dm, face, &support));
3949: PetscCall(DMPlexGetSupportSize(dm, face, &ssize));
3950: if (support[0] == cell) ncell = support[1];
3951: else if (support[1] == cell) ncell = support[0];
3952: else SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Face %" PetscInt_FMT " does not have cell %" PetscInt_FMT " in its support", face, cell);
3953: // Get closure of both face and cell, stick in cell for normal fields and face for cohesive fields
3954: PetscCall(DMGetCellDS(dm, ncell, &dsC, NULL));
3955: PetscCall(DMPlexVecGetClosure(plex, section, locX, ncell, &Nxc, &xc));
3956: if (locX_t) PetscCall(DMPlexVecGetClosure(plex, section, locX_t, ncell, NULL, &xc_t));
3957: for (f = 0; f < Nf; ++f) {
3958: PetscInt fdofIn, foffIn, foff;
3959: PetscBool cohesive;
3961: PetscCall(PetscDSGetCohesive(dsIn, f, &cohesive));
3962: if (cohesive) continue;
3963: PetscCall(PetscDSGetFieldSize(dsIn, f, &fdofIn));
3964: PetscCall(PetscDSGetFieldOffset(dsC, f, &foff));
3965: PetscCall(PetscDSGetFieldOffsetCohesive(dsIn, f, &foffIn));
3966: for (PetscInt i = 0; i < fdofIn; ++i) ul[foffIn + s * fdofIn + i] = xc[foff + i];
3967: if (locX_t)
3968: for (PetscInt i = 0; i < fdofIn; ++i) ul_t[foffIn + s * fdofIn + i] = xc_t[foff + i];
3969: Nx += fdofIn;
3970: }
3971: PetscCall(DMPlexVecRestoreClosure(plex, section, locX, ncell, &Nxc, &xc));
3972: if (locX_t) PetscCall(DMPlexVecRestoreClosure(plex, section, locX_t, ncell, NULL, &xc_t));
3973: }
3974: PetscCheck(Nx == totDim, PETSC_COMM_SELF, PETSC_ERR_ARG_INCOMP, "Closure size %" PetscInt_FMT " for cell %" PetscInt_FMT " does not match DS size %" PetscInt_FMT, Nx, cell, totDim);
3976: if (locA) {
3977: PetscScalar *al = &(*a)[cind * totDimAux];
3978: PetscInt subcell;
3980: PetscCall(DMGetEnclosurePoint(plexA, dm, encAux, cell, &subcell));
3981: PetscCall(DMPlexVecGetClosure(plexA, sectionAux, locA, subcell, &Nx, &x));
3982: PetscCheck(Nx == totDimAux, PETSC_COMM_SELF, PETSC_ERR_ARG_INCOMP, "Closure size %" PetscInt_FMT " for subcell %" PetscInt_FMT "does not match DS size %" PetscInt_FMT, Nx, subcell, totDimAux);
3983: for (PetscInt i = 0; i < totDimAux; ++i) al[i] = x[i];
3984: PetscCall(DMPlexVecRestoreClosure(plexA, sectionAux, locA, subcell, &Nx, &x));
3985: }
3986: }
3987: PetscCall(DMDestroy(&plex));
3988: PetscCall(DMDestroy(&plexA));
3989: PetscCall(ISRestorePointRange(cellIS, &cStart, &cEnd, &cells));
3990: PetscFunctionReturn(PETSC_SUCCESS);
3991: }
3993: /*
3994: DMPlexGetHybridFields - Get the field values for the negative side (s = 0) and positive side (s = 1) of the interface
3996: Input Parameters:
3997: + dm - The full domain DM
3998: . dmX - An array of DM for the field, say an auxiliary DM, indexed by s
3999: . dsX - An array of PetscDS for the field, indexed by s
4000: . cellIS - The interface cells for which we want values
4001: . locX - An array of local vectors with the field values, indexed by s
4002: - useCell - Flag to have values come from neighboring cell rather than endcap face
4004: Output Parameter:
4005: . x - An array of field values, indexed by s
4007: Note:
4008: The arrays in `x` will be allocated using `DMGetWorkArray()`, and must be returned using `DMPlexRestoreHybridFields()`.
4010: Level: advanced
4012: .seealso: `DMPlexRestoreHybridFields()`, `DMGetWorkArray()`
4013: */
4014: static PetscErrorCode DMPlexGetHybridFields(DM dm, DM dmX[], PetscDS dsX[], IS cellIS, Vec locX[], PetscBool useCell, PetscScalar *x[])
4015: {
4016: DM plexX[2];
4017: DMEnclosureType encX[2];
4018: PetscSection sectionX[2];
4019: const PetscInt *cells;
4020: PetscInt cStart, cEnd, numCells, c, s, totDimX[2];
4022: PetscFunctionBegin;
4023: PetscAssertPointer(locX, 5);
4024: if (!locX[0] || !locX[1]) PetscFunctionReturn(PETSC_SUCCESS);
4025: PetscAssertPointer(dmX, 2);
4026: PetscAssertPointer(dsX, 3);
4028: PetscAssertPointer(x, 7);
4029: PetscCall(ISGetPointRange(cellIS, &cStart, &cEnd, &cells));
4030: numCells = cEnd - cStart;
4031: for (s = 0; s < 2; ++s) {
4035: PetscCall(DMPlexConvertPlex(dmX[s], &plexX[s], PETSC_FALSE));
4036: PetscCall(DMGetEnclosureRelation(dmX[s], dm, &encX[s]));
4037: PetscCall(DMGetLocalSection(dmX[s], §ionX[s]));
4038: PetscCall(PetscDSGetTotalDimension(dsX[s], &totDimX[s]));
4039: PetscCall(DMGetWorkArray(dmX[s], numCells * totDimX[s], MPIU_SCALAR, &x[s]));
4040: }
4041: for (c = cStart; c < cEnd; ++c) {
4042: const PetscInt cell = cells ? cells[c] : c;
4043: const PetscInt cind = c - cStart;
4044: const PetscInt *cone, *ornt;
4046: PetscCall(DMPlexGetCone(dm, cell, &cone));
4047: PetscCall(DMPlexGetConeOrientation(dm, cell, &ornt));
4048: //PetscCheck(!ornt[0], PETSC_COMM_SELF, PETSC_ERR_SUP, "Face %" PetscInt_FMT " in hybrid cell %" PetscInt_FMT " has orientation %" PetscInt_FMT " != 0", cone[0], cell, ornt[0]);
4049: for (s = 0; s < 2; ++s) {
4050: const PetscInt tdX = totDimX[s];
4051: PetscScalar *closure = NULL, *xl = &x[s][cind * tdX];
4052: PetscInt face = cone[s], point = face, subpoint, Nx, i;
4054: if (useCell) {
4055: const PetscInt *support;
4056: PetscInt ssize;
4058: PetscCall(DMPlexGetSupport(dm, face, &support));
4059: PetscCall(DMPlexGetSupportSize(dm, face, &ssize));
4060: PetscCheck(ssize == 2, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Face %" PetscInt_FMT " from cell %" PetscInt_FMT " has support size %" PetscInt_FMT " != 2", face, cell, ssize);
4061: if (support[0] == cell) point = support[1];
4062: else if (support[1] == cell) point = support[0];
4063: else SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Face %" PetscInt_FMT " does not have cell %" PetscInt_FMT " in its support", face, cell);
4064: }
4065: PetscCall(DMGetEnclosurePoint(plexX[s], dm, encX[s], point, &subpoint));
4066: PetscCall(DMPlexVecGetOrientedClosure(plexX[s], sectionX[s], PETSC_FALSE, locX[s], subpoint, ornt[s], &Nx, &closure));
4067: PetscCheck(Nx == tdX, PETSC_COMM_SELF, PETSC_ERR_ARG_INCOMP, "Closure size %" PetscInt_FMT " for subpoint %" PetscInt_FMT " does not match DS size %" PetscInt_FMT, Nx, subpoint, tdX);
4068: for (i = 0; i < Nx; ++i) xl[i] = closure[i];
4069: PetscCall(DMPlexVecRestoreClosure(plexX[s], sectionX[s], locX[s], subpoint, &Nx, &closure));
4070: }
4071: }
4072: for (s = 0; s < 2; ++s) PetscCall(DMDestroy(&plexX[s]));
4073: PetscCall(ISRestorePointRange(cellIS, &cStart, &cEnd, &cells));
4074: PetscFunctionReturn(PETSC_SUCCESS);
4075: }
4077: static PetscErrorCode DMPlexRestoreHybridFields(DM dm, DM dmX[], PetscDS dsX[], IS cellIS, Vec locX[], PetscBool useCell, PetscScalar *x[])
4078: {
4079: PetscFunctionBegin;
4080: if (!locX[0] || !locX[1]) PetscFunctionReturn(PETSC_SUCCESS);
4081: PetscCall(DMRestoreWorkArray(dmX[0], 0, MPIU_SCALAR, &x[0]));
4082: PetscCall(DMRestoreWorkArray(dmX[1], 0, MPIU_SCALAR, &x[1]));
4083: PetscFunctionReturn(PETSC_SUCCESS);
4084: }
4086: /*@C
4087: DMPlexGetFaceFields - Retrieve the field values values for a chunk of faces
4089: Input Parameters:
4090: + dm - The `DM`
4091: . fStart - The first face to include
4092: . fEnd - The first face to exclude
4093: . locX - A local vector with the solution fields
4094: . locX_t - A local vector with solution field time derivatives, or `NULL`
4095: . faceGeometry - A local vector with face geometry
4096: . cellGeometry - A local vector with cell geometry
4097: - locGrad - A local vector with field gradients, or `NULL`
4099: Output Parameters:
4100: + Nface - The number of faces with field values
4101: . uL - The field values at the left side of the face
4102: - uR - The field values at the right side of the face
4104: Level: developer
4106: .seealso: [](ch_unstructured), `DM`, `DMPLEX`, `DMPlexGetCellFields()`
4107: @*/
4108: PetscErrorCode DMPlexGetFaceFields(DM dm, PetscInt fStart, PetscInt fEnd, Vec locX, PeOp Vec locX_t, Vec faceGeometry, Vec cellGeometry, PeOp Vec locGrad, PetscInt *Nface, PetscScalar *uL[], PetscScalar *uR[])
4109: {
4110: DM dmFace, dmCell, dmGrad = NULL;
4111: PetscSection section;
4112: PetscDS prob;
4113: DMLabel ghostLabel;
4114: const PetscScalar *facegeom, *cellgeom, *x, *lgrad;
4115: PetscBool *isFE;
4116: PetscInt dim, Nf, f, Nc, numFaces = fEnd - fStart, iface, face;
4118: PetscFunctionBegin;
4125: PetscAssertPointer(uL, 10);
4126: PetscAssertPointer(uR, 11);
4127: PetscCall(DMGetDimension(dm, &dim));
4128: PetscCall(DMGetDS(dm, &prob));
4129: PetscCall(DMGetLocalSection(dm, §ion));
4130: PetscCall(PetscDSGetNumFields(prob, &Nf));
4131: PetscCall(PetscDSGetTotalComponents(prob, &Nc));
4132: PetscCall(PetscMalloc1(Nf, &isFE));
4133: for (f = 0; f < Nf; ++f) {
4134: PetscObject obj;
4135: PetscClassId id;
4137: PetscCall(PetscDSGetDiscretization(prob, f, &obj));
4138: PetscCall(PetscObjectGetClassId(obj, &id));
4139: if (id == PETSCFE_CLASSID) {
4140: isFE[f] = PETSC_TRUE;
4141: } else if (id == PETSCFV_CLASSID) {
4142: isFE[f] = PETSC_FALSE;
4143: } else {
4144: isFE[f] = PETSC_FALSE;
4145: }
4146: }
4147: PetscCall(DMGetLabel(dm, "ghost", &ghostLabel));
4148: PetscCall(VecGetArrayRead(locX, &x));
4149: PetscCall(VecGetDM(faceGeometry, &dmFace));
4150: PetscCall(VecGetArrayRead(faceGeometry, &facegeom));
4151: PetscCall(VecGetDM(cellGeometry, &dmCell));
4152: PetscCall(VecGetArrayRead(cellGeometry, &cellgeom));
4153: if (locGrad) {
4154: PetscCall(VecGetDM(locGrad, &dmGrad));
4155: PetscCall(VecGetArrayRead(locGrad, &lgrad));
4156: }
4157: PetscCall(DMGetWorkArray(dm, numFaces * Nc, MPIU_SCALAR, uL));
4158: PetscCall(DMGetWorkArray(dm, numFaces * Nc, MPIU_SCALAR, uR));
4159: /* Right now just eat the extra work for FE (could make a cell loop) */
4160: for (face = fStart, iface = 0; face < fEnd; ++face) {
4161: const PetscInt *cells;
4162: PetscFVFaceGeom *fg;
4163: PetscFVCellGeom *cgL, *cgR;
4164: PetscScalar *xL, *xR, *gL, *gR;
4165: PetscScalar *uLl = *uL, *uRl = *uR;
4166: PetscInt ghost, nsupp, nchild;
4168: PetscCall(DMLabelGetValue(ghostLabel, face, &ghost));
4169: PetscCall(DMPlexGetSupportSize(dm, face, &nsupp));
4170: PetscCall(DMPlexGetTreeChildren(dm, face, &nchild, NULL));
4171: if (ghost >= 0 || nsupp > 2 || nchild > 0) continue;
4172: PetscCall(DMPlexPointLocalRead(dmFace, face, facegeom, &fg));
4173: PetscCall(DMPlexGetSupport(dm, face, &cells));
4174: PetscCall(DMPlexPointLocalRead(dmCell, cells[0], cellgeom, &cgL));
4175: PetscCall(DMPlexPointLocalRead(dmCell, cells[1], cellgeom, &cgR));
4176: for (f = 0; f < Nf; ++f) {
4177: PetscInt off;
4179: PetscCall(PetscDSGetComponentOffset(prob, f, &off));
4180: if (isFE[f]) {
4181: const PetscInt *cone;
4182: PetscInt comp, coneSizeL, coneSizeR, faceLocL, faceLocR, ldof, rdof, d;
4184: xL = xR = NULL;
4185: PetscCall(PetscSectionGetFieldComponents(section, f, &comp));
4186: PetscCall(DMPlexVecGetClosure(dm, section, locX, cells[0], &ldof, &xL));
4187: PetscCall(DMPlexVecGetClosure(dm, section, locX, cells[1], &rdof, &xR));
4188: PetscCall(DMPlexGetCone(dm, cells[0], &cone));
4189: PetscCall(DMPlexGetConeSize(dm, cells[0], &coneSizeL));
4190: for (faceLocL = 0; faceLocL < coneSizeL; ++faceLocL)
4191: if (cone[faceLocL] == face) break;
4192: PetscCall(DMPlexGetCone(dm, cells[1], &cone));
4193: PetscCall(DMPlexGetConeSize(dm, cells[1], &coneSizeR));
4194: for (faceLocR = 0; faceLocR < coneSizeR; ++faceLocR)
4195: if (cone[faceLocR] == face) break;
4196: PetscCheck(faceLocL != coneSizeL || faceLocR != coneSizeR, PETSC_COMM_SELF, PETSC_ERR_PLIB, "Could not find face %" PetscInt_FMT " in cone of cell %" PetscInt_FMT " or cell %" PetscInt_FMT, face, cells[0], cells[1]);
4197: /* Check that FEM field has values in the right cell (sometimes its an FV ghost cell) */
4198: /* TODO: this is a hack that might not be right for nonconforming */
4199: if (faceLocL < coneSizeL) {
4200: PetscCall(PetscFEEvaluateFaceFields_Internal(prob, f, faceLocL, xL, &uLl[iface * Nc + off]));
4201: if (rdof == ldof && faceLocR < coneSizeR) PetscCall(PetscFEEvaluateFaceFields_Internal(prob, f, faceLocR, xR, &uRl[iface * Nc + off]));
4202: else {
4203: for (d = 0; d < comp; ++d) uRl[iface * Nc + off + d] = uLl[iface * Nc + off + d];
4204: }
4205: } else {
4206: PetscCall(PetscFEEvaluateFaceFields_Internal(prob, f, faceLocR, xR, &uRl[iface * Nc + off]));
4207: PetscCall(PetscSectionGetFieldComponents(section, f, &comp));
4208: for (d = 0; d < comp; ++d) uLl[iface * Nc + off + d] = uRl[iface * Nc + off + d];
4209: }
4210: PetscCall(DMPlexVecRestoreClosure(dm, section, locX, cells[0], &ldof, &xL));
4211: PetscCall(DMPlexVecRestoreClosure(dm, section, locX, cells[1], &rdof, &xR));
4212: } else {
4213: PetscFV fv;
4214: PetscInt numComp, c;
4216: PetscCall(PetscDSGetDiscretization(prob, f, (PetscObject *)&fv));
4217: PetscCall(PetscFVGetNumComponents(fv, &numComp));
4218: PetscCall(DMPlexPointLocalFieldRead(dm, cells[0], f, x, &xL));
4219: PetscCall(DMPlexPointLocalFieldRead(dm, cells[1], f, x, &xR));
4220: if (dmGrad) {
4221: PetscReal dxL[3], dxR[3];
4223: PetscCall(DMPlexPointLocalRead(dmGrad, cells[0], lgrad, &gL));
4224: PetscCall(DMPlexPointLocalRead(dmGrad, cells[1], lgrad, &gR));
4225: DMPlex_WaxpyD_Internal(dim, -1, cgL->centroid, fg->centroid, dxL);
4226: DMPlex_WaxpyD_Internal(dim, -1, cgR->centroid, fg->centroid, dxR);
4227: for (c = 0; c < numComp; ++c) {
4228: uLl[iface * Nc + off + c] = xL[c] + DMPlex_DotD_Internal(dim, &gL[c * dim], dxL);
4229: uRl[iface * Nc + off + c] = xR[c] + DMPlex_DotD_Internal(dim, &gR[c * dim], dxR);
4230: }
4231: } else {
4232: for (c = 0; c < numComp; ++c) {
4233: uLl[iface * Nc + off + c] = xL[c];
4234: uRl[iface * Nc + off + c] = xR[c];
4235: }
4236: }
4237: }
4238: }
4239: ++iface;
4240: }
4241: *Nface = iface;
4242: PetscCall(VecRestoreArrayRead(locX, &x));
4243: PetscCall(VecRestoreArrayRead(faceGeometry, &facegeom));
4244: PetscCall(VecRestoreArrayRead(cellGeometry, &cellgeom));
4245: if (locGrad) PetscCall(VecRestoreArrayRead(locGrad, &lgrad));
4246: PetscCall(PetscFree(isFE));
4247: PetscFunctionReturn(PETSC_SUCCESS);
4248: }
4250: /*@C
4251: DMPlexRestoreFaceFields - Restore the field values values for a chunk of faces
4253: Input Parameters:
4254: + dm - The `DM`
4255: . fStart - The first face to include
4256: . fEnd - The first face to exclude
4257: . locX - A local vector with the solution fields
4258: . locX_t - A local vector with solution field time derivatives, or `NULL`
4259: . faceGeometry - A local vector with face geometry
4260: . cellGeometry - A local vector with cell geometry
4261: - locGrad - A local vector with field gradients, or `NULL`
4263: Output Parameters:
4264: + Nface - The number of faces with field values
4265: . uL - The field values at the left side of the face
4266: - uR - The field values at the right side of the face
4268: Level: developer
4270: .seealso: [](ch_unstructured), `DM`, `DMPLEX`, `DMPlexGetFaceFields()`
4271: @*/
4272: PetscErrorCode DMPlexRestoreFaceFields(DM dm, PetscInt fStart, PetscInt fEnd, Vec locX, PeOp Vec locX_t, Vec faceGeometry, Vec cellGeometry, PeOp Vec locGrad, PetscInt *Nface, PetscScalar *uL[], PetscScalar *uR[])
4273: {
4274: PetscFunctionBegin;
4275: PetscCall(DMRestoreWorkArray(dm, 0, MPIU_SCALAR, uL));
4276: PetscCall(DMRestoreWorkArray(dm, 0, MPIU_SCALAR, uR));
4277: PetscFunctionReturn(PETSC_SUCCESS);
4278: }
4280: /*@C
4281: DMPlexGetFaceGeometry - Retrieve the geometric values for a chunk of faces
4283: Input Parameters:
4284: + dm - The `DM`
4285: . fStart - The first face to include
4286: . fEnd - The first face to exclude
4287: . faceGeometry - A local vector with face geometry
4288: - cellGeometry - A local vector with cell geometry
4290: Output Parameters:
4291: + Nface - The number of faces with field values
4292: . fgeom - The face centroid and normals
4293: - vol - The cell volumes
4295: Level: developer
4297: .seealso: [](ch_unstructured), `DM`, `DMPLEX`, `DMPlexGetCellFields()`
4298: @*/
4299: PetscErrorCode DMPlexGetFaceGeometry(DM dm, PetscInt fStart, PetscInt fEnd, Vec faceGeometry, Vec cellGeometry, PetscInt *Nface, PetscFVFaceGeom *fgeom[], PetscReal *vol[])
4300: {
4301: DM dmFace, dmCell;
4302: DMLabel ghostLabel;
4303: const PetscScalar *facegeom, *cellgeom;
4304: PetscInt dim, numFaces = fEnd - fStart, iface, face;
4306: PetscFunctionBegin;
4310: PetscAssertPointer(fgeom, 7);
4311: PetscAssertPointer(vol, 8);
4312: PetscCall(DMGetDimension(dm, &dim));
4313: PetscCall(DMGetLabel(dm, "ghost", &ghostLabel));
4314: PetscCall(VecGetDM(faceGeometry, &dmFace));
4315: PetscCall(VecGetArrayRead(faceGeometry, &facegeom));
4316: PetscCall(VecGetDM(cellGeometry, &dmCell));
4317: PetscCall(VecGetArrayRead(cellGeometry, &cellgeom));
4318: PetscCall(PetscMalloc1(numFaces, fgeom));
4319: PetscCall(DMGetWorkArray(dm, numFaces * 2, MPIU_SCALAR, vol));
4320: for (face = fStart, iface = 0; face < fEnd; ++face) {
4321: const PetscInt *cells;
4322: PetscFVFaceGeom *fg;
4323: PetscFVCellGeom *cgL, *cgR;
4324: PetscFVFaceGeom *fgeoml = *fgeom;
4325: PetscReal *voll = *vol;
4326: PetscInt ghost, d, nchild, nsupp;
4328: PetscCall(DMLabelGetValue(ghostLabel, face, &ghost));
4329: PetscCall(DMPlexGetSupportSize(dm, face, &nsupp));
4330: PetscCall(DMPlexGetTreeChildren(dm, face, &nchild, NULL));
4331: if (ghost >= 0 || nsupp > 2 || nchild > 0) continue;
4332: PetscCall(DMPlexPointLocalRead(dmFace, face, facegeom, &fg));
4333: PetscCall(DMPlexGetSupport(dm, face, &cells));
4334: PetscCall(DMPlexPointLocalRead(dmCell, cells[0], cellgeom, &cgL));
4335: PetscCall(DMPlexPointLocalRead(dmCell, cells[1], cellgeom, &cgR));
4336: for (d = 0; d < dim; ++d) {
4337: fgeoml[iface].centroid[d] = fg->centroid[d];
4338: fgeoml[iface].normal[d] = fg->normal[d];
4339: }
4340: voll[iface * 2 + 0] = cgL->volume;
4341: voll[iface * 2 + 1] = cgR->volume;
4342: ++iface;
4343: }
4344: *Nface = iface;
4345: PetscCall(VecRestoreArrayRead(faceGeometry, &facegeom));
4346: PetscCall(VecRestoreArrayRead(cellGeometry, &cellgeom));
4347: PetscFunctionReturn(PETSC_SUCCESS);
4348: }
4350: /*@C
4351: DMPlexRestoreFaceGeometry - Restore the field values values for a chunk of faces
4353: Input Parameters:
4354: + dm - The `DM`
4355: . fStart - The first face to include
4356: . fEnd - The first face to exclude
4357: . faceGeometry - A local vector with face geometry
4358: - cellGeometry - A local vector with cell geometry
4360: Output Parameters:
4361: + Nface - The number of faces with field values
4362: . fgeom - The face centroid and normals
4363: - vol - The cell volumes
4365: Level: developer
4367: .seealso: [](ch_unstructured), `DM`, `DMPLEX`, `DMPlexGetFaceFields()`
4368: @*/
4369: PetscErrorCode DMPlexRestoreFaceGeometry(DM dm, PetscInt fStart, PetscInt fEnd, Vec faceGeometry, Vec cellGeometry, PetscInt *Nface, PetscFVFaceGeom *fgeom[], PetscReal *vol[])
4370: {
4371: PetscFunctionBegin;
4372: PetscCall(PetscFree(*fgeom));
4373: PetscCall(DMRestoreWorkArray(dm, 0, MPIU_REAL, vol));
4374: PetscFunctionReturn(PETSC_SUCCESS);
4375: }
4377: PetscErrorCode DMSNESGetFEGeom(DMField coordField, IS pointIS, PetscQuadrature quad, PetscFEGeomMode mode, PetscFEGeom **geom)
4378: {
4379: char composeStr[33] = {0};
4380: PetscObjectId id;
4381: PetscContainer container;
4383: PetscFunctionBegin;
4384: PetscCall(PetscObjectGetId((PetscObject)quad, &id));
4385: PetscCall(PetscSNPrintf(composeStr, 32, "DMSNESGetFEGeom_%" PetscInt64_FMT "\n", id));
4386: PetscCall(PetscObjectQuery((PetscObject)pointIS, composeStr, (PetscObject *)&container));
4387: if (container) {
4388: PetscCall(PetscContainerGetPointer(container, geom));
4389: } else {
4390: PetscCall(DMFieldCreateFEGeom(coordField, pointIS, quad, mode, geom));
4391: PetscCall(PetscContainerCreate(PETSC_COMM_SELF, &container));
4392: PetscCall(PetscContainerSetPointer(container, (void *)*geom));
4393: PetscCall(PetscContainerSetCtxDestroy(container, PetscContainerCtxDestroy_PetscFEGeom));
4394: PetscCall(PetscObjectCompose((PetscObject)pointIS, composeStr, (PetscObject)container));
4395: PetscCall(PetscContainerDestroy(&container));
4396: }
4397: PetscFunctionReturn(PETSC_SUCCESS);
4398: }
4400: PetscErrorCode DMSNESRestoreFEGeom(DMField coordField, IS pointIS, PetscQuadrature quad, PetscBool faceData, PetscFEGeom **geom)
4401: {
4402: PetscFunctionBegin;
4403: *geom = NULL;
4404: PetscFunctionReturn(PETSC_SUCCESS);
4405: }
4407: PetscErrorCode DMPlexComputeResidual_Patch_Internal(DM dm, PetscSection section, IS cellIS, PetscReal t, Vec locX, Vec locX_t, Vec locF, PetscCtx ctx)
4408: {
4409: DM_Plex *mesh = (DM_Plex *)dm->data;
4410: const char *name = "Residual";
4411: DM dmAux = NULL;
4412: DMLabel ghostLabel = NULL;
4413: PetscDS prob = NULL;
4414: PetscDS probAux = NULL;
4415: PetscBool useFEM = PETSC_FALSE;
4416: PetscBool isImplicit = (locX_t || t == PETSC_MIN_REAL) ? PETSC_TRUE : PETSC_FALSE;
4417: DMField coordField = NULL;
4418: Vec locA;
4419: PetscScalar *u = NULL, *u_t, *a, *uL = NULL, *uR = NULL;
4420: IS chunkIS;
4421: const PetscInt *cells;
4422: PetscInt cStart, cEnd, numCells;
4423: PetscInt Nf, f, totDim, totDimAux, numChunks, cellChunkSize, chunk, fStart, fEnd;
4424: PetscInt maxDegree = PETSC_INT_MAX;
4425: PetscFormKey key;
4426: PetscQuadrature affineQuad = NULL, *quads = NULL;
4427: PetscFEGeom *affineGeom = NULL, **geoms = NULL;
4429: PetscFunctionBegin;
4430: PetscCall(PetscLogEventBegin(DMPLEX_ResidualFEM, dm, 0, 0, 0));
4431: /* FEM+FVM */
4432: /* 1: Get sizes from dm and dmAux */
4433: PetscCall(DMGetLabel(dm, "ghost", &ghostLabel));
4434: PetscCall(DMGetDS(dm, &prob));
4435: PetscCall(PetscDSGetNumFields(prob, &Nf));
4436: PetscCall(PetscDSGetTotalDimension(prob, &totDim));
4437: PetscCall(DMGetAuxiliaryVec(dm, NULL, 0, 0, &locA));
4438: if (locA) {
4439: PetscCall(VecGetDM(locA, &dmAux));
4440: PetscCall(DMGetDS(dmAux, &probAux));
4441: PetscCall(PetscDSGetTotalDimension(probAux, &totDimAux));
4442: }
4443: /* 2: Get geometric data */
4444: for (f = 0; f < Nf; ++f) {
4445: PetscObject obj;
4446: PetscClassId id;
4447: PetscBool fimp;
4449: PetscCall(PetscDSGetImplicit(prob, f, &fimp));
4450: if (isImplicit != fimp) continue;
4451: PetscCall(PetscDSGetDiscretization(prob, f, &obj));
4452: PetscCall(PetscObjectGetClassId(obj, &id));
4453: if (id == PETSCFE_CLASSID) useFEM = PETSC_TRUE;
4454: PetscCheck(id != PETSCFV_CLASSID, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Use of FVM with PCPATCH not yet implemented");
4455: }
4456: if (useFEM) {
4457: PetscCall(DMGetCoordinateField(dm, &coordField));
4458: PetscCall(DMFieldGetDegree(coordField, cellIS, NULL, &maxDegree));
4459: if (maxDegree <= 1) {
4460: PetscCall(DMFieldCreateDefaultQuadrature(coordField, cellIS, &affineQuad));
4461: if (affineQuad) PetscCall(DMSNESGetFEGeom(coordField, cellIS, affineQuad, PETSC_FEGEOM_BASIC, &affineGeom));
4462: } else {
4463: PetscCall(PetscCalloc2(Nf, &quads, Nf, &geoms));
4464: for (f = 0; f < Nf; ++f) {
4465: PetscObject obj;
4466: PetscClassId id;
4467: PetscBool fimp;
4469: PetscCall(PetscDSGetImplicit(prob, f, &fimp));
4470: if (isImplicit != fimp) continue;
4471: PetscCall(PetscDSGetDiscretization(prob, f, &obj));
4472: PetscCall(PetscObjectGetClassId(obj, &id));
4473: if (id == PETSCFE_CLASSID) {
4474: PetscFE fe = (PetscFE)obj;
4476: PetscCall(PetscFEGetQuadrature(fe, &quads[f]));
4477: PetscCall(PetscObjectReference((PetscObject)quads[f]));
4478: PetscCall(DMSNESGetFEGeom(coordField, cellIS, quads[f], PETSC_FEGEOM_BASIC, &geoms[f]));
4479: }
4480: }
4481: }
4482: }
4483: /* Loop over chunks */
4484: PetscCall(ISGetPointRange(cellIS, &cStart, &cEnd, &cells));
4485: PetscCall(DMPlexGetHeightStratum(dm, 1, &fStart, &fEnd));
4486: if (useFEM) PetscCall(ISCreate(PETSC_COMM_SELF, &chunkIS));
4487: numCells = cEnd - cStart;
4488: numChunks = 1;
4489: cellChunkSize = numCells / numChunks;
4490: numChunks = PetscMin(1, numCells);
4491: key.label = NULL;
4492: key.value = 0;
4493: key.part = 0;
4494: for (chunk = 0; chunk < numChunks; ++chunk) {
4495: PetscScalar *elemVec, *fluxL = NULL, *fluxR = NULL;
4496: PetscReal *vol = NULL;
4497: PetscFVFaceGeom *fgeom = NULL;
4498: PetscInt cS = cStart + chunk * cellChunkSize, cE = PetscMin(cS + cellChunkSize, cEnd), numCells = cE - cS, c;
4499: PetscInt numFaces = 0;
4501: /* Extract field coefficients */
4502: if (useFEM) {
4503: PetscCall(ISGetPointSubrange(chunkIS, cS, cE, cells));
4504: PetscCall(DMPlexGetCellFields(dm, chunkIS, locX, locX_t, locA, &u, &u_t, &a));
4505: PetscCall(DMGetWorkArray(dm, numCells * totDim, MPIU_SCALAR, &elemVec));
4506: PetscCall(PetscArrayzero(elemVec, numCells * totDim));
4507: }
4508: /* TODO We will interlace both our field coefficients (u, u_t, uL, uR, etc.) and our output (elemVec, fL, fR). I think this works */
4509: /* Loop over fields */
4510: for (f = 0; f < Nf; ++f) {
4511: PetscObject obj;
4512: PetscClassId id;
4513: PetscBool fimp;
4514: PetscInt numChunks, numBatches, batchSize, numBlocks, blockSize, Ne, Nr, offset;
4516: key.field = f;
4517: PetscCall(PetscDSGetImplicit(prob, f, &fimp));
4518: if (isImplicit != fimp) continue;
4519: PetscCall(PetscDSGetDiscretization(prob, f, &obj));
4520: PetscCall(PetscObjectGetClassId(obj, &id));
4521: if (id == PETSCFE_CLASSID) {
4522: PetscFE fe = (PetscFE)obj;
4523: PetscFEGeom *geom = affineGeom ? affineGeom : geoms[f];
4524: PetscFEGeom *chunkGeom = NULL;
4525: PetscQuadrature quad = affineQuad ? affineQuad : quads[f];
4526: PetscInt Nq, Nb;
4528: PetscCall(PetscFEGetTileSizes(fe, NULL, &numBlocks, NULL, &numBatches));
4529: PetscCall(PetscQuadratureGetData(quad, NULL, NULL, &Nq, NULL, NULL));
4530: PetscCall(PetscFEGetDimension(fe, &Nb));
4531: blockSize = Nb;
4532: batchSize = numBlocks * blockSize;
4533: PetscCall(PetscFESetTileSizes(fe, blockSize, numBlocks, batchSize, numBatches));
4534: numChunks = numCells / (numBatches * batchSize);
4535: Ne = numChunks * numBatches * batchSize;
4536: Nr = numCells % (numBatches * batchSize);
4537: offset = numCells - Nr;
4538: /* Integrate FE residual to get elemVec (need fields at quadrature points) */
4539: /* For FV, I think we use a P0 basis and the cell coefficients (for subdivided cells, we can tweak the basis tabulation to be the indicator function) */
4540: PetscCall(PetscFEGeomGetChunk(geom, 0, offset, &chunkGeom));
4541: PetscCall(PetscFEIntegrateResidual(prob, key, Ne, chunkGeom, u, u_t, probAux, a, t, elemVec));
4542: PetscCall(PetscFEGeomGetChunk(geom, offset, numCells, &chunkGeom));
4543: PetscCall(PetscFEIntegrateResidual(prob, key, Nr, chunkGeom, &u[offset * totDim], PetscSafePointerPlusOffset(u_t, offset * totDim), probAux, &a[offset * totDimAux], t, &elemVec[offset * totDim]));
4544: PetscCall(PetscFEGeomRestoreChunk(geom, offset, numCells, &chunkGeom));
4545: } else if (id == PETSCFV_CLASSID) {
4546: PetscFV fv = (PetscFV)obj;
4548: Ne = numFaces;
4549: /* Riemann solve over faces (need fields at face centroids) */
4550: /* We need to evaluate FE fields at those coordinates */
4551: PetscCall(PetscFVIntegrateRHSFunction(fv, prob, f, Ne, fgeom, vol, uL, uR, fluxL, fluxR));
4552: } else SETERRQ(PetscObjectComm((PetscObject)dm), PETSC_ERR_ARG_WRONG, "Unknown discretization type for field %" PetscInt_FMT, f);
4553: }
4554: /* Loop over domain */
4555: if (useFEM) {
4556: /* Add elemVec to locX */
4557: for (c = cS; c < cE; ++c) {
4558: const PetscInt cell = cells ? cells[c] : c;
4559: const PetscInt cind = c - cStart;
4561: if (mesh->printFEM > 1) PetscCall(DMPrintCellVector(cell, name, totDim, &elemVec[cind * totDim]));
4562: if (ghostLabel) {
4563: PetscInt ghostVal;
4565: PetscCall(DMLabelGetValue(ghostLabel, cell, &ghostVal));
4566: if (ghostVal > 0) continue;
4567: }
4568: PetscCall(DMPlexVecSetClosure(dm, section, locF, cell, &elemVec[cind * totDim], ADD_ALL_VALUES));
4569: }
4570: }
4571: /* Handle time derivative */
4572: if (locX_t) {
4573: PetscScalar *x_t, *fa;
4575: PetscCall(VecGetArray(locF, &fa));
4576: PetscCall(VecGetArray(locX_t, &x_t));
4577: for (f = 0; f < Nf; ++f) {
4578: PetscFV fv;
4579: PetscObject obj;
4580: PetscClassId id;
4581: PetscInt pdim, d;
4583: PetscCall(PetscDSGetDiscretization(prob, f, &obj));
4584: PetscCall(PetscObjectGetClassId(obj, &id));
4585: if (id != PETSCFV_CLASSID) continue;
4586: fv = (PetscFV)obj;
4587: PetscCall(PetscFVGetNumComponents(fv, &pdim));
4588: for (c = cS; c < cE; ++c) {
4589: const PetscInt cell = cells ? cells[c] : c;
4590: PetscScalar *u_t, *r;
4592: if (ghostLabel) {
4593: PetscInt ghostVal;
4595: PetscCall(DMLabelGetValue(ghostLabel, cell, &ghostVal));
4596: if (ghostVal > 0) continue;
4597: }
4598: PetscCall(DMPlexPointLocalFieldRead(dm, cell, f, x_t, &u_t));
4599: PetscCall(DMPlexPointLocalFieldRef(dm, cell, f, fa, &r));
4600: for (d = 0; d < pdim; ++d) r[d] += u_t[d];
4601: }
4602: }
4603: PetscCall(VecRestoreArray(locX_t, &x_t));
4604: PetscCall(VecRestoreArray(locF, &fa));
4605: }
4606: if (useFEM) {
4607: PetscCall(DMPlexRestoreCellFields(dm, chunkIS, locX, locX_t, locA, &u, &u_t, &a));
4608: PetscCall(DMRestoreWorkArray(dm, numCells * totDim, MPIU_SCALAR, &elemVec));
4609: }
4610: }
4611: if (useFEM) PetscCall(ISDestroy(&chunkIS));
4612: PetscCall(ISRestorePointRange(cellIS, &cStart, &cEnd, &cells));
4613: /* TODO Could include boundary residual here (see DMPlexComputeResidualByKey) */
4614: if (useFEM) {
4615: if (maxDegree <= 1) {
4616: PetscCall(DMSNESRestoreFEGeom(coordField, cellIS, affineQuad, PETSC_FALSE, &affineGeom));
4617: PetscCall(PetscQuadratureDestroy(&affineQuad));
4618: } else {
4619: for (f = 0; f < Nf; ++f) {
4620: PetscCall(DMSNESRestoreFEGeom(coordField, cellIS, quads[f], PETSC_FALSE, &geoms[f]));
4621: PetscCall(PetscQuadratureDestroy(&quads[f]));
4622: }
4623: PetscCall(PetscFree2(quads, geoms));
4624: }
4625: }
4626: PetscCall(PetscLogEventEnd(DMPLEX_ResidualFEM, dm, 0, 0, 0));
4627: PetscFunctionReturn(PETSC_SUCCESS);
4628: }
4630: /*
4631: We always assemble JacP, and if the matrix is different from Jac and two different sets of point functions are provided, we also assemble Jac
4633: X - The local solution vector
4634: X_t - The local solution time derivative vector, or NULL
4635: */
4636: PetscErrorCode DMPlexComputeJacobian_Patch_Internal(DM dm, PetscSection section, PetscSection globalSection, IS cellIS, PetscReal t, PetscReal X_tShift, Vec X, Vec X_t, Mat Jac, Mat JacP, PetscCtx ctx)
4637: {
4638: DM_Plex *mesh = (DM_Plex *)dm->data;
4639: const char *name = "Jacobian", *nameP = "JacobianPre";
4640: DM dmAux = NULL;
4641: PetscDS prob, probAux = NULL;
4642: PetscSection sectionAux = NULL;
4643: Vec A;
4644: DMField coordField;
4645: PetscFEGeom *cgeomFEM;
4646: PetscQuadrature qGeom = NULL;
4647: Mat J = Jac, JP = JacP;
4648: PetscScalar *work, *u = NULL, *u_t = NULL, *a = NULL, *elemMat = NULL, *elemMatP = NULL, *elemMatD = NULL;
4649: PetscBool hasJac, hasPrec, hasDyn, assembleJac, *isFE, hasFV = PETSC_FALSE;
4650: const PetscInt *cells;
4651: PetscFormKey key;
4652: PetscInt Nf, fieldI, fieldJ, maxDegree, numCells, cStart, cEnd, numChunks, chunkSize, chunk, totDim, totDimAux = 0, sz, wsz, off = 0, offCell = 0;
4654: PetscFunctionBegin;
4655: PetscCall(ISGetLocalSize(cellIS, &numCells));
4656: PetscCall(ISGetPointRange(cellIS, &cStart, &cEnd, &cells));
4657: PetscCall(PetscLogEventBegin(DMPLEX_JacobianFEM, dm, 0, 0, 0));
4658: PetscCall(DMGetDS(dm, &prob));
4659: PetscCall(DMGetAuxiliaryVec(dm, NULL, 0, 0, &A));
4660: if (A) {
4661: PetscCall(VecGetDM(A, &dmAux));
4662: PetscCall(DMGetLocalSection(dmAux, §ionAux));
4663: PetscCall(DMGetDS(dmAux, &probAux));
4664: }
4665: /* Get flags */
4666: PetscCall(PetscDSGetNumFields(prob, &Nf));
4667: PetscCall(DMGetWorkArray(dm, Nf, MPI_C_BOOL, &isFE));
4668: for (fieldI = 0; fieldI < Nf; ++fieldI) {
4669: PetscObject disc;
4670: PetscClassId id;
4671: PetscCall(PetscDSGetDiscretization(prob, fieldI, &disc));
4672: PetscCall(PetscObjectGetClassId(disc, &id));
4673: if (id == PETSCFE_CLASSID) {
4674: isFE[fieldI] = PETSC_TRUE;
4675: } else if (id == PETSCFV_CLASSID) {
4676: hasFV = PETSC_TRUE;
4677: isFE[fieldI] = PETSC_FALSE;
4678: }
4679: }
4680: PetscCall(PetscDSHasJacobian(prob, &hasJac));
4681: PetscCall(PetscDSHasJacobianPreconditioner(prob, &hasPrec));
4682: PetscCall(PetscDSHasDynamicJacobian(prob, &hasDyn));
4683: assembleJac = hasJac && hasPrec && (Jac != JacP) ? PETSC_TRUE : PETSC_FALSE;
4684: hasDyn = hasDyn && (X_tShift != 0.0) ? PETSC_TRUE : PETSC_FALSE;
4685: if (hasFV) PetscCall(MatSetOption(JP, MAT_IGNORE_ZERO_ENTRIES, PETSC_TRUE)); /* No allocated space for FV stuff, so ignore the zero entries */
4686: PetscCall(PetscDSGetTotalDimension(prob, &totDim));
4687: if (probAux) PetscCall(PetscDSGetTotalDimension(probAux, &totDimAux));
4688: /* Compute batch sizes */
4689: if (isFE[0]) {
4690: PetscFE fe;
4691: PetscQuadrature q;
4692: PetscInt numQuadPoints, numBatches, batchSize, numBlocks, blockSize, Nb;
4694: PetscCall(PetscDSGetDiscretization(prob, 0, (PetscObject *)&fe));
4695: PetscCall(PetscFEGetQuadrature(fe, &q));
4696: PetscCall(PetscQuadratureGetData(q, NULL, NULL, &numQuadPoints, NULL, NULL));
4697: PetscCall(PetscFEGetDimension(fe, &Nb));
4698: PetscCall(PetscFEGetTileSizes(fe, NULL, &numBlocks, NULL, &numBatches));
4699: blockSize = Nb * numQuadPoints;
4700: batchSize = numBlocks * blockSize;
4701: chunkSize = numBatches * batchSize;
4702: numChunks = numCells / chunkSize + numCells % chunkSize;
4703: PetscCall(PetscFESetTileSizes(fe, blockSize, numBlocks, batchSize, numBatches));
4704: } else {
4705: chunkSize = numCells;
4706: numChunks = 1;
4707: }
4708: /* Get work space */
4709: wsz = (((X ? 1 : 0) + (X_t ? 1 : 0)) * totDim + (dmAux ? 1 : 0) * totDimAux + ((hasJac ? 1 : 0) + (hasPrec ? 1 : 0) + (hasDyn ? 1 : 0)) * totDim * totDim) * chunkSize;
4710: PetscCall(DMGetWorkArray(dm, wsz, MPIU_SCALAR, &work));
4711: PetscCall(PetscArrayzero(work, wsz));
4712: off = 0;
4713: u = X ? (sz = chunkSize * totDim, off += sz, work + off - sz) : NULL;
4714: u_t = X_t ? (sz = chunkSize * totDim, off += sz, work + off - sz) : NULL;
4715: a = dmAux ? (sz = chunkSize * totDimAux, off += sz, work + off - sz) : NULL;
4716: elemMat = hasJac ? (sz = chunkSize * totDim * totDim, off += sz, work + off - sz) : NULL;
4717: elemMatP = hasPrec ? (sz = chunkSize * totDim * totDim, off += sz, work + off - sz) : NULL;
4718: elemMatD = hasDyn ? (sz = chunkSize * totDim * totDim, off += sz, work + off - sz) : NULL;
4719: PetscCheck(off == wsz, PETSC_COMM_SELF, PETSC_ERR_PLIB, "Error is workspace size %" PetscInt_FMT " should be %" PetscInt_FMT, off, wsz);
4720: /* Setup geometry */
4721: PetscCall(DMGetCoordinateField(dm, &coordField));
4722: PetscCall(DMFieldGetDegree(coordField, cellIS, NULL, &maxDegree));
4723: if (maxDegree <= 1) PetscCall(DMFieldCreateDefaultQuadrature(coordField, cellIS, &qGeom));
4724: if (!qGeom) {
4725: PetscFE fe;
4727: PetscCall(PetscDSGetDiscretization(prob, 0, (PetscObject *)&fe));
4728: PetscCall(PetscFEGetQuadrature(fe, &qGeom));
4729: PetscCall(PetscObjectReference((PetscObject)qGeom));
4730: }
4731: PetscCall(DMSNESGetFEGeom(coordField, cellIS, qGeom, PETSC_FEGEOM_BASIC, &cgeomFEM));
4732: /* Compute volume integrals */
4733: if (assembleJac) PetscCall(MatZeroEntries(J));
4734: PetscCall(MatZeroEntries(JP));
4735: key.label = NULL;
4736: key.value = 0;
4737: key.part = 0;
4738: for (chunk = 0; chunk < numChunks; ++chunk, offCell += chunkSize) {
4739: const PetscInt Ncell = PetscMin(chunkSize, numCells - offCell);
4740: PetscInt c;
4742: /* Extract values */
4743: for (c = 0; c < Ncell; ++c) {
4744: const PetscInt cell = cells ? cells[c + offCell] : c + offCell;
4745: PetscScalar *x = NULL, *x_t = NULL;
4746: PetscInt i;
4748: if (X) {
4749: PetscCall(DMPlexVecGetClosure(dm, section, X, cell, NULL, &x));
4750: for (i = 0; i < totDim; ++i) u[c * totDim + i] = x[i];
4751: PetscCall(DMPlexVecRestoreClosure(dm, section, X, cell, NULL, &x));
4752: }
4753: if (X_t) {
4754: PetscCall(DMPlexVecGetClosure(dm, section, X_t, cell, NULL, &x_t));
4755: for (i = 0; i < totDim; ++i) u_t[c * totDim + i] = x_t[i];
4756: PetscCall(DMPlexVecRestoreClosure(dm, section, X_t, cell, NULL, &x_t));
4757: }
4758: if (dmAux) {
4759: PetscCall(DMPlexVecGetClosure(dmAux, sectionAux, A, cell, NULL, &x));
4760: for (i = 0; i < totDimAux; ++i) a[c * totDimAux + i] = x[i];
4761: PetscCall(DMPlexVecRestoreClosure(dmAux, sectionAux, A, cell, NULL, &x));
4762: }
4763: }
4764: for (fieldI = 0; fieldI < Nf; ++fieldI) {
4765: PetscFE fe;
4766: PetscCall(PetscDSGetDiscretization(prob, fieldI, (PetscObject *)&fe));
4767: for (fieldJ = 0; fieldJ < Nf; ++fieldJ) {
4768: key.field = fieldI * Nf + fieldJ;
4769: if (hasJac) PetscCall(PetscFEIntegrateJacobian(prob, prob, PETSCFE_JACOBIAN, key, Ncell, cgeomFEM, u, u_t, probAux, a, t, X_tShift, elemMat));
4770: if (hasPrec) PetscCall(PetscFEIntegrateJacobian(prob, prob, PETSCFE_JACOBIAN_PRE, key, Ncell, cgeomFEM, u, u_t, probAux, a, t, X_tShift, elemMatP));
4771: if (hasDyn) PetscCall(PetscFEIntegrateJacobian(prob, prob, PETSCFE_JACOBIAN_DYN, key, Ncell, cgeomFEM, u, u_t, probAux, a, t, X_tShift, elemMatD));
4772: }
4773: /* For finite volume, add the identity */
4774: if (!isFE[fieldI]) {
4775: PetscFV fv;
4776: PetscInt eOffset = 0, Nc, fc, foff;
4778: PetscCall(PetscDSGetFieldOffset(prob, fieldI, &foff));
4779: PetscCall(PetscDSGetDiscretization(prob, fieldI, (PetscObject *)&fv));
4780: PetscCall(PetscFVGetNumComponents(fv, &Nc));
4781: for (c = 0; c < chunkSize; ++c, eOffset += totDim * totDim) {
4782: for (fc = 0; fc < Nc; ++fc) {
4783: const PetscInt i = foff + fc;
4784: if (hasJac) elemMat[eOffset + i * totDim + i] = 1.0;
4785: if (hasPrec) elemMatP[eOffset + i * totDim + i] = 1.0;
4786: }
4787: }
4788: }
4789: }
4790: /* Add contribution from X_t */
4791: if (hasDyn) {
4792: for (c = 0; c < chunkSize * totDim * totDim; ++c) elemMat[c] += X_tShift * elemMatD[c];
4793: }
4794: /* Insert values into matrix */
4795: for (c = 0; c < Ncell; ++c) {
4796: const PetscInt cell = cells ? cells[c + offCell] : c + offCell;
4797: if (mesh->printFEM > 1) {
4798: if (hasJac) PetscCall(DMPrintCellMatrix(cell, name, totDim, totDim, &elemMat[(c - cStart) * totDim * totDim]));
4799: if (hasPrec) PetscCall(DMPrintCellMatrix(cell, nameP, totDim, totDim, &elemMatP[(c - cStart) * totDim * totDim]));
4800: }
4801: if (assembleJac) PetscCall(DMPlexMatSetClosure_Internal(dm, section, globalSection, mesh->useMatClPerm, Jac, cell, &elemMat[(c - cStart) * totDim * totDim], ADD_VALUES));
4802: PetscCall(DMPlexMatSetClosure_Internal(dm, section, globalSection, mesh->useMatClPerm, JP, cell, &elemMat[(c - cStart) * totDim * totDim], ADD_VALUES));
4803: }
4804: }
4805: /* Cleanup */
4806: PetscCall(DMSNESRestoreFEGeom(coordField, cellIS, qGeom, PETSC_FALSE, &cgeomFEM));
4807: PetscCall(PetscQuadratureDestroy(&qGeom));
4808: if (hasFV) PetscCall(MatSetOption(JacP, MAT_IGNORE_ZERO_ENTRIES, PETSC_FALSE));
4809: PetscCall(DMRestoreWorkArray(dm, Nf, MPI_C_BOOL, &isFE));
4810: PetscCall(DMRestoreWorkArray(dm, ((1 + (X_t ? 1 : 0) + (dmAux ? 1 : 0)) * totDim + ((hasJac ? 1 : 0) + (hasPrec ? 1 : 0) + (hasDyn ? 1 : 0)) * totDim * totDim) * chunkSize, MPIU_SCALAR, &work));
4811: /* Compute boundary integrals */
4812: /* PetscCall(DMPlexComputeBdJacobian_Internal(dm, X, X_t, t, X_tShift, Jac, JacP, ctx)); */
4813: /* Assemble matrix */
4814: if (assembleJac) {
4815: PetscCall(MatAssemblyBegin(Jac, MAT_FINAL_ASSEMBLY));
4816: PetscCall(MatAssemblyEnd(Jac, MAT_FINAL_ASSEMBLY));
4817: }
4818: PetscCall(MatAssemblyBegin(JacP, MAT_FINAL_ASSEMBLY));
4819: PetscCall(MatAssemblyEnd(JacP, MAT_FINAL_ASSEMBLY));
4820: PetscCall(PetscLogEventEnd(DMPLEX_JacobianFEM, dm, 0, 0, 0));
4821: PetscFunctionReturn(PETSC_SUCCESS);
4822: }
4824: /* FEM Assembly Function */
4826: static PetscErrorCode DMConvertPlex_Internal(DM dm, DM *plex, PetscBool copy)
4827: {
4828: PetscBool isPlex;
4830: PetscFunctionBegin;
4831: PetscCall(PetscObjectTypeCompare((PetscObject)dm, DMPLEX, &isPlex));
4832: if (isPlex) {
4833: *plex = dm;
4834: PetscCall(PetscObjectReference((PetscObject)dm));
4835: } else {
4836: PetscCall(PetscObjectQuery((PetscObject)dm, "dm_plex", (PetscObject *)plex));
4837: if (!*plex) {
4838: PetscCall(DMConvert(dm, DMPLEX, plex));
4839: PetscCall(PetscObjectCompose((PetscObject)dm, "dm_plex", (PetscObject)*plex));
4840: } else {
4841: PetscCall(PetscObjectReference((PetscObject)*plex));
4842: }
4843: if (copy) PetscCall(DMCopyAuxiliaryVec(dm, *plex));
4844: }
4845: PetscFunctionReturn(PETSC_SUCCESS);
4846: }
4848: /*@
4849: DMPlexGetGeometryFVM - Return precomputed geometric data
4851: Collective
4853: Input Parameter:
4854: . dm - The `DM`
4856: Output Parameters:
4857: + facegeom - The values precomputed from face geometry
4858: . cellgeom - The values precomputed from cell geometry
4859: - minRadius - The minimum radius over the mesh of an inscribed sphere in a cell, or `NULL` if not needed
4861: Level: developer
4863: .seealso: [](ch_unstructured), `DM`, `DMPLEX`, `DMTSSetRHSFunctionLocal()`
4864: @*/
4865: PetscErrorCode DMPlexGetGeometryFVM(DM dm, Vec *facegeom, Vec *cellgeom, PeOp PetscReal *minRadius)
4866: {
4867: DM plex;
4869: PetscFunctionBegin;
4871: PetscCall(DMConvertPlex_Internal(dm, &plex, PETSC_TRUE));
4872: PetscCall(DMPlexGetDataFVM(plex, NULL, cellgeom, facegeom, NULL));
4873: if (minRadius) PetscCall(DMPlexGetMinRadius(plex, minRadius));
4874: PetscCall(DMDestroy(&plex));
4875: PetscFunctionReturn(PETSC_SUCCESS);
4876: }
4878: /*@
4879: DMPlexGetGradientDM - Return gradient data layout
4881: Collective
4883: Input Parameters:
4884: + dm - The `DM`
4885: - fv - The `PetscFV`
4887: Output Parameter:
4888: . dmGrad - The layout for gradient values
4890: Level: developer
4892: .seealso: [](ch_unstructured), `DM`, `DMPLEX`, `DMPlexGetGeometryFVM()`
4893: @*/
4894: PetscErrorCode DMPlexGetGradientDM(DM dm, PetscFV fv, DM *dmGrad)
4895: {
4896: DM plex;
4897: PetscBool computeGradients;
4899: PetscFunctionBegin;
4902: PetscAssertPointer(dmGrad, 3);
4903: PetscCall(PetscFVGetComputeGradients(fv, &computeGradients));
4904: if (!computeGradients) {
4905: *dmGrad = NULL;
4906: PetscFunctionReturn(PETSC_SUCCESS);
4907: }
4908: PetscCall(DMConvertPlex_Internal(dm, &plex, PETSC_TRUE));
4909: PetscCall(DMPlexGetDataFVM(plex, fv, NULL, NULL, dmGrad));
4910: PetscCall(DMDestroy(&plex));
4911: PetscFunctionReturn(PETSC_SUCCESS);
4912: }
4914: /*@
4915: DMPlexComputeBdResidualSingleByKey - Compute the local boundary residual for terms matching the input key
4917: Not collective
4919: Input Parameters:
4920: + dm - The output `DM`
4921: . wf - The `PetscWeakForm` holding forms on this boundary
4922: . key - The `PetscFormKey` indicating what should be integrated
4923: . facetIS - The `IS` giving a set of faces to integrate over
4924: . locX - The local solution
4925: . locX_t - The time derivative of the local solution, or `NULL` for time-independent problems
4926: . t - The time
4927: - coordField - The `DMField` object with coordinates for these faces
4929: Output Parameter:
4930: . locF - The local residual
4932: Level: developer
4934: .seealso: `DMPlexComputeBdResidualSingle()`, `DMPlexComputeJacobianByKey()`, `DMPlexComputeResidualHybridByKey()`, `DMPlexComputeJacobianHybridByKey()`, `PetscFormKey`
4935: @*/
4936: PetscErrorCode DMPlexComputeBdResidualSingleByKey(DM dm, PetscWeakForm wf, PetscFormKey key, IS facetIS, Vec locX, Vec locX_t, PetscReal t, DMField coordField, Vec locF)
4937: {
4938: DM_Plex *mesh = (DM_Plex *)dm->data;
4939: DM plex = NULL, plexA = NULL;
4940: const char *name = "BdResidual";
4941: DMEnclosureType encAux;
4942: PetscDS prob, probAux = NULL;
4943: PetscSection section, sectionAux = NULL;
4944: Vec locA = NULL;
4945: PetscScalar *u = NULL, *u_t = NULL, *a = NULL, *elemVec = NULL;
4946: PetscInt totDim, totDimAux = 0;
4948: PetscFunctionBegin;
4949: PetscCall(DMConvert(dm, DMPLEX, &plex));
4950: PetscCall(DMGetLocalSection(dm, §ion));
4951: PetscCall(DMGetDS(dm, &prob));
4952: PetscCall(PetscDSGetTotalDimension(prob, &totDim));
4953: PetscCall(DMGetAuxiliaryVec(dm, key.label, key.value, key.part, &locA));
4954: if (locA) {
4955: DM dmAux;
4957: PetscCall(VecGetDM(locA, &dmAux));
4958: PetscCall(DMGetEnclosureRelation(dmAux, dm, &encAux));
4959: PetscCall(DMConvert(dmAux, DMPLEX, &plexA));
4960: PetscCall(DMGetDS(plexA, &probAux));
4961: PetscCall(PetscDSGetTotalDimension(probAux, &totDimAux));
4962: PetscCall(DMGetLocalSection(plexA, §ionAux));
4963: }
4964: {
4965: PetscFEGeom *fgeom;
4966: PetscInt maxDegree;
4967: PetscQuadrature qGeom = NULL;
4968: IS pointIS;
4969: const PetscInt *points;
4970: PetscInt numFaces, face, Nq;
4972: PetscCall(DMLabelGetStratumIS(key.label, key.value, &pointIS));
4973: if (!pointIS) goto end; /* No points with that id on this process */
4974: {
4975: IS isectIS;
4977: /* TODO: Special cases of ISIntersect where it is quick to check a priori if one is a superset of the other */
4978: PetscCall(ISIntersect_Caching_Internal(facetIS, pointIS, &isectIS));
4979: PetscCall(ISDestroy(&pointIS));
4980: pointIS = isectIS;
4981: }
4982: PetscCall(ISGetLocalSize(pointIS, &numFaces));
4983: PetscCall(ISGetIndices(pointIS, &points));
4984: PetscCall(PetscMalloc4(numFaces * totDim, &u, (locX_t ? (size_t)numFaces * totDim : 0), &u_t, numFaces * totDim, &elemVec, (locA ? (size_t)numFaces * totDimAux : 0), &a));
4985: PetscCall(DMFieldGetDegree(coordField, pointIS, NULL, &maxDegree));
4986: if (maxDegree <= 1) PetscCall(DMFieldCreateDefaultQuadrature(coordField, pointIS, &qGeom));
4987: if (!qGeom) {
4988: PetscFE fe;
4990: PetscCall(PetscDSGetDiscretization(prob, key.field, (PetscObject *)&fe));
4991: PetscCall(PetscFEGetFaceQuadrature(fe, &qGeom));
4992: PetscCall(PetscObjectReference((PetscObject)qGeom));
4993: }
4994: PetscCall(PetscQuadratureGetData(qGeom, NULL, NULL, &Nq, NULL, NULL));
4995: PetscCall(DMSNESGetFEGeom(coordField, pointIS, qGeom, PETSC_FEGEOM_BOUNDARY, &fgeom));
4996: for (face = 0; face < numFaces; ++face) {
4997: const PetscInt point = points[face], *support;
4998: PetscScalar *x = NULL;
4999: PetscInt i;
5001: PetscCall(DMPlexGetSupport(dm, point, &support));
5002: PetscCall(DMPlexVecGetClosure(plex, section, locX, support[0], NULL, &x));
5003: for (i = 0; i < totDim; ++i) u[face * totDim + i] = x[i];
5004: PetscCall(DMPlexVecRestoreClosure(plex, section, locX, support[0], NULL, &x));
5005: if (locX_t) {
5006: PetscCall(DMPlexVecGetClosure(plex, section, locX_t, support[0], NULL, &x));
5007: for (i = 0; i < totDim; ++i) u_t[face * totDim + i] = x[i];
5008: PetscCall(DMPlexVecRestoreClosure(plex, section, locX_t, support[0], NULL, &x));
5009: }
5010: if (locA) {
5011: PetscInt subp;
5013: PetscCall(DMGetEnclosurePoint(plexA, dm, encAux, support[0], &subp));
5014: PetscCall(DMPlexVecGetClosure(plexA, sectionAux, locA, subp, NULL, &x));
5015: for (i = 0; i < totDimAux; ++i) a[face * totDimAux + i] = x[i];
5016: PetscCall(DMPlexVecRestoreClosure(plexA, sectionAux, locA, subp, NULL, &x));
5017: }
5018: }
5019: PetscCall(PetscArrayzero(elemVec, numFaces * totDim));
5020: {
5021: PetscFE fe;
5022: PetscInt Nb;
5023: PetscFEGeom *chunkGeom = NULL;
5024: /* Conforming batches */
5025: PetscInt numChunks, numBatches, numBlocks, Ne, blockSize, batchSize;
5026: /* Remainder */
5027: PetscInt Nr, offset;
5029: PetscCall(PetscDSGetDiscretization(prob, key.field, (PetscObject *)&fe));
5030: PetscCall(PetscFEGetDimension(fe, &Nb));
5031: PetscCall(PetscFEGetTileSizes(fe, NULL, &numBlocks, NULL, &numBatches));
5032: /* TODO: documentation is unclear about what is going on with these numbers: how should Nb / Nq factor in ? */
5033: blockSize = Nb;
5034: batchSize = numBlocks * blockSize;
5035: PetscCall(PetscFESetTileSizes(fe, blockSize, numBlocks, batchSize, numBatches));
5036: numChunks = numFaces / (numBatches * batchSize);
5037: Ne = numChunks * numBatches * batchSize;
5038: Nr = numFaces % (numBatches * batchSize);
5039: offset = numFaces - Nr;
5040: PetscCall(PetscFEGeomGetChunk(fgeom, 0, offset, &chunkGeom));
5041: PetscCall(PetscFEIntegrateBdResidual(prob, wf, key, Ne, chunkGeom, u, u_t, probAux, a, t, elemVec));
5042: PetscCall(PetscFEGeomRestoreChunk(fgeom, 0, offset, &chunkGeom));
5043: PetscCall(PetscFEGeomGetChunk(fgeom, offset, numFaces, &chunkGeom));
5044: PetscCall(PetscFEIntegrateBdResidual(prob, wf, key, Nr, chunkGeom, &u[offset * totDim], PetscSafePointerPlusOffset(u_t, offset * totDim), probAux, PetscSafePointerPlusOffset(a, offset * totDimAux), t, &elemVec[offset * totDim]));
5045: PetscCall(PetscFEGeomRestoreChunk(fgeom, offset, numFaces, &chunkGeom));
5046: }
5047: for (face = 0; face < numFaces; ++face) {
5048: const PetscInt point = points[face], *support;
5050: if (mesh->printFEM > 1) PetscCall(DMPrintCellVector(point, name, totDim, &elemVec[face * totDim]));
5051: PetscCall(DMPlexGetSupport(plex, point, &support));
5052: PetscCall(DMPlexVecSetClosure(plex, NULL, locF, support[0], &elemVec[face * totDim], ADD_ALL_VALUES));
5053: }
5054: PetscCall(DMSNESRestoreFEGeom(coordField, pointIS, qGeom, PETSC_TRUE, &fgeom));
5055: PetscCall(PetscQuadratureDestroy(&qGeom));
5056: PetscCall(ISRestoreIndices(pointIS, &points));
5057: PetscCall(ISDestroy(&pointIS));
5058: PetscCall(PetscFree4(u, u_t, elemVec, a));
5059: }
5060: end:
5061: if (mesh->printFEM) {
5062: PetscSection s;
5063: Vec locFbc;
5064: PetscInt pStart, pEnd, maxDof;
5065: PetscScalar *zeroes;
5067: PetscCall(DMGetLocalSection(dm, &s));
5068: PetscCall(VecDuplicate(locF, &locFbc));
5069: PetscCall(VecCopy(locF, locFbc));
5070: PetscCall(PetscSectionGetChart(s, &pStart, &pEnd));
5071: PetscCall(PetscSectionGetMaxDof(s, &maxDof));
5072: PetscCall(PetscCalloc1(maxDof, &zeroes));
5073: for (PetscInt p = pStart; p < pEnd; p++) PetscCall(VecSetValuesSection(locFbc, s, p, zeroes, INSERT_BC_VALUES));
5074: PetscCall(PetscFree(zeroes));
5075: PetscCall(DMPrintLocalVec(dm, name, mesh->printTol, locFbc));
5076: PetscCall(VecDestroy(&locFbc));
5077: }
5078: PetscCall(DMDestroy(&plex));
5079: PetscCall(DMDestroy(&plexA));
5080: PetscFunctionReturn(PETSC_SUCCESS);
5081: }
5083: /*@
5084: DMPlexComputeBdResidualSingle - Compute the local boundary residual
5086: Not collective
5088: Input Parameters:
5089: + dm - The output `DM`
5090: . wf - The `PetscWeakForm` holding forms on this boundary
5091: . key - The `PetscFormKey` indicating what should be integrated
5092: . locX - The local solution
5093: . locX_t - The time derivative of the local solution, or `NULL` for time-independent problems
5094: - t - The time
5096: Output Parameter:
5097: . locF - The local residual
5099: Level: developer
5101: .seealso: `DMPlexComputeBdResidualSingleByKey()`, `DMPlexComputeJacobianByKey()`, `DMPlexComputeResidualHybridByKey()`, `DMPlexComputeJacobianHybridByKey()`, `PetscFormKey`
5102: @*/
5103: PetscErrorCode DMPlexComputeBdResidualSingle(DM dm, PetscWeakForm wf, PetscFormKey key, Vec locX, Vec locX_t, PetscReal t, Vec locF)
5104: {
5105: DMField coordField;
5106: DMLabel depthLabel;
5107: IS facetIS;
5108: PetscInt dim;
5110: PetscFunctionBegin;
5111: PetscCall(DMGetDimension(dm, &dim));
5112: PetscCall(DMPlexGetDepthLabel(dm, &depthLabel));
5113: PetscCall(DMLabelGetStratumIS(depthLabel, dim - 1, &facetIS));
5114: PetscCall(DMGetCoordinateField(dm, &coordField));
5115: PetscCall(DMPlexComputeBdResidualSingleByKey(dm, wf, key, facetIS, locX, locX_t, t, coordField, locF));
5116: PetscCall(ISDestroy(&facetIS));
5117: PetscFunctionReturn(PETSC_SUCCESS);
5118: }
5120: static PetscErrorCode DMPlexComputeBdResidual_Internal(DM dm, Vec locX, Vec locX_t, PetscReal t, Vec locF, PetscCtx ctx)
5121: {
5122: PetscDS prob;
5123: PetscInt numBd, bd;
5124: DMField coordField = NULL;
5125: IS facetIS = NULL;
5126: DMLabel depthLabel;
5127: PetscInt dim;
5129: PetscFunctionBegin;
5130: PetscCall(DMGetDS(dm, &prob));
5131: PetscCall(DMPlexGetDepthLabel(dm, &depthLabel));
5132: PetscCall(DMGetDimension(dm, &dim));
5133: PetscCall(DMLabelGetStratumIS(depthLabel, dim - 1, &facetIS));
5134: /* Filter out ghost facets (SF leaves) so that boundary residual contributions
5135: from shared facets are only assembled on the owning rank. Without this,
5136: internal boundary natural BCs at partition junctions get double-counted
5137: because LocalToGlobal with ADD_VALUES sums contributions from all ranks. */
5138: if (facetIS) {
5139: PetscSF sf;
5140: PetscInt nleaves;
5141: const PetscInt *leaves;
5143: PetscCall(DMGetPointSF(dm, &sf));
5144: PetscCall(PetscSFGetGraph(sf, NULL, &nleaves, &leaves, NULL));
5145: if (nleaves > 0 && leaves) {
5146: IS leafIS, ownedFacetIS;
5148: PetscCall(ISCreateGeneral(PETSC_COMM_SELF, nleaves, leaves, PETSC_USE_POINTER, &leafIS));
5149: PetscCall(ISDifference(facetIS, leafIS, &ownedFacetIS));
5150: PetscCall(ISDestroy(&leafIS));
5151: PetscCall(ISDestroy(&facetIS));
5152: facetIS = ownedFacetIS;
5153: }
5154: }
5155: PetscCall(PetscDSGetNumBoundary(prob, &numBd));
5156: for (bd = 0; bd < numBd; ++bd) {
5157: PetscWeakForm wf;
5158: DMBoundaryConditionType type;
5159: DMLabel label;
5160: const PetscInt *values;
5161: PetscInt field, numValues, v;
5162: PetscObject obj;
5163: PetscClassId id;
5164: PetscFormKey key;
5166: PetscCall(PetscDSGetBoundary(prob, bd, &wf, &type, NULL, &label, &numValues, &values, &field, NULL, NULL, NULL, NULL, NULL));
5167: if (type & DM_BC_ESSENTIAL) continue;
5168: PetscCall(PetscDSGetDiscretization(prob, field, &obj));
5169: PetscCall(PetscObjectGetClassId(obj, &id));
5170: if (id != PETSCFE_CLASSID) continue;
5171: if (!facetIS) {
5172: DMLabel depthLabel;
5173: PetscInt dim;
5175: PetscCall(DMPlexGetDepthLabel(dm, &depthLabel));
5176: PetscCall(DMGetDimension(dm, &dim));
5177: PetscCall(DMLabelGetStratumIS(depthLabel, dim - 1, &facetIS));
5178: }
5179: PetscCall(DMGetCoordinateField(dm, &coordField));
5180: for (v = 0; v < numValues; ++v) {
5181: key.label = label;
5182: key.value = values[v];
5183: key.field = field;
5184: key.part = 0;
5185: PetscCall(DMPlexComputeBdResidualSingleByKey(dm, wf, key, facetIS, locX, locX_t, t, coordField, locF));
5186: }
5187: }
5188: PetscCall(ISDestroy(&facetIS));
5189: PetscFunctionReturn(PETSC_SUCCESS);
5190: }
5192: /*@
5193: DMPlexComputeResidualByKey - Compute the local residual for terms matching the input key
5195: Collective
5197: Input Parameters:
5198: + dm - The output `DM`
5199: . key - The `PetscFormKey` indicating what should be integrated
5200: . cellIS - The `IS` giving a set of cells to integrate over
5201: . time - The time, or `PETSC_MIN_REAL` to include implicit terms in a time-independent problems
5202: . locX - The local solution
5203: . locX_t - The time derivative of the local solution, or `NULL` for time-independent problems
5204: . t - The time
5205: - ctx - An optional application context, passed to the pointwise functions
5207: Output Parameter:
5208: . locF - The local residual
5210: Level: developer
5212: .seealso: `DMPlexComputeJacobianByKey()`, `DMPlexComputeResidualHybridByKey()`, `DMPlexComputeJacobianHybridByKey()`, `PetscFormKey`
5213: @*/
5214: PetscErrorCode DMPlexComputeResidualByKey(DM dm, PetscFormKey key, IS cellIS, PetscReal time, Vec locX, Vec locX_t, PetscReal t, Vec locF, PetscCtx ctx)
5215: {
5216: DM_Plex *mesh = (DM_Plex *)dm->data;
5217: const char *name = "Residual";
5218: DM dmAux = NULL;
5219: DM dmGrad = NULL;
5220: DMLabel ghostLabel = NULL;
5221: PetscDS ds = NULL;
5222: PetscDS dsAux = NULL;
5223: PetscSection section = NULL;
5224: PetscBool useFEM = PETSC_FALSE;
5225: PetscBool useFVM = PETSC_FALSE;
5226: PetscBool isImplicit = (locX_t || time == PETSC_MIN_REAL) ? PETSC_TRUE : PETSC_FALSE;
5227: PetscFV fvm = NULL;
5228: DMField coordField = NULL;
5229: Vec locA, cellGeometryFVM = NULL, faceGeometryFVM = NULL, locGrad = NULL;
5230: PetscScalar *u = NULL, *u_t, *a, *uL, *uR;
5231: IS chunkIS;
5232: const PetscInt *cells;
5233: PetscInt cStart, cEnd, numCells;
5234: PetscInt Nf, f, totDim, totDimAux, numChunks, cellChunkSize, faceChunkSize, chunk, fStart, fEnd;
5235: PetscInt maxDegree = PETSC_INT_MAX;
5236: PetscQuadrature affineQuad = NULL, *quads = NULL;
5237: PetscFEGeom *affineGeom = NULL, **geoms = NULL;
5239: PetscFunctionBegin;
5240: PetscCall(PetscLogEventBegin(DMPLEX_ResidualFEM, dm, 0, 0, 0));
5241: if (!cellIS) goto end;
5242: PetscCall(ISGetPointRange(cellIS, &cStart, &cEnd, &cells));
5243: if (cStart >= cEnd) goto end;
5244: /* TODO The places where we have to use isFE are probably the member functions for the PetscDisc class */
5245: /* TODO The FVM geometry is over-manipulated. Make the precalc functions return exactly what we need */
5246: /* FEM+FVM */
5247: PetscCall(DMPlexGetHeightStratum(dm, 1, &fStart, &fEnd));
5248: /* 1: Get sizes from dm and dmAux */
5249: PetscCall(DMGetLocalSection(dm, §ion));
5250: PetscCall(DMGetLabel(dm, "ghost", &ghostLabel));
5251: PetscCall(DMGetCellDS(dm, cells ? cells[cStart] : cStart, &ds, NULL));
5252: PetscCall(PetscDSGetNumFields(ds, &Nf));
5253: PetscCall(PetscDSGetTotalDimension(ds, &totDim));
5254: PetscCall(DMGetAuxiliaryVec(dm, key.label, key.value, key.part, &locA));
5255: if (locA) {
5256: PetscInt subcell;
5257: PetscCall(VecGetDM(locA, &dmAux));
5258: PetscCall(DMGetEnclosurePoint(dmAux, dm, DM_ENC_UNKNOWN, cells ? cells[cStart] : cStart, &subcell));
5259: PetscCall(DMGetCellDS(dmAux, subcell, &dsAux, NULL));
5260: PetscCall(PetscDSGetTotalDimension(dsAux, &totDimAux));
5261: }
5262: /* 2: Get geometric data */
5263: for (f = 0; f < Nf; ++f) {
5264: PetscObject obj;
5265: PetscClassId id;
5266: PetscBool fimp;
5268: PetscCall(PetscDSGetImplicit(ds, f, &fimp));
5269: if (isImplicit != fimp) continue;
5270: PetscCall(PetscDSGetDiscretization(ds, f, &obj));
5271: PetscCall(PetscObjectGetClassId(obj, &id));
5272: if (id == PETSCFE_CLASSID) useFEM = PETSC_TRUE;
5273: if (id == PETSCFV_CLASSID) {
5274: useFVM = PETSC_TRUE;
5275: fvm = (PetscFV)obj;
5276: }
5277: }
5278: if (useFEM) {
5279: PetscCall(DMGetCoordinateField(dm, &coordField));
5280: PetscCall(DMFieldGetDegree(coordField, cellIS, NULL, &maxDegree));
5281: if (maxDegree <= 1) {
5282: PetscCall(DMFieldCreateDefaultQuadrature(coordField, cellIS, &affineQuad));
5283: if (affineQuad) PetscCall(DMSNESGetFEGeom(coordField, cellIS, affineQuad, PETSC_FEGEOM_BASIC, &affineGeom));
5284: } else {
5285: PetscCall(PetscCalloc2(Nf, &quads, Nf, &geoms));
5286: for (f = 0; f < Nf; ++f) {
5287: PetscObject obj;
5288: PetscClassId id;
5289: PetscBool fimp;
5291: PetscCall(PetscDSGetImplicit(ds, f, &fimp));
5292: if (isImplicit != fimp) continue;
5293: PetscCall(PetscDSGetDiscretization(ds, f, &obj));
5294: PetscCall(PetscObjectGetClassId(obj, &id));
5295: if (id == PETSCFE_CLASSID) {
5296: PetscFE fe = (PetscFE)obj;
5298: PetscCall(PetscFEGetQuadrature(fe, &quads[f]));
5299: PetscCall(PetscObjectReference((PetscObject)quads[f]));
5300: PetscCall(DMSNESGetFEGeom(coordField, cellIS, quads[f], PETSC_FEGEOM_BASIC, &geoms[f]));
5301: }
5302: }
5303: }
5304: }
5305: // Handle non-essential (e.g. outflow) boundary values
5306: if (useFVM) {
5307: PetscCall(DMPlexInsertBoundaryValuesFVM(dm, fvm, locX, time, &locGrad));
5308: PetscCall(DMPlexGetGeometryFVM(dm, &faceGeometryFVM, &cellGeometryFVM, NULL));
5309: PetscCall(DMPlexGetGradientDM(dm, fvm, &dmGrad));
5310: }
5311: /* Loop over chunks */
5312: if (useFEM) PetscCall(ISCreate(PETSC_COMM_SELF, &chunkIS));
5313: numCells = cEnd - cStart;
5314: numChunks = 1;
5315: cellChunkSize = numCells / numChunks;
5316: faceChunkSize = (fEnd - fStart) / numChunks;
5317: numChunks = PetscMin(1, numCells);
5318: for (chunk = 0; chunk < numChunks; ++chunk) {
5319: PetscScalar *elemVec, *fluxL, *fluxR;
5320: PetscReal *vol;
5321: PetscFVFaceGeom *fgeom;
5322: PetscInt cS = cStart + chunk * cellChunkSize, cE = PetscMin(cS + cellChunkSize, cEnd), numCells = cE - cS, c;
5323: PetscInt fS = fStart + chunk * faceChunkSize, fE = PetscMin(fS + faceChunkSize, fEnd), numFaces = 0, face;
5325: /* Extract field coefficients */
5326: if (useFEM) {
5327: PetscCall(ISGetPointSubrange(chunkIS, cS, cE, cells));
5328: PetscCall(DMPlexGetCellFields(dm, chunkIS, locX, locX_t, locA, &u, &u_t, &a));
5329: PetscCall(DMGetWorkArray(dm, numCells * totDim, MPIU_SCALAR, &elemVec));
5330: PetscCall(PetscArrayzero(elemVec, numCells * totDim));
5331: }
5332: if (useFVM) {
5333: PetscCall(DMPlexGetFaceFields(dm, fS, fE, locX, locX_t, faceGeometryFVM, cellGeometryFVM, locGrad, &numFaces, &uL, &uR));
5334: PetscCall(DMPlexGetFaceGeometry(dm, fS, fE, faceGeometryFVM, cellGeometryFVM, &numFaces, &fgeom, &vol));
5335: PetscCall(DMGetWorkArray(dm, numFaces * totDim, MPIU_SCALAR, &fluxL));
5336: PetscCall(DMGetWorkArray(dm, numFaces * totDim, MPIU_SCALAR, &fluxR));
5337: PetscCall(PetscArrayzero(fluxL, numFaces * totDim));
5338: PetscCall(PetscArrayzero(fluxR, numFaces * totDim));
5339: }
5340: /* TODO We will interlace both our field coefficients (u, u_t, uL, uR, etc.) and our output (elemVec, fL, fR). I think this works */
5341: /* Loop over fields */
5342: for (f = 0; f < Nf; ++f) {
5343: PetscObject obj;
5344: PetscClassId id;
5345: PetscBool fimp;
5346: PetscInt numChunks, numBatches, batchSize, numBlocks, blockSize, Ne, Nr, offset;
5348: key.field = f;
5349: PetscCall(PetscDSGetImplicit(ds, f, &fimp));
5350: if (isImplicit != fimp) continue;
5351: PetscCall(PetscDSGetDiscretization(ds, f, &obj));
5352: PetscCall(PetscObjectGetClassId(obj, &id));
5353: if (id == PETSCFE_CLASSID) {
5354: PetscFE fe = (PetscFE)obj;
5355: PetscFEGeom *geom = affineGeom ? affineGeom : geoms[f];
5356: PetscFEGeom *chunkGeom = NULL;
5357: PetscQuadrature quad = affineQuad ? affineQuad : quads[f];
5358: PetscInt Nq, Nb;
5360: PetscCall(PetscFEGetTileSizes(fe, NULL, &numBlocks, NULL, &numBatches));
5361: PetscCall(PetscQuadratureGetData(quad, NULL, NULL, &Nq, NULL, NULL));
5362: PetscCall(PetscFEGetDimension(fe, &Nb));
5363: blockSize = Nb;
5364: batchSize = numBlocks * blockSize;
5365: PetscCall(PetscFESetTileSizes(fe, blockSize, numBlocks, batchSize, numBatches));
5366: numChunks = numCells / (numBatches * batchSize);
5367: Ne = numChunks * numBatches * batchSize;
5368: Nr = numCells % (numBatches * batchSize);
5369: offset = numCells - Nr;
5370: /* Integrate FE residual to get elemVec (need fields at quadrature points) */
5371: /* For FV, I think we use a P0 basis and the cell coefficients (for subdivided cells, we can tweak the basis tabulation to be the indicator function) */
5372: PetscCall(PetscFEGeomGetChunk(geom, 0, offset, &chunkGeom));
5373: PetscCall(PetscFEIntegrateResidual(ds, key, Ne, chunkGeom, u, u_t, dsAux, a, t, elemVec));
5374: PetscCall(PetscFEGeomGetChunk(geom, offset, numCells, &chunkGeom));
5375: PetscCall(PetscFEIntegrateResidual(ds, key, Nr, chunkGeom, &u[offset * totDim], PetscSafePointerPlusOffset(u_t, offset * totDim), dsAux, PetscSafePointerPlusOffset(a, offset * totDimAux), t, &elemVec[offset * totDim]));
5376: PetscCall(PetscFEGeomRestoreChunk(geom, offset, numCells, &chunkGeom));
5377: } else if (id == PETSCFV_CLASSID) {
5378: PetscFV fv = (PetscFV)obj;
5380: Ne = numFaces;
5381: /* Riemann solve over faces (need fields at face centroids) */
5382: /* We need to evaluate FE fields at those coordinates */
5383: PetscCall(PetscFVIntegrateRHSFunction(fv, ds, f, Ne, fgeom, vol, uL, uR, fluxL, fluxR));
5384: } else SETERRQ(PetscObjectComm((PetscObject)dm), PETSC_ERR_ARG_WRONG, "Unknown discretization type for field %" PetscInt_FMT, f);
5385: }
5386: /* Loop over domain */
5387: if (useFEM) {
5388: /* Add elemVec to locX */
5389: for (c = cS; c < cE; ++c) {
5390: const PetscInt cell = cells ? cells[c] : c;
5391: const PetscInt cind = c - cStart;
5393: if (mesh->printFEM > 1) PetscCall(DMPrintCellVector(cell, name, totDim, &elemVec[cind * totDim]));
5394: if (ghostLabel) {
5395: PetscInt ghostVal;
5397: PetscCall(DMLabelGetValue(ghostLabel, cell, &ghostVal));
5398: if (ghostVal > 0) continue;
5399: }
5400: PetscCall(DMPlexVecSetClosure(dm, section, locF, cell, &elemVec[cind * totDim], ADD_ALL_VALUES));
5401: }
5402: }
5403: if (useFVM) {
5404: PetscScalar *fa;
5405: PetscInt iface;
5407: PetscCall(VecGetArray(locF, &fa));
5408: for (f = 0; f < Nf; ++f) {
5409: PetscFV fv;
5410: PetscObject obj;
5411: PetscClassId id;
5412: PetscInt cdim, foff, pdim;
5414: PetscCall(DMGetCoordinateDim(dm, &cdim));
5415: PetscCall(PetscDSGetDiscretization(ds, f, &obj));
5416: PetscCall(PetscDSGetFieldOffset(ds, f, &foff));
5417: PetscCall(PetscObjectGetClassId(obj, &id));
5418: if (id != PETSCFV_CLASSID) continue;
5419: fv = (PetscFV)obj;
5420: PetscCall(PetscFVGetNumComponents(fv, &pdim));
5421: /* Accumulate fluxes to cells */
5422: for (face = fS, iface = 0; face < fE; ++face) {
5423: const PetscInt *scells;
5424: PetscScalar *fL = NULL, *fR = NULL;
5425: PetscInt ghost, d, nsupp, nchild;
5427: PetscCall(DMLabelGetValue(ghostLabel, face, &ghost));
5428: PetscCall(DMPlexGetSupportSize(dm, face, &nsupp));
5429: PetscCall(DMPlexGetTreeChildren(dm, face, &nchild, NULL));
5430: if (ghost >= 0 || nsupp > 2 || nchild > 0) continue;
5431: PetscCall(DMPlexGetSupport(dm, face, &scells));
5432: PetscCall(DMLabelGetValue(ghostLabel, scells[0], &ghost));
5433: if (ghost <= 0) PetscCall(DMPlexPointLocalFieldRef(dm, scells[0], f, fa, &fL));
5434: PetscCall(DMLabelGetValue(ghostLabel, scells[1], &ghost));
5435: if (ghost <= 0) PetscCall(DMPlexPointLocalFieldRef(dm, scells[1], f, fa, &fR));
5436: if (mesh->printFVM > 1) {
5437: PetscCall(DMPrintCellVectorReal(face, "Residual: normal", cdim, fgeom[iface].normal));
5438: PetscCall(DMPrintCellVector(face, "Residual: left state", pdim, &uL[iface * totDim + foff]));
5439: PetscCall(DMPrintCellVector(face, "Residual: right state", pdim, &uR[iface * totDim + foff]));
5440: PetscCall(DMPrintCellVector(face, "Residual: left flux", pdim, &fluxL[iface * totDim + foff]));
5441: PetscCall(DMPrintCellVector(face, "Residual: right flux", pdim, &fluxR[iface * totDim + foff]));
5442: }
5443: for (d = 0; d < pdim; ++d) {
5444: if (fL) fL[d] -= fluxL[iface * totDim + foff + d];
5445: if (fR) fR[d] += fluxR[iface * totDim + foff + d];
5446: }
5447: ++iface;
5448: }
5449: }
5450: PetscCall(VecRestoreArray(locF, &fa));
5451: }
5452: /* Handle time derivative */
5453: if (locX_t) {
5454: PetscScalar *x_t, *fa;
5456: PetscCall(VecGetArray(locF, &fa));
5457: PetscCall(VecGetArray(locX_t, &x_t));
5458: for (f = 0; f < Nf; ++f) {
5459: PetscFV fv;
5460: PetscObject obj;
5461: PetscClassId id;
5462: PetscInt pdim, d;
5464: PetscCall(PetscDSGetDiscretization(ds, f, &obj));
5465: PetscCall(PetscObjectGetClassId(obj, &id));
5466: if (id != PETSCFV_CLASSID) continue;
5467: fv = (PetscFV)obj;
5468: PetscCall(PetscFVGetNumComponents(fv, &pdim));
5469: for (c = cS; c < cE; ++c) {
5470: const PetscInt cell = cells ? cells[c] : c;
5471: PetscScalar *u_t, *r;
5473: if (ghostLabel) {
5474: PetscInt ghostVal;
5476: PetscCall(DMLabelGetValue(ghostLabel, cell, &ghostVal));
5477: if (ghostVal > 0) continue;
5478: }
5479: PetscCall(DMPlexPointLocalFieldRead(dm, cell, f, x_t, &u_t));
5480: PetscCall(DMPlexPointLocalFieldRef(dm, cell, f, fa, &r));
5481: for (d = 0; d < pdim; ++d) r[d] += u_t[d];
5482: }
5483: }
5484: PetscCall(VecRestoreArray(locX_t, &x_t));
5485: PetscCall(VecRestoreArray(locF, &fa));
5486: }
5487: if (useFEM) {
5488: PetscCall(DMPlexRestoreCellFields(dm, chunkIS, locX, locX_t, locA, &u, &u_t, &a));
5489: PetscCall(DMRestoreWorkArray(dm, numCells * totDim, MPIU_SCALAR, &elemVec));
5490: }
5491: if (useFVM) {
5492: PetscCall(DMPlexRestoreFaceFields(dm, fS, fE, locX, locX_t, faceGeometryFVM, cellGeometryFVM, locGrad, &numFaces, &uL, &uR));
5493: PetscCall(DMPlexRestoreFaceGeometry(dm, fS, fE, faceGeometryFVM, cellGeometryFVM, &numFaces, &fgeom, &vol));
5494: PetscCall(DMRestoreWorkArray(dm, numFaces * totDim, MPIU_SCALAR, &fluxL));
5495: PetscCall(DMRestoreWorkArray(dm, numFaces * totDim, MPIU_SCALAR, &fluxR));
5496: if (dmGrad) PetscCall(DMRestoreLocalVector(dmGrad, &locGrad));
5497: }
5498: }
5499: if (useFEM) PetscCall(ISDestroy(&chunkIS));
5500: PetscCall(ISRestorePointRange(cellIS, &cStart, &cEnd, &cells));
5502: if (useFEM) {
5503: PetscCall(DMPlexComputeBdResidual_Internal(dm, locX, locX_t, t, locF, ctx));
5505: if (maxDegree <= 1) {
5506: PetscCall(DMSNESRestoreFEGeom(coordField, cellIS, affineQuad, PETSC_FALSE, &affineGeom));
5507: PetscCall(PetscQuadratureDestroy(&affineQuad));
5508: } else {
5509: for (f = 0; f < Nf; ++f) {
5510: PetscCall(DMSNESRestoreFEGeom(coordField, cellIS, quads[f], PETSC_FALSE, &geoms[f]));
5511: PetscCall(PetscQuadratureDestroy(&quads[f]));
5512: }
5513: PetscCall(PetscFree2(quads, geoms));
5514: }
5515: }
5517: /* FEM */
5518: /* 1: Get sizes from dm and dmAux */
5519: /* 2: Get geometric data */
5520: /* 3: Handle boundary values */
5521: /* 4: Loop over domain */
5522: /* Extract coefficients */
5523: /* Loop over fields */
5524: /* Set tiling for FE*/
5525: /* Integrate FE residual to get elemVec */
5526: /* Loop over subdomain */
5527: /* Loop over quad points */
5528: /* Transform coords to real space */
5529: /* Evaluate field and aux fields at point */
5530: /* Evaluate residual at point */
5531: /* Transform residual to real space */
5532: /* Add residual to elemVec */
5533: /* Loop over domain */
5534: /* Add elemVec to locX */
5536: /* FVM */
5537: /* Get geometric data */
5538: /* If using gradients */
5539: /* Compute gradient data */
5540: /* Loop over domain faces */
5541: /* Count computational faces */
5542: /* Reconstruct cell gradient */
5543: /* Loop over domain cells */
5544: /* Limit cell gradients */
5545: /* Handle boundary values */
5546: /* Loop over domain faces */
5547: /* Read out field, centroid, normal, volume for each side of face */
5548: /* Riemann solve over faces */
5549: /* Loop over domain faces */
5550: /* Accumulate fluxes to cells */
5551: /* TODO Change printFEM to printDisc here */
5552: if (mesh->printFEM) {
5553: Vec locFbc;
5554: PetscInt pStart, pEnd, p, maxDof;
5555: PetscScalar *zeroes;
5557: PetscCall(VecDuplicate(locF, &locFbc));
5558: PetscCall(VecCopy(locF, locFbc));
5559: PetscCall(PetscSectionGetChart(section, &pStart, &pEnd));
5560: PetscCall(PetscSectionGetMaxDof(section, &maxDof));
5561: PetscCall(PetscCalloc1(maxDof, &zeroes));
5562: for (p = pStart; p < pEnd; p++) PetscCall(VecSetValuesSection(locFbc, section, p, zeroes, INSERT_BC_VALUES));
5563: PetscCall(PetscFree(zeroes));
5564: PetscCall(DMPrintLocalVec(dm, name, mesh->printTol, locFbc));
5565: PetscCall(VecDestroy(&locFbc));
5566: }
5567: end:
5568: PetscCall(PetscLogEventEnd(DMPLEX_ResidualFEM, dm, 0, 0, 0));
5569: PetscFunctionReturn(PETSC_SUCCESS);
5570: }
5572: /*@
5573: DMPlexComputeResidualHybridByKey - Compute the local residual over hybrid cells for terms matching the input key
5575: Collective
5577: Input Parameters:
5578: + dm - The output `DM`
5579: . key - The `PetscFormKey` array (left cell, right cell, cohesive cell) indicating what should be integrated
5580: . cellIS - The `IS` give a set of cells to integrate over
5581: . time - The time, or `PETSC_MIN_REAL` to include implicit terms in a time-independent problems
5582: . locX - The local solution
5583: . locX_t - The time derivative of the local solution, or `NULL` for time-independent problems
5584: . t - The time
5585: - ctx - An optional application context, passed to the pointwise functions
5587: Output Parameter:
5588: . locF - The local residual
5590: Level: developer
5592: .seealso: `DMPlexComputeResidualByKey()`, `DMPlexComputeJacobianByKey()`, `DMPlexComputeJacobianHybridByKey()`, `PetscFormKey`
5593: @*/
5594: PetscErrorCode DMPlexComputeResidualHybridByKey(DM dm, PetscFormKey key[], IS cellIS, PetscReal time, Vec locX, Vec locX_t, PetscReal t, Vec locF, PetscCtx ctx)
5595: {
5596: DM_Plex *mesh = (DM_Plex *)dm->data;
5597: const char *name = "Hybrid Residual";
5598: DM dmAux[3] = {NULL, NULL, NULL};
5599: DMLabel ghostLabel = NULL;
5600: PetscDS ds = NULL;
5601: PetscDS dsIn = NULL;
5602: PetscDS dsAux[3] = {NULL, NULL, NULL};
5603: Vec locA[3] = {NULL, NULL, NULL};
5604: DM dmScale[3] = {NULL, NULL, NULL};
5605: PetscDS dsScale[3] = {NULL, NULL, NULL};
5606: Vec locS[3] = {NULL, NULL, NULL};
5607: PetscSection section = NULL;
5608: DMField coordField = NULL;
5609: PetscScalar *a[3] = {NULL, NULL, NULL};
5610: PetscScalar *s[3] = {NULL, NULL, NULL};
5611: PetscScalar *u = NULL, *u_t;
5612: PetscScalar *elemVecNeg, *elemVecPos, *elemVecCoh;
5613: IS chunkISF, chunkISN;
5614: const PetscInt *cells;
5615: PetscInt *faces, *neighbors;
5616: PetscInt cStart, cEnd, numCells;
5617: PetscInt Nf, f, totDim, totDimIn, totDimAux[3], totDimScale[3], numChunks, cellChunkSize, chunk;
5618: PetscInt maxDegree = PETSC_INT_MAX;
5619: PetscQuadrature affineQuadF = NULL, *quadsF = NULL;
5620: PetscFEGeom *affineGeomF = NULL, **geomsF = NULL;
5621: PetscQuadrature affineQuadN = NULL, *quadsN = NULL;
5622: PetscFEGeom *affineGeomN = NULL, **geomsN = NULL;
5624: PetscFunctionBegin;
5625: PetscCall(PetscLogEventBegin(DMPLEX_ResidualFEM, dm, 0, 0, 0));
5626: if (!cellIS) goto end;
5627: PetscCall(ISGetPointRange(cellIS, &cStart, &cEnd, &cells));
5628: PetscCall(ISGetLocalSize(cellIS, &numCells));
5629: if (cStart >= cEnd) goto end;
5630: if ((key[0].label == key[1].label) && (key[0].value == key[1].value) && (key[0].part == key[1].part)) {
5631: const char *name;
5632: PetscCall(PetscObjectGetName((PetscObject)key[0].label, &name));
5633: SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Form keys for each side of a cohesive surface must be different (%s, %" PetscInt_FMT ", %" PetscInt_FMT ")", name, key[0].value, key[0].part);
5634: }
5635: /* TODO The places where we have to use isFE are probably the member functions for the PetscDisc class */
5636: /* FEM */
5637: /* 1: Get sizes from dm and dmAux */
5638: PetscCall(DMGetLocalSection(dm, §ion));
5639: PetscCall(DMGetLabel(dm, "ghost", &ghostLabel));
5640: PetscCall(DMGetCellDS(dm, cells ? cells[cStart] : cStart, &ds, &dsIn));
5641: PetscCall(PetscDSGetNumFields(ds, &Nf));
5642: PetscCall(PetscDSGetTotalDimension(ds, &totDim));
5643: PetscCall(PetscDSGetTotalDimension(dsIn, &totDimIn));
5644: PetscCall(DMGetAuxiliaryVec(dm, key[2].label, key[2].value, key[2].part, &locA[2]));
5645: if (locA[2]) {
5646: const PetscInt cellStart = cells ? cells[cStart] : cStart;
5648: PetscCall(VecGetDM(locA[2], &dmAux[2]));
5649: PetscCall(DMGetCellDS(dmAux[2], cellStart, &dsAux[2], NULL));
5650: PetscCall(PetscDSGetTotalDimension(dsAux[2], &totDimAux[2]));
5651: {
5652: const PetscInt *cone;
5653: PetscInt c;
5655: PetscCall(DMPlexGetCone(dm, cellStart, &cone));
5656: for (c = 0; c < 2; ++c) {
5657: const PetscInt *support;
5658: PetscInt ssize, s;
5660: PetscCall(DMPlexGetSupport(dm, cone[c], &support));
5661: PetscCall(DMPlexGetSupportSize(dm, cone[c], &ssize));
5662: PetscCheck(ssize == 2, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Face %" PetscInt_FMT " from cell %" PetscInt_FMT " has support size %" PetscInt_FMT " != 2", cone[c], cellStart, ssize);
5663: if (support[0] == cellStart) s = 1;
5664: else if (support[1] == cellStart) s = 0;
5665: else SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Face %" PetscInt_FMT " does not have cell %" PetscInt_FMT " in its support", cone[c], cellStart);
5666: PetscCall(DMGetAuxiliaryVec(dm, key[c].label, key[c].value, key[c].part, &locA[c]));
5667: PetscCheck(locA[c], PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Must have auxiliary vector for (%p, %" PetscInt_FMT ", %" PetscInt_FMT ")", (void *)key[c].label, key[c].value, key[c].part);
5668: if (locA[c]) PetscCall(VecGetDM(locA[c], &dmAux[c]));
5669: else dmAux[c] = dmAux[2];
5670: PetscCall(DMGetCellDS(dmAux[c], support[s], &dsAux[c], NULL));
5671: PetscCall(PetscDSGetTotalDimension(dsAux[c], &totDimAux[c]));
5672: }
5673: }
5674: }
5675: /* Handle mass matrix scaling
5676: The field in key[2] is the field to be scaled, and the scaling field is the first in the dsScale */
5677: PetscCall(DMGetAuxiliaryVec(dm, key[2].label, -key[2].value, key[2].part, &locS[2]));
5678: if (locS[2]) {
5679: const PetscInt cellStart = cells ? cells[cStart] : cStart;
5680: PetscInt Nb, Nbs;
5682: PetscCall(VecGetDM(locS[2], &dmScale[2]));
5683: PetscCall(DMGetCellDS(dmScale[2], cellStart, &dsScale[2], NULL));
5684: PetscCall(PetscDSGetTotalDimension(dsScale[2], &totDimScale[2]));
5685: // BRAD: This is not set correctly
5686: key[2].field = 2;
5687: PetscCall(PetscDSGetFieldSize(ds, key[2].field, &Nb));
5688: PetscCall(PetscDSGetFieldSize(dsScale[2], 0, &Nbs));
5689: PetscCheck(Nb == Nbs, PETSC_COMM_SELF, PETSC_ERR_ARG_INCOMP, "Field %" PetscInt_FMT " of size %" PetscInt_FMT " cannot be scaled by field of size %" PetscInt_FMT, key[2].field, Nb, Nbs);
5690: {
5691: const PetscInt *cone;
5692: PetscInt c;
5694: locS[1] = locS[0] = locS[2];
5695: dmScale[1] = dmScale[0] = dmScale[2];
5696: PetscCall(DMPlexGetCone(dm, cellStart, &cone));
5697: for (c = 0; c < 2; ++c) {
5698: const PetscInt *support;
5699: PetscInt ssize, s;
5701: PetscCall(DMPlexGetSupport(dm, cone[c], &support));
5702: PetscCall(DMPlexGetSupportSize(dm, cone[c], &ssize));
5703: PetscCheck(ssize == 2, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Face %" PetscInt_FMT " from cell %" PetscInt_FMT " has support size %" PetscInt_FMT " != 2", cone[c], cellStart, ssize);
5704: if (support[0] == cellStart) s = 1;
5705: else if (support[1] == cellStart) s = 0;
5706: else SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Face %" PetscInt_FMT " does not have cell %" PetscInt_FMT " in its support", cone[c], cellStart);
5707: PetscCall(DMGetCellDS(dmScale[c], support[s], &dsScale[c], NULL));
5708: PetscCall(PetscDSGetTotalDimension(dsScale[c], &totDimScale[c]));
5709: }
5710: }
5711: }
5712: /* 2: Setup geometric data */
5713: PetscCall(DMGetCoordinateField(dm, &coordField));
5714: PetscCall(DMFieldGetDegree(coordField, cellIS, NULL, &maxDegree));
5715: if (maxDegree > 1) {
5716: PetscCall(PetscCalloc4(Nf, &quadsF, Nf, &geomsF, Nf, &quadsN, Nf, &geomsN));
5717: for (f = 0; f < Nf; ++f) {
5718: PetscFE fe;
5719: PetscBool isCohesiveField;
5721: PetscCall(PetscDSGetDiscretization(ds, f, (PetscObject *)&fe));
5722: if (fe) {
5723: PetscCall(PetscFEGetQuadrature(fe, &quadsF[f]));
5724: PetscCall(PetscObjectReference((PetscObject)quadsF[f]));
5725: }
5726: PetscCall(PetscDSGetDiscretization(dsIn, f, (PetscObject *)&fe));
5727: PetscCall(PetscDSGetCohesive(dsIn, f, &isCohesiveField));
5728: if (fe) {
5729: if (isCohesiveField) {
5730: for (PetscInt g = 0; g < Nf; ++g) {
5731: PetscCall(PetscDSGetDiscretization(dsIn, g, (PetscObject *)&fe));
5732: PetscCall(PetscDSGetCohesive(dsIn, g, &isCohesiveField));
5733: if (!isCohesiveField) break;
5734: }
5735: }
5736: PetscCall(PetscFEGetQuadrature(fe, &quadsN[f]));
5737: PetscCall(PetscObjectReference((PetscObject)quadsN[f]));
5738: }
5739: }
5740: }
5741: /* Loop over chunks */
5742: cellChunkSize = numCells;
5743: numChunks = !numCells ? 0 : PetscCeilReal(((PetscReal)numCells) / cellChunkSize);
5744: PetscCall(PetscCalloc2(2 * cellChunkSize, &faces, 2 * cellChunkSize, &neighbors));
5745: PetscCall(ISCreateGeneral(PETSC_COMM_SELF, 2 * cellChunkSize, faces, PETSC_USE_POINTER, &chunkISF));
5746: PetscCall(ISCreateGeneral(PETSC_COMM_SELF, 2 * cellChunkSize, neighbors, PETSC_USE_POINTER, &chunkISN));
5747: /* Extract field coefficients */
5748: /* NOTE This needs the end cap faces to have identical orientations */
5749: PetscCall(DMPlexGetHybridCellFields(dm, cellIS, locX, locX_t, locA[2], &u, &u_t, &a[2]));
5750: PetscCall(DMPlexGetHybridFields(dm, dmAux, dsAux, cellIS, locA, PETSC_TRUE, a));
5751: PetscCall(DMPlexGetHybridFields(dm, dmScale, dsScale, cellIS, locS, PETSC_TRUE, s));
5752: PetscCall(DMGetWorkArray(dm, cellChunkSize * totDim, MPIU_SCALAR, &elemVecNeg));
5753: PetscCall(DMGetWorkArray(dm, cellChunkSize * totDim, MPIU_SCALAR, &elemVecPos));
5754: PetscCall(DMGetWorkArray(dm, cellChunkSize * totDim, MPIU_SCALAR, &elemVecCoh));
5755: for (chunk = 0; chunk < numChunks; ++chunk) {
5756: PetscInt cS = cStart + chunk * cellChunkSize, cE = PetscMin(cS + cellChunkSize, cEnd), numCells = cE - cS, c;
5758: PetscCall(PetscArrayzero(elemVecNeg, cellChunkSize * totDim));
5759: PetscCall(PetscArrayzero(elemVecPos, cellChunkSize * totDim));
5760: PetscCall(PetscArrayzero(elemVecCoh, cellChunkSize * totDim));
5761: /* Get faces and neighbors */
5762: for (c = cS; c < cE; ++c) {
5763: const PetscInt cell = cells ? cells[c] : c;
5764: const PetscInt *cone, *support;
5765: PetscCall(DMPlexGetCone(dm, cell, &cone));
5766: faces[(c - cS) * 2 + 0] = cone[0];
5767: faces[(c - cS) * 2 + 1] = cone[1];
5768: PetscCall(DMPlexGetSupport(dm, cone[0], &support));
5769: neighbors[(c - cS) * 2 + 0] = support[0] == cell ? support[1] : support[0];
5770: PetscCall(DMPlexGetSupport(dm, cone[1], &support));
5771: neighbors[(c - cS) * 2 + 1] = support[0] == cell ? support[1] : support[0];
5772: }
5773: PetscCall(ISGeneralSetIndices(chunkISF, 2 * cellChunkSize, faces, PETSC_USE_POINTER));
5774: PetscCall(ISGeneralSetIndices(chunkISN, 2 * cellChunkSize, neighbors, PETSC_USE_POINTER));
5775: /* Get geometric data */
5776: if (maxDegree <= 1) {
5777: if (!affineQuadF) PetscCall(DMFieldCreateDefaultQuadrature(coordField, chunkISF, &affineQuadF));
5778: if (affineQuadF) PetscCall(DMSNESGetFEGeom(coordField, chunkISF, affineQuadF, PETSC_FEGEOM_COHESIVE, &affineGeomF));
5779: if (!affineQuadN) {
5780: PetscInt dim;
5781: PetscCall(PetscQuadratureGetData(affineQuadF, &dim, NULL, NULL, NULL, NULL));
5782: PetscCall(DMFieldCreateDefaultFaceQuadrature(coordField, chunkISN, &affineQuadN));
5783: PetscCall(PetscQuadratureSetData(affineQuadN, dim + 1, PETSC_DECIDE, PETSC_DECIDE, NULL, NULL));
5784: }
5785: if (affineQuadN) PetscCall(DMSNESGetFEGeom(coordField, chunkISN, affineQuadN, PETSC_FEGEOM_BASIC, &affineGeomN));
5786: } else {
5787: for (f = 0; f < Nf; ++f) {
5788: if (quadsF[f]) PetscCall(DMSNESGetFEGeom(coordField, chunkISF, quadsF[f], PETSC_FEGEOM_COHESIVE, &geomsF[f]));
5789: if (quadsN[f]) PetscCall(DMSNESGetFEGeom(coordField, chunkISN, quadsN[f], PETSC_FEGEOM_BASIC, &geomsN[f]));
5790: }
5791: }
5792: /* Loop over fields */
5793: for (f = 0; f < Nf; ++f) {
5794: PetscFE fe;
5795: PetscFEGeom *geomF = affineGeomF ? affineGeomF : geomsF[f];
5796: PetscFEGeom *chunkGeomF = NULL, *remGeomF = NULL;
5797: PetscFEGeom *geomN = affineGeomN ? affineGeomN : geomsN[f];
5798: PetscFEGeom *chunkGeomN = NULL, *remGeomN = NULL;
5799: PetscQuadrature quadF = affineQuadF ? affineQuadF : quadsF[f];
5800: PetscInt numChunks, numBatches, batchSize, numBlocks, blockSize, Ne, Nr, offset, Nq, Nb;
5801: PetscBool isCohesiveField;
5803: PetscCall(PetscDSGetDiscretization(ds, f, (PetscObject *)&fe));
5804: if (!fe) continue;
5805: PetscCall(PetscFEGetTileSizes(fe, NULL, &numBlocks, NULL, &numBatches));
5806: PetscCall(PetscQuadratureGetData(quadF, NULL, NULL, &Nq, NULL, NULL));
5807: PetscCall(PetscFEGetDimension(fe, &Nb));
5808: blockSize = Nb;
5809: batchSize = numBlocks * blockSize;
5810: PetscCall(PetscFESetTileSizes(fe, blockSize, numBlocks, batchSize, numBatches));
5811: numChunks = numCells / (numBatches * batchSize);
5812: Ne = numChunks * numBatches * batchSize;
5813: Nr = numCells % (numBatches * batchSize);
5814: offset = numCells - Nr;
5815: PetscCall(PetscFEGeomGetChunk(geomF, 0, offset * 2, &chunkGeomF));
5816: PetscCall(PetscFEGeomGetChunk(geomF, offset * 2, numCells * 2, &remGeomF));
5817: PetscCall(PetscFEGeomGetChunk(geomN, 0, offset * 2, &chunkGeomN));
5818: PetscCall(PetscFEGeomGetChunk(geomN, offset * 2, numCells * 2, &remGeomN));
5819: PetscCall(PetscDSGetCohesive(ds, f, &isCohesiveField));
5820: // TODO Do I need to set isCohesive on the chunks?
5821: key[0].field = f;
5822: key[1].field = f;
5823: key[2].field = f;
5824: PetscCall(PetscFEIntegrateHybridResidual(ds, dsIn, key[0], 0, Ne, chunkGeomF, chunkGeomN, u, u_t, dsAux[0], a[0], t, elemVecNeg));
5825: PetscCall(PetscFEIntegrateHybridResidual(ds, dsIn, key[0], 0, Nr, remGeomF, remGeomN, &u[offset * totDimIn], PetscSafePointerPlusOffset(u_t, offset * totDimIn), dsAux[0], PetscSafePointerPlusOffset(a[0], offset * totDimAux[0]), t, &elemVecNeg[offset * totDim]));
5826: PetscCall(PetscFEIntegrateHybridResidual(ds, dsIn, key[1], 1, Ne, chunkGeomF, chunkGeomN, u, u_t, dsAux[1], a[1], t, elemVecPos));
5827: PetscCall(PetscFEIntegrateHybridResidual(ds, dsIn, key[1], 1, Nr, remGeomF, remGeomN, &u[offset * totDimIn], PetscSafePointerPlusOffset(u_t, offset * totDimIn), dsAux[1], PetscSafePointerPlusOffset(a[1], offset * totDimAux[1]), t, &elemVecPos[offset * totDim]));
5828: PetscCall(PetscFEIntegrateHybridResidual(ds, dsIn, key[2], 2, Ne, chunkGeomF, chunkGeomN, u, u_t, dsAux[2], a[2], t, elemVecCoh));
5829: PetscCall(PetscFEIntegrateHybridResidual(ds, dsIn, key[2], 2, Nr, remGeomF, remGeomN, &u[offset * totDimIn], PetscSafePointerPlusOffset(u_t, offset * totDimIn), dsAux[2], PetscSafePointerPlusOffset(a[2], offset * totDimAux[2]), t, &elemVecCoh[offset * totDim]));
5830: PetscCall(PetscFEGeomRestoreChunk(geomF, offset, numCells, &remGeomF));
5831: PetscCall(PetscFEGeomRestoreChunk(geomF, 0, offset, &chunkGeomF));
5832: PetscCall(PetscFEGeomRestoreChunk(geomN, offset, numCells, &remGeomN));
5833: PetscCall(PetscFEGeomRestoreChunk(geomN, 0, offset, &chunkGeomN));
5834: }
5835: /* Add elemVec to locX */
5836: for (c = cS; c < cE; ++c) {
5837: const PetscInt cell = cells ? cells[c] : c;
5838: const PetscInt cind = c - cStart;
5839: PetscInt i;
5841: /* Scale element values */
5842: if (locS[0]) {
5843: PetscInt Nb, off = cind * totDim, soff = cind * totDimScale[0];
5844: PetscBool cohesive;
5846: for (f = 0; f < Nf; ++f) {
5847: PetscCall(PetscDSGetFieldSize(ds, f, &Nb));
5848: PetscCall(PetscDSGetCohesive(ds, f, &cohesive));
5849: if (f == key[2].field) {
5850: PetscCheck(cohesive, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Scaling should not happen for face fields");
5851: // No cohesive scaling field is currently input
5852: for (i = 0; i < Nb; ++i) elemVecCoh[off + i] += s[0][soff + i] * elemVecNeg[off + i] + s[1][soff + i] * elemVecPos[off + i];
5853: off += Nb;
5854: } else {
5855: const PetscInt N = cohesive ? Nb : Nb * 2;
5857: for (i = 0; i < N; ++i) elemVecCoh[off + i] += elemVecNeg[off + i] + elemVecPos[off + i];
5858: off += N;
5859: }
5860: }
5861: } else {
5862: for (i = cind * totDim; i < (cind + 1) * totDim; ++i) elemVecCoh[i] += elemVecNeg[i] + elemVecPos[i];
5863: }
5864: if (mesh->printFEM > 1) PetscCall(DMPrintCellVector(cell, name, totDim, &elemVecCoh[cind * totDim]));
5865: if (ghostLabel) {
5866: PetscInt ghostVal;
5868: PetscCall(DMLabelGetValue(ghostLabel, cell, &ghostVal));
5869: if (ghostVal > 0) continue;
5870: }
5871: PetscCall(DMPlexVecSetClosure(dm, section, locF, cell, &elemVecCoh[cind * totDim], ADD_ALL_VALUES));
5872: }
5873: }
5874: PetscCall(DMPlexRestoreCellFields(dm, cellIS, locX, locX_t, locA[2], &u, &u_t, &a[2]));
5875: PetscCall(DMPlexRestoreHybridFields(dm, dmAux, dsAux, cellIS, locA, PETSC_TRUE, a));
5876: PetscCall(DMPlexRestoreHybridFields(dm, dmScale, dsScale, cellIS, locS, PETSC_TRUE, s));
5877: PetscCall(DMRestoreWorkArray(dm, numCells * totDim, MPIU_SCALAR, &elemVecNeg));
5878: PetscCall(DMRestoreWorkArray(dm, numCells * totDim, MPIU_SCALAR, &elemVecPos));
5879: PetscCall(DMRestoreWorkArray(dm, numCells * totDim, MPIU_SCALAR, &elemVecCoh));
5880: PetscCall(PetscFree2(faces, neighbors));
5881: PetscCall(ISDestroy(&chunkISF));
5882: PetscCall(ISDestroy(&chunkISN));
5883: PetscCall(ISRestorePointRange(cellIS, &cStart, &cEnd, &cells));
5884: if (maxDegree <= 1) {
5885: PetscCall(DMSNESRestoreFEGeom(coordField, cellIS, affineQuadF, PETSC_FALSE, &affineGeomF));
5886: PetscCall(PetscQuadratureDestroy(&affineQuadF));
5887: PetscCall(DMSNESRestoreFEGeom(coordField, cellIS, affineQuadN, PETSC_FALSE, &affineGeomN));
5888: PetscCall(PetscQuadratureDestroy(&affineQuadN));
5889: } else {
5890: for (f = 0; f < Nf; ++f) {
5891: if (geomsF) PetscCall(DMSNESRestoreFEGeom(coordField, cellIS, quadsF[f], PETSC_FALSE, &geomsF[f]));
5892: if (quadsF) PetscCall(PetscQuadratureDestroy(&quadsF[f]));
5893: if (geomsN) PetscCall(DMSNESRestoreFEGeom(coordField, cellIS, quadsN[f], PETSC_FALSE, &geomsN[f]));
5894: if (quadsN) PetscCall(PetscQuadratureDestroy(&quadsN[f]));
5895: }
5896: PetscCall(PetscFree4(quadsF, geomsF, quadsN, geomsN));
5897: }
5898: if (mesh->printFEM) {
5899: Vec locFbc;
5900: PetscInt pStart, pEnd, p, maxDof;
5901: PetscScalar *zeroes;
5903: PetscCall(VecDuplicate(locF, &locFbc));
5904: PetscCall(VecCopy(locF, locFbc));
5905: PetscCall(PetscSectionGetChart(section, &pStart, &pEnd));
5906: PetscCall(PetscSectionGetMaxDof(section, &maxDof));
5907: PetscCall(PetscCalloc1(maxDof, &zeroes));
5908: for (p = pStart; p < pEnd; p++) PetscCall(VecSetValuesSection(locFbc, section, p, zeroes, INSERT_BC_VALUES));
5909: PetscCall(PetscFree(zeroes));
5910: PetscCall(DMPrintLocalVec(dm, name, mesh->printTol, locFbc));
5911: PetscCall(VecDestroy(&locFbc));
5912: }
5913: end:
5914: PetscCall(PetscLogEventEnd(DMPLEX_ResidualFEM, dm, 0, 0, 0));
5915: PetscFunctionReturn(PETSC_SUCCESS);
5916: }
5918: /*@
5919: DMPlexComputeBdJacobianSingleByLabel - Compute the local boundary Jacobian for terms matching the input label
5921: Not collective
5923: Input Parameters:
5924: + dm - The output `DM`
5925: . wf - The `PetscWeakForm` holding forms on this boundary
5926: . label - The `DMLabel` indicating what faces should be integrated over
5927: . numValues - The number of label values
5928: . values - The array of label values
5929: . fieldI - The test field for these integrals
5930: . facetIS - The `IS` giving the set of possible faces to integrate over (intersected with the label)
5931: . locX - The local solution
5932: . locX_t - The time derivative of the local solution, or `NULL` for time-independent problems
5933: . t - The time
5934: . coordField - The `DMField` object with coordinates for these faces
5935: - X_tShift - The multiplier for dF/dxdot
5937: Output Parameters:
5938: + Jac - The local Jacobian
5939: - JacP - The local Jacobian preconditioner
5941: Level: developer
5943: .seealso: `DMPlexComputeBdJacobianSingle()`, `DMPlexComputeJacobianByKey()`, `DMPlexComputeResidualHybridByKey()`, `DMPlexComputeJacobianHybridByKey()`, `PetscFormKey`
5944: @*/
5945: PetscErrorCode DMPlexComputeBdJacobianSingleByLabel(DM dm, PetscWeakForm wf, DMLabel label, PetscInt numValues, const PetscInt values[], PetscInt fieldI, IS facetIS, Vec locX, Vec locX_t, PetscReal t, DMField coordField, PetscReal X_tShift, Mat Jac, Mat JacP)
5946: {
5947: DM_Plex *mesh = (DM_Plex *)dm->data;
5948: DM plex = NULL, plexA = NULL, tdm;
5949: DMEnclosureType encAux;
5950: PetscDS ds, dsAux = NULL;
5951: PetscSection section, sectionAux = NULL;
5952: PetscSection globalSection;
5953: Vec locA = NULL, tv;
5954: PetscScalar *u = NULL, *u_t = NULL, *a = NULL, *elemMat = NULL, *elemMatP = NULL;
5955: PetscInt v;
5956: PetscInt Nf, totDim, totDimAux = 0;
5957: PetscBool hasJac = PETSC_FALSE, hasPrec = PETSC_FALSE, transform;
5959: PetscFunctionBegin;
5960: PetscCall(DMHasBasisTransform(dm, &transform));
5961: PetscCall(DMGetBasisTransformDM_Internal(dm, &tdm));
5962: PetscCall(DMGetBasisTransformVec_Internal(dm, &tv));
5963: PetscCall(DMGetLocalSection(dm, §ion));
5964: PetscCall(DMGetDS(dm, &ds));
5965: PetscCall(PetscDSGetNumFields(ds, &Nf));
5966: PetscCall(PetscDSGetTotalDimension(ds, &totDim));
5967: PetscCall(PetscWeakFormHasBdJacobian(wf, &hasJac));
5968: PetscCall(PetscWeakFormHasBdJacobianPreconditioner(wf, &hasPrec));
5969: if (!hasJac && !hasPrec) PetscFunctionReturn(PETSC_SUCCESS);
5970: PetscCall(DMConvert(dm, DMPLEX, &plex));
5971: PetscCall(DMGetAuxiliaryVec(dm, label, values[0], 0, &locA));
5972: if (locA) {
5973: DM dmAux;
5975: PetscCall(VecGetDM(locA, &dmAux));
5976: PetscCall(DMGetEnclosureRelation(dmAux, dm, &encAux));
5977: PetscCall(DMConvert(dmAux, DMPLEX, &plexA));
5978: PetscCall(DMGetDS(plexA, &dsAux));
5979: PetscCall(PetscDSGetTotalDimension(dsAux, &totDimAux));
5980: PetscCall(DMGetLocalSection(plexA, §ionAux));
5981: }
5983: PetscCall(DMGetGlobalSection(dm, &globalSection));
5984: for (v = 0; v < numValues; ++v) {
5985: PetscFEGeom *fgeom;
5986: PetscInt maxDegree;
5987: PetscQuadrature qGeom = NULL;
5988: IS pointIS;
5989: const PetscInt *points;
5990: PetscFormKey key;
5991: PetscInt numFaces, face, Nq;
5993: key.label = label;
5994: key.value = values[v];
5995: key.part = 0;
5996: PetscCall(DMLabelGetStratumIS(label, values[v], &pointIS));
5997: if (!pointIS) continue; /* No points with that id on this process */
5998: {
5999: IS isectIS;
6001: /* TODO: Special cases of ISIntersect where it is quick to check a prior if one is a superset of the other */
6002: PetscCall(ISIntersect_Caching_Internal(facetIS, pointIS, &isectIS));
6003: PetscCall(ISDestroy(&pointIS));
6004: pointIS = isectIS;
6005: }
6006: PetscCall(ISGetLocalSize(pointIS, &numFaces));
6007: PetscCall(ISGetIndices(pointIS, &points));
6008: PetscCall(PetscMalloc5(numFaces * totDim, &u, (locX_t ? (size_t)numFaces * totDim : 0), &u_t, (hasJac ? (size_t)numFaces * totDim * totDim : 0), &elemMat, (hasPrec ? (size_t)numFaces * totDim * totDim : 0), &elemMatP, (locA ? (size_t)numFaces * totDimAux : 0), &a));
6009: PetscCall(DMFieldGetDegree(coordField, pointIS, NULL, &maxDegree));
6010: if (maxDegree <= 1) PetscCall(DMFieldCreateDefaultQuadrature(coordField, pointIS, &qGeom));
6011: if (!qGeom) {
6012: PetscFE fe;
6014: PetscCall(PetscDSGetDiscretization(ds, fieldI, (PetscObject *)&fe));
6015: PetscCall(PetscFEGetFaceQuadrature(fe, &qGeom));
6016: PetscCall(PetscObjectReference((PetscObject)qGeom));
6017: }
6018: PetscCall(PetscQuadratureGetData(qGeom, NULL, NULL, &Nq, NULL, NULL));
6019: PetscCall(DMSNESGetFEGeom(coordField, pointIS, qGeom, PETSC_FEGEOM_BOUNDARY, &fgeom));
6020: for (face = 0; face < numFaces; ++face) {
6021: const PetscInt point = points[face], *support;
6022: PetscScalar *x = NULL;
6023: PetscInt i;
6025: PetscCall(DMPlexGetSupport(dm, point, &support));
6026: PetscCall(DMPlexVecGetClosure(plex, section, locX, support[0], NULL, &x));
6027: for (i = 0; i < totDim; ++i) u[face * totDim + i] = x[i];
6028: PetscCall(DMPlexVecRestoreClosure(plex, section, locX, support[0], NULL, &x));
6029: if (locX_t) {
6030: PetscCall(DMPlexVecGetClosure(plex, section, locX_t, support[0], NULL, &x));
6031: for (i = 0; i < totDim; ++i) u_t[face * totDim + i] = x[i];
6032: PetscCall(DMPlexVecRestoreClosure(plex, section, locX_t, support[0], NULL, &x));
6033: }
6034: if (locA) {
6035: PetscInt subp;
6036: PetscCall(DMGetEnclosurePoint(plexA, dm, encAux, support[0], &subp));
6037: PetscCall(DMPlexVecGetClosure(plexA, sectionAux, locA, subp, NULL, &x));
6038: for (i = 0; i < totDimAux; ++i) a[face * totDimAux + i] = x[i];
6039: PetscCall(DMPlexVecRestoreClosure(plexA, sectionAux, locA, subp, NULL, &x));
6040: }
6041: }
6042: if (elemMat) PetscCall(PetscArrayzero(elemMat, numFaces * totDim * totDim));
6043: if (elemMatP) PetscCall(PetscArrayzero(elemMatP, numFaces * totDim * totDim));
6044: {
6045: PetscFE fe;
6046: PetscInt Nb;
6047: /* Conforming batches */
6048: PetscInt numChunks, numBatches, numBlocks, Ne, blockSize, batchSize;
6049: /* Remainder */
6050: PetscFEGeom *chunkGeom = NULL;
6051: PetscInt fieldJ, Nr, offset;
6053: PetscCall(PetscDSGetDiscretization(ds, fieldI, (PetscObject *)&fe));
6054: PetscCall(PetscFEGetDimension(fe, &Nb));
6055: PetscCall(PetscFEGetTileSizes(fe, NULL, &numBlocks, NULL, &numBatches));
6056: blockSize = Nb;
6057: batchSize = numBlocks * blockSize;
6058: PetscCall(PetscFESetTileSizes(fe, blockSize, numBlocks, batchSize, numBatches));
6059: numChunks = numFaces / (numBatches * batchSize);
6060: Ne = numChunks * numBatches * batchSize;
6061: Nr = numFaces % (numBatches * batchSize);
6062: offset = numFaces - Nr;
6063: PetscCall(PetscFEGeomGetChunk(fgeom, 0, offset, &chunkGeom));
6064: for (fieldJ = 0; fieldJ < Nf; ++fieldJ) {
6065: key.field = fieldI * Nf + fieldJ;
6066: if (hasJac) PetscCall(PetscFEIntegrateBdJacobian(ds, wf, PETSCFE_JACOBIAN, key, Ne, chunkGeom, u, u_t, dsAux, a, t, X_tShift, elemMat));
6067: if (hasPrec) PetscCall(PetscFEIntegrateBdJacobian(ds, wf, PETSCFE_JACOBIAN_PRE, key, Ne, chunkGeom, u, u_t, dsAux, a, t, X_tShift, elemMatP));
6068: }
6069: PetscCall(PetscFEGeomGetChunk(fgeom, offset, numFaces, &chunkGeom));
6070: for (fieldJ = 0; fieldJ < Nf; ++fieldJ) {
6071: key.field = fieldI * Nf + fieldJ;
6072: if (hasJac)
6073: PetscCall(PetscFEIntegrateBdJacobian(ds, wf, PETSCFE_JACOBIAN, key, Nr, chunkGeom, &u[offset * totDim], PetscSafePointerPlusOffset(u_t, offset * totDim), dsAux, PetscSafePointerPlusOffset(a, offset * totDimAux), t, X_tShift, &elemMat[offset * totDim * totDim]));
6074: if (hasPrec)
6075: PetscCall(PetscFEIntegrateBdJacobian(ds, wf, PETSCFE_JACOBIAN_PRE, key, Nr, chunkGeom, &u[offset * totDim], PetscSafePointerPlusOffset(u_t, offset * totDim), dsAux, PetscSafePointerPlusOffset(a, offset * totDimAux), t, X_tShift, &elemMatP[offset * totDim * totDim]));
6076: }
6077: PetscCall(PetscFEGeomRestoreChunk(fgeom, offset, numFaces, &chunkGeom));
6078: }
6079: for (face = 0; face < numFaces; ++face) {
6080: const PetscInt point = points[face], *support;
6082: /* Transform to global basis before insertion in Jacobian */
6083: PetscCall(DMPlexGetSupport(plex, point, &support));
6084: if (hasJac && transform) PetscCall(DMPlexBasisTransformPointTensor_Internal(dm, tdm, tv, support[0], PETSC_TRUE, totDim, &elemMat[face * totDim * totDim]));
6085: if (hasPrec && transform) PetscCall(DMPlexBasisTransformPointTensor_Internal(dm, tdm, tv, support[0], PETSC_TRUE, totDim, &elemMatP[face * totDim * totDim]));
6086: if (hasPrec) {
6087: if (hasJac) {
6088: if (mesh->printFEM > 1) PetscCall(DMPrintCellMatrix(point, "BdJacobian", totDim, totDim, &elemMat[face * totDim * totDim]));
6089: PetscCall(DMPlexMatSetClosure_Internal(plex, section, globalSection, mesh->useMatClPerm, Jac, support[0], &elemMat[face * totDim * totDim], ADD_VALUES));
6090: }
6091: if (mesh->printFEM > 1) PetscCall(DMPrintCellMatrix(point, "BdJacobian", totDim, totDim, &elemMatP[face * totDim * totDim]));
6092: PetscCall(DMPlexMatSetClosure_Internal(plex, section, globalSection, mesh->useMatClPerm, JacP, support[0], &elemMatP[face * totDim * totDim], ADD_VALUES));
6093: } else {
6094: if (hasJac) {
6095: if (mesh->printFEM > 1) PetscCall(DMPrintCellMatrix(point, "BdJacobian", totDim, totDim, &elemMat[face * totDim * totDim]));
6096: PetscCall(DMPlexMatSetClosure_Internal(plex, section, globalSection, mesh->useMatClPerm, Jac, support[0], &elemMat[face * totDim * totDim], ADD_VALUES));
6097: }
6098: }
6099: }
6100: PetscCall(DMSNESRestoreFEGeom(coordField, pointIS, qGeom, PETSC_TRUE, &fgeom));
6101: PetscCall(PetscQuadratureDestroy(&qGeom));
6102: PetscCall(ISRestoreIndices(pointIS, &points));
6103: PetscCall(ISDestroy(&pointIS));
6104: PetscCall(PetscFree5(u, u_t, elemMat, elemMatP, a));
6105: }
6106: if (plex) PetscCall(DMDestroy(&plex));
6107: if (plexA) PetscCall(DMDestroy(&plexA));
6108: PetscFunctionReturn(PETSC_SUCCESS);
6109: }
6111: /*@
6112: DMPlexComputeBdJacobianSingle - Compute the local boundary Jacobian
6114: Not collective
6116: Input Parameters:
6117: + dm - The output `DM`
6118: . wf - The `PetscWeakForm` holding forms on this boundary
6119: . label - The `DMLabel` indicating what faces should be integrated over
6120: . numValues - The number of label values
6121: . values - The array of label values
6122: . fieldI - The test field for these integrals
6123: . locX - The local solution
6124: . locX_t - The time derivative of the local solution, or `NULL` for time-independent problems
6125: . t - The time
6126: - X_tShift - The multiplier for dF/dxdot
6128: Output Parameters:
6129: + Jac - The local Jacobian
6130: - JacP - The local Jacobian preconditioner
6132: Level: developer
6134: .seealso: `DMPlexComputeBdJacobianSingleByLabel()`, `DMPlexComputeJacobianByKey()`, `DMPlexComputeResidualHybridByKey()`, `DMPlexComputeJacobianHybridByKey()`, `PetscFormKey`
6135: @*/
6136: PetscErrorCode DMPlexComputeBdJacobianSingle(DM dm, PetscWeakForm wf, DMLabel label, PetscInt numValues, const PetscInt values[], PetscInt fieldI, Vec locX, Vec locX_t, PetscReal t, PetscReal X_tShift, Mat Jac, Mat JacP)
6137: {
6138: DMField coordField;
6139: DMLabel depthLabel;
6140: IS facetIS;
6141: PetscInt dim;
6143: PetscFunctionBegin;
6144: PetscCall(DMGetDimension(dm, &dim));
6145: PetscCall(DMPlexGetDepthLabel(dm, &depthLabel));
6146: PetscCall(DMLabelGetStratumIS(depthLabel, dim - 1, &facetIS));
6147: PetscCall(DMGetCoordinateField(dm, &coordField));
6148: PetscCall(DMPlexComputeBdJacobianSingleByLabel(dm, wf, label, numValues, values, fieldI, facetIS, locX, locX_t, t, coordField, X_tShift, Jac, JacP));
6149: PetscCall(ISDestroy(&facetIS));
6150: PetscFunctionReturn(PETSC_SUCCESS);
6151: }
6153: static PetscErrorCode DMPlexComputeBdJacobian_Internal(DM dm, Vec locX, Vec locX_t, PetscReal t, PetscReal X_tShift, Mat Jac, Mat JacP, PetscCtx ctx)
6154: {
6155: PetscDS prob;
6156: PetscInt dim, numBd, bd;
6157: DMLabel depthLabel;
6158: DMField coordField = NULL;
6159: IS facetIS;
6161: PetscFunctionBegin;
6162: PetscCall(DMGetDS(dm, &prob));
6163: PetscCall(DMPlexGetDepthLabel(dm, &depthLabel));
6164: PetscCall(DMGetDimension(dm, &dim));
6165: PetscCall(DMLabelGetStratumIS(depthLabel, dim - 1, &facetIS));
6166: PetscCall(PetscDSGetNumBoundary(prob, &numBd));
6167: PetscCall(DMGetCoordinateField(dm, &coordField));
6168: for (bd = 0; bd < numBd; ++bd) {
6169: PetscWeakForm wf;
6170: DMBoundaryConditionType type;
6171: DMLabel label;
6172: const PetscInt *values;
6173: PetscInt fieldI, numValues;
6174: PetscObject obj;
6175: PetscClassId id;
6177: PetscCall(PetscDSGetBoundary(prob, bd, &wf, &type, NULL, &label, &numValues, &values, &fieldI, NULL, NULL, NULL, NULL, NULL));
6178: if (type & DM_BC_ESSENTIAL) continue;
6179: PetscCall(PetscDSGetDiscretization(prob, fieldI, &obj));
6180: PetscCall(PetscObjectGetClassId(obj, &id));
6181: if (id != PETSCFE_CLASSID) continue;
6182: PetscCall(DMPlexComputeBdJacobianSingleByLabel(dm, wf, label, numValues, values, fieldI, facetIS, locX, locX_t, t, coordField, X_tShift, Jac, JacP));
6183: }
6184: PetscCall(ISDestroy(&facetIS));
6185: PetscFunctionReturn(PETSC_SUCCESS);
6186: }
6188: /*@
6189: DMPlexComputeJacobianByKey - Compute the local Jacobian for terms matching the input key
6191: Collective
6193: Input Parameters:
6194: + dm - The output `DM`
6195: . key - The `PetscFormKey` indicating what should be integrated
6196: . cellIS - The `IS` give a set of cells to integrate over
6197: . t - The time
6198: . X_tShift - The multiplier for the Jacobian with respect to $X_t$
6199: . locX - The local solution
6200: . locX_t - The time derivative of the local solution, or `NULL` for time-independent problems
6201: - ctx - An optional application context, passed to the pointwise functions
6203: Output Parameters:
6204: + Jac - The local Jacobian
6205: - JacP - The local Jacobian preconditioner
6207: Level: developer
6209: .seealso: `DMPlexComputeResidualByKey()`, `DMPlexComputeResidualHybridByKey()`, `DMPlexComputeJacobianHybridByKey()`, `PetscFormKey`
6210: @*/
6211: PetscErrorCode DMPlexComputeJacobianByKey(DM dm, PetscFormKey key, IS cellIS, PetscReal t, PetscReal X_tShift, Vec locX, Vec locX_t, Mat Jac, Mat JacP, PetscCtx ctx)
6212: {
6213: DM_Plex *mesh = (DM_Plex *)dm->data;
6214: const char *name = "Jacobian";
6215: DM dmAux = NULL, plex, tdm;
6216: DMEnclosureType encAux;
6217: Vec A, tv;
6218: DMField coordField;
6219: PetscDS prob, probAux = NULL;
6220: PetscSection section, globalSection, sectionAux;
6221: PetscScalar *elemMat, *elemMatP, *elemMatD, *u, *u_t, *a = NULL;
6222: const PetscInt *cells;
6223: PetscInt Nf, fieldI, fieldJ;
6224: PetscInt totDim, totDimAux = 0, cStart, cEnd, numCells, c;
6225: PetscBool hasJac = PETSC_FALSE, hasPrec = PETSC_FALSE, hasDyn, hasFV = PETSC_FALSE, transform;
6227: PetscFunctionBegin;
6228: PetscCall(PetscLogEventBegin(DMPLEX_JacobianFEM, dm, 0, 0, 0));
6229: PetscCall(DMGetLocalSection(dm, §ion));
6230: PetscCall(DMGetGlobalSection(dm, &globalSection));
6231: PetscCall(DMGetAuxiliaryVec(dm, key.label, key.value, key.part, &A));
6232: if (A) {
6233: PetscCall(VecGetDM(A, &dmAux));
6234: PetscCall(DMGetEnclosureRelation(dmAux, dm, &encAux));
6235: PetscCall(DMConvert(dmAux, DMPLEX, &plex));
6236: PetscCall(DMGetLocalSection(plex, §ionAux));
6237: PetscCall(DMGetDS(dmAux, &probAux));
6238: PetscCall(PetscDSGetTotalDimension(probAux, &totDimAux));
6239: }
6240: PetscCall(DMGetCoordinateField(dm, &coordField));
6241: if (!cellIS) goto end;
6242: PetscCall(ISGetPointRange(cellIS, &cStart, &cEnd, &cells));
6243: PetscCall(ISGetLocalSize(cellIS, &numCells));
6244: if (cStart >= cEnd) goto end;
6245: PetscCall(DMHasBasisTransform(dm, &transform));
6246: PetscCall(DMGetBasisTransformDM_Internal(dm, &tdm));
6247: PetscCall(DMGetBasisTransformVec_Internal(dm, &tv));
6248: PetscCall(DMGetCellDS(dm, cells ? cells[cStart] : cStart, &prob, NULL));
6249: PetscCall(PetscDSGetNumFields(prob, &Nf));
6250: PetscCall(PetscDSGetTotalDimension(prob, &totDim));
6251: PetscCall(PetscDSHasJacobian(prob, &hasJac));
6252: PetscCall(PetscDSHasJacobianPreconditioner(prob, &hasPrec));
6253: /* user passed in the same matrix, avoid double contributions and
6254: only assemble the Jacobian */
6255: if (hasJac && Jac == JacP) hasPrec = PETSC_FALSE;
6256: PetscCall(PetscDSHasDynamicJacobian(prob, &hasDyn));
6257: hasDyn = hasDyn && (X_tShift != 0.0) ? PETSC_TRUE : PETSC_FALSE;
6258: PetscCall(PetscMalloc5(numCells * totDim, &u, (locX_t ? (size_t)numCells * totDim : 0), &u_t, (hasJac ? (size_t)numCells * totDim * totDim : 0), &elemMat, (hasPrec ? (size_t)numCells * totDim * totDim : 0), &elemMatP, (hasDyn ? (size_t)numCells * totDim * totDim : 0), &elemMatD));
6259: if (dmAux) PetscCall(PetscMalloc1(numCells * totDimAux, &a));
6260: for (c = cStart; c < cEnd; ++c) {
6261: const PetscInt cell = cells ? cells[c] : c;
6262: const PetscInt cind = c - cStart;
6263: PetscScalar *x = NULL, *x_t = NULL;
6264: PetscInt i;
6266: PetscCall(DMPlexVecGetClosure(dm, section, locX, cell, NULL, &x));
6267: for (i = 0; i < totDim; ++i) u[cind * totDim + i] = x[i];
6268: PetscCall(DMPlexVecRestoreClosure(dm, section, locX, cell, NULL, &x));
6269: if (locX_t) {
6270: PetscCall(DMPlexVecGetClosure(dm, section, locX_t, cell, NULL, &x_t));
6271: for (i = 0; i < totDim; ++i) u_t[cind * totDim + i] = x_t[i];
6272: PetscCall(DMPlexVecRestoreClosure(dm, section, locX_t, cell, NULL, &x_t));
6273: }
6274: if (dmAux) {
6275: PetscInt subcell;
6276: PetscCall(DMGetEnclosurePoint(dmAux, dm, encAux, cell, &subcell));
6277: PetscCall(DMPlexVecGetClosure(plex, sectionAux, A, subcell, NULL, &x));
6278: for (i = 0; i < totDimAux; ++i) a[cind * totDimAux + i] = x[i];
6279: PetscCall(DMPlexVecRestoreClosure(plex, sectionAux, A, subcell, NULL, &x));
6280: }
6281: }
6282: if (hasJac) PetscCall(PetscArrayzero(elemMat, numCells * totDim * totDim));
6283: if (hasPrec) PetscCall(PetscArrayzero(elemMatP, numCells * totDim * totDim));
6284: if (hasDyn) PetscCall(PetscArrayzero(elemMatD, numCells * totDim * totDim));
6285: for (fieldI = 0; fieldI < Nf; ++fieldI) {
6286: PetscClassId id;
6287: PetscFE fe;
6288: PetscQuadrature qGeom = NULL;
6289: PetscInt Nb;
6290: /* Conforming batches */
6291: PetscInt numChunks, numBatches, numBlocks, Ne, blockSize, batchSize;
6292: /* Remainder */
6293: PetscInt Nr, offset, Nq;
6294: PetscInt maxDegree;
6295: PetscFEGeom *cgeomFEM, *chunkGeom = NULL, *remGeom = NULL;
6297: PetscCall(PetscDSGetDiscretization(prob, fieldI, (PetscObject *)&fe));
6298: PetscCall(PetscObjectGetClassId((PetscObject)fe, &id));
6299: if (id == PETSCFV_CLASSID) {
6300: hasFV = PETSC_TRUE;
6301: continue;
6302: }
6303: PetscCall(PetscFEGetDimension(fe, &Nb));
6304: PetscCall(PetscFEGetTileSizes(fe, NULL, &numBlocks, NULL, &numBatches));
6305: PetscCall(DMFieldGetDegree(coordField, cellIS, NULL, &maxDegree));
6306: if (maxDegree <= 1) PetscCall(DMFieldCreateDefaultQuadrature(coordField, cellIS, &qGeom));
6307: if (!qGeom) {
6308: PetscCall(PetscFEGetQuadrature(fe, &qGeom));
6309: PetscCall(PetscObjectReference((PetscObject)qGeom));
6310: }
6311: PetscCall(PetscQuadratureGetData(qGeom, NULL, NULL, &Nq, NULL, NULL));
6312: PetscCall(DMSNESGetFEGeom(coordField, cellIS, qGeom, PETSC_FEGEOM_BASIC, &cgeomFEM));
6313: blockSize = Nb;
6314: batchSize = numBlocks * blockSize;
6315: PetscCall(PetscFESetTileSizes(fe, blockSize, numBlocks, batchSize, numBatches));
6316: numChunks = numCells / (numBatches * batchSize);
6317: Ne = numChunks * numBatches * batchSize;
6318: Nr = numCells % (numBatches * batchSize);
6319: offset = numCells - Nr;
6320: PetscCall(PetscFEGeomGetChunk(cgeomFEM, 0, offset, &chunkGeom));
6321: PetscCall(PetscFEGeomGetChunk(cgeomFEM, offset, numCells, &remGeom));
6322: for (fieldJ = 0; fieldJ < Nf; ++fieldJ) {
6323: key.field = fieldI * Nf + fieldJ;
6324: if (hasJac) {
6325: PetscCall(PetscFEIntegrateJacobian(prob, prob, PETSCFE_JACOBIAN, key, Ne, chunkGeom, u, u_t, probAux, a, t, X_tShift, elemMat));
6326: PetscCall(PetscFEIntegrateJacobian(prob, prob, PETSCFE_JACOBIAN, key, Nr, remGeom, &u[offset * totDim], PetscSafePointerPlusOffset(u_t, offset * totDim), probAux, PetscSafePointerPlusOffset(a, offset * totDimAux), t, X_tShift, &elemMat[offset * totDim * totDim]));
6327: }
6328: if (hasPrec) {
6329: PetscCall(PetscFEIntegrateJacobian(prob, prob, PETSCFE_JACOBIAN_PRE, key, Ne, chunkGeom, u, u_t, probAux, a, t, X_tShift, elemMatP));
6330: PetscCall(PetscFEIntegrateJacobian(prob, prob, PETSCFE_JACOBIAN_PRE, key, Nr, remGeom, &u[offset * totDim], PetscSafePointerPlusOffset(u_t, offset * totDim), probAux, PetscSafePointerPlusOffset(a, offset * totDimAux), t, X_tShift, &elemMatP[offset * totDim * totDim]));
6331: }
6332: if (hasDyn) {
6333: PetscCall(PetscFEIntegrateJacobian(prob, prob, PETSCFE_JACOBIAN_DYN, key, Ne, chunkGeom, u, u_t, probAux, a, t, X_tShift, elemMatD));
6334: PetscCall(PetscFEIntegrateJacobian(prob, prob, PETSCFE_JACOBIAN_DYN, key, Nr, remGeom, &u[offset * totDim], PetscSafePointerPlusOffset(u_t, offset * totDim), probAux, PetscSafePointerPlusOffset(a, offset * totDimAux), t, X_tShift, &elemMatD[offset * totDim * totDim]));
6335: }
6336: }
6337: PetscCall(PetscFEGeomRestoreChunk(cgeomFEM, offset, numCells, &remGeom));
6338: PetscCall(PetscFEGeomRestoreChunk(cgeomFEM, 0, offset, &chunkGeom));
6339: PetscCall(DMSNESRestoreFEGeom(coordField, cellIS, qGeom, PETSC_FALSE, &cgeomFEM));
6340: PetscCall(PetscQuadratureDestroy(&qGeom));
6341: }
6342: /* Add contribution from X_t */
6343: if (hasDyn) {
6344: for (c = 0; c < numCells * totDim * totDim; ++c) elemMat[c] += X_tShift * elemMatD[c];
6345: }
6346: if (hasFV) {
6347: PetscClassId id;
6348: PetscFV fv;
6349: PetscInt offsetI, NcI, NbI = 1, fc, f;
6351: for (fieldI = 0; fieldI < Nf; ++fieldI) {
6352: PetscCall(PetscDSGetDiscretization(prob, fieldI, (PetscObject *)&fv));
6353: PetscCall(PetscDSGetFieldOffset(prob, fieldI, &offsetI));
6354: PetscCall(PetscObjectGetClassId((PetscObject)fv, &id));
6355: if (id != PETSCFV_CLASSID) continue;
6356: /* Put in the weighted identity */
6357: PetscCall(PetscFVGetNumComponents(fv, &NcI));
6358: for (c = cStart; c < cEnd; ++c) {
6359: const PetscInt cind = c - cStart;
6360: const PetscInt eOffset = cind * totDim * totDim;
6361: PetscReal vol;
6363: PetscCall(DMPlexComputeCellGeometryFVM(dm, c, &vol, NULL, NULL));
6364: for (fc = 0; fc < NcI; ++fc) {
6365: for (f = 0; f < NbI; ++f) {
6366: const PetscInt i = offsetI + f * NcI + fc;
6367: if (hasPrec) {
6368: if (hasJac) elemMat[eOffset + i * totDim + i] = vol;
6369: elemMatP[eOffset + i * totDim + i] = vol;
6370: } else {
6371: elemMat[eOffset + i * totDim + i] = vol;
6372: }
6373: }
6374: }
6375: }
6376: }
6377: /* No allocated space for FV stuff, so ignore the zero entries */
6378: PetscCall(MatSetOption(JacP, MAT_IGNORE_ZERO_ENTRIES, PETSC_TRUE));
6379: }
6380: /* Insert values into matrix */
6381: for (c = cStart; c < cEnd; ++c) {
6382: const PetscInt cell = cells ? cells[c] : c;
6383: const PetscInt cind = c - cStart;
6385: /* Transform to global basis before insertion in Jacobian */
6386: if (transform) PetscCall(DMPlexBasisTransformPointTensor_Internal(dm, tdm, tv, cell, PETSC_TRUE, totDim, &elemMat[cind * totDim * totDim]));
6387: if (hasPrec) {
6388: if (hasJac) {
6389: if (mesh->printFEM > 1) PetscCall(DMPrintCellMatrix(cell, name, totDim, totDim, &elemMat[cind * totDim * totDim]));
6390: PetscCall(DMPlexMatSetClosure_Internal(dm, section, globalSection, mesh->useMatClPerm, Jac, cell, &elemMat[cind * totDim * totDim], ADD_VALUES));
6391: }
6392: if (mesh->printFEM > 1) PetscCall(DMPrintCellMatrix(cell, name, totDim, totDim, &elemMatP[cind * totDim * totDim]));
6393: PetscCall(DMPlexMatSetClosure_Internal(dm, section, globalSection, mesh->useMatClPerm, JacP, cell, &elemMatP[cind * totDim * totDim], ADD_VALUES));
6394: } else {
6395: if (hasJac) {
6396: if (mesh->printFEM > 1) PetscCall(DMPrintCellMatrix(cell, name, totDim, totDim, &elemMat[cind * totDim * totDim]));
6397: PetscCall(DMPlexMatSetClosure_Internal(dm, section, globalSection, mesh->useMatClPerm, JacP, cell, &elemMat[cind * totDim * totDim], ADD_VALUES));
6398: }
6399: }
6400: }
6401: PetscCall(ISRestorePointRange(cellIS, &cStart, &cEnd, &cells));
6402: if (hasFV) PetscCall(MatSetOption(JacP, MAT_IGNORE_ZERO_ENTRIES, PETSC_FALSE));
6403: PetscCall(PetscFree5(u, u_t, elemMat, elemMatP, elemMatD));
6404: if (dmAux) PetscCall(PetscFree(a));
6405: /* Compute boundary integrals */
6406: PetscCall(DMPlexComputeBdJacobian_Internal(dm, locX, locX_t, t, X_tShift, Jac, JacP, ctx));
6407: /* Assemble matrix */
6408: end: {
6409: PetscBool assOp = hasJac && hasPrec ? PETSC_TRUE : PETSC_FALSE, gassOp;
6411: if (dmAux) PetscCall(DMDestroy(&plex));
6412: PetscCallMPI(MPIU_Allreduce(&assOp, &gassOp, 1, MPI_C_BOOL, MPI_LOR, PetscObjectComm((PetscObject)dm)));
6413: if (hasJac && hasPrec) {
6414: PetscCall(MatAssemblyBegin(Jac, MAT_FINAL_ASSEMBLY));
6415: PetscCall(MatAssemblyEnd(Jac, MAT_FINAL_ASSEMBLY));
6416: }
6417: }
6418: PetscCall(MatAssemblyBegin(JacP, MAT_FINAL_ASSEMBLY));
6419: PetscCall(MatAssemblyEnd(JacP, MAT_FINAL_ASSEMBLY));
6420: PetscCall(PetscLogEventEnd(DMPLEX_JacobianFEM, dm, 0, 0, 0));
6421: PetscFunctionReturn(PETSC_SUCCESS);
6422: }
6424: PetscErrorCode DMPlexComputeJacobianByKeyGeneral(DM dmr, DM dmc, PetscFormKey key, IS cellIS, PetscReal t, PetscReal X_tShift, Vec locX, Vec locX_t, Mat Jac, Mat JacP, PetscCtx ctx)
6425: {
6426: DM_Plex *mesh = (DM_Plex *)dmr->data;
6427: const char *name = "Jacobian";
6428: DM dmAux = NULL, plex, tdm;
6429: PetscInt printFEM = mesh->printFEM;
6430: PetscBool clPerm = mesh->useMatClPerm;
6431: DMEnclosureType encAux;
6432: Vec A, tv;
6433: DMField coordField;
6434: PetscDS rds, cds, dsAux = NULL;
6435: PetscSection rsection, rglobalSection, csection, cglobalSection, sectionAux;
6436: PetscScalar *elemMat, *elemMatP, *elemMatD, *u, *u_t, *a = NULL;
6437: const PetscInt *cells;
6438: PetscInt Nf, cNf;
6439: PetscInt totDim, ctotDim, totDimAux = 0, cStart, cEnd, numCells;
6440: PetscBool hasJac = PETSC_FALSE, hasPrec = PETSC_FALSE, hasDyn, hasFV = PETSC_FALSE, transform;
6441: MPI_Comm comm;
6443: PetscFunctionBegin;
6444: PetscCall(PetscObjectGetComm((PetscObject)dmr, &comm));
6445: PetscCall(PetscLogEventBegin(DMPLEX_JacobianFEM, dmr, 0, 0, 0));
6446: PetscCall(DMGetLocalSection(dmr, &rsection));
6447: PetscCall(DMGetGlobalSection(dmr, &rglobalSection));
6448: PetscCall(DMGetLocalSection(dmc, &csection));
6449: PetscCall(DMGetGlobalSection(dmc, &cglobalSection));
6450: PetscCall(DMGetAuxiliaryVec(dmr, key.label, key.value, key.part, &A));
6451: if (A) {
6452: PetscCall(VecGetDM(A, &dmAux));
6453: PetscCall(DMGetEnclosureRelation(dmAux, dmr, &encAux));
6454: PetscCall(DMConvert(dmAux, DMPLEX, &plex));
6455: PetscCall(DMGetLocalSection(plex, §ionAux));
6456: PetscCall(DMGetDS(dmAux, &dsAux));
6457: PetscCall(PetscDSGetTotalDimension(dsAux, &totDimAux));
6458: }
6459: PetscCall(DMGetCoordinateField(dmr, &coordField));
6460: if (!cellIS) goto end;
6461: PetscCall(ISGetPointRange(cellIS, &cStart, &cEnd, &cells));
6462: PetscCall(ISGetLocalSize(cellIS, &numCells));
6463: if (cStart >= cEnd) goto end;
6464: PetscCall(DMHasBasisTransform(dmr, &transform));
6465: PetscCall(DMGetBasisTransformDM_Internal(dmr, &tdm));
6466: PetscCall(DMGetBasisTransformVec_Internal(dmr, &tv));
6467: PetscCall(DMGetCellDS(dmr, cells ? cells[cStart] : cStart, &rds, NULL));
6468: PetscCall(DMGetCellDS(dmc, cells ? cells[cStart] : cStart, &cds, NULL));
6469: PetscCall(PetscDSGetNumFields(rds, &Nf));
6470: PetscCall(PetscDSGetNumFields(cds, &cNf));
6471: PetscCheck(Nf == cNf, comm, PETSC_ERR_ARG_WRONG, "Number of row fields %" PetscInt_FMT " != %" PetscInt_FMT " number of columns field", Nf, cNf);
6472: PetscCall(PetscDSGetTotalDimension(rds, &totDim));
6473: PetscCall(PetscDSGetTotalDimension(cds, &ctotDim));
6474: PetscCall(PetscDSHasJacobian(rds, &hasJac));
6475: PetscCall(PetscDSHasJacobianPreconditioner(rds, &hasPrec));
6476: /* user passed in the same matrix, avoid double contributions and
6477: only assemble the Jacobian */
6478: if (hasJac && Jac == JacP) hasPrec = PETSC_FALSE;
6479: PetscCall(PetscDSHasDynamicJacobian(rds, &hasDyn));
6480: hasDyn = hasDyn && (X_tShift != 0.0) ? PETSC_TRUE : PETSC_FALSE;
6481: PetscCall(PetscMalloc5(numCells * totDim, &u, (locX_t ? (size_t)numCells * totDim : 0), &u_t, (hasJac ? (size_t)numCells * totDim * ctotDim : 0), &elemMat, (hasPrec ? (size_t)numCells * totDim * ctotDim : 0), &elemMatP, (hasDyn ? (size_t)numCells * totDim * ctotDim : 0), &elemMatD));
6482: if (dmAux) PetscCall(PetscMalloc1(numCells * totDimAux, &a));
6483: for (PetscInt c = cStart; c < cEnd; ++c) {
6484: const PetscInt cell = cells ? cells[c] : c;
6485: const PetscInt cind = c - cStart;
6486: PetscScalar *x = NULL, *x_t = NULL;
6487: PetscInt i;
6489: PetscCall(DMPlexVecGetClosure(dmr, rsection, locX, cell, NULL, &x));
6490: for (i = 0; i < totDim; ++i) u[cind * totDim + i] = x[i];
6491: PetscCall(DMPlexVecRestoreClosure(dmr, rsection, locX, cell, NULL, &x));
6492: if (locX_t) {
6493: PetscCall(DMPlexVecGetClosure(dmr, rsection, locX_t, cell, NULL, &x_t));
6494: for (i = 0; i < totDim; ++i) u_t[cind * totDim + i] = x_t[i];
6495: PetscCall(DMPlexVecRestoreClosure(dmr, rsection, locX_t, cell, NULL, &x_t));
6496: }
6497: if (dmAux) {
6498: PetscInt subcell;
6499: PetscCall(DMGetEnclosurePoint(dmAux, dmr, encAux, cell, &subcell));
6500: PetscCall(DMPlexVecGetClosure(plex, sectionAux, A, subcell, NULL, &x));
6501: for (i = 0; i < totDimAux; ++i) a[cind * totDimAux + i] = x[i];
6502: PetscCall(DMPlexVecRestoreClosure(plex, sectionAux, A, subcell, NULL, &x));
6503: }
6504: }
6505: if (hasJac) PetscCall(PetscArrayzero(elemMat, numCells * totDim * ctotDim));
6506: if (hasPrec) PetscCall(PetscArrayzero(elemMatP, numCells * totDim * ctotDim));
6507: if (hasDyn) PetscCall(PetscArrayzero(elemMatD, numCells * totDim * ctotDim));
6508: for (PetscInt fieldI = 0; fieldI < Nf; ++fieldI) {
6509: PetscClassId id;
6510: PetscFE fe;
6511: PetscQuadrature qGeom = NULL;
6512: PetscInt Nb;
6513: /* Conforming batches */
6514: PetscInt numChunks, numBatches, numBlocks, Ne, blockSize, batchSize;
6515: /* Remainder */
6516: PetscInt Nr, offset, Nq;
6517: PetscInt maxDegree;
6518: PetscFEGeom *cgeomFEM, *chunkGeom = NULL, *remGeom = NULL;
6520: PetscCall(PetscDSGetDiscretization(rds, fieldI, (PetscObject *)&fe));
6521: PetscCall(PetscObjectGetClassId((PetscObject)fe, &id));
6522: if (id == PETSCFV_CLASSID) {
6523: hasFV = PETSC_TRUE;
6524: continue;
6525: }
6526: PetscCall(PetscFEGetDimension(fe, &Nb));
6527: PetscCall(PetscFEGetTileSizes(fe, NULL, &numBlocks, NULL, &numBatches));
6528: PetscCall(DMFieldGetDegree(coordField, cellIS, NULL, &maxDegree));
6529: if (maxDegree <= 1) PetscCall(DMFieldCreateDefaultQuadrature(coordField, cellIS, &qGeom));
6530: if (!qGeom) {
6531: PetscCall(PetscFEGetQuadrature(fe, &qGeom));
6532: PetscCall(PetscObjectReference((PetscObject)qGeom));
6533: }
6534: PetscCall(PetscQuadratureGetData(qGeom, NULL, NULL, &Nq, NULL, NULL));
6535: PetscCall(DMSNESGetFEGeom(coordField, cellIS, qGeom, PETSC_FEGEOM_BASIC, &cgeomFEM));
6536: blockSize = Nb;
6537: batchSize = numBlocks * blockSize;
6538: PetscCall(PetscFESetTileSizes(fe, blockSize, numBlocks, batchSize, numBatches));
6539: numChunks = numCells / (numBatches * batchSize);
6540: Ne = numChunks * numBatches * batchSize;
6541: Nr = numCells % (numBatches * batchSize);
6542: offset = numCells - Nr;
6543: PetscCall(PetscFEGeomGetChunk(cgeomFEM, 0, offset, &chunkGeom));
6544: PetscCall(PetscFEGeomGetChunk(cgeomFEM, offset, numCells, &remGeom));
6545: for (PetscInt fieldJ = 0; fieldJ < Nf; ++fieldJ) {
6546: key.field = fieldI * Nf + fieldJ;
6547: if (hasJac) {
6548: PetscCall(PetscFEIntegrateJacobian(rds, cds, PETSCFE_JACOBIAN, key, Ne, chunkGeom, u, u_t, dsAux, a, t, X_tShift, elemMat));
6549: PetscCall(PetscFEIntegrateJacobian(rds, cds, PETSCFE_JACOBIAN, key, Nr, remGeom, &u[offset * totDim], PetscSafePointerPlusOffset(u_t, offset * totDim), dsAux, PetscSafePointerPlusOffset(a, offset * totDimAux), t, X_tShift, &elemMat[offset * totDim * ctotDim]));
6550: }
6551: if (hasPrec) {
6552: PetscCall(PetscFEIntegrateJacobian(rds, cds, PETSCFE_JACOBIAN_PRE, key, Ne, chunkGeom, u, u_t, dsAux, a, t, X_tShift, elemMatP));
6553: PetscCall(PetscFEIntegrateJacobian(rds, cds, PETSCFE_JACOBIAN_PRE, key, Nr, remGeom, &u[offset * totDim], PetscSafePointerPlusOffset(u_t, offset * totDim), dsAux, PetscSafePointerPlusOffset(a, offset * totDimAux), t, X_tShift, &elemMatP[offset * totDim * ctotDim]));
6554: }
6555: if (hasDyn) {
6556: PetscCall(PetscFEIntegrateJacobian(rds, cds, PETSCFE_JACOBIAN_DYN, key, Ne, chunkGeom, u, u_t, dsAux, a, t, X_tShift, elemMatD));
6557: PetscCall(PetscFEIntegrateJacobian(rds, cds, PETSCFE_JACOBIAN_DYN, key, Nr, remGeom, &u[offset * totDim], PetscSafePointerPlusOffset(u_t, offset * totDim), dsAux, PetscSafePointerPlusOffset(a, offset * totDimAux), t, X_tShift, &elemMatD[offset * totDim * ctotDim]));
6558: }
6559: }
6560: PetscCall(PetscFEGeomRestoreChunk(cgeomFEM, offset, numCells, &remGeom));
6561: PetscCall(PetscFEGeomRestoreChunk(cgeomFEM, 0, offset, &chunkGeom));
6562: PetscCall(DMSNESRestoreFEGeom(coordField, cellIS, qGeom, PETSC_FALSE, &cgeomFEM));
6563: PetscCall(PetscQuadratureDestroy(&qGeom));
6564: }
6565: /* Add contribution from X_t */
6566: if (hasDyn) {
6567: for (PetscInt c = 0; c < numCells * totDim * ctotDim; ++c) elemMat[c] += X_tShift * elemMatD[c];
6568: }
6569: if (hasFV) {
6570: PetscClassId id;
6571: PetscFV fv;
6572: PetscInt offsetI, NcI, NbI = 1;
6574: for (PetscInt fieldI = 0; fieldI < Nf; ++fieldI) {
6575: PetscCall(PetscDSGetDiscretization(rds, fieldI, (PetscObject *)&fv));
6576: PetscCall(PetscDSGetFieldOffset(rds, fieldI, &offsetI));
6577: PetscCall(PetscObjectGetClassId((PetscObject)fv, &id));
6578: if (id != PETSCFV_CLASSID) continue;
6579: /* Put in the weighted identity */
6580: PetscCall(PetscFVGetNumComponents(fv, &NcI));
6581: for (PetscInt c = cStart; c < cEnd; ++c) {
6582: const PetscInt cind = c - cStart;
6583: const PetscInt eOffset = cind * totDim * ctotDim;
6584: PetscReal vol;
6586: PetscCall(DMPlexComputeCellGeometryFVM(dmr, c, &vol, NULL, NULL));
6587: for (PetscInt fc = 0; fc < NcI; ++fc) {
6588: for (PetscInt f = 0; f < NbI; ++f) {
6589: const PetscInt i = offsetI + f * NcI + fc;
6590: if (hasPrec) {
6591: if (hasJac) elemMat[eOffset + i * ctotDim + i] = vol;
6592: elemMatP[eOffset + i * ctotDim + i] = vol;
6593: } else {
6594: elemMat[eOffset + i * ctotDim + i] = vol;
6595: }
6596: }
6597: }
6598: }
6599: }
6600: /* No allocated space for FV stuff, so ignore the zero entries */
6601: PetscCall(MatSetOption(JacP, MAT_IGNORE_ZERO_ENTRIES, PETSC_TRUE));
6602: }
6603: /* Insert values into matrix */
6604: for (PetscInt c = cStart; c < cEnd; ++c) {
6605: const PetscInt cell = cells ? cells[c] : c;
6606: const PetscInt cind = c - cStart;
6608: /* Transform to global basis before insertion in Jacobian */
6609: if (transform) PetscCall(DMPlexBasisTransformPointTensor_Internal(dmr, tdm, tv, cell, PETSC_TRUE, totDim, &elemMat[cind * totDim * ctotDim]));
6610: if (hasPrec) {
6611: if (hasJac) {
6612: if (printFEM > 1) PetscCall(DMPrintCellMatrix(cell, name, totDim, ctotDim, &elemMat[cind * totDim * ctotDim]));
6613: PetscCall(DMPlexMatSetClosureGeneral(dmr, rsection, rglobalSection, clPerm, dmc, csection, cglobalSection, clPerm, Jac, cell, &elemMat[cind * totDim * ctotDim], ADD_VALUES));
6614: }
6615: if (printFEM > 1) PetscCall(DMPrintCellMatrix(cell, name, totDim, ctotDim, &elemMatP[cind * totDim * ctotDim]));
6616: PetscCall(DMPlexMatSetClosureGeneral(dmr, rsection, rglobalSection, clPerm, dmc, csection, cglobalSection, clPerm, JacP, cell, &elemMatP[cind * totDim * ctotDim], ADD_VALUES));
6617: } else {
6618: if (hasJac) {
6619: if (printFEM > 1) PetscCall(DMPrintCellMatrix(cell, name, totDim, ctotDim, &elemMat[cind * totDim * ctotDim]));
6620: PetscCall(DMPlexMatSetClosureGeneral(dmr, rsection, rglobalSection, clPerm, dmc, csection, cglobalSection, clPerm, JacP, cell, &elemMat[cind * totDim * ctotDim], ADD_VALUES));
6621: }
6622: }
6623: }
6624: PetscCall(ISRestorePointRange(cellIS, &cStart, &cEnd, &cells));
6625: if (hasFV) PetscCall(MatSetOption(JacP, MAT_IGNORE_ZERO_ENTRIES, PETSC_FALSE));
6626: PetscCall(PetscFree5(u, u_t, elemMat, elemMatP, elemMatD));
6627: if (dmAux) PetscCall(PetscFree(a));
6628: /* Compute boundary integrals */
6629: PetscCall(DMPlexComputeBdJacobian_Internal(dmr, locX, locX_t, t, X_tShift, Jac, JacP, ctx));
6630: /* Assemble matrix */
6631: end: {
6632: PetscBool assOp = hasJac && hasPrec ? PETSC_TRUE : PETSC_FALSE, gassOp;
6634: if (dmAux) PetscCall(DMDestroy(&plex));
6635: PetscCallMPI(MPIU_Allreduce(&assOp, &gassOp, 1, MPI_C_BOOL, MPI_LOR, comm));
6636: if (hasJac && hasPrec) {
6637: PetscCall(MatAssemblyBegin(Jac, MAT_FINAL_ASSEMBLY));
6638: PetscCall(MatAssemblyEnd(Jac, MAT_FINAL_ASSEMBLY));
6639: }
6640: }
6641: PetscCall(MatAssemblyBegin(JacP, MAT_FINAL_ASSEMBLY));
6642: PetscCall(MatAssemblyEnd(JacP, MAT_FINAL_ASSEMBLY));
6643: PetscCall(PetscLogEventEnd(DMPLEX_JacobianFEM, dmr, 0, 0, 0));
6644: PetscFunctionReturn(PETSC_SUCCESS);
6645: }
6647: /*@
6648: DMPlexComputeJacobianHybridByKey - Compute the local Jacobian over hybrid cells for terms matching the input key
6650: Collective
6652: Input Parameters:
6653: + dm - The output `DM`
6654: . key - The `PetscFormKey` array (left cell, right cell, cohesive cell) indicating what should be integrated
6655: . cellIS - The `IS` give a set of cells to integrate over
6656: . t - The time
6657: . X_tShift - The multiplier for the Jacobian with respect to $X_t$
6658: . locX - The local solution
6659: . locX_t - The time derivative of the local solution, or `NULL` for time-independent problems
6660: - ctx - An optional application context, passed to the pointwise functions
6662: Output Parameters:
6663: + Jac - The local Jacobian
6664: - JacP - The local Jacobian preconditioner
6666: Level: developer
6668: .seealso: `DMPlexComputeResidualByKey()`, `DMPlexComputeJacobianByKey()`, `DMPlexComputeResidualHybridByKey()`, `PetscFormKey`
6669: @*/
6670: PetscErrorCode DMPlexComputeJacobianHybridByKey(DM dm, PetscFormKey key[], IS cellIS, PetscReal t, PetscReal X_tShift, Vec locX, Vec locX_t, Mat Jac, Mat JacP, PetscCtx ctx)
6671: {
6672: DM_Plex *mesh = (DM_Plex *)dm->data;
6673: const char *name = "Hybrid Jacobian";
6674: DM dmAux[3] = {NULL, NULL, NULL};
6675: DMLabel ghostLabel = NULL;
6676: DM plex = NULL;
6677: DM plexA = NULL;
6678: PetscDS ds = NULL;
6679: PetscDS dsIn = NULL;
6680: PetscDS dsAux[3] = {NULL, NULL, NULL};
6681: Vec locA[3] = {NULL, NULL, NULL};
6682: DM dmScale[3] = {NULL, NULL, NULL};
6683: PetscDS dsScale[3] = {NULL, NULL, NULL};
6684: Vec locS[3] = {NULL, NULL, NULL};
6685: PetscSection section = NULL;
6686: PetscSection sectionAux[3] = {NULL, NULL, NULL};
6687: DMField coordField = NULL;
6688: PetscScalar *a[3] = {NULL, NULL, NULL};
6689: PetscScalar *s[3] = {NULL, NULL, NULL};
6690: PetscScalar *u = NULL, *u_t;
6691: PetscScalar *elemMatNeg, *elemMatPos, *elemMatCoh;
6692: PetscScalar *elemMatNegP, *elemMatPosP, *elemMatCohP;
6693: PetscSection globalSection;
6694: IS chunkISF, chunkISN;
6695: const PetscInt *cells;
6696: PetscInt *faces, *neighbors;
6697: PetscInt cStart, cEnd, numCells;
6698: PetscInt Nf, fieldI, fieldJ, totDim, totDimIn, totDimAux[3], totDimScale[3], numChunks, cellChunkSize, chunk;
6699: PetscInt maxDegree = PETSC_INT_MAX;
6700: PetscQuadrature affineQuadF = NULL, *quadsF = NULL;
6701: PetscFEGeom *affineGeomF = NULL, **geomsF = NULL;
6702: PetscQuadrature affineQuadN = NULL;
6703: PetscFEGeom *affineGeomN = NULL;
6704: PetscBool hasBdJac, hasBdPrec;
6706: PetscFunctionBegin;
6707: PetscCall(PetscLogEventBegin(DMPLEX_JacobianFEM, dm, 0, 0, 0));
6708: if (!cellIS) goto end;
6709: PetscCall(ISGetPointRange(cellIS, &cStart, &cEnd, &cells));
6710: PetscCall(ISGetLocalSize(cellIS, &numCells));
6711: if (cStart >= cEnd) goto end;
6712: if ((key[0].label == key[1].label) && (key[0].value == key[1].value) && (key[0].part == key[1].part)) {
6713: const char *name;
6714: PetscCall(PetscObjectGetName((PetscObject)key[0].label, &name));
6715: SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Form keys for each side of a cohesive surface must be different (%s, %" PetscInt_FMT ", %" PetscInt_FMT ")", name, key[0].value, key[0].part);
6716: }
6717: PetscCall(DMConvert(dm, DMPLEX, &plex));
6718: PetscCall(DMGetLocalSection(dm, §ion));
6719: PetscCall(DMGetGlobalSection(dm, &globalSection));
6720: PetscCall(DMGetLabel(dm, "ghost", &ghostLabel));
6721: PetscCall(DMGetCellDS(dm, cells ? cells[cStart] : cStart, &ds, &dsIn));
6722: PetscCall(PetscDSGetNumFields(ds, &Nf));
6723: PetscCall(PetscDSGetTotalDimension(ds, &totDim));
6724: PetscCall(PetscDSGetTotalDimension(dsIn, &totDimIn));
6725: PetscCall(PetscDSHasBdJacobian(ds, &hasBdJac));
6726: PetscCall(PetscDSHasBdJacobianPreconditioner(ds, &hasBdPrec));
6727: PetscCall(DMGetAuxiliaryVec(dm, key[2].label, key[2].value, key[2].part, &locA[2]));
6728: if (locA[2]) {
6729: const PetscInt cellStart = cells ? cells[cStart] : cStart;
6731: PetscCall(VecGetDM(locA[2], &dmAux[2]));
6732: PetscCall(DMConvert(dmAux[2], DMPLEX, &plexA));
6733: PetscCall(DMGetLocalSection(dmAux[2], §ionAux[2]));
6734: PetscCall(DMGetCellDS(dmAux[2], cellStart, &dsAux[2], NULL));
6735: PetscCall(PetscDSGetTotalDimension(dsAux[2], &totDimAux[2]));
6736: {
6737: const PetscInt *cone;
6738: PetscInt c;
6740: PetscCall(DMPlexGetCone(dm, cellStart, &cone));
6741: for (c = 0; c < 2; ++c) {
6742: const PetscInt *support;
6743: PetscInt ssize, s;
6745: PetscCall(DMPlexGetSupport(dm, cone[c], &support));
6746: PetscCall(DMPlexGetSupportSize(dm, cone[c], &ssize));
6747: PetscCheck(ssize == 2, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Face %" PetscInt_FMT " from cell %" PetscInt_FMT " has support size %" PetscInt_FMT " != 2", cone[c], cellStart, ssize);
6748: if (support[0] == cellStart) s = 1;
6749: else if (support[1] == cellStart) s = 0;
6750: else SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Face %" PetscInt_FMT " does not have cell %" PetscInt_FMT " in its support", cone[c], cellStart);
6751: PetscCall(DMGetAuxiliaryVec(dm, key[c].label, key[c].value, key[c].part, &locA[c]));
6752: if (locA[c]) PetscCall(VecGetDM(locA[c], &dmAux[c]));
6753: else dmAux[c] = dmAux[2];
6754: PetscCall(DMGetCellDS(dmAux[c], support[s], &dsAux[c], NULL));
6755: PetscCall(PetscDSGetTotalDimension(dsAux[c], &totDimAux[c]));
6756: }
6757: }
6758: }
6759: /* Handle mass matrix scaling
6760: The field in key[2] is the field to be scaled, and the scaling field is the first in the dsScale */
6761: PetscCall(DMGetAuxiliaryVec(dm, key[2].label, -key[2].value, key[2].part, &locS[2]));
6762: if (locS[2]) {
6763: const PetscInt cellStart = cells ? cells[cStart] : cStart;
6764: PetscInt Nb, Nbs;
6766: PetscCall(VecGetDM(locS[2], &dmScale[2]));
6767: PetscCall(DMGetCellDS(dmScale[2], cells ? cells[cStart] : cStart, &dsScale[2], NULL));
6768: PetscCall(PetscDSGetTotalDimension(dsScale[2], &totDimScale[2]));
6769: // BRAD: This is not set correctly
6770: key[2].field = 2;
6771: PetscCall(PetscDSGetFieldSize(ds, key[2].field, &Nb));
6772: PetscCall(PetscDSGetFieldSize(dsScale[2], 0, &Nbs));
6773: PetscCheck(Nb == Nbs, PETSC_COMM_SELF, PETSC_ERR_ARG_INCOMP, "Field %" PetscInt_FMT " of size %" PetscInt_FMT " cannot be scaled by field of size %" PetscInt_FMT, key[2].field, Nb, Nbs);
6774: {
6775: const PetscInt *cone;
6776: PetscInt c;
6778: locS[1] = locS[0] = locS[2];
6779: dmScale[1] = dmScale[0] = dmScale[2];
6780: PetscCall(DMPlexGetCone(dm, cellStart, &cone));
6781: for (c = 0; c < 2; ++c) {
6782: const PetscInt *support;
6783: PetscInt ssize, s;
6785: PetscCall(DMPlexGetSupport(dm, cone[c], &support));
6786: PetscCall(DMPlexGetSupportSize(dm, cone[c], &ssize));
6787: PetscCheck(ssize == 2, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Face %" PetscInt_FMT " from cell %" PetscInt_FMT " has support size %" PetscInt_FMT " != 2", cone[c], cellStart, ssize);
6788: if (support[0] == cellStart) s = 1;
6789: else if (support[1] == cellStart) s = 0;
6790: else SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Face %" PetscInt_FMT " does not have cell %" PetscInt_FMT " in its support", cone[c], cellStart);
6791: PetscCall(DMGetCellDS(dmScale[c], support[s], &dsScale[c], NULL));
6792: PetscCall(PetscDSGetTotalDimension(dsScale[c], &totDimScale[c]));
6793: }
6794: }
6795: }
6796: /* 2: Setup geometric data */
6797: PetscCall(DMGetCoordinateField(dm, &coordField));
6798: PetscCall(DMFieldGetDegree(coordField, cellIS, NULL, &maxDegree));
6799: if (maxDegree > 1) {
6800: PetscInt f;
6801: PetscCall(PetscCalloc2(Nf, &quadsF, Nf, &geomsF));
6802: for (f = 0; f < Nf; ++f) {
6803: PetscFE fe;
6805: PetscCall(PetscDSGetDiscretization(ds, f, (PetscObject *)&fe));
6806: if (fe) {
6807: PetscCall(PetscFEGetQuadrature(fe, &quadsF[f]));
6808: PetscCall(PetscObjectReference((PetscObject)quadsF[f]));
6809: }
6810: }
6811: }
6812: /* Loop over chunks */
6813: cellChunkSize = numCells;
6814: numChunks = !numCells ? 0 : PetscCeilReal(((PetscReal)numCells) / cellChunkSize);
6815: PetscCall(PetscCalloc2(2 * cellChunkSize, &faces, 2 * cellChunkSize, &neighbors));
6816: PetscCall(ISCreateGeneral(PETSC_COMM_SELF, 2 * cellChunkSize, faces, PETSC_USE_POINTER, &chunkISF));
6817: PetscCall(ISCreateGeneral(PETSC_COMM_SELF, 2 * cellChunkSize, neighbors, PETSC_USE_POINTER, &chunkISN));
6818: /* Extract field coefficients */
6819: /* NOTE This needs the end cap faces to have identical orientations */
6820: PetscCall(DMPlexGetHybridCellFields(dm, cellIS, locX, locX_t, locA[2], &u, &u_t, &a[2]));
6821: PetscCall(DMPlexGetHybridFields(dm, dmAux, dsAux, cellIS, locA, PETSC_TRUE, a));
6822: PetscCall(DMPlexGetHybridFields(dm, dmScale, dsScale, cellIS, locS, PETSC_TRUE, s));
6823: PetscCall(DMGetWorkArray(dm, hasBdJac ? cellChunkSize * totDim * totDim : 0, MPIU_SCALAR, &elemMatNeg));
6824: PetscCall(DMGetWorkArray(dm, hasBdJac ? cellChunkSize * totDim * totDim : 0, MPIU_SCALAR, &elemMatPos));
6825: PetscCall(DMGetWorkArray(dm, hasBdJac ? cellChunkSize * totDim * totDim : 0, MPIU_SCALAR, &elemMatCoh));
6826: PetscCall(DMGetWorkArray(dm, hasBdPrec ? cellChunkSize * totDim * totDim : 0, MPIU_SCALAR, &elemMatNegP));
6827: PetscCall(DMGetWorkArray(dm, hasBdPrec ? cellChunkSize * totDim * totDim : 0, MPIU_SCALAR, &elemMatPosP));
6828: PetscCall(DMGetWorkArray(dm, hasBdPrec ? cellChunkSize * totDim * totDim : 0, MPIU_SCALAR, &elemMatCohP));
6829: for (chunk = 0; chunk < numChunks; ++chunk) {
6830: PetscInt cS = cStart + chunk * cellChunkSize, cE = PetscMin(cS + cellChunkSize, cEnd), numCells = cE - cS, c;
6832: if (hasBdJac) {
6833: PetscCall(PetscArrayzero(elemMatNeg, cellChunkSize * totDim * totDim));
6834: PetscCall(PetscArrayzero(elemMatPos, cellChunkSize * totDim * totDim));
6835: PetscCall(PetscArrayzero(elemMatCoh, cellChunkSize * totDim * totDim));
6836: }
6837: if (hasBdPrec) {
6838: PetscCall(PetscArrayzero(elemMatNegP, cellChunkSize * totDim * totDim));
6839: PetscCall(PetscArrayzero(elemMatPosP, cellChunkSize * totDim * totDim));
6840: PetscCall(PetscArrayzero(elemMatCohP, cellChunkSize * totDim * totDim));
6841: }
6842: /* Get faces */
6843: for (c = cS; c < cE; ++c) {
6844: const PetscInt cell = cells ? cells[c] : c;
6845: const PetscInt *cone, *support;
6846: PetscCall(DMPlexGetCone(plex, cell, &cone));
6847: faces[(c - cS) * 2 + 0] = cone[0];
6848: faces[(c - cS) * 2 + 1] = cone[1];
6849: PetscCall(DMPlexGetSupport(dm, cone[0], &support));
6850: neighbors[(c - cS) * 2 + 0] = support[0] == cell ? support[1] : support[0];
6851: PetscCall(DMPlexGetSupport(dm, cone[1], &support));
6852: neighbors[(c - cS) * 2 + 1] = support[0] == cell ? support[1] : support[0];
6853: }
6854: PetscCall(ISGeneralSetIndices(chunkISF, 2 * cellChunkSize, faces, PETSC_USE_POINTER));
6855: PetscCall(ISGeneralSetIndices(chunkISN, 2 * cellChunkSize, neighbors, PETSC_USE_POINTER));
6856: if (maxDegree <= 1) {
6857: if (!affineQuadF) PetscCall(DMFieldCreateDefaultQuadrature(coordField, chunkISF, &affineQuadF));
6858: if (affineQuadF) PetscCall(DMSNESGetFEGeom(coordField, chunkISF, affineQuadF, PETSC_FEGEOM_COHESIVE, &affineGeomF));
6859: if (!affineQuadN) {
6860: PetscInt dim;
6861: PetscCall(PetscQuadratureGetData(affineQuadF, &dim, NULL, NULL, NULL, NULL));
6862: PetscCall(DMFieldCreateDefaultFaceQuadrature(coordField, chunkISN, &affineQuadN));
6863: PetscCall(PetscQuadratureSetData(affineQuadN, dim + 1, PETSC_DECIDE, PETSC_DECIDE, NULL, NULL));
6864: }
6865: if (affineQuadN) PetscCall(DMSNESGetFEGeom(coordField, chunkISN, affineQuadN, PETSC_FEGEOM_BASIC, &affineGeomN));
6866: } else {
6867: PetscInt f;
6868: for (f = 0; f < Nf; ++f) {
6869: if (quadsF[f]) PetscCall(DMSNESGetFEGeom(coordField, chunkISF, quadsF[f], PETSC_FEGEOM_COHESIVE, &geomsF[f]));
6870: }
6871: }
6873: for (fieldI = 0; fieldI < Nf; ++fieldI) {
6874: PetscFE feI;
6875: PetscFEGeom *geomF = affineGeomF ? affineGeomF : geomsF[fieldI];
6876: PetscFEGeom *chunkGeomF = NULL, *remGeomF = NULL;
6877: PetscFEGeom *geomN = affineGeomN ? affineGeomN : geomsF[fieldI];
6878: PetscFEGeom *chunkGeomN = NULL, *remGeomN = NULL;
6879: PetscQuadrature quadF = affineQuadF ? affineQuadF : quadsF[fieldI];
6880: PetscInt numChunks, numBatches, batchSize, numBlocks, blockSize, Ne, Nr, offset, Nq, Nb;
6881: PetscBool isCohesiveField;
6883: PetscCall(PetscDSGetDiscretization(ds, fieldI, (PetscObject *)&feI));
6884: if (!feI) continue;
6885: PetscCall(PetscFEGetTileSizes(feI, NULL, &numBlocks, NULL, &numBatches));
6886: PetscCall(PetscQuadratureGetData(quadF, NULL, NULL, &Nq, NULL, NULL));
6887: PetscCall(PetscFEGetDimension(feI, &Nb));
6888: blockSize = Nb;
6889: batchSize = numBlocks * blockSize;
6890: PetscCall(PetscFESetTileSizes(feI, blockSize, numBlocks, batchSize, numBatches));
6891: numChunks = numCells / (numBatches * batchSize);
6892: Ne = numChunks * numBatches * batchSize;
6893: Nr = numCells % (numBatches * batchSize);
6894: offset = numCells - Nr;
6895: PetscCall(PetscFEGeomGetChunk(geomF, 0, offset * 2, &chunkGeomF));
6896: PetscCall(PetscFEGeomGetChunk(geomF, offset * 2, numCells * 2, &remGeomF));
6897: PetscCall(PetscFEGeomGetChunk(geomN, 0, offset * 2, &chunkGeomN));
6898: PetscCall(PetscFEGeomGetChunk(geomN, offset * 2, numCells * 2, &remGeomN));
6899: PetscCall(PetscDSGetCohesive(ds, fieldI, &isCohesiveField));
6900: for (fieldJ = 0; fieldJ < Nf; ++fieldJ) {
6901: PetscFE feJ;
6903: PetscCall(PetscDSGetDiscretization(ds, fieldJ, (PetscObject *)&feJ));
6904: if (!feJ) continue;
6905: key[0].field = fieldI * Nf + fieldJ;
6906: key[1].field = fieldI * Nf + fieldJ;
6907: key[2].field = fieldI * Nf + fieldJ;
6908: if (hasBdJac) {
6909: PetscCall(PetscFEIntegrateHybridJacobian(ds, dsIn, PETSCFE_JACOBIAN, key[0], 0, Ne, chunkGeomF, chunkGeomN, u, u_t, dsAux[0], a[0], t, X_tShift, elemMatNeg));
6910: PetscCall(PetscFEIntegrateHybridJacobian(ds, dsIn, PETSCFE_JACOBIAN, key[0], 0, Nr, remGeomF, remGeomN, &u[offset * totDimIn], PetscSafePointerPlusOffset(u_t, offset * totDimIn), dsAux[0], PetscSafePointerPlusOffset(a[0], offset * totDimAux[0]), t, X_tShift, &elemMatNeg[offset * totDim * totDim]));
6911: PetscCall(PetscFEIntegrateHybridJacobian(ds, dsIn, PETSCFE_JACOBIAN, key[1], 1, Ne, chunkGeomF, chunkGeomN, u, u_t, dsAux[1], a[1], t, X_tShift, elemMatPos));
6912: PetscCall(PetscFEIntegrateHybridJacobian(ds, dsIn, PETSCFE_JACOBIAN, key[1], 1, Nr, remGeomF, remGeomN, &u[offset * totDimIn], PetscSafePointerPlusOffset(u_t, offset * totDimIn), dsAux[1], PetscSafePointerPlusOffset(a[1], offset * totDimAux[1]), t, X_tShift, &elemMatPos[offset * totDim * totDim]));
6913: }
6914: if (hasBdPrec) {
6915: PetscCall(PetscFEIntegrateHybridJacobian(ds, dsIn, PETSCFE_JACOBIAN_PRE, key[0], 0, Ne, chunkGeomF, chunkGeomN, u, u_t, dsAux[0], a[0], t, X_tShift, elemMatNegP));
6916: PetscCall(PetscFEIntegrateHybridJacobian(ds, dsIn, PETSCFE_JACOBIAN_PRE, key[0], 0, Nr, remGeomF, remGeomN, &u[offset * totDimIn], PetscSafePointerPlusOffset(u_t, offset * totDimIn), dsAux[0], &a[0][offset * totDimAux[0]], t, X_tShift, &elemMatNegP[offset * totDim * totDim]));
6917: PetscCall(PetscFEIntegrateHybridJacobian(ds, dsIn, PETSCFE_JACOBIAN_PRE, key[1], 1, Ne, chunkGeomF, chunkGeomN, u, u_t, dsAux[1], a[1], t, X_tShift, elemMatPosP));
6918: PetscCall(PetscFEIntegrateHybridJacobian(ds, dsIn, PETSCFE_JACOBIAN_PRE, key[1], 1, Nr, remGeomF, remGeomN, &u[offset * totDimIn], PetscSafePointerPlusOffset(u_t, offset * totDimIn), dsAux[1], &a[1][offset * totDimAux[1]], t, X_tShift, &elemMatPosP[offset * totDim * totDim]));
6919: }
6920: if (hasBdJac) {
6921: PetscCall(PetscFEIntegrateHybridJacobian(ds, dsIn, PETSCFE_JACOBIAN, key[2], 2, Ne, chunkGeomF, chunkGeomN, u, u_t, dsAux[2], a[2], t, X_tShift, elemMatCoh));
6922: PetscCall(PetscFEIntegrateHybridJacobian(ds, dsIn, PETSCFE_JACOBIAN, key[2], 2, Nr, remGeomF, remGeomN, &u[offset * totDimIn], PetscSafePointerPlusOffset(u_t, offset * totDimIn), dsAux[2], PetscSafePointerPlusOffset(a[2], offset * totDimAux[2]), t, X_tShift, &elemMatCoh[offset * totDim * totDim]));
6923: }
6924: if (hasBdPrec) {
6925: PetscCall(PetscFEIntegrateHybridJacobian(ds, dsIn, PETSCFE_JACOBIAN_PRE, key[2], 2, Ne, chunkGeomF, chunkGeomN, u, u_t, dsAux[2], a[2], t, X_tShift, elemMatCohP));
6926: PetscCall(PetscFEIntegrateHybridJacobian(ds, dsIn, PETSCFE_JACOBIAN_PRE, key[2], 2, Nr, remGeomF, remGeomN, &u[offset * totDimIn], PetscSafePointerPlusOffset(u_t, offset * totDimIn), dsAux[2], &a[2][offset * totDimAux[2]], t, X_tShift, &elemMatCohP[offset * totDim * totDim]));
6927: }
6928: }
6929: PetscCall(PetscFEGeomRestoreChunk(geomF, offset, numCells, &remGeomF));
6930: PetscCall(PetscFEGeomRestoreChunk(geomF, 0, offset, &chunkGeomF));
6931: PetscCall(PetscFEGeomRestoreChunk(geomN, offset, numCells, &remGeomN));
6932: PetscCall(PetscFEGeomRestoreChunk(geomN, 0, offset, &chunkGeomN));
6933: }
6934: /* Insert values into matrix */
6935: for (c = cS; c < cE; ++c) {
6936: const PetscInt cell = cells ? cells[c] : c;
6937: const PetscInt cind = c - cS, coff = cind * totDim * totDim;
6938: PetscInt i, j;
6940: /* Scale element values */
6941: if (locS[0]) {
6942: PetscInt Nb, soff = cind * totDimScale[0], off = 0;
6943: PetscBool cohesive;
6945: for (fieldI = 0; fieldI < Nf; ++fieldI) {
6946: PetscCall(PetscDSGetFieldSize(ds, fieldI, &Nb));
6947: PetscCall(PetscDSGetCohesive(ds, fieldI, &cohesive));
6949: if (fieldI == key[2].field) {
6950: PetscCheck(cohesive, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Scaling should not happen for face fields");
6951: for (i = 0; i < Nb; ++i) {
6952: for (j = 0; j < totDim; ++j) elemMatCoh[coff + (off + i) * totDim + j] += s[0][soff + i] * elemMatNeg[coff + (off + i) * totDim + j] + s[1][soff + i] * elemMatPos[coff + (off + i) * totDim + j];
6953: if (hasBdPrec)
6954: for (j = 0; j < totDim; ++j) elemMatCohP[coff + (off + i) * totDim + j] += s[0][soff + i] * elemMatNegP[coff + (off + i) * totDim + j] + s[1][soff + i] * elemMatPosP[coff + (off + i) * totDim + j];
6955: }
6956: off += Nb;
6957: } else {
6958: const PetscInt N = cohesive ? Nb : Nb * 2;
6960: for (i = 0; i < N; ++i) {
6961: for (j = 0; j < totDim; ++j) elemMatCoh[coff + (off + i) * totDim + j] += elemMatNeg[coff + (off + i) * totDim + j] + elemMatPos[coff + (off + i) * totDim + j];
6962: if (hasBdPrec)
6963: for (j = 0; j < totDim; ++j) elemMatCohP[coff + (off + i) * totDim + j] += elemMatNegP[coff + (off + i) * totDim + j] + elemMatPosP[coff + (off + i) * totDim + j];
6964: }
6965: off += N;
6966: }
6967: }
6968: } else {
6969: for (i = 0; i < totDim * totDim; ++i) elemMatCoh[coff + i] += elemMatNeg[coff + i] + elemMatPos[coff + i];
6970: if (hasBdPrec)
6971: for (i = 0; i < totDim * totDim; ++i) elemMatCohP[coff + i] += elemMatNegP[coff + i] + elemMatPosP[coff + i];
6972: }
6973: if (hasBdPrec) {
6974: if (hasBdJac) {
6975: if (mesh->printFEM > 1) PetscCall(DMPrintCellMatrix(cell, name, totDim, totDim, &elemMatCoh[cind * totDim * totDim]));
6976: PetscCall(DMPlexMatSetClosure_Internal(plex, section, globalSection, mesh->useMatClPerm, Jac, cell, &elemMatCoh[cind * totDim * totDim], ADD_VALUES));
6977: }
6978: if (mesh->printFEM > 1) PetscCall(DMPrintCellMatrix(cell, name, totDim, totDim, &elemMatCohP[cind * totDim * totDim]));
6979: PetscCall(DMPlexMatSetClosure(plex, section, globalSection, JacP, cell, &elemMatCohP[cind * totDim * totDim], ADD_VALUES));
6980: } else if (hasBdJac) {
6981: if (mesh->printFEM > 1) PetscCall(DMPrintCellMatrix(cell, name, totDim, totDim, &elemMatCoh[cind * totDim * totDim]));
6982: PetscCall(DMPlexMatSetClosure_Internal(plex, section, globalSection, mesh->useMatClPerm, JacP, cell, &elemMatCoh[cind * totDim * totDim], ADD_VALUES));
6983: }
6984: }
6985: }
6986: PetscCall(DMPlexRestoreCellFields(dm, cellIS, locX, locX_t, locA[2], &u, &u_t, &a[2]));
6987: PetscCall(DMPlexRestoreHybridFields(dm, dmAux, dsAux, cellIS, locA, PETSC_TRUE, a));
6988: PetscCall(DMRestoreWorkArray(dm, hasBdJac ? cellChunkSize * totDim * totDim : 0, MPIU_SCALAR, &elemMatNeg));
6989: PetscCall(DMRestoreWorkArray(dm, hasBdJac ? cellChunkSize * totDim * totDim : 0, MPIU_SCALAR, &elemMatPos));
6990: PetscCall(DMRestoreWorkArray(dm, hasBdJac ? cellChunkSize * totDim * totDim : 0, MPIU_SCALAR, &elemMatCoh));
6991: PetscCall(DMRestoreWorkArray(dm, hasBdPrec ? cellChunkSize * totDim * totDim : 0, MPIU_SCALAR, &elemMatNegP));
6992: PetscCall(DMRestoreWorkArray(dm, hasBdPrec ? cellChunkSize * totDim * totDim : 0, MPIU_SCALAR, &elemMatPosP));
6993: PetscCall(DMRestoreWorkArray(dm, hasBdPrec ? cellChunkSize * totDim * totDim : 0, MPIU_SCALAR, &elemMatCohP));
6994: PetscCall(PetscFree2(faces, neighbors));
6995: PetscCall(ISDestroy(&chunkISF));
6996: PetscCall(ISDestroy(&chunkISN));
6997: PetscCall(ISRestorePointRange(cellIS, &cStart, &cEnd, &cells));
6998: if (maxDegree <= 1) {
6999: PetscCall(DMSNESRestoreFEGeom(coordField, cellIS, affineQuadF, PETSC_FALSE, &affineGeomF));
7000: PetscCall(PetscQuadratureDestroy(&affineQuadF));
7001: PetscCall(DMSNESRestoreFEGeom(coordField, cellIS, affineQuadN, PETSC_FALSE, &affineGeomN));
7002: PetscCall(PetscQuadratureDestroy(&affineQuadN));
7003: } else {
7004: PetscInt f;
7005: for (f = 0; f < Nf; ++f) {
7006: if (geomsF) PetscCall(DMSNESRestoreFEGeom(coordField, cellIS, quadsF[f], PETSC_FALSE, &geomsF[f]));
7007: if (quadsF) PetscCall(PetscQuadratureDestroy(&quadsF[f]));
7008: }
7009: PetscCall(PetscFree2(quadsF, geomsF));
7010: }
7011: if (dmAux[2]) PetscCall(DMDestroy(&plexA));
7012: PetscCall(DMDestroy(&plex));
7013: end:
7014: PetscCall(PetscLogEventEnd(DMPLEX_JacobianFEM, dm, 0, 0, 0));
7015: PetscFunctionReturn(PETSC_SUCCESS);
7016: }
7018: /*@
7019: DMPlexComputeJacobianActionByKey - Compute the local Jacobian for terms matching the input key
7021: Collective
7023: Input Parameters:
7024: + dm - The output `DM`
7025: . key - The `PetscFormKey` indicating what should be integrated
7026: . cellIS - The `IS` give a set of cells to integrate over
7027: . t - The time
7028: . X_tShift - The multiplier for the Jacobian with respect to $X_t$
7029: . locX - The local solution
7030: . locX_t - The time derivative of the local solution, or `NULL` for time-independent problems
7031: . locY - The local vector acted on by J
7032: - ctx - An optional application context, passed to the pointwise functions
7034: Output Parameter:
7035: . locF - The local residual F = J(X) Y
7037: Level: developer
7039: .seealso: `DMPlexComputeResidualByKey()`, `DMPlexComputeJacobianByKey()`, `DMPlexComputeResidualHybridByKey()`, `DMPlexComputeJacobianHybridByKey()`, `PetscFormKey`
7040: @*/
7041: PetscErrorCode DMPlexComputeJacobianActionByKey(DM dm, PetscFormKey key, IS cellIS, PetscReal t, PetscReal X_tShift, Vec locX, Vec locX_t, Vec locY, Vec locF, PetscCtx ctx)
7042: {
7043: DM_Plex *mesh = (DM_Plex *)dm->data;
7044: const char *name = "Jacobian";
7045: DM dmAux = NULL, plex, plexAux = NULL;
7046: DMEnclosureType encAux;
7047: Vec A;
7048: DMField coordField;
7049: PetscDS prob, probAux = NULL;
7050: PetscQuadrature quad;
7051: PetscSection section, globalSection, sectionAux;
7052: PetscScalar *elemMat, *elemMatD, *u, *u_t, *a = NULL, *y, *z;
7053: const PetscInt *cells;
7054: PetscInt Nf, fieldI, fieldJ;
7055: PetscInt totDim, totDimAux = 0, cStart, cEnd, numCells, c;
7056: PetscBool hasDyn;
7058: PetscFunctionBegin;
7059: PetscCall(PetscLogEventBegin(DMPLEX_JacobianFEM, dm, 0, 0, 0));
7060: PetscCall(DMConvert(dm, DMPLEX, &plex));
7061: PetscCall(ISGetLocalSize(cellIS, &numCells));
7062: PetscCall(ISGetPointRange(cellIS, &cStart, &cEnd, &cells));
7063: PetscCall(DMGetLocalSection(dm, §ion));
7064: PetscCall(DMGetGlobalSection(dm, &globalSection));
7065: PetscCall(DMGetCellDS(dm, cells ? cells[cStart] : cStart, &prob, NULL));
7066: PetscCall(PetscDSGetNumFields(prob, &Nf));
7067: PetscCall(PetscDSGetTotalDimension(prob, &totDim));
7068: PetscCall(PetscDSHasDynamicJacobian(prob, &hasDyn));
7069: hasDyn = hasDyn && (X_tShift != 0.0) ? PETSC_TRUE : PETSC_FALSE;
7070: PetscCall(DMGetAuxiliaryVec(dm, key.label, key.value, key.part, &A));
7071: if (A) {
7072: PetscCall(VecGetDM(A, &dmAux));
7073: PetscCall(DMGetEnclosureRelation(dmAux, dm, &encAux));
7074: PetscCall(DMConvert(dmAux, DMPLEX, &plexAux));
7075: PetscCall(DMGetLocalSection(plexAux, §ionAux));
7076: PetscCall(DMGetDS(dmAux, &probAux));
7077: PetscCall(PetscDSGetTotalDimension(probAux, &totDimAux));
7078: }
7079: PetscCall(VecSet(locF, 0.0));
7080: PetscCall(PetscMalloc6(numCells * totDim, &u, (locX_t ? (size_t)numCells * totDim : 0), &u_t, numCells * totDim * totDim, &elemMat, (hasDyn ? (size_t)numCells * totDim * totDim : 0), &elemMatD, numCells * totDim, &y, totDim, &z));
7081: if (dmAux) PetscCall(PetscMalloc1(numCells * totDimAux, &a));
7082: PetscCall(DMGetCoordinateField(dm, &coordField));
7083: for (c = cStart; c < cEnd; ++c) {
7084: const PetscInt cell = cells ? cells[c] : c;
7085: const PetscInt cind = c - cStart;
7086: PetscScalar *x = NULL, *x_t = NULL;
7087: PetscInt i;
7089: PetscCall(DMPlexVecGetClosure(plex, section, locX, cell, NULL, &x));
7090: for (i = 0; i < totDim; ++i) u[cind * totDim + i] = x[i];
7091: PetscCall(DMPlexVecRestoreClosure(plex, section, locX, cell, NULL, &x));
7092: if (locX_t) {
7093: PetscCall(DMPlexVecGetClosure(plex, section, locX_t, cell, NULL, &x_t));
7094: for (i = 0; i < totDim; ++i) u_t[cind * totDim + i] = x_t[i];
7095: PetscCall(DMPlexVecRestoreClosure(plex, section, locX_t, cell, NULL, &x_t));
7096: }
7097: if (dmAux) {
7098: PetscInt subcell;
7099: PetscCall(DMGetEnclosurePoint(dmAux, dm, encAux, cell, &subcell));
7100: PetscCall(DMPlexVecGetClosure(plexAux, sectionAux, A, subcell, NULL, &x));
7101: for (i = 0; i < totDimAux; ++i) a[cind * totDimAux + i] = x[i];
7102: PetscCall(DMPlexVecRestoreClosure(plexAux, sectionAux, A, subcell, NULL, &x));
7103: }
7104: PetscCall(DMPlexVecGetClosure(plex, section, locY, cell, NULL, &x));
7105: for (i = 0; i < totDim; ++i) y[cind * totDim + i] = x[i];
7106: PetscCall(DMPlexVecRestoreClosure(plex, section, locY, cell, NULL, &x));
7107: }
7108: PetscCall(PetscArrayzero(elemMat, numCells * totDim * totDim));
7109: if (hasDyn) PetscCall(PetscArrayzero(elemMatD, numCells * totDim * totDim));
7110: for (fieldI = 0; fieldI < Nf; ++fieldI) {
7111: PetscFE fe;
7112: PetscInt Nb;
7113: /* Conforming batches */
7114: PetscInt numChunks, numBatches, numBlocks, Ne, blockSize, batchSize;
7115: /* Remainder */
7116: PetscInt Nr, offset, Nq;
7117: PetscQuadrature qGeom = NULL;
7118: PetscInt maxDegree;
7119: PetscFEGeom *cgeomFEM, *chunkGeom = NULL, *remGeom = NULL;
7121: PetscCall(PetscDSGetDiscretization(prob, fieldI, (PetscObject *)&fe));
7122: PetscCall(PetscFEGetQuadrature(fe, &quad));
7123: PetscCall(PetscFEGetDimension(fe, &Nb));
7124: PetscCall(PetscFEGetTileSizes(fe, NULL, &numBlocks, NULL, &numBatches));
7125: PetscCall(DMFieldGetDegree(coordField, cellIS, NULL, &maxDegree));
7126: if (maxDegree <= 1) PetscCall(DMFieldCreateDefaultQuadrature(coordField, cellIS, &qGeom));
7127: if (!qGeom) {
7128: PetscCall(PetscFEGetQuadrature(fe, &qGeom));
7129: PetscCall(PetscObjectReference((PetscObject)qGeom));
7130: }
7131: PetscCall(PetscQuadratureGetData(qGeom, NULL, NULL, &Nq, NULL, NULL));
7132: PetscCall(DMSNESGetFEGeom(coordField, cellIS, qGeom, PETSC_FEGEOM_BASIC, &cgeomFEM));
7133: blockSize = Nb;
7134: batchSize = numBlocks * blockSize;
7135: PetscCall(PetscFESetTileSizes(fe, blockSize, numBlocks, batchSize, numBatches));
7136: numChunks = numCells / (numBatches * batchSize);
7137: Ne = numChunks * numBatches * batchSize;
7138: Nr = numCells % (numBatches * batchSize);
7139: offset = numCells - Nr;
7140: PetscCall(PetscFEGeomGetChunk(cgeomFEM, 0, offset, &chunkGeom));
7141: PetscCall(PetscFEGeomGetChunk(cgeomFEM, offset, numCells, &remGeom));
7142: for (fieldJ = 0; fieldJ < Nf; ++fieldJ) {
7143: key.field = fieldI * Nf + fieldJ;
7144: PetscCall(PetscFEIntegrateJacobian(prob, prob, PETSCFE_JACOBIAN, key, Ne, chunkGeom, u, u_t, probAux, a, t, X_tShift, elemMat));
7145: PetscCall(PetscFEIntegrateJacobian(prob, prob, PETSCFE_JACOBIAN, key, Nr, remGeom, &u[offset * totDim], PetscSafePointerPlusOffset(u_t, offset * totDim), probAux, PetscSafePointerPlusOffset(a, offset * totDimAux), t, X_tShift, &elemMat[offset * totDim * totDim]));
7146: if (hasDyn) {
7147: PetscCall(PetscFEIntegrateJacobian(prob, prob, PETSCFE_JACOBIAN_DYN, key, Ne, chunkGeom, u, u_t, probAux, a, t, X_tShift, elemMatD));
7148: PetscCall(PetscFEIntegrateJacobian(prob, prob, PETSCFE_JACOBIAN_DYN, key, Nr, remGeom, &u[offset * totDim], PetscSafePointerPlusOffset(u_t, offset * totDim), probAux, &a[offset * totDimAux], t, X_tShift, &elemMatD[offset * totDim * totDim]));
7149: }
7150: }
7151: PetscCall(PetscFEGeomRestoreChunk(cgeomFEM, offset, numCells, &remGeom));
7152: PetscCall(PetscFEGeomRestoreChunk(cgeomFEM, 0, offset, &chunkGeom));
7153: PetscCall(DMSNESRestoreFEGeom(coordField, cellIS, qGeom, PETSC_FALSE, &cgeomFEM));
7154: PetscCall(PetscQuadratureDestroy(&qGeom));
7155: }
7156: if (hasDyn) {
7157: for (c = 0; c < numCells * totDim * totDim; ++c) elemMat[c] += X_tShift * elemMatD[c];
7158: }
7159: for (c = cStart; c < cEnd; ++c) {
7160: const PetscInt cell = cells ? cells[c] : c;
7161: const PetscInt cind = c - cStart;
7162: const PetscBLASInt one = 1;
7163: PetscBLASInt M;
7164: const PetscScalar a = 1.0, b = 0.0;
7166: PetscCall(PetscBLASIntCast(totDim, &M));
7167: PetscCallBLAS("BLASgemv", BLASgemv_("N", &M, &M, &a, &elemMat[cind * totDim * totDim], &M, &y[cind * totDim], &one, &b, z, &one));
7168: if (mesh->printFEM > 1) {
7169: PetscCall(DMPrintCellMatrix(c, name, totDim, totDim, &elemMat[cind * totDim * totDim]));
7170: PetscCall(DMPrintCellVector(c, "Y", totDim, &y[cind * totDim]));
7171: PetscCall(DMPrintCellVector(c, "Z", totDim, z));
7172: }
7173: PetscCall(DMPlexVecSetClosure(dm, section, locF, cell, z, ADD_VALUES));
7174: }
7175: PetscCall(PetscFree6(u, u_t, elemMat, elemMatD, y, z));
7176: if (mesh->printFEM) {
7177: PetscCall(PetscPrintf(PetscObjectComm((PetscObject)locF), "Z:\n"));
7178: PetscCall(VecView(locF, NULL));
7179: }
7180: PetscCall(ISRestorePointRange(cellIS, &cStart, &cEnd, &cells));
7181: PetscCall(PetscFree(a));
7182: PetscCall(DMDestroy(&plexAux));
7183: PetscCall(DMDestroy(&plex));
7184: PetscCall(PetscLogEventEnd(DMPLEX_JacobianFEM, dm, 0, 0, 0));
7185: PetscFunctionReturn(PETSC_SUCCESS);
7186: }
7188: static void f0_1(PetscInt dim, PetscInt Nf, PetscInt NfAux, const PetscInt uOff[], const PetscInt uOff_x[], const PetscScalar u[], const PetscScalar u_t[], const PetscScalar u_x[], const PetscInt aOff[], const PetscInt aOff_x[], const PetscScalar a[], const PetscScalar a_t[], const PetscScalar a_x[], PetscReal t, const PetscReal x[], PetscInt numConstants, const PetscScalar constants[], PetscScalar f0[])
7189: {
7190: f0[0] = u[0];
7191: }
7193: static void f0_x(PetscInt dim, PetscInt Nf, PetscInt NfAux, const PetscInt uOff[], const PetscInt uOff_x[], const PetscScalar u[], const PetscScalar u_t[], const PetscScalar u_x[], const PetscInt aOff[], const PetscInt aOff_x[], const PetscScalar a[], const PetscScalar a_t[], const PetscScalar a_x[], PetscReal t, const PetscReal x[], PetscInt numConstants, const PetscScalar constants[], PetscScalar f0[])
7194: {
7195: f0[0] = x[(int)PetscRealPart(constants[0])] * u[0];
7196: }
7198: static void f0_x2(PetscInt dim, PetscInt Nf, PetscInt NfAux, const PetscInt uOff[], const PetscInt uOff_x[], const PetscScalar u[], const PetscScalar u_t[], const PetscScalar u_x[], const PetscInt aOff[], const PetscInt aOff_x[], const PetscScalar a[], const PetscScalar a_t[], const PetscScalar a_x[], PetscReal t, const PetscReal x[], PetscInt numConstants, const PetscScalar constants[], PetscScalar f0[])
7199: {
7200: PetscInt d;
7202: f0[0] = 0.0;
7203: for (d = 0; d < dim; ++d) f0[0] += PetscSqr(x[d]) * u[0];
7204: }
7206: /*@
7207: DMPlexComputeMoments - Compute the first three moments for a field
7209: Noncollective
7211: Input Parameters:
7212: + dm - the `DMPLEX`
7213: - u - the field
7215: Output Parameter:
7216: . moments - the field moments
7218: Level: intermediate
7220: Note:
7221: The `moments` array should be of length cdim + 2, where cdim is the number of components for the coordinate field.
7223: .seealso: `DM`, `DMPLEX`, `DMSwarmComputeMoments()`
7224: @*/
7225: PetscErrorCode DMPlexComputeMoments(DM dm, Vec u, PetscReal moments[])
7226: {
7227: PetscDS ds;
7228: PetscScalar mom, constants[1];
7229: const PetscScalar *oldConstants;
7230: PetscInt cdim, Nf, field = 0, Ncon;
7231: MPI_Comm comm;
7232: void *ctx;
7234: PetscFunctionBeginUser;
7235: PetscCall(PetscObjectGetComm((PetscObject)dm, &comm));
7236: PetscCall(DMGetCoordinateDim(dm, &cdim));
7237: PetscCall(DMGetApplicationContext(dm, &ctx));
7238: PetscCall(DMGetDS(dm, &ds));
7239: PetscCall(PetscDSGetNumFields(ds, &Nf));
7240: PetscCall(PetscDSGetConstants(ds, &Ncon, &oldConstants));
7241: PetscCheck(Nf == 1, comm, PETSC_ERR_ARG_WRONG, "We currently only support 1 field, not %" PetscInt_FMT, Nf);
7242: PetscCall(PetscDSSetObjective(ds, field, &f0_1));
7243: PetscCall(DMPlexComputeIntegralFEM(dm, u, &mom, ctx));
7244: moments[0] = PetscRealPart(mom);
7245: for (PetscInt c = 0; c < cdim; ++c) {
7246: constants[0] = c;
7247: PetscCall(PetscDSSetConstants(ds, 1, constants));
7248: PetscCall(PetscDSSetObjective(ds, field, &f0_x));
7249: PetscCall(DMPlexComputeIntegralFEM(dm, u, &mom, ctx));
7250: moments[c + 1] = PetscRealPart(mom);
7251: }
7252: PetscCall(PetscDSSetObjective(ds, field, &f0_x2));
7253: PetscCall(DMPlexComputeIntegralFEM(dm, u, &mom, ctx));
7254: moments[cdim + 1] = PetscRealPart(mom);
7255: PetscCall(PetscDSSetConstants(ds, Ncon, (PetscScalar *)oldConstants));
7256: PetscFunctionReturn(PETSC_SUCCESS);
7257: }